问:
How to convert Tensor to numpy array inside a map function using tf.py_function
I am trying to create an image augmentation pipeline for an object detection network, where my training examples are augmented as they go into the network. The images and the bounding boxes need to be augmented, but the standard tf.image methods don't work with bounding box data.

All the easy augmentation libraries that work with bounding boxes need numpy arrays but I don't know how to convert my Tensors into numpy arrays inside my .map() function. Even when I wrap my augment function in a tf.py_function call I still get the error AttributeError: 'Tensor' object has no attribute 'numpy' when I try to convert my image via image = image.numpy().

my dataset is loaded via this:

```<code>def load_tfrecord_dataset(file_pattern, class_file, size=416):
    LINE_NUMBER = -1
    class_table = tf.lookup.StaticHashTable(tf.lookup.TextFileInitializer(
        class_file, tf.string, 0, tf.int64, LINE_NUMBER, delimiter="\n"), -1)

    files = tf.data.Dataset.list_files(file_pattern)
    dataset = files.flat_map(tf.data.TFRecordDataset)
    return dataset.map(lambda x: tf.py_function(parse_tfrecord(x, class_table, size), [x], tf.float32))
    # return dataset.map(lambda x: parse_tfrecord(x, class_table, size))
</code>```

this calls my parsing function:

```<code>def parse_tfrecord(tfrecord, class_table, size):
    x = tf.io.parse_single_example(tfrecord, IMAGE_FEATURE_MAP)
    x_train = tf.image.decode_jpeg(x['image/encoded'], channels=3)
    x_train = tf.image.resize(x_train, (size, size))

    class_text = tf.sparse.to_dense(
        x['image/object/class/text'], default_value='')
    labels = tf.cast(class_table.lookup(class_text), tf.float32)

    y_train = tf.stack([tf.sparse.to_dense(x['image/object/bbox/xmin']),
                        tf.sparse.to_dense(x['image/object/bbox/ymin']),
                        tf.sparse.to_dense(x['image/object/bbox/xmax']),
                        tf.sparse.to_dense(x['image/object/bbox/ymax']),
                        labels], axis=1)

    x_train, y_train = tf.py_function(augment_images(x_train, y_train), [], tf.uint8)

    paddings = [[0, FLAGS.yolo_max_boxes - tf.shape(y_train)[0]], [0, 0]]
    y_train = tf.pad(y_train, paddings)

    return x_train, y_train
</code>```

which calls my augment function:

```<code>def augment_images(image, boxes):

    image = image.numpy()

    seq = iaa.Sequential([
        iaa.Fliplr(0.5),
        iaa.Flipud(0.5)
    ])

    image, label = seq(image=image, bounding_boxes=boxes)

    return image, label
</code>```

But no matter which parts of the code I wrap in a tf.py_function or where I try to convert to a numpy array, I always get the same error.

What am I doing wrong?

答:
I was able to recreate your error. This happens only when I try to use numpy() on an image and the error thrown is AttributeError: 'Image' object has no attribute 'numpy', but the numpy() function works perfectly fine in other cases.

In the below simple program, I am reading an image(.jpg file) of bird and later doing tf.image.central_crop to crop the central part of the image. The numpy() worked perfectly fine when we tried to extract string(file path) from the tensor using bytes.decode(path.numpy()), but threw error AttributeError: 'Image' object has no attribute 'numpy' when we tried to use numpy() on image type.

Code to recreate the issue -

```<code>%tensorflow_version 2.x
import tensorflow as tf
print(tf.__version__)
from tensorflow.keras.preprocessing.image import load_img
from tensorflow.keras.preprocessing.image import img_to_array, array_to_img
from matplotlib import pyplot as plt
import numpy as np

def load_file_and_process(path):
    image = load_img(bytes.decode(path.numpy()), target_size=(224, 224))
    image = image.numpy()
    image = tf.image.central_crop(image, np.random.uniform(0.50, 1.00))
    return image

train_dataset = tf.data.Dataset.list_files('/content/bird.jpg')
train_dataset = train_dataset.map(lambda x: tf.py_function(load_file_and_process, [x], [tf.float32]))

for f in train_dataset:
  for l in f:
    image = np.array(array_to_img(l))
    plt.imshow(image)
</code>```

Output -

```<code>2.2.0
---------------------------------------------------------------------------
UnknownError                              Traceback (most recent call last)
/usr/local/lib/python3.6/dist-packages/tensorflow/python/eager/context.py in execution_mode(mode)
   1985       ctx.executor = executor_new
-> 1986       yield
   1987     finally:

10 frames
UnknownError: AttributeError: 'Image' object has no attribute 'numpy'
Traceback (most recent call last):

  File "/usr/local/lib/python3.6/dist-packages/tensorflow/python/ops/script_ops.py", line 241, in __call__
    return func(device, token, args)

  File "/usr/local/lib/python3.6/dist-packages/tensorflow/python/ops/script_ops.py", line 130, in __call__
    ret = self._func(*args)

  File "/usr/local/lib/python3.6/dist-packages/tensorflow/python/autograph/impl/api.py", line 309, in wrapper
    return func(*args, **kwargs)

  File "<ipython-input-22-2aab1a57781b>", line 11, in load_file_and_process
    image = image.numpy()

AttributeError: 'Image' object has no attribute 'numpy'

     [[{{node EagerPyFunc}}]] [Op:IteratorGetNext]

During handling of the above exception, another exception occurred:

UnknownError                              Traceback (most recent call last)
/usr/local/lib/python3.6/dist-packages/tensorflow/python/eager/executor.py in wait(self)
     65   def wait(self):
     66     """Waits for ops dispatched in this executor to finish."""
---> 67     pywrap_tfe.TFE_ExecutorWaitForAllPendingNodes(self._handle)
     68
     69   def clear_error(self):

UnknownError: AttributeError: 'Image' object has no attribute 'numpy'
Traceback (most recent call last):

  File "/usr/local/lib/python3.6/dist-packages/tensorflow/python/ops/script_ops.py", line 241, in __call__
    return func(device, token, args)

  File "/usr/local/lib/python3.6/dist-packages/tensorflow/python/ops/script_ops.py", line 130, in __call__
    ret = self._func(*args)

  File "/usr/local/lib/python3.6/dist-packages/tensorflow/python/autograph/impl/api.py", line 309, in wrapper
    return func(*args, **kwargs)

  File "<ipython-input-22-2aab1a57781b>", line 11, in load_file_and_process
    image = image.numpy()

AttributeError: 'Image' object has no attribute 'numpy'

     [[{{node EagerPyFunc}}]]
</code>```

Solution -  Use img_to_array and array_to_img to convert the image to array and array to image respectively. You need to include from tensorflow.keras.preprocessing.image import img_to_array, array_to_img in your program.

Fixed Code -

```<code>%tensorflow_version 2.x
import tensorflow as tf
print(tf.__version__)
from tensorflow.keras.preprocessing.image import load_img
from tensorflow.keras.preprocessing.image import img_to_array, array_to_img
from matplotlib import pyplot as plt
import numpy as np

def load_file_and_process(path):
    image = load_img(bytes.decode(path.numpy()), target_size=(224, 224))
    image = img_to_array(image)
    image = tf.image.central_crop(image, np.random.uniform(0.50, 1.00))
    return image

train_dataset = tf.data.Dataset.list_files('/content/bird.jpg')
train_dataset = train_dataset.map(lambda x: tf.py_function(load_file_and_process, [x], [tf.float32]))

for f in train_dataset:
  for l in f:
    image = np.array(array_to_img(l))
    plt.imshow(image)
</code>```

Output -
2.2.0

Hope this answers your question. Happy Learning.

Body:
I am trying to create an image augmentation pipeline for an object detection network, where my training examples are augmented as they go into the network. The images and the bounding boxes need to be augmented, but the standard tf.image methods don't work with bounding box data.

All the easy augmentation libraries that work with bounding boxes need numpy arrays but I don't know how to convert my Tensors into numpy arrays inside my .map() function. Even when I wrap my augment function in a tf.py_function call I still get the error AttributeError: 'Tensor' object has no attribute 'numpy' when I try to convert my image via image = image.numpy().

my dataset is loaded via this:

def load_tfrecord_dataset(file_pattern, class_file, size=416):
    LINE_NUMBER = -1
    class_table = tf.lookup.StaticHashTable(tf.lookup.TextFileInitializer(
        class_file, tf.string, 0, tf.int64, LINE_NUMBER, delimiter="\n"), -1)

    files = tf.data.Dataset.list_files(file_pattern)
    dataset = files.flat_map(tf.data.TFRecordDataset)
    return dataset.map(lambda x: tf.py_function(parse_tfrecord(x, class_table, size), [x], tf.float32))
    # return dataset.map(lambda x: parse_tfrecord(x, class_table, size))

this calls my parsing function:

def parse_tfrecord(tfrecord, class_table, size):
    x = tf.io.parse_single_example(tfrecord, IMAGE_FEATURE_MAP)
    x_train = tf.image.decode_jpeg(x['image/encoded'], channels=3)
    x_train = tf.image.resize(x_train, (size, size))

    class_text = tf.sparse.to_dense(
        x['image/object/class/text'], default_value='')
    labels = tf.cast(class_table.lookup(class_text), tf.float32)

    y_train = tf.stack([tf.sparse.to_dense(x['image/object/bbox/xmin']),
                        tf.sparse.to_dense(x['image/object/bbox/ymin']),
                        tf.sparse.to_dense(x['image/object/bbox/xmax']),
                        tf.sparse.to_dense(x['image/object/bbox/ymax']),
                        labels], axis=1)

    x_train, y_train = tf.py_function(augment_images(x_train, y_train), [], tf.uint8)

    paddings = [[0, FLAGS.yolo_max_boxes - tf.shape(y_train)[0]], [0, 0]]
    y_train = tf.pad(y_train, paddings)

    return x_train, y_train

which calls my augment function:

def augment_images(image, boxes):

    image = image.numpy()

    seq = iaa.Sequential([
        iaa.Fliplr(0.5),
        iaa.Flipud(0.5)
    ])

    image, label = seq(image=image, bounding_boxes=boxes)

    return image, label

But no matter which parts of the code I wrap in a tf.py_function or where I try to convert to a numpy array, I always get the same error.

What am I doing wrong?

Body:
I was able to recreate your error. This happens only when I try to use numpy() on an image and the error thrown is AttributeError: 'Image' object has no attribute 'numpy', but the numpy() function works perfectly fine in other cases.

In the below simple program, I am reading an image(.jpg file) of bird and later doing tf.image.central_crop to crop the central part of the image. The numpy() worked perfectly fine when we tried to extract string(file path) from the tensor using bytes.decode(path.numpy()), but threw error AttributeError: 'Image' object has no attribute 'numpy' when we tried to use numpy() on image type.

Code to recreate the issue -

%tensorflow_version 2.x
import tensorflow as tf
print(tf.__version__)
from tensorflow.keras.preprocessing.image import load_img
from tensorflow.keras.preprocessing.image import img_to_array, array_to_img
from matplotlib import pyplot as plt
import numpy as np

def load_file_and_process(path):
    image = load_img(bytes.decode(path.numpy()), target_size=(224, 224))
    image = image.numpy()
    image = tf.image.central_crop(image, np.random.uniform(0.50, 1.00))
    return image

train_dataset = tf.data.Dataset.list_files('/content/bird.jpg')
train_dataset = train_dataset.map(lambda x: tf.py_function(load_file_and_process, [x], [tf.float32]))

for f in train_dataset:
  for l in f:
    image = np.array(array_to_img(l))
    plt.imshow(image)

Output -

2.2.0
---------------------------------------------------------------------------
UnknownError                              Traceback (most recent call last)
/usr/local/lib/python3.6/dist-packages/tensorflow/python/eager/context.py in execution_mode(mode)
   1985       ctx.executor = executor_new
-> 1986       yield
   1987     finally:

10 frames
UnknownError: AttributeError: 'Image' object has no attribute 'numpy'
Traceback (most recent call last):

  File "/usr/local/lib/python3.6/dist-packages/tensorflow/python/ops/script_ops.py", line 241, in __call__
    return func(device, token, args)

  File "/usr/local/lib/python3.6/dist-packages/tensorflow/python/ops/script_ops.py", line 130, in __call__
    ret = self._func(*args)

  File "/usr/local/lib/python3.6/dist-packages/tensorflow/python/autograph/impl/api.py", line 309, in wrapper
    return func(*args, **kwargs)

  File "<ipython-input-22-2aab1a57781b>", line 11, in load_file_and_process
    image = image.numpy()

AttributeError: 'Image' object has no attribute 'numpy'

     [[{{node EagerPyFunc}}]] [Op:IteratorGetNext]

During handling of the above exception, another exception occurred:

UnknownError                              Traceback (most recent call last)
/usr/local/lib/python3.6/dist-packages/tensorflow/python/eager/executor.py in wait(self)
     65   def wait(self):
     66     """Waits for ops dispatched in this executor to finish."""
---> 67     pywrap_tfe.TFE_ExecutorWaitForAllPendingNodes(self._handle)
     68
     69   def clear_error(self):

UnknownError: AttributeError: 'Image' object has no attribute 'numpy'
Traceback (most recent call last):

  File "/usr/local/lib/python3.6/dist-packages/tensorflow/python/ops/script_ops.py", line 241, in __call__
    return func(device, token, args)

  File "/usr/local/lib/python3.6/dist-packages/tensorflow/python/ops/script_ops.py", line 130, in __call__
    ret = self._func(*args)

  File "/usr/local/lib/python3.6/dist-packages/tensorflow/python/autograph/impl/api.py", line 309, in wrapper
    return func(*args, **kwargs)

  File "<ipython-input-22-2aab1a57781b>", line 11, in load_file_and_process
    image = image.numpy()

AttributeError: 'Image' object has no attribute 'numpy'

     [[{{node EagerPyFunc}}]]

Solution -  Use img_to_array and array_to_img to convert the image to array and array to image respectively. You need to include from tensorflow.keras.preprocessing.image import img_to_array, array_to_img in your program.

Fixed Code -

%tensorflow_version 2.x
import tensorflow as tf
print(tf.__version__)
from tensorflow.keras.preprocessing.image import load_img
from tensorflow.keras.preprocessing.image import img_to_array, array_to_img
from matplotlib import pyplot as plt
import numpy as np

def load_file_and_process(path):
    image = load_img(bytes.decode(path.numpy()), target_size=(224, 224))
    image = img_to_array(image)
    image = tf.image.central_crop(image, np.random.uniform(0.50, 1.00))
    return image

train_dataset = tf.data.Dataset.list_files('/content/bird.jpg')
train_dataset = train_dataset.map(lambda x: tf.py_function(load_file_and_process, [x], [tf.float32]))

for f in train_dataset:
  for l in f:
    image = np.array(array_to_img(l))
    plt.imshow(image)

Output -
2.2.0

Hope this answers your question. Happy Learning.


来源: stackexchange

问:
fireEvent is calling Found multiple elements by: data-testid error in react-testing-library
I'm calling a function by finding the button with the data-testid with "show_more_button"

```<code><OurSecondaryButton test={"show_more_button"} onClick={(e) => showComments(e)} component="span" color="secondary">
    View {min !== -1 && min !== -2 ? min : 0} More Comments
</OurSecondaryButton>
</code>```

showComments

```<code>const showComments = (e) => {
  e.preventDefault();
  if (inc + 2 && inc <= the_comments) {
     setShowMore(inc + 2);
     setShowLessFlag(true);
  } else {
     setShowMore(the_comments);
  }
};
</code>```

which renders this

```<code>const showMoreComments = () => {
    return filterComments.map((comment, i) => (
        <div data-testid="comment-show-more" key={i}>
            <CommentListContainer ref={ref} comment={comment} openModal={openModal} handleCloseModal={handleCloseModal} isBold={isBold} handleClickOpen={handleClickOpen} {...props} />
        </div>
    ));
};
</code>```

and upon executing fireEvent the function gets called which is good but, im getting the error:

TestingLibraryElementError: Found multiple elements by:
  [data-testid="comment-show-more"]

```<code>(If this is intentional, then use the `*AllBy*` variant of the query (like `queryAllByText`, `getAllByText`, or `findAllByText`)).
</code>```

There is only one data-testid with "comment-show-more", i doubled checked, this function must be getting triggered multiple times in the same test i guess, Im not sure..

CommentList.test.tsx

```<code>   it("should fire show more action", () => {
      const { getByTestId } = render(<CommentList {...props} />);
      const showMore = getByTestId("show_more_button");
      fireEvent.click(showMore);
      expect(getByTestId("comment-show-more").firstChild).toBeTruthy();
   });
</code>```

CommentList.test.tsx (full code)

```<code>import "@testing-library/jest-dom";
import React, { Ref } from "react";
import CommentList from "./CommentList";
import { render, getByText, queryByText, getAllByTestId, fireEvent } from "@testing-library/react";
import { Provider } from "react-redux";
import { store } from "../../../store";

const props = {
    user: {},
    postId: null,
    userId: null,
    currentUser: {},
    ref: {
        current: undefined,
    },
    comments: [
        {
            author: { username: "barnowl", gravatar: "https://api.adorable.io/avatars/400/bf1eed82fbe37add91cb4192e4d14de6.png", bio: null },
            comment_body: "fsfsfsfsfs",
            createdAt: "2020-05-27T14:32:01.682Z",
            gifUrl: "",
            id: 520,
            postId: 28,
            updatedAt: "2020-05-27T14:32:01.682Z",
            userId: 9,
        },
        {
            author: { username: "barnowl", gravatar: "https://api.adorable.io/avatars/400/bf1eed82fbe37add91cb4192e4d14de6.png", bio: null },
            comment_body: "fsfsfsfsfs",
            createdAt: "2020-05-27T14:32:01.682Z",
            gifUrl: "",
            id: 519,
            postId: 27,
            updatedAt: "2020-05-27T14:32:01.682Z",
            userId: 10,
        },
        {
            author: { username: "barnowl2", gravatar: "https://api.adorable.io/avatars/400/bf1eed82fbe37add91cb4192e4d14de6.png", bio: null },
            comment_body: "fsfsfsfsfs",
            createdAt: "2020-05-27T14:32:01.682Z",
            gifUrl: "",
            id: 518,
            postId: 28,
            updatedAt: "2020-05-27T14:32:01.682Z",
            userId: 11,
        },
    ],
    deleteComment: jest.fn(),
};
describe("Should render <CommentList/>", () => {
    it("should render <CommentList/>", () => {
        const commentList = render(<CommentList {...props} />);
        expect(commentList).toBeTruthy();
    });

    it("should render first comment", () => {
        const { getByTestId } = render(<CommentList {...props} />);
        const commentList = getByTestId("comment-list-div");
        expect(commentList.firstChild).toBeTruthy();
    });

    it("should render second child", () => {
        const { getByTestId } = render(<CommentList {...props} />);
        const commentList = getByTestId("comment-list-div");
        expect(commentList.lastChild).toBeTruthy();
    });

    it("should check comments", () => {
        const rtl = render(<CommentList {...props} />);

        expect(rtl.getByTestId("comment-list-div")).toBeTruthy();
        expect(rtl.getByTestId("comment-list-div")).toBeTruthy();

        expect(rtl.getByTestId("comment-list-div").querySelectorAll(".comment").length).toEqual(2);
    });
    // it("should match snapshot", () => {
    //     const rtl = render(<CommentList {...props} />);
    //     expect(rtl).toMatchSnapshot();
    // });

    it("should check more comments", () => {
        const { queryByTestId } = render(<CommentList {...props} />);
        const commentList = queryByTestId("comment-show-more");
        expect(commentList).toBeNull();
    });

    it("should fire show more action", () => {
        const { getByTestId } = render(<CommentList {...props} />);
        const showMore = getByTestId("show_more_button");
        fireEvent.click(showMore);
        expect(getByTestId("comment-show-more").firstChild).toBeTruthy();
    });
});
</code>```

答:
Try to clean up the DOM after each test

import { cleanup } from '@testing-library/react'
// Other import and mock props
describe("Should render <CommentList/>", () => {
    afterEach(cleanup)
    // your test
}```

Note: You have filterComments.map so make sure filterComments have one item.

ContentLicense: CC BY-SA 4.0

Body:
I'm calling a function by finding the button with the data-testid with "show_more_button"

<OurSecondaryButton test={"show_more_button"} onClick={(e) => showComments(e)} component="span" color="secondary">
    View {min !== -1 && min !== -2 ? min : 0} More Comments
</OurSecondaryButton>

showComments

const showComments = (e) => {
  e.preventDefault();
  if (inc + 2 && inc <= the_comments) {
     setShowMore(inc + 2);
     setShowLessFlag(true);
  } else {
     setShowMore(the_comments);
  }
};

which renders this

const showMoreComments = () => {
    return filterComments.map((comment, i) => (

            <CommentListContainer ref={ref} comment={comment} openModal={openModal} handleCloseModal={handleCloseModal} isBold={isBold} handleClickOpen={handleClickOpen} {...props} />

    ));
};

and upon executing fireEvent the function gets called which is good but, im getting the error:

TestingLibraryElementError: Found multiple elements by:
  [data-testid="comment-show-more"]

(If this is intentional, then use the `*AllBy*` variant of the query (like `queryAllByText`, `getAllByText`, or `findAllByText`)).

There is only one data-testid with "comment-show-more", i doubled checked, this function must be getting triggered multiple times in the same test i guess, Im not sure..

CommentList.test.tsx

   it("should fire show more action", () => {
      const { getByTestId } = render(<CommentList {...props} />);
      const showMore = getByTestId("show_more_button");
      fireEvent.click(showMore);
      expect(getByTestId("comment-show-more").firstChild).toBeTruthy();
   });

CommentList.test.tsx (full code)

import "@testing-library/jest-dom";
import React, { Ref } from "react";
import CommentList from "./CommentList";
import { render, getByText, queryByText, getAllByTestId, fireEvent } from "@testing-library/react";
import { Provider } from "react-redux";
import { store } from "../../../store";

const props = {
    user: {},
    postId: null,
    userId: null,
    currentUser: {},
    ref: {
        current: undefined,
    },
    comments: [
        {
            author: { username: "barnowl", gravatar: "https://api.adorable.io/avatars/400/bf1eed82fbe37add91cb4192e4d14de6.png", bio: null },
            comment_body: "fsfsfsfsfs",
            createdAt: "2020-05-27T14:32:01.682Z",
            gifUrl: "",
            id: 520,
            postId: 28,
            updatedAt: "2020-05-27T14:32:01.682Z",
            userId: 9,
        },
        {
            author: { username: "barnowl", gravatar: "https://api.adorable.io/avatars/400/bf1eed82fbe37add91cb4192e4d14de6.png", bio: null },
            comment_body: "fsfsfsfsfs",
            createdAt: "2020-05-27T14:32:01.682Z",
            gifUrl: "",
            id: 519,
            postId: 27,
            updatedAt: "2020-05-27T14:32:01.682Z",
            userId: 10,
        },
        {
            author: { username: "barnowl2", gravatar: "https://api.adorable.io/avatars/400/bf1eed82fbe37add91cb4192e4d14de6.png", bio: null },
            comment_body: "fsfsfsfsfs",
            createdAt: "2020-05-27T14:32:01.682Z",
            gifUrl: "",
            id: 518,
            postId: 28,
            updatedAt: "2020-05-27T14:32:01.682Z",
            userId: 11,
        },
    ],
    deleteComment: jest.fn(),
};
describe("Should render <CommentList/>", () => {
    it("should render <CommentList/>", () => {
        const commentList = render(<CommentList {...props} />);
        expect(commentList).toBeTruthy();
    });

    it("should render first comment", () => {
        const { getByTestId } = render(<CommentList {...props} />);
        const commentList = getByTestId("comment-list-div");
        expect(commentList.firstChild).toBeTruthy();
    });

    it("should render second child", () => {
        const { getByTestId } = render(<CommentList {...props} />);
        const commentList = getByTestId("comment-list-div");
        expect(commentList.lastChild).toBeTruthy();
    });

    it("should check comments", () => {
        const rtl = render(<CommentList {...props} />);

        expect(rtl.getByTestId("comment-list-div")).toBeTruthy();
        expect(rtl.getByTestId("comment-list-div")).toBeTruthy();

        expect(rtl.getByTestId("comment-list-div").querySelectorAll(".comment").length).toEqual(2);
    });
    // it("should match snapshot", () => {
    //     const rtl = render(<CommentList {...props} />);
    //     expect(rtl).toMatchSnapshot();
    // });

    it("should check more comments", () => {
        const { queryByTestId } = render(<CommentList {...props} />);
        const commentList = queryByTestId("comment-show-more");
        expect(commentList).toBeNull();
    });

    it("should fire show more action", () => {
        const { getByTestId } = render(<CommentList {...props} />);
        const showMore = getByTestId("show_more_button");
        fireEvent.click(showMore);
        expect(getByTestId("comment-show-more").firstChild).toBeTruthy();
    });
});

Body:
Try to clean up the DOM after each test

import { cleanup } from '@testing-library/react'
// Other import and mock props
describe("Should render <CommentList/>", () => {
    afterEach(cleanup)
    // your test
}

Note: You have filterComments.map so make sure filterComments have one item.


问:
Print the count of element in a column in table format
Given this dataframe:

```<code>import pandas as pd
df=pd.DataFrame({"Name":["A","A","B"]})
</code>```

I want to print the count of element in Name column in table format as follows:

This is what I am doing right now:

```<code>df['Name'].value_counts().reset_index().rename(columns={'index':'Name','Name':'Count'})
</code>```

Though it works, is there a simpler (shorter way) to achieve the same result?

答:
You can try: </p>

```<code>df['Name'].value_counts().rename_axis('Name').reset_index(name='Count')
#or df.groupby('Name')['Name'].count().rename('Count').reset_index()
</code>```

Body:
Given this dataframe:

import pandas as pd
df=pd.DataFrame({"Name":["A","A","B"]})

I want to print the count of element in Name column in table format as follows:

This is what I am doing right now:

df['Name'].value_counts().reset_index().rename(columns={'index':'Name','Name':'Count'})

Though it works, is there a simpler (shorter way) to achieve the same result?

Body:
You can try:

df['Name'].value_counts().rename_axis('Name').reset_index(name='Count')
#or df.groupby('Name')['Name'].count().rename('Count').reset_index()


问:
How to start at a specific index in the range?
The program must print out n + 41 as 6 rows of 7 numbers, the first row will be n + 6, the second will be n + 7 to n + 7 + 6 and so on.

```<code>n = int(input('Enter number between -6 between 2: '))

if -6 <= n <= 2:
  for x in range(n, 37, 7):
    for r in range(x,  x + 7):
        print("{:>2}".format(r), end=" ")
    print()

else:
  print("Wrong input!!")
</code>```

Sample Output for -2 is:

5  6  7  8  9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31 32
33 34 35 36 37 38 39

答:
This should work for you. It skips the first 7 numbers but checking to see if x in the range is equal to the input value. If it is, is restarts the loop and continues from there.

```<code>n = int(input('Enter number between -6 between 2: '))

if -6 <= n <= 2:
  for x in range(n, 37, 7):
    if x == n:
          continue
    for r in range(x,  x + 7):
      print("{:>2}".format(r), end=" ")

else:
  print("Wrong input!!")

</code>```

Output:

```<code>5  6  7  8  9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39
</code>```

Body:
The program must print out n + 41 as 6 rows of 7 numbers, the first row will be n + 6, the second will be n + 7 to n + 7 + 6 and so on.

n = int(input('Enter number between -6 between 2: '))

if -6 <= n <= 2:
  for x in range(n, 37, 7):
    for r in range(x,  x + 7):
        print("{:>2}".format(r), end=" ")
    print()

else:
  print("Wrong input!!")

Sample Output for -2 is:

5  6  7  8  9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31 32
33 34 35 36 37 38 39

Body:
This should work for you. It skips the first 7 numbers but checking to see if x in the range is equal to the input value. If it is, is restarts the loop and continues from there.

n = int(input('Enter number between -6 between 2: '))

if -6 <= n <= 2:
  for x in range(n, 37, 7):
    if x == n:
          continue
    for r in range(x,  x + 7):
      print("{:>2}".format(r), end=" ")

else:
  print("Wrong input!!")

Output:

5  6  7  8  9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39


问:
Api Create user WEB_LOGIN_REQUIRED
When I try to create a user using Api Admin SDK, this user is created but is suspended. The reason is WEB_LOGIN_REQUIRED. When the user try to enter in this account have to verify this account using phone sms. These users are students, so they dont have phone. ¿How do I create this account without having to verify?

To create this user account we use a service account. This is the code to create

```<code>    UsersResource.InsertRequest user = service.Users.Insert(new User
    {
        PrimaryEmail = usuarionuevo.Email,
        Name = new UserName
        {
            GivenName = usuarionuevo.NombreSimple,
            FamilyName = usuarionuevo.Apellidos,
            FullName = usuarionuevo.Nombre,
        },
        Suspended = false,
        Password = usuarionuevo.Password,
        ChangePasswordAtNextLogin = true
    });
</code>```

Validation Page

答:
It is true that a Web Login is required to confirm that the user exists and really wants to use his account

However, the phone verification is optional

When the users see the following screen:

they just need to press on CONFIRM to start using their account

Phone verification is good for safety reasons but optional unless there is suspicion for unauthorized access

UPDATE

A possible reason while your account might be considered as "suspicious" and require additional authentication is if you are a trial user.

Title: Api Create user WEB_LOGIN_REQUIRED

Body:
When I try to create a user using Api Admin SDK, this user is created but is suspended. The reason is WEB_LOGIN_REQUIRED. When the user try to enter in this account have to verify this account using phone sms. These users are students, so they dont have phone. ¿How do I create this account without having to verify?

To create this user account we use a service account. This is the code to create

    UsersResource.InsertRequest user = service.Users.Insert(new User
    {
        PrimaryEmail = usuarionuevo.Email,
        Name = new UserName
        {
            GivenName = usuarionuevo.NombreSimple,
            FamilyName = usuarionuevo.Apellidos,
            FullName = usuarionuevo.Nombre,
        },
        Suspended = false,
        Password = usuarionuevo.Password,
        ChangePasswordAtNextLogin = true
    });

Validation Page


问:
how to stop overwriting an index number in python list which is already written once?
I have a list with index number 0 to 5. I am telling user to input position where they want to mark ('X') into the list and then printing the list each time the user input's a index number. I want the user to input only once in a index number of the list and if user try to overwrite the written value in a list I want to give a message to user as a input 'you can't go there please try again in different position'. I want to keep running the input until the user enters a value in non-written position in the list.

I tried to do it in OOP as I am practicing OOP. I make a board then display the board with print_Board() method. In method input_Value() I tried to make it run under a while loop and break the loop when all positions are filled... also used a try catch error... which will check if the input value must have the index number from 1 to 6 only.

```<code>class Overwrite:

    list = ['.', '.', '.', '.', '.', '.']

    def print_Board(self):
        print(self.list[0:3])
        print(self.list[3:6])

    def input_Value(self):
        while True:
            try:
                self.position = input('enter a number between 1 to 6:')     # input a value
                if self.position not in ['1', '2', '3', '4', '5', '6']: # checking if the number is in range(1 to 6) or not
                    print('please try again a number between 1 to 6')
                    continue
                self.position = int(self.position) - 1  # putting -1 so that user input is different than
                self.list[self.position] = 'X'
                self.print_Board()
            except IndexError:
                print('please try again a number between 1 to 6:')
            except ValueError:
                print('please try again a number between 1 to 6:')
            else:
                if '.' not in self.list:  # it will stop the program when all the positions are filled
                    break

    def gameplay(self):
        self.print_Board()
        self.input_Value()
</code>```

答:
You can define a new list class with a different __setitem__ method.

class ListNoOverwrite(list):

    def __setitem__(self, key, value):
        if super().__getitem__(key) == 'X':
            print("Sorry, you can't do that")
            return 1
        else:
            super().__setitem__(key, value)
            return 0
```

Body:
I have a list with index number 0 to 5. I am telling user to input position where they want to mark ('X') into the list and then printing the list each time the user input's a index number. I want the user to input only once in a index number of the list and if user try to overwrite the written value in a list I want to give a message to user as a input 'you can't go there please try again in different position'. I want to keep running the input until the user enters a value in non-written position in the list.

I tried to do it in OOP as I am practicing OOP. I make a board then display the board with print_Board() method. In method input_Value() I tried to make it run under a while loop and break the loop when all positions are filled... also used a try catch error... which will check if the input value must have the index number from 1 to 6 only.

class Overwrite:

    list = ['.', '.', '.', '.', '.', '.']

    def print_Board(self):
        print(self.list[0:3])
        print(self.list[3:6])

    def input_Value(self):
        while True:
            try:
                self.position = input('enter a number between 1 to 6:')     # input a value
                if self.position not in ['1', '2', '3', '4', '5', '6']: # checking if the number is in range(1 to 6) or not
                    print('please try again a number between 1 to 6')
                    continue
                self.position = int(self.position) - 1  # putting -1 so that user input is different than
                self.list[self.position] = 'X'
                self.print_Board()
            except IndexError:
                print('please try again a number between 1 to 6:')
            except ValueError:
                print('please try again a number between 1 to 6:')
            else:
                if '.' not in self.list:  # it will stop the program when all the positions are filled
                    break

    def gameplay(self):
        self.print_Board()
        self.input_Value()


问:
call() is not working with getter and setter in javascript

let Name = {
   get fullname() {
        return this.fname + this.last
    }
}

function pension() {
    return this.age > 60
}
let firstclass_employee = [{
    fname: "sangeth",
    last: "AV",
    age: 21,
    address: {
        housename: "good house",
        place: "goodplace",
        city: "goodtwon",
        postcode: 121212
    },
    hobbies: ["driving", "travelling", "sports"]
}, {
    fname: "ramu",
    last: "kv",
    age: 29,
    address: {
        housename: "etho veedu",
        place: "vayadi",
        city: "kalur",
        postcode: 11111
    },
    hobbies: ["travelling", "sports"]
}]
console.log(" objects::\t", Name, "\n", firstclass_employee)
    //calling a out side function for an object(out side function may be inside an object oe not)
console.log("Fullname of first employee::", Name.fullname.call(firstclass_employee[0]))
console.log("Pension status of of first emlpoyee::", pension.call(firstclass_employee[0]))
console.log("Fullname of 2nd employee::", Name.fullname.call(firstclass_employee[1]))
console.log("Pension status of of 2nd emlpoyee::", pension.call(firstclass_employee[1]))```

AND getting error--->
console.log("Fullname of first employee::", Name.fullname.call(firstclass_employee[0]))
                                                          ^

TypeError: Name.fullname.call is not a function

答:
remove get - which is not a valid here

```<code>let Name = {
   fullname() {
        return this.fname + this.last
    }
}
</code>```

Body:
let Name = {
   get fullname() {
        return this.fname + this.last
    }
}

function pension() {
    return this.age > 60
}
let firstclass_employee = [{
    fname: "sangeth",
    last: "AV",
    age: 21,
    address: {
        housename: "good house",
        place: "goodplace",
        city: "goodtwon",
        postcode: 121212
    },
    hobbies: ["driving", "travelling", "sports"]
}, {
    fname: "ramu",
    last: "kv",
    age: 29,
    address: {
        housename: "etho veedu",
        place: "vayadi",
        city: "kalur",
        postcode: 11111
    },
    hobbies: ["travelling", "sports"]
}]
console.log(" objects::\t", Name, "\n", firstclass_employee)
    //calling a out side function for an object(out side function may be inside an object oe not)
console.log("Fullname of first employee::", Name.fullname.call(firstclass_employee[0]))
console.log("Pension status of of first emlpoyee::", pension.call(firstclass_employee[0]))
console.log("Fullname of 2nd employee::", Name.fullname.call(firstclass_employee[1]))
console.log("Pension status of of 2nd emlpoyee::", pension.call(firstclass_employee[1]))

AND getting error--->
console.log("Fullname of first employee::", Name.fullname.call(firstclass_employee[0]))
                                                          ^

TypeError: Name.fullname.call is not a function

Body:
remove get - which is not a valid here

let Name = {
   fullname() {
        return this.fname + this.last
    }
}


问:
How can I make the Control Center slider editable?
I'm working on an app that will play sound files. If I open apple music app, the slider let me moving between the song where I am.

Other apps like spotify or overcast does not allow this behaviour.

Until now, I have been able to change all parameters of the control center with that exception. Is there any way of making this slider useful?

I'm using something like the following code:

```<code>MPRemoteCommandCenter *commandCenter = [MPRemoteCommandCenter sharedCommandCenter];

NSArray *commands = @[commandCenter.playCommand, commandCenter.pauseCommand, commandCenter.nextTrackCommand, commandCenter.previousTrackCommand, commandCenter.bookmarkCommand, commandCenter.changePlaybackPositionCommand, commandCenter.changePlaybackRateCommand, commandCenter.dislikeCommand, commandCenter.enableLanguageOptionCommand, commandCenter.likeCommand, commandCenter.ratingCommand, commandCenter.seekBackwardCommand, commandCenter.seekForwardCommand, commandCenter.skipBackwardCommand, commandCenter.skipForwardCommand, commandCenter.stopCommand, commandCenter.togglePlayPauseCommand];

for (MPRemoteCommand *command in commands) {
    [command removeTarget:nil];
    [command setEnabled:NO];
}

[commandCenter.playCommand addTarget:self action:@selector(playTrack)];
[commandCenter.pauseCommand addTarget:self action:@selector(pauseTrack)];
[commandCenter.playCommand setEnabled:YES];
[commandCenter.pauseCommand setEnabled:YES];
</code>```

答:
As of 2020 with Swift 5, if we only use commandCenter.changePlaybackPositionCommand it won't work, we also need to set metadata with MPMediaItemPropertyPlaybackDuration for the player then we can use the slider.

Check this article from Apple:
https://developer.apple.com/documentation/avfoundation/media_assets_playback_and_editing/creating_a_basic_video_player_ios_and_tvos/controlling_background_audio

Look at the section: Provide Display Metadata

ContentLicense: CC BY-SA 3.0

Body:
I'm working on an app that will play sound files. If I open apple music app, the slider let me moving between the song where I am.

Other apps like spotify or overcast does not allow this behaviour.

Until now, I have been able to change all parameters of the control center with that exception. Is there any way of making this slider useful?

I'm using something like the following code:

MPRemoteCommandCenter *commandCenter = [MPRemoteCommandCenter sharedCommandCenter];

NSArray *commands = @[commandCenter.playCommand, commandCenter.pauseCommand, commandCenter.nextTrackCommand, commandCenter.previousTrackCommand, commandCenter.bookmarkCommand, commandCenter.changePlaybackPositionCommand, commandCenter.changePlaybackRateCommand, commandCenter.dislikeCommand, commandCenter.enableLanguageOptionCommand, commandCenter.likeCommand, commandCenter.ratingCommand, commandCenter.seekBackwardCommand, commandCenter.seekForwardCommand, commandCenter.skipBackwardCommand, commandCenter.skipForwardCommand, commandCenter.stopCommand, commandCenter.togglePlayPauseCommand];

for (MPRemoteCommand *command in commands) {
    [command removeTarget:nil];
    [command setEnabled:NO];
}

[commandCenter.playCommand addTarget:self action:@selector(playTrack)];
[commandCenter.pauseCommand addTarget:self action:@selector(pauseTrack)];
[commandCenter.playCommand setEnabled:YES];
[commandCenter.pauseCommand setEnabled:YES];


问:
linq (to nhibernate) where clause on dynamic property in sql
My entity has a property which is derived from other properties

```<code>public class MyClass
{
    public DateTime Deadline { get; set; }
    public Severity Severity
    {
        return (DateTime.Now - Deadline < new TimeSpan(5, 0, 0, 0)) ? Severity.High : Severity.Low;
    }
}
</code>```

is there a way I can modify the following

```<code>return repository.Query().Where(myClass => myClass.Severity == High);
</code>```

so that the where clause evaluates in sql rather than in code?

I tried to do something like this, but to no avail

```<code>public class MyClass
{
    public DateTime Deadline { get; set; }
    public Func<MyClass, bool> SeverityFunc = (DateTime.Now - Deadline < new TimeSpan(5, 0, 0, 0)) ? Severity.High : Severity.Low;
    public Severity Severity
    {
        return SeverityFunc.Invoke(this);
    }
}

return repository.Query().Where(myClass => myClass.SeverityFunc(myclass) == High);
</code>```

I'm guessing because the func cant be evaluated to SQL. Is there some other way to do this without ending up with duplicate calculations for severity

Any help appreciated, ta

Edit: This is a simplified version of what im trying to do, i'm looking for answers that cover the theory of this rather than a specific fix (though still welcome). Im interested in whats possible, and best practices to achieve this sort of thing.

Andrew

答:
I have used something similar on a mapper. Make sure to wrap the Func on on Expr, like:

```<code>public Expr<Func<MyClass, bool>> SeverityFunc ...
</code>```

By wrapping it with expr linq2sql will be able to look at the full expression and translate appropiately. I haven't used it as part of a class instance like the one you have, so I am not sure how that would affect it.

Regarding on where to put it, I had to move on the last time I worked on a similar scenario, in my case it ended up in the mapper, but mostly because it was more a mapping concern from an awfully database schema than domain logic. I didn't even had the property dynamically calculated on the domain entity for that matter (a different scenario for sure).

OwnerDisplayName: Andrew Bullock

ContentLicense: CC BY-SA 2.5

Body:
My entity has a property which is derived from other properties

public class MyClass
{
    public DateTime Deadline { get; set; }
    public Severity Severity
    {
        return (DateTime.Now - Deadline < new TimeSpan(5, 0, 0, 0)) ? Severity.High : Severity.Low;
    }
}

is there a way I can modify the following

return repository.Query().Where(myClass => myClass.Severity == High);

so that the where clause evaluates in sql rather than in code?

I tried to do something like this, but to no avail

public class MyClass
{
    public DateTime Deadline { get; set; }
    public Func<MyClass, bool> SeverityFunc = (DateTime.Now - Deadline < new TimeSpan(5, 0, 0, 0)) ? Severity.High : Severity.Low;
    public Severity Severity
    {
        return SeverityFunc.Invoke(this);
    }
}

return repository.Query().Where(myClass => myClass.SeverityFunc(myclass) == High);

I'm guessing because the func cant be evaluated to SQL. Is there some other way to do this without ending up with duplicate calculations for severity

Any help appreciated, ta

Edit: This is a simplified version of what im trying to do, i'm looking for answers that cover the theory of this rather than a specific fix (though still welcome). Im interested in whats possible, and best practices to achieve this sort of thing.

Andrew

LastEditorDisplayName: Andrew Bullock

Body:
I have used something similar on a mapper. Make sure to wrap the Func on on Expr, like:

public Expr<Func<MyClass, bool>> SeverityFunc ...

By wrapping it with expr linq2sql will be able to look at the full expression and translate appropiately. I haven't used it as part of a class instance like the one you have, so I am not sure how that would affect it.

Regarding on where to put it, I had to move on the last time I worked on a similar scenario, in my case it ended up in the mapper, but mostly because it was more a mapping concern from an awfully database schema than domain logic. I didn't even had the property dynamically calculated on the domain entity for that matter (a different scenario for sure).

OwnerDisplayName: Freddy Rios

LastEditorDisplayName: Freddy Rios


问:
Accessing an ActionScript function via Javascript
I'm trying to call a function in an action script using the ExternalInterface.addCallback API, but I can't seem to get it to work.  Here's what I have:

ActionScript:

```<code>//MyClass.as
package {

    import flash.display.Sprite;
    import flash.external.ExternalInterface;

    public class MyClass extends Sprite
    {
        public function MyClass()
        {
            ExternalInterface.addCallback('getStringJS', getStringAS);
        }

        public function getStringAS():String
        {
            return "Hello World!";
        }
    }
}
</code>```

NOTE: I'm compiling this into an swf using the flex mxmlc compiler if that matters.

HTML/Javascript:

```<code><!doctype html>
<html>
    <head>
        <title>User Identification</title>
    <head>
    <body>
        <object id="MyClass" name="MyClass" type="application/x-shockwave-flash" data="MyClass.swf" width="1" height="1">
            <param name="movie" value="MyClass.swf">
            <embed src="MyClass.swf" width="1" height="1">
        </object>
        <script type="text/javascript">
            var flash = document.getElementById("MyClass");
            var str = flash.getStringJS();
            alert(str);
        </script>
    </body>
</html>
</code>```

The error I'm getting is:

```<code>Uncaught TypeError: Object #<HTMLObjectElement> has no method 'getStringJS'
</code>```

I also tried adding in a timeout in case the swf file wasn't loading, but I didn't have any success with that method either.

Any thoughts?

Cheers,

Mike

答:
I figured it out. The key way to signal the javascipt through ExternalInterface.call so we know for sure that the swf is loaded. The most "Universal" way to do this is as follows:

MyClass.as

```<code>//MyClass.as
package {

    import flash.display.Sprite;
    import flash.external.ExternalInterface;

    public class MyClass extends Sprite
    {
        public function MyClass()
        {
            ExternalInterface.addCallback('getStringJS', getStringAS);
            if  (ExternalInterface.available) {
                ExternalInterface.call("isConnectedFlex");
            }
        }

        public function getStringAS():String
        {
            return "Hello World!";
        }
    }
}
</code>```

index.html

```<code><!doctype html>
<html>
    <head>
        <title>User Identification</title>
    <head>
    <body>
        <object id="MyClass" name="MyClass" type="application/x-shockwave-flash" data="MyClass.swf" width="1" height="1">
            <param name="movie" value="MyClass.swf">
            <embed src="MyClass.swf" width="1" height="1">
        </object>
        <script type="text/javascript">

            var flash = document.getElementById("MyClass");

            function isConnectedFlex() {
                var str = flash.getStringJS();
                alert(str);
            }

        </script>
    </body>
</html>
</code>```

Body:
I'm trying to call a function in an action script using the ExternalInterface.addCallback API, but I can't seem to get it to work.  Here's what I have:

ActionScript:

//MyClass.as
package {

    import flash.display.Sprite;
    import flash.external.ExternalInterface;

    public class MyClass extends Sprite
    {
        public function MyClass()
        {
            ExternalInterface.addCallback('getStringJS', getStringAS);
        }

        public function getStringAS():String
        {
            return "Hello World!";
        }
    }
}

NOTE: I'm compiling this into an swf using the flex mxmlc compiler if that matters.

HTML/Javascript:

<!doctype html>

        <title>User Identification</title>

        <object id="MyClass" name="MyClass" type="application/x-shockwave-flash" data="MyClass.swf" width="1" height="1">
            <param name="movie" value="MyClass.swf">
            <embed src="MyClass.swf" width="1" height="1">
        </object>

The error I'm getting is:

Uncaught TypeError: Object #<HTMLObjectElement> has no method 'getStringJS'

I also tried adding in a timeout in case the swf file wasn't loading, but I didn't have any success with that method either.

Any thoughts?

Cheers,

Mike

Body:
I figured it out. The key way to signal the javascipt through ExternalInterface.call so we know for sure that the swf is loaded. The most "Universal" way to do this is as follows:

MyClass.as

//MyClass.as
package {

    import flash.display.Sprite;
    import flash.external.ExternalInterface;

    public class MyClass extends Sprite
    {
        public function MyClass()
        {
            ExternalInterface.addCallback('getStringJS', getStringAS);
            if  (ExternalInterface.available) {
                ExternalInterface.call("isConnectedFlex");
            }
        }

        public function getStringAS():String
        {
            return "Hello World!";
        }
    }
}

index.html

<!doctype html>
<html>
    <head>
        <title>User Identification</title>
    <head>
    <body>
        <object id="MyClass" name="MyClass" type="application/x-shockwave-flash" data="MyClass.swf" width="1" height="1">
            <param name="movie" value="MyClass.swf">
            <embed src="MyClass.swf" width="1" height="1">
        </object>
        <script type="text/javascript">

            var flash = document.getElementById("MyClass");

            function isConnectedFlex() {
                var str = flash.getStringJS();
                alert(str);
            }

        </script>
    </body>
</html>


问:
showAsDropDown Gravity parameter not working
I am trying to center horizontally a PopUpWindow on the anchored view, but the Gravity.CENTER parameter is being ignored.

This is the method I am using:

```<code>popupWindow.showAsDropDown(anchorView, 0, 0, Gravity.CENTER);
</code>```

No matter what CENTER gravity value I enter (also TOP or BOTTOM don't work), the pop-up always displays at the same place: the anchor's top left corner, unless I use the START or END values.

The documentation and javaDoc does not list any restriction on the values that it accepts, so I assume that it also accepts any of the CENTER, TOP and BOTTOM values: https://developer.android.com/reference/android/widget/PopupWindow#showAsDropDown(android.view.View,%20int,%20int,%20int)

I also tested this with anchor views that are smaller, equal and larger than the pop-up window and the pop-up window is set to not fill the screen width, as intended.

It appears that this method does nothing different from the equivalent method that does not take the gravity parameter

```<code>popupWindow.showAsDropDown(anchorView, 0, 0);
</code>```

Is this a bug or is this not how it is suppose to be used?

答:
This is a bit late, but if you want to center the pop up window with showAsDropDown(), you can do this:

```<code>target.post(() -> {
        popupWindow.showAsDropDown(anchor, (anchor.getWidth() / 2), yOffset, Gravity.CENTER);
    });
</code>```

It is inside target.post() to ensure that the anchor is drawn when we call getWidth(), otherwise it returns 0.

Body:
I am trying to center horizontally a PopUpWindow on the anchored view, but the Gravity.CENTER parameter is being ignored.

This is the method I am using:

popupWindow.showAsDropDown(anchorView, 0, 0, Gravity.CENTER);

No matter what CENTER gravity value I enter (also TOP or BOTTOM don't work), the pop-up always displays at the same place: the anchor's top left corner, unless I use the START or END values.

The documentation and javaDoc does not list any restriction on the values that it accepts, so I assume that it also accepts any of the CENTER, TOP and BOTTOM values: https://developer.android.com/reference/android/widget/PopupWindow#showAsDropDown(android.view.View,%20int,%20int,%20int)

I also tested this with anchor views that are smaller, equal and larger than the pop-up window and the pop-up window is set to not fill the screen width, as intended.

It appears that this method does nothing different from the equivalent method that does not take the gravity parameter

popupWindow.showAsDropDown(anchorView, 0, 0);

Is this a bug or is this not how it is suppose to be used?

Body:
This is a bit late, but if you want to center the pop up window with showAsDropDown(), you can do this:

target.post(() -> {
        popupWindow.showAsDropDown(anchor, (anchor.getWidth() / 2), yOffset, Gravity.CENTER);
    });

It is inside target.post() to ensure that the anchor is drawn when we call getWidth(), otherwise it returns 0.


问:
Failed to register a ServiceWorker for scope ('https://.xxx.net/firebase-cloud-messaging-push-scope')
I want to send Firebase web notifications from FCM to PWA app. I tried doing that and ended up with the below error.

I've gone through sever links in StackOverflow but no luck.

Firebase web push notification Service worker issue

FirebaseError: Messaging: We are unable to register the default service worker

A bad HTTP response code (404) was received when fetching the script.

An error occurred while retrieving token. FirebaseError: Messaging: We are unable to register the default service worker. Failed to register a ServiceWorker for scope ('https://dms-uat.xxxxxx.net/firebase-cloud-messaging-push-scope') with script ('https://dms-uat.xxxxxx.net/firebase-messaging-sw.js'): A bad HTTP response code (404) was received when fetching the script. (messaging/failed-service-worker-registration).
at rt. (https://www.gstatic.com/firebasejs/7.14.0/firebase-messaging.js:1:31316)
at https://www.gstatic.com/firebasejs/7.14.0/firebase-messaging.js:1:1935
at Object.throw (https://www.gstatic.com/firebasejs/7.14.0/firebase-messaging.js:1:2040)
at i (https://www.gstatic.com/firebasejs/7.14.0/firebase-messaging.js:1:834)
```

<p>Both <code>index.html</code> and <code>firebase-messaging-sw.js</code> files are currently in the <code>domain/messaging</code> folder.</p>

<p>I was taught that <code>firebase-messaging-sw.js</code> file should be in the root folder which means <code>domain/firebase-messaging-sw.js</code>, is this correct? If so, how could I make it done?</p>

<p>Service worker in browser:</p>

<p><img src="https://i.stack.imgur.com/xOKuV.png" alt="service worker"></p>

<p>Here is my firebase-messaging-sw.js file.  </p>

```// These scripts are made available when the app is served or deployed on Firebase Hosting
// If you do not serve/host your project using Firebase Hosting see https://firebase.google.com/docs/web/setup
importScripts('https://www.gstatic.com/firebasejs/7.14.0/firebase-app.js');
importScripts('https://www.gstatic.com/firebasejs/7.14.0/firebase-messaging.js');
importScripts('https://www.gstatic.com/firebasejs/7.14.0/init.js');

const messaging = firebase.messaging();

var firebaseConfig = {
            apiKey: "xxxxxxxx-l7lKJ6nAtsmyfXRX5gXcl2_0a3Y",
            authDomain: "xxxxxx-9fa59.firebaseapp.com",
            databaseURL: "https://xxxxxx-9fa59.firebaseio.com",
            projectId: "xxxxx-9fa59",
            storageBucket: "xxxxxx-9fa59.appspot.com",
            messagingSenderId: "123456789",
            appId: "1:215883024305:web:f1b6b2148bd185584d1f90",
            measurementId: "G-MP1GQDZ18D"
        };
        // Initialize Firebase
        firebase.initializeApp(firebaseConfig);
        //firebase.analytics();

/**
 * Here is is the code snippet to initialize Firebase Messaging in the Service
 * Worker when your app is not hosted on Firebase Hosting.

 // [START initialize_firebase_in_sw]
 // Give the service worker access to Firebase Messaging.
 // Note that you can only use Firebase Messaging here, other Firebase libraries
 // are not available in the service worker.
 importScripts('https://www.gstatic.com/firebasejs/7.14.0/firebase-app.js');
 importScripts('https://www.gstatic.com/firebasejs/7.14.0/firebase-messaging.js');

 // Initialize the Firebase app in the service worker by passing in
 // your app's Firebase config object.
 // https://firebase.google.com/docs/web/setup#config-object
 firebase.initializeApp({
   apiKey: 'api-key',
   authDomain: 'project-id.firebaseapp.com',
   databaseURL: 'https://project-id.firebaseio.com',
   projectId: 'project-id',
   storageBucket: 'project-id.appspot.com',
   messagingSenderId: 'sender-id',
   appId: 'app-id',
   measurementId: 'G-measurement-id',
 });

 // Retrieve an instance of Firebase Messaging so that it can handle background
 // messages.
 const messaging = firebase.messaging();
 // [END initialize_firebase_in_sw]
 **/

// If you would like to customize notifications that are received in the
// background (Web app is closed or not in browser focus) then you should
// implement this optional method.
// [START background_handler]
messaging.setBackgroundMessageHandler(function(payload) {
  console.log('[firebase-messaging-sw.js] Received background message ', payload);
  // Customize notification here
  const notificationTitle = 'Background Message Title';
  const notificationOptions = {
    body: 'Background Message body.',
    icon: './firebase-logo.png'
  };

  return self.registration.showNotification(notificationTitle,
    notificationOptions);
});
// [END background_handler]
```

<p>Here is my index.html </p>

```

<meta charset=utf-8 />
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Firebase Cloud Messaging Example</title>

<link rel="stylesheet" href="https://code.getmdl.io/1.1.3/material.orange-indigo.min.css">
<link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons">

<link rel="stylesheet" href="./main.css">

<link rel="manifest" href="./manifest.json">

Firebase Cloud Messaging

Instance ID Token

                          <button class="mdl-button mdl-js-button mdl-button--raised mdl-button--colored"
                                  onclick="deleteToken()">
                              Delete Token
                          </button>

Needs Permission

                          <button class="mdl-button mdl-js-button mdl-button--raised mdl-button--colored"
                                  onclick="requestPermission()">
                              Request Permission
                          </button>

```

I didn't much changes except firebase-ap.js, firebase-mesaging.js files.
Please let me know if you need more info.

答:
Here is the answer, this useServiceWorker (...) saves my day

```<code>if('serviceWorker' in navigator) {
          navigator.serviceWorker.register('../firebase-messaging-sw.js')
        .then(function(registration) {
         console.log("Service Worker Registered");
        messaging.useServiceWorker(registration);
          });
          }
</code>```

Body:
I want to send Firebase web notifications from FCM to PWA app. I tried doing that and ended up with the below error.

I've gone through sever links in StackOverflow but no luck.

Firebase web push notification Service worker issue

FirebaseError: Messaging: We are unable to register the default service worker

A bad HTTP response code (404) was received when fetching the script.

An error occurred while retrieving token. FirebaseError: Messaging: We are unable to register the default service worker. Failed to register a ServiceWorker for scope ('https://dms-uat.xxxxxx.net/firebase-cloud-messaging-push-scope') with script ('https://dms-uat.xxxxxx.net/firebase-messaging-sw.js'): A bad HTTP response code (404) was received when fetching the script. (messaging/failed-service-worker-registration).
at rt. (https://www.gstatic.com/firebasejs/7.14.0/firebase-messaging.js:1:31316)
at https://www.gstatic.com/firebasejs/7.14.0/firebase-messaging.js:1:1935
at Object.throw (https://www.gstatic.com/firebasejs/7.14.0/firebase-messaging.js:1:2040)
at i (https://www.gstatic.com/firebasejs/7.14.0/firebase-messaging.js:1:834)

Both index.html and firebase-messaging-sw.js files are currently in the domain/messaging folder.

I was taught that firebase-messaging-sw.js file should be in the root folder which means domain/firebase-messaging-sw.js, is this correct? If so, how could I make it done?

Service worker in browser:

Here is my firebase-messaging-sw.js file.

// These scripts are made available when the app is served or deployed on Firebase Hosting
// If you do not serve/host your project using Firebase Hosting see https://firebase.google.com/docs/web/setup
importScripts('https://www.gstatic.com/firebasejs/7.14.0/firebase-app.js');
importScripts('https://www.gstatic.com/firebasejs/7.14.0/firebase-messaging.js');
importScripts('https://www.gstatic.com/firebasejs/7.14.0/init.js');

const messaging = firebase.messaging();

var firebaseConfig = {
            apiKey: "xxxxxxxx-l7lKJ6nAtsmyfXRX5gXcl2_0a3Y",
            authDomain: "xxxxxx-9fa59.firebaseapp.com",
            databaseURL: "https://xxxxxx-9fa59.firebaseio.com",
            projectId: "xxxxx-9fa59",
            storageBucket: "xxxxxx-9fa59.appspot.com",
            messagingSenderId: "123456789",
            appId: "1:215883024305:web:f1b6b2148bd185584d1f90",
            measurementId: "G-MP1GQDZ18D"
        };
        // Initialize Firebase
        firebase.initializeApp(firebaseConfig);
        //firebase.analytics();

/**
 * Here is is the code snippet to initialize Firebase Messaging in the Service
 * Worker when your app is not hosted on Firebase Hosting.

 // [START initialize_firebase_in_sw]
 // Give the service worker access to Firebase Messaging.
 // Note that you can only use Firebase Messaging here, other Firebase libraries
 // are not available in the service worker.
 importScripts('https://www.gstatic.com/firebasejs/7.14.0/firebase-app.js');
 importScripts('https://www.gstatic.com/firebasejs/7.14.0/firebase-messaging.js');

 // Initialize the Firebase app in the service worker by passing in
 // your app's Firebase config object.
 // https://firebase.google.com/docs/web/setup#config-object
 firebase.initializeApp({
   apiKey: 'api-key',
   authDomain: 'project-id.firebaseapp.com',
   databaseURL: 'https://project-id.firebaseio.com',
   projectId: 'project-id',
   storageBucket: 'project-id.appspot.com',
   messagingSenderId: 'sender-id',
   appId: 'app-id',
   measurementId: 'G-measurement-id',
 });

 // Retrieve an instance of Firebase Messaging so that it can handle background
 // messages.
 const messaging = firebase.messaging();
 // [END initialize_firebase_in_sw]
 **/

// If you would like to customize notifications that are received in the
// background (Web app is closed or not in browser focus) then you should
// implement this optional method.
// [START background_handler]
messaging.setBackgroundMessageHandler(function(payload) {
  console.log('[firebase-messaging-sw.js] Received background message ', payload);
  // Customize notification here
  const notificationTitle = 'Background Message Title';
  const notificationOptions = {
    body: 'Background Message body.',
    icon: './firebase-logo.png'
  };

  return self.registration.showNotification(notificationTitle,
    notificationOptions);
});
// [END background_handler]

Here is my index.html

<meta charset=utf-8 />
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Firebase Cloud Messaging Example</title>

<link rel="stylesheet" href="https://code.getmdl.io/1.1.3/material.orange-indigo.min.css">
<link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons">

<link rel="stylesheet" href="./main.css">

<link rel="manifest" href="./manifest.json">

Firebase Cloud Messaging

Instance ID Token

                          <button class="mdl-button mdl-js-button mdl-button--raised mdl-button--colored"
                                  onclick="deleteToken()">
                              Delete Token
                          </button>

Needs Permission

                          <button class="mdl-button mdl-js-button mdl-button--raised mdl-button--colored"
                                  onclick="requestPermission()">
                              Request Permission
                          </button>

I didn't much changes except firebase-ap.js, firebase-mesaging.js files.
Please let me know if you need more info.

Body:
Here is the answer, this useServiceWorker (...) saves my day

if('serviceWorker' in navigator) {
          navigator.serviceWorker.register('../firebase-messaging-sw.js')
        .then(function(registration) {
         console.log("Service Worker Registered");
        messaging.useServiceWorker(registration);
          });
          }


问:
Citrus Test Framework Message Store not Saving Messages
I am grabbing messages off of an AMQ broker and needing to validate plain text payloads. It seems citrus is very limited with plain text validation, and the validation matchers don't get me where I need to be so I need to deal with it using java code.

Code is done using basic java objects to set up messages being sent and received. When

```<code>    sendMessageToAMQ(message);

    receivePlainTextMessage(message)
            .selector(message.getHeaderName()+"='"+message.getHeaderValue()+"'")
            .name("sampleName");

    context.getMessageStore().getMessage("sampleName").getPayload();
</code>```

Context is passed in text level as a Citrus Resource. The above line of code (last line) throws a null pointer because the message isn't showing as stored aka message store size = 0. All while echo("citrus:message(sampleName.payload())") prints the payload just fine.

I've even tried variable("msg", "citrus:message(sampleName.payload())") but that returns an error saying cannot find message with name.

Please help

答:
The key is: you should use the next method for that .messageName() instead of .name()

Then the message data will be saved into Citrus context

Body:
I am grabbing messages off of an AMQ broker and needing to validate plain text payloads. It seems citrus is very limited with plain text validation, and the validation matchers don't get me where I need to be so I need to deal with it using java code.

Code is done using basic java objects to set up messages being sent and received. When

    sendMessageToAMQ(message);

    receivePlainTextMessage(message)
            .selector(message.getHeaderName()+"='"+message.getHeaderValue()+"'")
            .name("sampleName");

    context.getMessageStore().getMessage("sampleName").getPayload();

Context is passed in text level as a Citrus Resource. The above line of code (last line) throws a null pointer because the message isn't showing as stored aka message store size = 0. All while echo("citrus:message(sampleName.payload())") prints the payload just fine.

I've even tried variable("msg", "citrus:message(sampleName.payload())") but that returns an error saying cannot find message with name.

Please help


问:
Spring Boot 2 Authorization Server for public clients (PKCE)
is possible create authorization server for PKCE authentication in current version of spring security?

I did research and I found out this authorization server project https://github.com/spring-projects-experimental/spring-authorization-server but there is no usable sample for that project.

I also find out that spring recommends Keycloak as authorization server, but it is not fit for my case.
We need be able fetch and verify user against remote service, and then use authorization server only for generating and verifying jwt tokens. In my knowledge Keycloak should holds also users right? So the best solution would be custom spring standalone authorization server. Is it possible in some way? Thank you!

答:
You may have a look to this project: CloudFoundry User Account and Authentication (UAA) Server.
UAA is a (Spring MVC) component of Cloud Foundry but it could be used as a stand alone OAuth2 server. It can support external authentication service. And there is a Pull Request that implements PKCE: https://github.com/cloudfoundry/uaa/pull/939 (not yet merged, but under review).

You can find an example on how to use UAA on baeldung.com.


问:
How do you setcap in Ubuntu 16.04.6 to allow Grafana to bind to port 80?
The Grafana config docs state that "To use port 80 you need to ... give the Grafana binary permission." When I run the instructed command

```<code>sudo setcap 'cap_net_bind_service=+ep' /usr/sbin/grafana-server
</code>```

I get

```<code>Failed to set capabilities on file `/usr/sbin/grafana-server' (Invalid argument)
The value of the capability argument is not permitted for a file. Or the file is not a regular (non-symlink) file
</code>```

When I run

```<code>sudo setcap ‘cap_net_bind_service=+ep’ /usr/sbin/grafana-server
</code>```

I get

```<code>fatal error: Invalid argument
usage: setcap [-q] [-v] (-r|-|<caps>) <filename> [ ... (-r|-|<capsN>) <filenameN> ]

 Note <filename> must be a regular (non-symlink) file.
</code>```

How do I allow Grafana to bind to port 80?

答:
When one follows the "Install from APT repository" instructions, I notice that /usr/sbin/ contains a file called grafana but not one named grafana-server. I changed the command to

```<code>sudo setcap cap_net_bind_service=+ep /usr/sbin/grafana
</code>```

set port 80 in /etc/grafana/grafana.ini

```<code># The HTTP port  to use
http_port = 80
</code>```

then started the server again,

```<code>sudo systemctl start grafana-server
</code>```

and it works fine. Perhaps this is a recent change that is awaiting an update in the Grafana docs. Alternatively, follow the "Install .deb package" instrucitons.

Body:
The Grafana config docs state that "To use port 80 you need to ... give the Grafana binary permission." When I run the instructed command

sudo setcap 'cap_net_bind_service=+ep' /usr/sbin/grafana-server

I get

Failed to set capabilities on file `/usr/sbin/grafana-server' (Invalid argument)
The value of the capability argument is not permitted for a file. Or the file is not a regular (non-symlink) file

When I run

sudo setcap ‘cap_net_bind_service=+ep’ /usr/sbin/grafana-server

I get

fatal error: Invalid argument
usage: setcap [-q] [-v] (-r|-|<caps>) <filename> [ ... (-r|-|<capsN>) <filenameN> ]

 Note <filename> must be a regular (non-symlink) file.

How do I allow Grafana to bind to port 80?

Body:
When one follows the "Install from APT repository" instructions, I notice that /usr/sbin/ contains a file called grafana but not one named grafana-server. I changed the command to

sudo setcap cap_net_bind_service=+ep /usr/sbin/grafana

set port 80 in /etc/grafana/grafana.ini

# The HTTP port  to use
http_port = 80

then started the server again,

sudo systemctl start grafana-server

and it works fine. Perhaps this is a recent change that is awaiting an update in the Grafana docs. Alternatively, follow the "Install .deb package" instrucitons.


问:
How to query array inside nested object using mongoose?
I have complex object stored in my mongodb look like this:

```<code>     const collectionFromMongodb = [
      {
        id: ObjectID(),
        text: 'blabla',
        data: {
          foo: [
            { id: ObjectID(), status: 'ready' },
            { id: ObjectID(), status: 'notready' },
          ],
          bar: [
            { id: ObjectID(), status: 'ready' },
            { id: ObjectID(), status: 'notready' },
          ],
        },
      },
    ];
</code>```

I want to query the all the object (find) but the object that return will have in foo and bar only object that status are ready. (data.foo.[?].status === 'ready' and/or data.bar.[?].status === 'ready').

I expect to get all the object (since my filter is only on data), but the fields of foo and bar contains only the status of 'ready'.

Note: In foo and bar I have data size of 1mb.

How to do that with mongoose query? is it possible to do? or just query all object and use filter and map?

I did this but not works, because its gets all the statuses in data.foo:

find('data.foo': { $elemMatch: { status: 'ready' })

答:
Hope this is what you need. Change the $match pipeline to whatever u need to find.

https://mongoplayground.net/p/o1qk4wla5C6

```<code>db.collection.aggregate([
  {
    $match: {
      "data.bar.status": "ready"
    }
  },
  {
    $project: {
      "data.foo": {
        $filter: {
          input: "$data.foo",
          as: "foo",
          cond: {
            $eq: [
              "$$foo.status",
              "ready"
            ]
          }
        }
      },
      "data.bar": {
        $filter: {
          input: "$data.bar",
          as: "bar",
          cond: {
            $eq: [
              "$$bar.status",
              "ready"
            ]
          }
        }
      }
    }
  }
])
</code>```

Body:
I have complex object stored in my mongodb look like this:

     const collectionFromMongodb = [
      {
        id: ObjectID(),
        text: 'blabla',
        data: {
          foo: [
            { id: ObjectID(), status: 'ready' },
            { id: ObjectID(), status: 'notready' },
          ],
          bar: [
            { id: ObjectID(), status: 'ready' },
            { id: ObjectID(), status: 'notready' },
          ],
        },
      },
    ];

I want to query the all the object (find) but the object that return will have in foo and bar only object that status are ready. (data.foo.[?].status === 'ready' and/or data.bar.[?].status === 'ready').

I expect to get all the object (since my filter is only on data), but the fields of foo and bar contains only the status of 'ready'.

Note: In foo and bar I have data size of 1mb.

How to do that with mongoose query? is it possible to do? or just query all object and use filter and map?

I did this but not works, because its gets all the statuses in data.foo:

find('data.foo': { $elemMatch: { status: 'ready' })

Body:
Hope this is what you need. Change the $match pipeline to whatever u need to find.

https://mongoplayground.net/p/o1qk4wla5C6

db.collection.aggregate([
  {
    $match: {
      "data.bar.status": "ready"
    }
  },
  {
    $project: {
      "data.foo": {
        $filter: {
          input: "$data.foo",
          as: "foo",
          cond: {
            $eq: [
              "$$foo.status",
              "ready"
            ]
          }
        }
      },
      "data.bar": {
        $filter: {
          input: "$data.bar",
          as: "bar",
          cond: {
            $eq: [
              "$$bar.status",
              "ready"
            ]
          }
        }
      }
    }
  }
])


问:
comboBox.SelectedItem problem
ComboBox is binding database

```<code>string str= comboBox1.SelectedItem.ToString();
</code>```

the line gives System.Data.DataRowView value for str but not giving selected item name.

答:
ToString() is inherited from the Object-Class. The default implementation states the Class Name of the corresponding object.

you may want to cast the SelectedItem to a DataRowView to access the column-values for that row

Ex:

```<code>String str = ((DataRowView)comboBox1.SelectedItem)["ColumnNameHere"];
</code>```

Title: comboBox.SelectedItem problem

Body:
ComboBox is binding database

string str= comboBox1.SelectedItem.ToString();

the line gives System.Data.DataRowView value for str but not giving selected item name.

Body:
ToString() is inherited from the Object-Class. The default implementation states the Class Name of the corresponding object.

you may want to cast the SelectedItem to a DataRowView to access the column-values for that row

Ex:

String str = ((DataRowView)comboBox1.SelectedItem)["ColumnNameHere"];


问:
Spark driver as a REST API
Can we have one spark driver which acts as a Rest API?
Using this Rest API (1 driver) i can spin up multiple executors on fly(real time).
I mean when ever a new request comes to spark Driver(RestAPI) it need to spin up  new executors not another new driver.

Example scenario:

```<code>Assume you have a model with 3 steps
1) Read from one set of tables and applies join and many transformations.
2) Read from second set of tables and applies join and many transformations.
3) Finally compare above dataframes and update back some records.

Here we have 3 input values to the model.
Likewise we have 1000 combinations of input values for the model  to run.
</code>```

答:
Offcourse, you can use the driver as rest api.

When ever you get a request just prepare your RDD/DF then perform an action and it`ll work.

You can do it in the driver (which mean SparkContext always up and it take resources), or you can wrap it with REST Api that submit jobs to your cluster by request.(And then for each job a new SparkContext will be created).

Title: Spark driver as a REST API

Body:
Can we have one spark driver which acts as a Rest API?
Using this Rest API (1 driver) i can spin up multiple executors on fly(real time).
I mean when ever a new request comes to spark Driver(RestAPI) it need to spin up  new executors not another new driver.

Example scenario:

Assume you have a model with 3 steps
1) Read from one set of tables and applies join and many transformations.
2) Read from second set of tables and applies join and many transformations.
3) Finally compare above dataframes and update back some records.

Here we have 3 input values to the model.
Likewise we have 1000 combinations of input values for the model  to run.


答:
If you only want to print from 5 and end at 39 if the input value is -2 then this will work for you,

```<code>n = int(input('Enter number between -6 between 2: '))

if -6 <= n <= 2:
  for x in range(n, 37, 7):
    for r in range(x,  x + 7):
        print("{:>2}".format(r), end=" ")
    print()

else:
  print("Wrong input!!")
</code>```

output:

```<code>Enter number between -6 between 2: -2
 5  6  7  8  9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31 32
33 34 35 36 37 38 39
</code>```

Title: How to start at a specific index in the range?

Body:
The program must print out n + 41 as 6 rows of 7 numbers, the first row will be n + 6, the second will be n + 7 to n + 7 + 6 and so on.

n = int(input('Enter number between -6 between 2: '))

if -6 <= n <= 2:
  for x in range(n, 37, 7):
    for r in range(x,  x + 7):
        print("{:>2}".format(r), end=" ")
    print()

else:
  print("Wrong input!!")

Sample Output for -2 is:

5  6  7  8  9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31 32
33 34 35 36 37 38 39

Body:
If you only want to print from 5 and end at 39 if the input value is -2 then this will work for you,

n = int(input('Enter number between -6 between 2: '))

if -6 <= n <= 2:
  for x in range(n, 37, 7):
    for r in range(x,  x + 7):
        print("{:>2}".format(r), end=" ")
    print()

else:
  print("Wrong input!!")

output:

Enter number between -6 between 2: -2
 5  6  7  8  9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31 32
33 34 35 36 37 38 39


问:
Git clean exclude nested sub directory
I'am having trouble with git clean and exclude options for nested dirs.

I would like to clean all uncommitted files from repo excluding vendor/bundle dir.
My test repo loks like:

```<code>debugg-dir/
  .git/
  file.txt
  not-commited-file
  not-commited-folder
      another-not-commited-file
  vendor/
    bundle/
      another-not-commited-file
</code>```

Reproduce test repo with:

```<code>git init debugg-dir && cd debugg-dir
touch file.txt && g a . && git ci -m "Commit"
mkdir -p not-commited-folder && touch not-commited-folder/another-not-commited-file
mkdir -p vendor/bundle && touch vendor/bundle/another-not-commited-file && touch not-commited-file
</code>```

Git clean command:

```<code>git clean -d -x -n -e vendor/bundle
</code>```

After clean expected to have:

```<code>debugg-dir/
  .git/
  file.txt
  vendor/
    bundle/
      another-not-commited-file
</code>```

Is there any proper way to exclude nested dir from git clean command?

# EDIT:

Explanation:

There is no "clean" solution for this situation.
Git clean excludes dirs with git clean -d -x -n -e dir_name but this doesn't work with nested dirs.
Is this bug in git or there is some good reason for that? More info why this doesnt work you can find in source. Long story short, exclude pattern only works for strings till first '/' in pattern.

My solution:

```<code>cd vendor && git clean -dxf -e bundle && cd ..
git clean -dxf -e vendor
</code>```

With this i  managed to only keep nested dir and it's contents.

答:
This is the code I use to clean up my git repos while excluding the venv/ directory and sub-directory:

```<code>git clean -nXd -e \!venv -e \!venv/**
</code>```

For your case, the first exclusion will be enough:

```<code>git clean -nXd -e \!vendor
</code>```

The second exclusion \!venv/** are for other rules in .gitignore that may apply to file or folder inside vendor. Ex:

```<code>.gitignore
*.log

vendor/
  bundle/
    another-not-commited-file.log
</code>```

Title: Git clean exclude nested sub directory

Body:
I'am having trouble with git clean and exclude options for nested dirs.

I would like to clean all uncommitted files from repo excluding vendor/bundle dir.
My test repo loks like:

debugg-dir/
  .git/
  file.txt
  not-commited-file
  not-commited-folder
      another-not-commited-file
  vendor/
    bundle/
      another-not-commited-file

Reproduce test repo with:

git init debugg-dir && cd debugg-dir
touch file.txt && g a . && git ci -m "Commit"
mkdir -p not-commited-folder && touch not-commited-folder/another-not-commited-file
mkdir -p vendor/bundle && touch vendor/bundle/another-not-commited-file && touch not-commited-file

Git clean command:

git clean -d -x -n -e vendor/bundle

After clean expected to have:

debugg-dir/
  .git/
  file.txt
  vendor/
    bundle/
      another-not-commited-file

Is there any proper way to exclude nested dir from git clean command?

# EDIT:

Explanation:

There is no "clean" solution for this situation.
Git clean excludes dirs with git clean -d -x -n -e dir_name but this doesn't work with nested dirs.
Is this bug in git or there is some good reason for that? More info why this doesnt work you can find in source. Long story short, exclude pattern only works for strings till first '/' in pattern.

My solution:

cd vendor && git clean -dxf -e bundle && cd ..
git clean -dxf -e vendor

With this i  managed to only keep nested dir and it's contents.

Body:
This is the code I use to clean up my git repos while excluding the venv/ directory and sub-directory:

git clean -nXd -e \!venv -e \!venv/**

For your case, the first exclusion will be enough:

git clean -nXd -e \!vendor

The second exclusion \!venv/** are for other rules in .gitignore that may apply to file or folder inside vendor. Ex:

.gitignore
*.log

vendor/
  bundle/
    another-not-commited-file.log


问:
In need of a python script to upload a file with IP address every few minutes
I'm using windows server 2008, and one of the things I need to do in order to pair to a domain name is send a file with the computers current IP address (it's not static) to a server via sftp every few minutes. The problem is that I'm not sure how to do this.</p>

答:
I would send it via XMPP.  You can set up a listener service for the server.

Send an xmpp message using a python library

Here are some ideas on XMPP servers to run on your IIS server (listening to recieve the incoming messages from clients http://metajack.im/2008/08/26/choosing-an-xmpp-server/

Pretzel looks nice

this python code can be run client side to get the public IP address.

```<code>host, aliaslist, lan_ip = socket.gethostbyname_ex(socket.gethostname())
print host
print aliaslist
print lan_ip[0]
</code>```

Than you would send via XMPP message containing the IP to the server you have set up on your IIS server.   Depending on what you want to do with the IP address once it gets to the server, you will handle the message serverside

Body:
I would send it via XMPP.  You can set up a listener service for the server.

Send an xmpp message using a python library

Here are some ideas on XMPP servers to run on your IIS server (listening to recieve the incoming messages from clients http://metajack.im/2008/08/26/choosing-an-xmpp-server/

Pretzel looks nice

this python code can be run client side to get the public IP address.

host, aliaslist, lan_ip = socket.gethostbyname_ex(socket.gethostname())
print host
print aliaslist
print lan_ip[0]

Than you would send via XMPP message containing the IP to the server you have set up on your IIS server.   Depending on what you want to do with the IP address once it gets to the server, you will handle the message serverside