问:
How to reduce/optimize memory usage when calculating area of skyline?
I'm trying to calculate the area of skyline (overlapping rectangles with same baseline)

```<code>building_count = int(input())
items = {} # dictionary, location on x axis is the key, height is the value
count = 0 # total area
for j in range(building_count):
    line = input().split(' ')
    H = int(line[0]) # height
    L = int(line[1]) # left point (start of the building)
    R = int(line[2]) # right point (end of the building)
    for k in range(R - L):
        if not (L+k in  items): # if it's not there, add it
            items[L+k] = H
        elif H > items[L+k]: # if we have a higher building on that index
            items[L+k] = H
for value in items.values(): # we add each column basically
    count += value
print(count)
</code>```

sample input would be:

5
3 -3 0
2 -1 1
4 2 4
2 3 7
3 6 8
```

and output is 29.

The issue is memory efficiency, when there are lots of values, the script simply throws MemoryError. Anyone have some ideas for optimizing memory usage?

答:
You are allocating a separate key-value pair for every single integer value in your range. Imagine the case where R = 1 and L = 100000. Your items dictionary will be filled with 1000000 items. Your basic idea of processing/removing overlaps is is sound, but the way you do it is massive overkill.

Like so much else in life, this is a graph problem in disguise. Imaging the vertices being the rectangles you are trying to process and the (weighted) edges being the overlaps. The complication is that you can not just add up the areas of the vertices and subtract the areas of the overlaps, because many of the overlaps overlap each other as well. The overlap issue can be resolved by applying a transformation that converts two overlapping rectangles into non-overlapping rectangles, effectively cutting the edge that connects them. The transformation is shown in the image below. Notice that in some cases one of the vertices will be removed as well, simplifying the graph, while in another case a new vertex is added:

Green: overlap to be chopped out.

Normally, if we have m rectangles and n overlaps between them, constructing the graph would be an O(m2) operation because we would have to check all vertices for overlaps against each other. However, we can bypass a construction of the input graph entirely to get a O(m + n) traversal algorithm, which is going to be optimal since we will only analyze each rectangle once, and construct the output graph with no overlaps as efficiently as possible. O(m + n) assumes that your input rectangles are sorted according to their left edges in ascending order. If that is not the case, the algorithm will be O(mlog(m) + n) to account for the initial sorting step. Note that as the graph density increases, n will go from ~m to ~m2. This confirms the intuitive idea that the fewer overlaps there are, them more you would expect the process will run in O(m) time, while the more overlaps there are, the closer you will run to O(m2) time.

The space complexity of the proposed algorithm will be O(m): each rectangle in the input will result in at most two rectangles in the output, and 2m = O(m).

Enough about complexity analysis and on to the algorithm itself. The input will be a sequence of rectangles defined by L, R, H as you have now. I will assume that the input is sorted by the leftmost edge L. The output graph will be a linked list of rectangles defined by the same parameters, sorted in descending order by the rightmost edge. The head of the list will be the rightmost rectangle. The output will have no overlaps between any rectangles, so the total area of the skyline will just be the sum of H * (R - L) for each of the ~m output rectangles.

The reason for picking a linked list is that the only two operations we need is iteration from the head node and the cheapest insertion possible to maintain the list in sorted order. The sorting will be done as part of overlap checking, so we do not need to do any kind of binary searches through the list or anything like that.

Since the input list is ordered by increasing left edge and the output list is ordered by decreasing right edge, we can guarantee that each rectangle added will be checked only against the rectangles it actually overlaps1. We will do overlap checking and removal as shown in the diagram above until we reach a rectangle whose left edge is less than or equal to the left edge of the new rectangle. All further rectangles in the output list are guaranteed not to overlap with the new rectangle. This check-and-chop operation guarantees that each overlap is visited at most once, and that no non-overlapping rectangles are processed unnecessarily, making the algorithm optimal.

Before I show code, here is a diagram of the algorithm in action. Red rectangles are new rectangles; note that their left edges progress to the right. Blue rectangles are ones that are already added and have overlap with the new rectangle. Black rectangles are already added and have no overlap with the new one. The numbering represents the order of the output list. It is always done from the right. A linked list is a perfect structure to maintain this progression since it allows cheap insertions and replacements:

Here is an implementation of the algorithm which assumes that the input coordinates are passed in as an iterable of objects having the attributes l, r, and h. The iteration order is assumed to be sorted by the left edge. If that is not the case, apply sorted or list.sort to the input first:

```<code>from collections import namedtuple

# Defined in this order so you can sort a list by left edge without a custom key
Rect = namedtuple('Rect', ['l', 'r', 'h'])

class LinkedList:
    __slots__ = ['value', 'next']

    """
    Implements a singly-linked list with mutable nodes and an iterator.
    """
    def __init__(self, value=None, next=None):
        self.value = value
        self.next = next

    def __iter__(self):
        """
        Iterate over the *nodes* in the list, starting with this one.

        The `value` and `next` attribute of any node may be modified
        during iteration.
        """
        while self:
            yield self
            self = self.next

    def __str__(self):
        """
        Provided for inspection purposes.

        Works well with `namedtuple` values.
        """
        return ' -> '.join(repr(x.value) for x in self)

def process_skyline(skyline):
    """
    Turns an iterable of rectangles sharing a common baseline into a
    `LinkedList` of rectangles containing no overlaps.

    The input is assumed to be sorted in ascending order by left edge.
    Each element of the input must have the attributes `l`, r`, `h`.

    The output will be sorted in descending order by right edge.

    Return `None` if the input is empty.
    """
    def intersect(r1, r2, default=None):
        """
        Return (1) a flag indicating the order of `r1` and `r2`,
        (2) a linked list of between one and three non-overlapping
        rectangles covering the exact same area as `r1` and `r2`,
        and (3) a pointer to the last nodes (4) a pointer to the
        second-to-last node, or `default` if there is only one node.

        The flag is set to True if the left edge of `r2` is strictly less
        than the left edge of `r1`. That would indicate that the left-most
        (last) chunk of the tuple came from `r2` instead of `r1`. For the
        algorithm as a whole, that means that we need to keep checking for
        overlaps.

        The resulting list is always returned sorted descending by the
        right edge. The input rectangles will not be modified. If they are
        not returned as-is, a `Rect` object will be used instead.
        """
        # Swap so left edge of r1 < left edge of r2
        if r1.l > r2.l:
            r1, r2 = r2, r1
            swapped = True
        else:
            swapped = False

        if r2.l >= r1.r:
            # case 0: no overlap at all
            last = LinkedList(r1)
            s2l = result = LinkedList(r2, last)
        elif r1.r < r2.r:
            # case 1: simple overlap
            if r1.h > r2.h:
                # Chop r2
                r2 = Rect(r1.r, r2.r, r2.h)
            else:
                r1 = Rect(r1.l, r2.l, r1.h)
            last = LinkedList(r1)
            s2l = result = LinkedList(r2, last)
        elif r1.h < r2.h:
            # case 2: split into 3
            r1a = Rect(r1.l, r2.l, r1.h)
            r1b = Rect(r2.r, r1.r, r1.h)
            last = LinkedList(r1a)
            s2l = LinkedList(r2, last)
            result = LinkedList(r1b, s2l)
        else:
            # case 3: complete containment
            result = LinkedList(r1)
            last = result
            s2l = default

        return swapped, result, last, s2l

    root = LinkedList()

    skyline = iter(skyline)
    try:
        # Add the first node as-is
        root.next = LinkedList(next(skyline))
    except StopIteration:
        # Empty input iterator
        return None

    for new_rect in skyline:
        prev = root
        for rect in root.next:
            need_to_continue, replacement, last, second2last = \
                    intersect(rect.value, new_rect, prev)
            # Replace the rectangle with the de-overlapped regions
            prev.next = replacement
            if not need_to_continue:
                # Retain the remainder of the list
                last.next = rect.next
                break
            # Force the iterator to move on to the last node
            new_rect = last.value
            prev = second2last

    return root.next
</code>```

Computing the total area is now trivial:

```<code>skyline = [
    Rect(-3, 0, 3), Rect(-1, 1, 2), Rect(2, 4, 4),
    Rect(3, 7, 2), Rect(6, 8, 3),
]
processed = process_skyline(skyline)
area = sum((x.value.r - x.value.l) * x.value.h for x in processed) if processed else None
</code>```

Notice the altered order of the input parameters (h moved to the end). The resulting area is 29. This matches with what I get by doing the computation by hand. You can also do

```<code>>>> print(processed)
Rect(l=6, r=8, h=3) -> Rect(l=4, r=6, h=2) -> Rect(l=2, r=4, h=4) ->
Rect(l=0, r=1, h=2) -> Rect(l=-3, r=0, h=3)
</code>```

This is to be expected from the diagram of the inputs/output shown below:

As an additional verification, I added a new building, Rect(-4, 9, 1) to the start of the list. It overlaps all the others and adds three units to area, or a final result of 32. processed comes out as:

```
<b>Rect(l=8, r=9, h=1)</b> -> Rect(l=6, r=8, h=3) -> Rect(l=4, r=6, h=2) ->
Rect(l=2, r=4, h=4) -> <b>Rect(l=1, r=2, h=1)</b> -> Rect(l=0, r=1, h=2) ->
Rect(l=-3, r=0, h=3) -> <b>Rect(l=-4, r=-3, h=1)</b>
```

Note:

While I am sure that this problem has been solved many times over, the solution I present here is entirely my own work, done without consulting any other references. The idea of using an implicit graph representation and the resulting analysis is inspired by a recent reading of Steven Skiena's Algorithm Design Manual, Second Edition. It is one of the best comp-sci books I have ever come across.

1 Technically, if a new rectangle does not overlap any other rectangles, it will be checked against one rectangle it does not overlap. If that extra check was always the case, the algorithm would have an additional m - 1 comparisons to do. Fortunately, m + m + n - 1 = O(m + n) even if we always had to check one extra rectangle (which we don't).

Body:
I'm trying to calculate the area of skyline (overlapping rectangles with same baseline)

building_count = int(input())
items = {} # dictionary, location on x axis is the key, height is the value
count = 0 # total area
for j in range(building_count):
    line = input().split(' ')
    H = int(line[0]) # height
    L = int(line[1]) # left point (start of the building)
    R = int(line[2]) # right point (end of the building)
    for k in range(R - L):
        if not (L+k in  items): # if it's not there, add it
            items[L+k] = H
        elif H > items[L+k]: # if we have a higher building on that index
            items[L+k] = H
for value in items.values(): # we add each column basically
    count += value
print(count)

sample input would be:

5
3 -3 0
2 -1 1
4 2 4
2 3 7
3 6 8

and output is 29.

The issue is memory efficiency, when there are lots of values, the script simply throws MemoryError. Anyone have some ideas for optimizing memory usage?

Body:
You are allocating a separate key-value pair for every single integer value in your range. Imagine the case where R = 1 and L = 100000. Your items dictionary will be filled with 1000000 items. Your basic idea of processing/removing overlaps is is sound, but the way you do it is massive overkill.

Like so much else in life, this is a graph problem in disguise. Imaging the vertices being the rectangles you are trying to process and the (weighted) edges being the overlaps. The complication is that you can not just add up the areas of the vertices and subtract the areas of the overlaps, because many of the overlaps overlap each other as well. The overlap issue can be resolved by applying a transformation that converts two overlapping rectangles into non-overlapping rectangles, effectively cutting the edge that connects them. The transformation is shown in the image below. Notice that in some cases one of the vertices will be removed as well, simplifying the graph, while in another case a new vertex is added:

Green: overlap to be chopped out.

Normally, if we have m rectangles and n overlaps between them, constructing the graph would be an O(m2) operation because we would have to check all vertices for overlaps against each other. However, we can bypass a construction of the input graph entirely to get a O(m + n) traversal algorithm, which is going to be optimal since we will only analyze each rectangle once, and construct the output graph with no overlaps as efficiently as possible. O(m + n) assumes that your input rectangles are sorted according to their left edges in ascending order. If that is not the case, the algorithm will be O(mlog(m) + n) to account for the initial sorting step. Note that as the graph density increases, n will go from ~m to ~m2. This confirms the intuitive idea that the fewer overlaps there are, them more you would expect the process will run in O(m) time, while the more overlaps there are, the closer you will run to O(m2) time.

The space complexity of the proposed algorithm will be O(m): each rectangle in the input will result in at most two rectangles in the output, and 2m = O(m).

Enough about complexity analysis and on to the algorithm itself. The input will be a sequence of rectangles defined by L, R, H as you have now. I will assume that the input is sorted by the leftmost edge L. The output graph will be a linked list of rectangles defined by the same parameters, sorted in descending order by the rightmost edge. The head of the list will be the rightmost rectangle. The output will have no overlaps between any rectangles, so the total area of the skyline will just be the sum of H * (R - L) for each of the ~m output rectangles.

The reason for picking a linked list is that the only two operations we need is iteration from the head node and the cheapest insertion possible to maintain the list in sorted order. The sorting will be done as part of overlap checking, so we do not need to do any kind of binary searches through the list or anything like that.

Since the input list is ordered by increasing left edge and the output list is ordered by decreasing right edge, we can guarantee that each rectangle added will be checked only against the rectangles it actually overlaps1. We will do overlap checking and removal as shown in the diagram above until we reach a rectangle whose left edge is less than or equal to the left edge of the new rectangle. All further rectangles in the output list are guaranteed not to overlap with the new rectangle. This check-and-chop operation guarantees that each overlap is visited at most once, and that no non-overlapping rectangles are processed unnecessarily, making the algorithm optimal.

Before I show code, here is a diagram of the algorithm in action. Red rectangles are new rectangles; note that their left edges progress to the right. Blue rectangles are ones that are already added and have overlap with the new rectangle. Black rectangles are already added and have no overlap with the new one. The numbering represents the order of the output list. It is always done from the right. A linked list is a perfect structure to maintain this progression since it allows cheap insertions and replacements:

Here is an implementation of the algorithm which assumes that the input coordinates are passed in as an iterable of objects having the attributes l, r, and h. The iteration order is assumed to be sorted by the left edge. If that is not the case, apply sorted or list.sort to the input first:

from collections import namedtuple

# Defined in this order so you can sort a list by left edge without a custom key
Rect = namedtuple('Rect', ['l', 'r', 'h'])

class LinkedList:
    __slots__ = ['value', 'next']

    """
    Implements a singly-linked list with mutable nodes and an iterator.
    """
    def __init__(self, value=None, next=None):
        self.value = value
        self.next = next

    def __iter__(self):
        """
        Iterate over the *nodes* in the list, starting with this one.

        The `value` and `next` attribute of any node may be modified
        during iteration.
        """
        while self:
            yield self
            self = self.next

    def __str__(self):
        """
        Provided for inspection purposes.

        Works well with `namedtuple` values.
        """
        return ' -> '.join(repr(x.value) for x in self)

def process_skyline(skyline):
    """
    Turns an iterable of rectangles sharing a common baseline into a
    `LinkedList` of rectangles containing no overlaps.

    The input is assumed to be sorted in ascending order by left edge.
    Each element of the input must have the attributes `l`, r`, `h`.

    The output will be sorted in descending order by right edge.

    Return `None` if the input is empty.
    """
    def intersect(r1, r2, default=None):
        """
        Return (1) a flag indicating the order of `r1` and `r2`,
        (2) a linked list of between one and three non-overlapping
        rectangles covering the exact same area as `r1` and `r2`,
        and (3) a pointer to the last nodes (4) a pointer to the
        second-to-last node, or `default` if there is only one node.

        The flag is set to True if the left edge of `r2` is strictly less
        than the left edge of `r1`. That would indicate that the left-most
        (last) chunk of the tuple came from `r2` instead of `r1`. For the
        algorithm as a whole, that means that we need to keep checking for
        overlaps.

        The resulting list is always returned sorted descending by the
        right edge. The input rectangles will not be modified. If they are
        not returned as-is, a `Rect` object will be used instead.
        """
        # Swap so left edge of r1 < left edge of r2
        if r1.l > r2.l:
            r1, r2 = r2, r1
            swapped = True
        else:
            swapped = False

        if r2.l >= r1.r:
            # case 0: no overlap at all
            last = LinkedList(r1)
            s2l = result = LinkedList(r2, last)
        elif r1.r < r2.r:
            # case 1: simple overlap
            if r1.h > r2.h:
                # Chop r2
                r2 = Rect(r1.r, r2.r, r2.h)
            else:
                r1 = Rect(r1.l, r2.l, r1.h)
            last = LinkedList(r1)
            s2l = result = LinkedList(r2, last)
        elif r1.h < r2.h:
            # case 2: split into 3
            r1a = Rect(r1.l, r2.l, r1.h)
            r1b = Rect(r2.r, r1.r, r1.h)
            last = LinkedList(r1a)
            s2l = LinkedList(r2, last)
            result = LinkedList(r1b, s2l)
        else:
            # case 3: complete containment
            result = LinkedList(r1)
            last = result
            s2l = default

        return swapped, result, last, s2l

    root = LinkedList()

    skyline = iter(skyline)
    try:
        # Add the first node as-is
        root.next = LinkedList(next(skyline))
    except StopIteration:
        # Empty input iterator
        return None

    for new_rect in skyline:
        prev = root
        for rect in root.next:
            need_to_continue, replacement, last, second2last = \
                    intersect(rect.value, new_rect, prev)
            # Replace the rectangle with the de-overlapped regions
            prev.next = replacement
            if not need_to_continue:
                # Retain the remainder of the list
                last.next = rect.next
                break
            # Force the iterator to move on to the last node
            new_rect = last.value
            prev = second2last

    return root.next

Computing the total area is now trivial:

skyline = [
    Rect(-3, 0, 3), Rect(-1, 1, 2), Rect(2, 4, 4),
    Rect(3, 7, 2), Rect(6, 8, 3),
]
processed = process_skyline(skyline)
area = sum((x.value.r - x.value.l) * x.value.h for x in processed) if processed else None

Notice the altered order of the input parameters (h moved to the end). The resulting area is 29. This matches with what I get by doing the computation by hand. You can also do

>>> print(processed)
Rect(l=6, r=8, h=3) -> Rect(l=4, r=6, h=2) -> Rect(l=2, r=4, h=4) ->
Rect(l=0, r=1, h=2) -> Rect(l=-3, r=0, h=3)

This is to be expected from the diagram of the inputs/output shown below:

As an additional verification, I added a new building, Rect(-4, 9, 1) to the start of the list. It overlaps all the others and adds three units to area, or a final result of 32. processed comes out as:

Rect(l=8, r=9, h=1) -> Rect(l=6, r=8, h=3) -> Rect(l=4, r=6, h=2) ->
Rect(l=2, r=4, h=4) -> Rect(l=1, r=2, h=1) -> Rect(l=0, r=1, h=2) ->
Rect(l=-3, r=0, h=3) -> Rect(l=-4, r=-3, h=1)

Note:

While I am sure that this problem has been solved many times over, the solution I present here is entirely my own work, done without consulting any other references. The idea of using an implicit graph representation and the resulting analysis is inspired by a recent reading of Steven Skiena's Algorithm Design Manual, Second Edition. It is one of the best comp-sci books I have ever come across.

1 Technically, if a new rectangle does not overlap any other rectangles, it will be checked against one rectangle it does not overlap. If that extra check was always the case, the algorithm would have an additional m - 1 comparisons to do. Fortunately, m + m + n - 1 = O(m + n) even if we always had to check one extra rectangle (which we don't).


来源: stackexchange

问:
WCAG2.0 AA Test lead
Recently I've been put in charge of testing and implementing WCAG 2.0 AA compliance into our websites (php CMS based). However, my experience with this is pretty limited. My questions are:

Is Mac VoiceOver sufficient enough to test?

Should I test with JAWS on Windows instead?

Any tools besides the VO's I should be using while developing and QAing our products?

I use the Wave tool as of now to check code, but not sure if there any thing else that could help this process speed up.

Thank you for your suggestions and help. This is a big step for us and we are hoping to create a standard where accessibility and compliance is 2nd nature to us and our devs.

答:
Testing accessibility with a screenreader is just a small part of testing accessibility. There's no requisit about using one screenreader for testing as your website is required with any assistive technologies (which includes many screenreaders, screen magnifier, braille display, eye tracking devices, voice activated navigation, keyboard-only/mouse-only/touch-only navigation, ...) by conforming to the guidelines.

Automatic tools can partially speed up the process. You can use the WCAG list to test a few of them, but Stackoverflow is not the place to ask for this question : Where can I ask about "finding a tool, library or favorite off-site resource?"

ContentLicense: CC BY-SA 3.0

Title: WCAG2.0 AA Test lead


问:
Can I get JSON to load into an OrderedDict?
Ok so I can use an OrderedDict in json.dump. That is, an OrderedDict can be used as an input to JSON.

But can it be used as an output? If so how? In my case I'd like to load into an OrderedDict so I can keep the order of the keys in the file.

If not, is there some kind of workaround?

答:
The normally used load command will work if you specify the object_pairs_hook parameter:

```<code>import json
from  collections import OrderedDict
with open('foo.json', 'r') as fp:
    metrics_types = json.load(fp, object_pairs_hook=OrderedDict)
</code>```

Body:
The normally used load command will work if you specify the object_pairs_hook parameter:

import json
from  collections import OrderedDict
with open('foo.json', 'r') as fp:
    metrics_types = json.load(fp, object_pairs_hook=OrderedDict)


问:
How to return several list without the model in Rest Framework?
How can I returns serval list in Rest Framework?

I have serializers.py

```<code>class HostTypeSerializer(ModelSerializer):

    class Meta:
        model = HostType
        fields = "__all__"
class DiskOSTypeSerializer(ModelSerializer):
    class Meta:
        model = DiskOSType
        fields = "__all__"
class DiskEssenceTypeSerializer(ModelSerializer):
    class Meta:
        model = DiskEssenceType
        fields = "__all__"
</code>```

I have the three Serializers, and I want to return data like bellow:

```<code>{
    hosttypes:[the HostTypeSerializer's list data ],
    diskostype:[the DiskOSTypeSerializer's list data],
    diskessencetype:[the DiskEssenceTypeSerializer's list data],
}
</code>```

I tried but failed, but I don't know how to do with that:

```<code>class DiskPreCreateSerialzer(ModelSerializer):
    hosttypes = HostTypeSerializer(many=True, read_only=True)
    diskostypes = DiskOSTypeSerializer(many=True, read_only=True)
    diskessencetypes = DiskEssenceTypeSerializer(many=True, read_only=True)
    class Meta:

        fields = (
            "hosttypes",
            "diskostypes",
            "diskessencetypes",
        )
</code>```

In views.py:

```<code>class DiskPreCreateAPIView(APIView):
    serializer_class = DiskPreCreateSerialzer
    permission_classes = []
    ...
</code>```

I want to use this Serializer to returns my requirement, but failed, how can I get that?

EDIT

I don't know how to write my DiskPreCreateAPIView now, because I don't know how to get the data to return.

```<code>class DiskPreCreateAPIView(APIView):
    serializer_class = DiskPreCreateSerialzer
    permission_classes = []

    def post(self, request):

        return Response(data=xxx, status=HTTP_200_OK)
</code>```

答:
Try to use base Serializer instead of ModelSerializer:

```<code>class DiskPreCreateSerialzer(Serializer):
    hosttypes = HostTypeSerializer(many=True, read_only=True)
    diskostypes = DiskOSTypeSerializer(many=True, read_only=True)
    diskessencetypes = DiskEssenceTypeSerializer(many=True, read_only=True)
</code>```

And in your view pass dict with your lists to this serializer:

```<code>class DiskPreCreateAPIView(APIView):
    serializer_class = DiskPreCreateSerialzer
    permission_classes = []

    def post(self, request):
        ...
        serializer = self.serializer_class({
            'hosttypes': hosttypes_qs,
            'diskostype':diskostype_qs,
            'diskessencetype': diskessencetype_qs,
        })
        return Response(data=serializer.data, status=HTTP_200_OK)
</code>```

Body:
How can I returns serval list in Rest Framework?

I have serializers.py

class HostTypeSerializer(ModelSerializer):

    class Meta:
        model = HostType
        fields = "__all__"
class DiskOSTypeSerializer(ModelSerializer):
    class Meta:
        model = DiskOSType
        fields = "__all__"
class DiskEssenceTypeSerializer(ModelSerializer):
    class Meta:
        model = DiskEssenceType
        fields = "__all__"

I have the three Serializers, and I want to return data like bellow:

{
    hosttypes:[the HostTypeSerializer's list data ],
    diskostype:[the DiskOSTypeSerializer's list data],
    diskessencetype:[the DiskEssenceTypeSerializer's list data],
}

I tried but failed, but I don't know how to do with that:

class DiskPreCreateSerialzer(ModelSerializer):
    hosttypes = HostTypeSerializer(many=True, read_only=True)
    diskostypes = DiskOSTypeSerializer(many=True, read_only=True)
    diskessencetypes = DiskEssenceTypeSerializer(many=True, read_only=True)
    class Meta:

        fields = (
            "hosttypes",
            "diskostypes",
            "diskessencetypes",
        )

In views.py:

class DiskPreCreateAPIView(APIView):
    serializer_class = DiskPreCreateSerialzer
    permission_classes = []
    ...

I want to use this Serializer to returns my requirement, but failed, how can I get that?

EDIT

I don't know how to write my DiskPreCreateAPIView now, because I don't know how to get the data to return.

class DiskPreCreateAPIView(APIView):
    serializer_class = DiskPreCreateSerialzer
    permission_classes = []

    def post(self, request):

        return Response(data=xxx, status=HTTP_200_OK)

Body:
Try to use base Serializer instead of ModelSerializer:

class DiskPreCreateSerialzer(Serializer):
    hosttypes = HostTypeSerializer(many=True, read_only=True)
    diskostypes = DiskOSTypeSerializer(many=True, read_only=True)
    diskessencetypes = DiskEssenceTypeSerializer(many=True, read_only=True)

And in your view pass dict with your lists to this serializer:

class DiskPreCreateAPIView(APIView):
    serializer_class = DiskPreCreateSerialzer
    permission_classes = []

    def post(self, request):
        ...
        serializer = self.serializer_class({
            'hosttypes': hosttypes_qs,
            'diskostype':diskostype_qs,
            'diskessencetype': diskessencetype_qs,
        })
        return Response(data=serializer.data, status=HTTP_200_OK)


问:
How to change button background button in another activity?
hi i have 3 XML layout with Button (without class or activity or fragment) and use in view pager in another activity ... now i want change button background in view pager activity when my condition is true. how to do it ?

this image :
enter image description here

答:
To change the background of a button, first you must have the button initialized. Lets say you initialize the button as such:

```<code>Button myButton = (Button) findViewById(R.id.theButton);
</code>```

Of course, the ID of your button is whatever you set it as in the XML file. You can change the background color whenever you want in the same scope as your declaration of the button as such:

```<code>myButton.setBackgroundColor(R.color.anyColor);
</code>```

Hopefully this answers your question as it's quite confusing.

Body:
To change the background of a button, first you must have the button initialized. Lets say you initialize the button as such:

Button myButton = (Button) findViewById(R.id.theButton);

Of course, the ID of your button is whatever you set it as in the XML file. You can change the background color whenever you want in the same scope as your declaration of the button as such:

myButton.setBackgroundColor(R.color.anyColor);

Hopefully this answers your question as it's quite confusing.


问:
Japanese and Korean characters are not displayed well
I tried looking at this post Korean characters are displayed as empty boxes on JTextField This is a closer one but not fits my actual issue.

I have a text box where it accepts japan or korean input depending on user langauge selection.
When the user tries to input japan or korean characters, this is diplayed in some what wierd way and words are getting scattered.

Below is the image how Korean characters are getting diplayed in a wierd way.

Font I have used is
 font:0px 'Arial Unicode MS',sans-serif,'hanja','kanji'

Can anyone aware of this kind and help me out ?

Thanks in advance.

答:
'hanja' and 'kanji' are not font family so typing them in that way would not help

The problem here seems to be input instead of display. For Korean input, user typically type multiple character parts and let the input method to compose those parts, is the input box somehow preventing this from happening?


问:
How to combine number of commits of same author
I have been contributing to an open source project. At first, all my commits were under name yathartha. But after a while, I changed the name to Yathartha Joshi and now my new commits are under this name. So is it possible to combine the number of commits? If so how, otherwise what can I do to combine them.

I have 8 commits under yathartha and 14 commits under Yathartha Joshi.

答:
If the project has a .mailmap under the root, you can add this line to it:

```<code>Yathartha Joshi <oldmail@xxx> yathartha <newmail@xxx>
</code>```

The second name and email will be replaced by the first. If the mail is not changed, the newmail part can be omitted.

Not sure if it works for the number on Github. .mailmap is used to help git shortlog summarize the output of git log. Before this line is added, git shortlog --all displays:

```<code>yathartha (8):
      commit1
      commit2
      ...
      commit8

Yathartha Joshi (14):
      commit9
      ...
      commit22
</code>```

And afterwards, it displays:

```<code>Yathartha Joshi (22):
      commit1
      commit2
      ...
      commit22
</code>```

Body:
If the project has a .mailmap under the root, you can add this line to it:

Yathartha Joshi <oldmail@xxx> yathartha <newmail@xxx>

The second name and email will be replaced by the first. If the mail is not changed, the newmail part can be omitted.

Not sure if it works for the number on Github. .mailmap is used to help git shortlog summarize the output of git log. Before this line is added, git shortlog --all displays:

yathartha (8):
      commit1
      commit2
      ...
      commit8

Yathartha Joshi (14):
      commit9
      ...
      commit22

And afterwards, it displays:

Yathartha Joshi (22):
      commit1
      commit2
      ...
      commit22


问:
How to get data in Array category wise?
I have below data coming from loop:

```<code>$array = Array(
[0]=>Array(
    [0]=>Cat 1
    [1]=> Q1
    [2]=> A1
    )
[1]=>Array(
    [0]=>Cat 1
    [1]=> Q2
    [2]=> A2
    )
[2]=>Array(
    [0]=>Cat 2
    [1]=> Q1
    [2]=> A1
    )
[3]=>Array(
    [0]=>Cat 3
    [1]=>Sub Cat 3
    [2]=>Q1
    [3]=>A1
    )
[4]=>Array(
    [0]=>Cat 3
    [1]=>Sub Cat 3
    [2]=>Q2
    [3]=>A2
    )
)
)
</code>```

I need data in Array like

```<code>$array_res = Array(
['Cat 1']=>Array(
    [0]=>Array(
        [0]=> Q1
        [1]=> A1
        )
    [1]=>Array(
        [0]=> Q2
        [1]=> A2
        )
    )
['Cat 2']=>Array(
    [0]=>Array(
        [0]=> Q1
        [1]=> A1
        )
    )
['Cat 3']=>Array(
    ['Sub Cat 3']=>Array(
        [0]=>Array(
            [0]=> Q1
            [1]=> A1
        )
        [1]=>Array(
            [0]=> Q2
            [1]=> A2
        )
        )
    )

)
</code>```

It should return data in Array/Associative Array. So can fetch data loop wise & print it. I want the arrays created dynamically when there are array values inside an array like sub cat 3.

答:
Here is the code. I've explained my answer with my comment. You can try it here https://3v4l.org/K1kZ6

Answer:

```<code>$cat_array = array(
    0=>array(
        0=>'Cat 1',
        1=>'Q1',
        2=>'A1'
        ),
    1=>array(
        0=>'Cat 1',
        1=>'Q2',
        2=>'A2'
        ),
    2=>array(
        0=>'Cat 2',
        1=>'Q1',
        2=>'A1'
        ),
    3=>array(
        0=>'Cat 3',
        1=>'Sub Cat 3',
        2=>'Q1',
        3=>'A1'
        ),
    4=>array(
        0=>'Cat 3',
        1=>'Sub Cat 3',
        2=>'Q2',
        3=>'A2'
        )
);

$converted_array = array();
foreach($cat_array as $key => $array){

    // Split the cat and 3
    $temp = explode(' ', $array[0]);

    //Check if key(Cat 1,2,3,etc..) exists in converted array
    if(!array_key_exists($array[0],$converted_array)){
        $converted_array[$array[0]] = array();
    }

    //Get and check if there is a Sub Cat
    $sub_temp = explode(' ', $array[1]);

    //Check in array if there is a sub in $sub_temp array.
    if(!in_array('sub' , array_map("strtolower", $sub_temp))){
        //If doesn't have sub
        //Store key(Cat 1,2,3...) before we unset
        $temp_key = $array[0];
        unset($array[0]);

        //Get the total count to provide as our starting index
        $l = count($converted_array[$temp_key]);

        // $temp_key = "Cat 1,2,3,etc..." and $l = 0,1,2...
        foreach($array as $val){
            $converted_array[$temp_key][$l][]= $val;
        }
    }else{

        //Check if sub is inside of sub array
        if(!array_key_exists($array[1],$converted_array[$array[0]])){
            $converted_array[$array[0]][$array[1]] = array();
        }

        //Same as the above, we store key first before we unset.
        $temp_key = $array[0];
        $temp_sub_key = $array[1];

        unset($array[0]);
        unset($array[1]);
        //Same as the above but with sub category
        $l = count($converted_array[$temp_key][$temp_sub_key]);
        foreach($array as $val){
            $converted_array[$temp_key][$temp_sub_key][$l][]= $val;
        }
    }
}
echo "```";
print_r($converted_array);
```

<p><strong>Output:</strong></p>

```Array
(
    [Cat 1] => Array
        (
            [0] => Array
                (
                    [0] => Q1
                    [1] => A1
                )

            [1] => Array
                (
                    [0] => Q2
                    [1] => A2
                )

        )

    [Cat 2] => Array
        (
            [0] => Array
                (
                    [0] => Q1
                    [1] => A1
                )

        )

    [Cat 3] => Array
        (
            [Sub Cat 3] => Array
                (
                    [0] => Array
                        (
                            [0] => Q1
                            [1] => A1
                        )

                    [1] => Array
                        (
                            [0] => Q2
                            [1] => A2
                        )

                )

        )

)
```

Title: How to get data in Array category wise?

Body:
I have below data coming from loop:

$array = Array(
[0]=>Array(
    [0]=>Cat 1
    [1]=> Q1
    [2]=> A1
    )
[1]=>Array(
    [0]=>Cat 1
    [1]=> Q2
    [2]=> A2
    )
[2]=>Array(
    [0]=>Cat 2
    [1]=> Q1
    [2]=> A1
    )
[3]=>Array(
    [0]=>Cat 3
    [1]=>Sub Cat 3
    [2]=>Q1
    [3]=>A1
    )
[4]=>Array(
    [0]=>Cat 3
    [1]=>Sub Cat 3
    [2]=>Q2
    [3]=>A2
    )
)
)

I need data in Array like

$array_res = Array(
['Cat 1']=>Array(
    [0]=>Array(
        [0]=> Q1
        [1]=> A1
        )
    [1]=>Array(
        [0]=> Q2
        [1]=> A2
        )
    )
['Cat 2']=>Array(
    [0]=>Array(
        [0]=> Q1
        [1]=> A1
        )
    )
['Cat 3']=>Array(
    ['Sub Cat 3']=>Array(
        [0]=>Array(
            [0]=> Q1
            [1]=> A1
        )
        [1]=>Array(
            [0]=> Q2
            [1]=> A2
        )
        )
    )

)

It should return data in Array/Associative Array. So can fetch data loop wise & print it. I want the arrays created dynamically when there are array values inside an array like sub cat 3.

Body:
Here is the code. I've explained my answer with my comment. You can try it here https://3v4l.org/K1kZ6

Answer:

$cat_array = array(
    0=>array(
        0=>'Cat 1',
        1=>'Q1',
        2=>'A1'
        ),
    1=>array(
        0=>'Cat 1',
        1=>'Q2',
        2=>'A2'
        ),
    2=>array(
        0=>'Cat 2',
        1=>'Q1',
        2=>'A1'
        ),
    3=>array(
        0=>'Cat 3',
        1=>'Sub Cat 3',
        2=>'Q1',
        3=>'A1'
        ),
    4=>array(
        0=>'Cat 3',
        1=>'Sub Cat 3',
        2=>'Q2',
        3=>'A2'
        )
);

$converted_array = array();
foreach($cat_array as $key => $array){

    // Split the cat and 3
    $temp = explode(' ', $array[0]);

    //Check if key(Cat 1,2,3,etc..) exists in converted array
    if(!array_key_exists($array[0],$converted_array)){
        $converted_array[$array[0]] = array();
    }

    //Get and check if there is a Sub Cat
    $sub_temp = explode(' ', $array[1]);

    //Check in array if there is a sub in $sub_temp array.
    if(!in_array('sub' , array_map("strtolower", $sub_temp))){
        //If doesn't have sub
        //Store key(Cat 1,2,3...) before we unset
        $temp_key = $array[0];
        unset($array[0]);

        //Get the total count to provide as our starting index
        $l = count($converted_array[$temp_key]);

        // $temp_key = "Cat 1,2,3,etc..." and $l = 0,1,2...
        foreach($array as $val){
            $converted_array[$temp_key][$l][]= $val;
        }
    }else{

        //Check if sub is inside of sub array
        if(!array_key_exists($array[1],$converted_array[$array[0]])){
            $converted_array[$array[0]][$array[1]] = array();
        }

        //Same as the above, we store key first before we unset.
        $temp_key = $array[0];
        $temp_sub_key = $array[1];

        unset($array[0]);
        unset($array[1]);
        //Same as the above but with sub category
        $l = count($converted_array[$temp_key][$temp_sub_key]);
        foreach($array as $val){
            $converted_array[$temp_key][$temp_sub_key][$l][]= $val;
        }
    }
}
echo "<pre>";
print_r($converted_array);

Output:

Array
(
    [Cat 1] => Array
        (
            [0] => Array
                (
                    [0] => Q1
                    [1] => A1
                )

            [1] => Array
                (
                    [0] => Q2
                    [1] => A2
                )

        )

    [Cat 2] => Array
        (
            [0] => Array
                (
                    [0] => Q1
                    [1] => A1
                )

        )

    [Cat 3] => Array
        (
            [Sub Cat 3] => Array
                (
                    [0] => Array
                        (
                            [0] => Q1
                            [1] => A1
                        )

                    [1] => Array
                        (
                            [0] => Q2
                            [1] => A2
                        )

                )

        )

)


问:
Make a MATLAB plot disappear behind a 2D Gaussian of single color with varying values of transparency
The MATLAB code below draws a 2D green Gaussian with varaying values of transparancy, which represent a wave function.

The code also draws a red plot, which represents a laser pulse. (See the attached figure).

I want to have the red laser pulse be plotted in the background, so that the part of it which crosses the 2D Gaussian will be invisible.

Is there some kind of a way to achieve this ??

```<code>function forQ
    close all; clc
    figure
    xlim_min=-11;
    xlim_max=11;
    ylim_min=-11;
    ylim_max=11;
    global size_of_wavefunction;  size_of_wavefunction=2.5;
    global x_laser; x_laser=-10.5:0.01:10.5;
    global omega; omega=8;
    global laser_strength; laser_strength=10;

    draw_main_wave_function;
    hold on
    laser_x_offset=-1.2;
    hold on
    drawLaser(laser_x_offset);
    hold on
    draw_main_wave_function;
    ylim([ylim_min ylim_max])
    xlim([xlim_min xlim_max])
    axis square
end

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

function drawLaser(x_offset)
    global x_laser;
    global omega;
    global laser_strength;
    envelope_extinction=3;
    y_laser=laser_strength*exp(-envelope_extinction*(x_laser/10).^2).*cos(omega*(x_laser/10));
    y_laser_for_plot=-y_laser;
    x_laser_for_plot=x_laser+x_offset;
    plot(x_laser_for_plot,y_laser_for_plot,'-r','LineWidth',3)
end

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

function draw_main_wave_function

    global size_of_wavefunction;

    pre_exp_factor=0.5*0.8;
    c1=size_of_wavefunction*0.3;
    in_exp_factor=c1;
    x_offset=0;
    y_offset=0;

    draw_wave_function(pre_exp_factor, in_exp_factor, x_offset, y_offset);
end

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

function draw_wave_function( pre_exp_factor,in_exp_factor,...
                             x_offset, y_offset )

    x=-3:0.01:3;
    y=-3:0.01:3;
    if (y_offset~=0)
        x=-5:0.1:5;
        y=-11:0.1:11;
    end
    [X,Y]=meshgrid(x,y);

    w_function=pre_exp_factor*exp(-in_exp_factor*((X-x_offset).^2+...
                                      (Y-y_offset).^2));

    colorMap = [0 , 1, 0];
    colormap(colorMap);

    min_alpha = 0; % desired minimum alpha
    max_alpha = 1; % desired maximum alpha
    alpha = min_alpha + (max_alpha-min_alpha)/max(w_function(:))*w_function; % compute alpha
    imagesc(x,y,w_function,'AlphaData',alpha,'AlphaDataMapping','none'); % image with alpha

end
</code>```

答:
Use 3D plots with plot3 and manually set the placement of objects.

view(2) set the 3D figure view to the xy-plot (it might not be necessary in your code).

```<code>x = 0:0.1:2*pi;
figure
hold all
y = x(32);
plot3(y,sin(y),0*y+1,'go','MarkerSize',22,'MarkerFaceColor','g')
plot3(x,sin(x),0*x,'r-','LineWidth',3)
view(2)
</code>```

Body:
The MATLAB code below draws a 2D green Gaussian with varaying values of transparancy, which represent a wave function.

The code also draws a red plot, which represents a laser pulse. (See the attached figure).

I want to have the red laser pulse be plotted in the background, so that the part of it which crosses the 2D Gaussian will be invisible.

Is there some kind of a way to achieve this ??

function forQ
    close all; clc
    figure
    xlim_min=-11;
    xlim_max=11;
    ylim_min=-11;
    ylim_max=11;
    global size_of_wavefunction;  size_of_wavefunction=2.5;
    global x_laser; x_laser=-10.5:0.01:10.5;
    global omega; omega=8;
    global laser_strength; laser_strength=10;

    draw_main_wave_function;
    hold on
    laser_x_offset=-1.2;
    hold on
    drawLaser(laser_x_offset);
    hold on
    draw_main_wave_function;
    ylim([ylim_min ylim_max])
    xlim([xlim_min xlim_max])
    axis square
end

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

function drawLaser(x_offset)
    global x_laser;
    global omega;
    global laser_strength;
    envelope_extinction=3;
    y_laser=laser_strength*exp(-envelope_extinction*(x_laser/10).^2).*cos(omega*(x_laser/10));
    y_laser_for_plot=-y_laser;
    x_laser_for_plot=x_laser+x_offset;
    plot(x_laser_for_plot,y_laser_for_plot,'-r','LineWidth',3)
end

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

function draw_main_wave_function

    global size_of_wavefunction;

    pre_exp_factor=0.5*0.8;
    c1=size_of_wavefunction*0.3;
    in_exp_factor=c1;
    x_offset=0;
    y_offset=0;

    draw_wave_function(pre_exp_factor, in_exp_factor, x_offset, y_offset);
end

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

function draw_wave_function( pre_exp_factor,in_exp_factor,...
                             x_offset, y_offset )

    x=-3:0.01:3;
    y=-3:0.01:3;
    if (y_offset~=0)
        x=-5:0.1:5;
        y=-11:0.1:11;
    end
    [X,Y]=meshgrid(x,y);

    w_function=pre_exp_factor*exp(-in_exp_factor*((X-x_offset).^2+...
                                      (Y-y_offset).^2));

    colorMap = [0 , 1, 0];
    colormap(colorMap);

    min_alpha = 0; % desired minimum alpha
    max_alpha = 1; % desired maximum alpha
    alpha = min_alpha + (max_alpha-min_alpha)/max(w_function(:))*w_function; % compute alpha
    imagesc(x,y,w_function,'AlphaData',alpha,'AlphaDataMapping','none'); % image with alpha

end

Body:
Use 3D plots with plot3 and manually set the placement of objects.

view(2) set the 3D figure view to the xy-plot (it might not be necessary in your code).

x = 0:0.1:2*pi;
figure
hold all
y = x(32);
plot3(y,sin(y),0*y+1,'go','MarkerSize',22,'MarkerFaceColor','g')
plot3(x,sin(x),0*x,'r-','LineWidth',3)
view(2)


问:
Go runtime logging verbosity change
I need to change logging verbosity/level while Golang application is running, without restarting

I came from PHP where there are several logging frameworks supporting DB-based configuration change on run-time

What's the most standard/canonical way to achieve this kind of functionality in Go?

答: I would recommend using a library like https://github.com/sirupsen/logrus that has built in logging levels. Also can do structured logging</p>

Title: Go runtime logging verbosity change


问:
WinForms : Form loses visual style when opened as Modal
I am using DevComponents components to create forms and as you know these components come with a StyleManager that user can change the visual style of a form. the problem is when i try to open these forms as Modal, they lose their visual style and switch back to original windows style.

this is the code from Form1.Designer (as i mentioned i am using OfficeForm) :

```<code>Partial Class Form1
    Inherits DevComponents.DotNetBar.OfficeForm
.
.
.
</code>```

this is the code which i use that opens form as MDIChild which works just fine :

```<code>Public Sub OpenMDI(ByVal frm As Form)
    frm.MdiParent = MainMenu
    frm.Show()
End Sub
</code>```

this is the code i am using to open form as Modal :

```<code>Form1.ShowDialog()
</code>```

and these are the screenshots with and without visual styles ( - )

答:
Set EnableGlass property of from to False

eg. :

```<code>Form1.EnableGlass = False;
</code>```

Body:
I am using DevComponents components to create forms and as you know these components come with a StyleManager that user can change the visual style of a form. the problem is when i try to open these forms as Modal, they lose their visual style and switch back to original windows style.

this is the code from Form1.Designer (as i mentioned i am using OfficeForm) :

Partial Class Form1
    Inherits DevComponents.DotNetBar.OfficeForm
.
.
.

this is the code which i use that opens form as MDIChild which works just fine :

Public Sub OpenMDI(ByVal frm As Form)
    frm.MdiParent = MainMenu
    frm.Show()
End Sub

this is the code i am using to open form as Modal :

Form1.ShowDialog()

and these are the screenshots with and without visual styles ( - )

Body:
Set EnableGlass property of from to False

eg. :

Form1.EnableGlass = False;


问:
Extract Spring Boot User Properties
Hey guys I have been trying to determine which properties in Spring boot were configured by users vs. spring auto-configuration.  I am able to list all properties, but I am not certain how to just get the properties declared by the user.

//This method gets all properties in the Spring environment

```<code>public Properties getSpringEnvironmentProperties() {
    Properties props = new Properties();
    MutablePropertySources propSrcs = ((AbstractEnvironment) env).getPropertySources();
    StreamSupport.stream(propSrcs.spliterator(), false)
        .filter(ps -> ps instanceof EnumerablePropertySource)
        .map(ps -> ((EnumerablePropertySource) ps).getPropertyNames())
        .flatMap(Arrays::<String>stream)
        .forEach(propName -> props.setProperty(propName, env.getProperty(propName)));
    return props;
  }
</code>```

Is there any way to only get properties that are user declared in files like:  application.properties?

答:
You can use @ConfigurationProperties for the Complex Properties file, following the steps:

Step 1: Create application.properties which store these properties

```<code>#App
app.menus[0].label=Home
app.menus[0].path=/
app.menus[1].label=Java Core
app.menus[1].path=/javacore
app.menus[2].label=Spring
app.menus[2].path=/spring
</code>```

Step 2: Declare java properties class

```<code>@ConfigurationProperties("app")
public class AppProperties {

    private List<Menu> menus = new ArrayList<Menu>();
    //do stuff
}
</code>```

Step 3: Inject properties into your service

```<code>private AppProperties app;
</code>```

You can find the working example from the post Spring boot configuration properties example

Hope this help!

Title: Extract Spring Boot User Properties

Body:
Hey guys I have been trying to determine which properties in Spring boot were configured by users vs. spring auto-configuration.  I am able to list all properties, but I am not certain how to just get the properties declared by the user.

//This method gets all properties in the Spring environment

public Properties getSpringEnvironmentProperties() {
    Properties props = new Properties();
    MutablePropertySources propSrcs = ((AbstractEnvironment) env).getPropertySources();
    StreamSupport.stream(propSrcs.spliterator(), false)
        .filter(ps -> ps instanceof EnumerablePropertySource)
        .map(ps -> ((EnumerablePropertySource) ps).getPropertyNames())
        .flatMap(Arrays::<String>stream)
        .forEach(propName -> props.setProperty(propName, env.getProperty(propName)));
    return props;
  }

Is there any way to only get properties that are user declared in files like:  application.properties?

Body:
You can use @ConfigurationProperties for the Complex Properties file, following the steps:

Step 1: Create application.properties which store these properties

#App
app.menus[0].label=Home
app.menus[0].path=/
app.menus[1].label=Java Core
app.menus[1].path=/javacore
app.menus[2].label=Spring
app.menus[2].path=/spring

Step 2: Declare java properties class

@ConfigurationProperties("app")
public class AppProperties {

    private List<Menu> menus = new ArrayList<Menu>();
    //do stuff
}

Step 3: Inject properties into your service

private AppProperties app;

You can find the working example from the post Spring boot configuration properties example

Hope this help!


问:
Is C++11 is faster than C++03 in terms of efficiency?
I work in trading firm and here latency matters a lot. The project assigns to me is developed using a mix of c and c++98 parts, But I believe we can make same project using C++11 without losing efficiency. As discussed with my seniors, they say you should stick with C and c++03 as they are efficient compare to C++11 at micro level.
Can anyone highlight me If I go with C++11, will I get better results?</p>

答:
Honestly, this is highly dependent on the specific code snippet. C++11 is only a newer revision of the C++ language standard (ISO/IEC 14882:2011).

A newer revision only changes the grammar of certain expressions and statements, and usage of certain keywords, as well as introducing new (and useful) stuffs, like rvalue reference (T&&), auto type deduction (auto and decltype), variadic template parameters (template <typename... Args>) and so on. In spite of the fact that some introductions may help you write more efficient codes (e.g. move semantics), it essentially does not change the way compilers are required to generate CPU instructions from C++ source codes.

So in micro-instruction level, the compiled instructions from the same source would mostly remain the same under C++98/0x/11, so there should not be any observable difference in performance.

What in fact matters the more is the algorithm you choose and the specific implementation you write, as well as compiler optimization (usually -O# command line argument). With new standards, you are allowed to write faster codes with move semantics, range-based for loop, decltype(auto) (this one is C++14, though)

In fact, this code generates exactly the same assembly code, when language standards is the only different option supplied to the compiler:

```<code>#include <iostream>
using std::cout;
using std::endl;

int main() {
    cout << "Hello world" << endl;
    return 0;
}
</code>```

But when you start working with STL, which always use the latest features whenever possible, then it starts to make a difference:

```<code>#include <iostream>
#include <string>
using std::string;

string getString(void) {
    string str("");
    for (int i = 0; i < 100000; i ++)
        str.append("A");
    return str;
}

int main() {
    std::cout << getString() << std::endl;
    return 0;
}
</code>```

Body:
Honestly, this is highly dependent on the specific code snippet. C++11 is only a newer revision of the C++ language standard (ISO/IEC 14882:2011).

A newer revision only changes the grammar of certain expressions and statements, and usage of certain keywords, as well as introducing new (and useful) stuffs, like rvalue reference (T&&), auto type deduction (auto and decltype), variadic template parameters (template <typename... Args>) and so on. In spite of the fact that some introductions may help you write more efficient codes (e.g. move semantics), it essentially does not change the way compilers are required to generate CPU instructions from C++ source codes.

So in micro-instruction level, the compiled instructions from the same source would mostly remain the same under C++98/0x/11, so there should not be any observable difference in performance.

What in fact matters the more is the algorithm you choose and the specific implementation you write, as well as compiler optimization (usually -O# command line argument). With new standards, you are allowed to write faster codes with move semantics, range-based for loop, decltype(auto) (this one is C++14, though)

In fact, this code generates exactly the same assembly code, when language standards is the only different option supplied to the compiler:

#include <iostream>
using std::cout;
using std::endl;

int main() {
    cout << "Hello world" << endl;
    return 0;
}

But when you start working with STL, which always use the latest features whenever possible, then it starts to make a difference:

#include <iostream>
#include <string>
using std::string;

string getString(void) {
    string str("");
    for (int i = 0; i < 100000; i ++)
        str.append("A");
    return str;
}

int main() {
    std::cout << getString() << std::endl;
    return 0;
}


问:
Laravel Spark Installation in MAC
I'm new to mac and I don't know how to add path to the system. I have already cloned the file for spark and done composer update. I need to this next step. How do I do it in MAC?

Next, make sure the spark-installer directory is added to your systems $PATH variable, so that your machine will be able to locate the spark executable when you issue Spark commands.

答:
You do it by updating the PATH variable.

export PATH=$HOME/.composer/vendor/bin:$PATH

However, this will not persist. If you close the terminal window, the PATH will be restored to its original value. You need to add this line to your ~/.bash_profile

Run this command to add the line to your ~/bash_profile

echo 'export PATH=$HOME/.composer/vendor/bin:$PATH' >> ~/.bash_profile

To verify that you have the correct path: echo $PATH, and you should see .composer/vendor/bin in the middle of the output

For spark specifically, you need to add the path to the location where you cloned the repo.

echo 'export PATH=path/to/spark/repo:$PATH' >> ~/.bash_profile

Here is a full list of commands to install Spark:

```<code>cd $HOME
git clone https://github.com/laravel/spark-installer.git
echo 'export PATH=$HOME/spark-installer:$PATH' >> ~/.bash_profile
source ~/.bash_profile
cd ~/spark-installer
composer install
spark
</code>```

Title: Laravel Spark Installation in MAC

Body:
You do it by updating the PATH variable.

export PATH=$HOME/.composer/vendor/bin:$PATH

However, this will not persist. If you close the terminal window, the PATH will be restored to its original value. You need to add this line to your ~/.bash_profile

Run this command to add the line to your ~/bash_profile

echo 'export PATH=$HOME/.composer/vendor/bin:$PATH' >> ~/.bash_profile

To verify that you have the correct path: echo $PATH, and you should see .composer/vendor/bin in the middle of the output

For spark specifically, you need to add the path to the location where you cloned the repo.

echo 'export PATH=path/to/spark/repo:$PATH' >> ~/.bash_profile

Here is a full list of commands to install Spark:

cd $HOME
git clone https://github.com/laravel/spark-installer.git
echo 'export PATH=$HOME/spark-installer:$PATH' >> ~/.bash_profile
source ~/.bash_profile
cd ~/spark-installer
composer install
spark


问:
List each sections vertically but show items inside it horizontal with SectionedRecyclerViewAdapter
What I want to show is something like in google play. I have many product category. so I need to show it vertically, but I want the user be able to scroll product inside each category horizontal(left & right) with 2 items.

I've followed this tutorial already https://github.com/luizgrp/SectionedRecyclerViewAdapter
I've change the layoutmanager to Horizontal with following code:

```<code>recyclerView.setLayoutManager(new LinearLayoutManager(getActivity(), LinearLayoutManager.HORIZONTAL, false));
</code>```

but it showed all sections and items horizonally.

what I want is something like the image below

Is it possible? Please help!!

答:
Psuedo Code:

Use Recycler View and set its layout to vertical

```<code>RecyclerView my_recycler_view = (RecyclerView) findViewById(R.id.my_recycler_view);
my_recycler_view.setHasFixedSize(true);
RecyclerViewDataAdapter adapter = new RecyclerViewDataAdapter(this, allSampleData);
my_recycler_view.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
</code>```

Inside Recycler Adapter inflate the layout and set another adapter to fill in data for that layout in onBindViewHolder.Also set that layout to horizontal.

```<code>  @Override
    public ItemRowHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
        View v = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.list_item, null);
        ItemRowHolder mh = new ItemRowHolder(v);
        return mh;
    }

    @Override
    public void onBindViewHolder(ItemRowHolder itemRowHolder, int i) {

        final String sectionName = dataList.get(i).getHeaderTitle();

        ArrayList singleSectionItems = dataList.get(i).getAllItemsInSection();

        itemRowHolder.itemTitle.setText(sectionName);

        SectionListDataAdapter itemListDataAdapter = new SectionListDataAdapter(mContext, singleSectionItems);

        itemRowHolder.recycler_view_list.setHasFixedSize(true);
        itemRowHolder.recycler_view_list.setLayoutManager(new LinearLayoutManager(mContext, LinearLayoutManager.HORIZONTAL, false));
        itemRowHolder.recycler_view_list.setAdapter(itemListDataAdapter);

        itemRowHolder.recycler_view_list.setNestedScrollingEnabled(false);
</code>```

This blog has more explanation and code.

The Download link for same code given on the blog.

Body:
What I want to show is something like in google play. I have many product category. so I need to show it vertically, but I want the user be able to scroll product inside each category horizontal(left & right) with 2 items.

I've followed this tutorial already https://github.com/luizgrp/SectionedRecyclerViewAdapter
I've change the layoutmanager to Horizontal with following code:

recyclerView.setLayoutManager(new LinearLayoutManager(getActivity(), LinearLayoutManager.HORIZONTAL, false));

but it showed all sections and items horizonally.

what I want is something like the image below

Is it possible? Please help!!

Body:
Psuedo Code:

Use Recycler View and set its layout to vertical

RecyclerView my_recycler_view = (RecyclerView) findViewById(R.id.my_recycler_view);
my_recycler_view.setHasFixedSize(true);
RecyclerViewDataAdapter adapter = new RecyclerViewDataAdapter(this, allSampleData);
my_recycler_view.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));

Inside Recycler Adapter inflate the layout and set another adapter to fill in data for that layout in onBindViewHolder.Also set that layout to horizontal.

  @Override
    public ItemRowHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
        View v = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.list_item, null);
        ItemRowHolder mh = new ItemRowHolder(v);
        return mh;
    }

    @Override
    public void onBindViewHolder(ItemRowHolder itemRowHolder, int i) {

        final String sectionName = dataList.get(i).getHeaderTitle();

        ArrayList singleSectionItems = dataList.get(i).getAllItemsInSection();

        itemRowHolder.itemTitle.setText(sectionName);

        SectionListDataAdapter itemListDataAdapter = new SectionListDataAdapter(mContext, singleSectionItems);

        itemRowHolder.recycler_view_list.setHasFixedSize(true);
        itemRowHolder.recycler_view_list.setLayoutManager(new LinearLayoutManager(mContext, LinearLayoutManager.HORIZONTAL, false));
        itemRowHolder.recycler_view_list.setAdapter(itemListDataAdapter);

        itemRowHolder.recycler_view_list.setNestedScrollingEnabled(false);

This blog has more explanation and code.

The Download link for same code given on the blog.


问:
How to get a vuetify data table to span the entire width of a container when it is inside a card?
I have a Vuetify data table that is nested inside a v-card so that I can enable an inline search on the data table, but this is causing it to shrink down and only take up a small amount of the overall container whereas it was filling the entire container when not nested in the v-card.

I have reproduced a minimal example of this on codepen at https://codepen.io/bigtunacan/project/editor/XGRpVL

The main area of concern though is here.

```<code>      <v-list-tile @click="">
        <v-list-tile-action>
          <v-icon>dashboard</v-icon>
        </v-list-tile-action>
        <v-list-tile-content>
          <v-list-tile-title>Dashboard</v-list-tile-title>
        </v-list-tile-content>
      </v-list-tile>

      <v-list-tile @click="">
        <v-list-tile-action>
          <v-icon>settings</v-icon>
        </v-list-tile-action>
        <v-list-tile-content>
          <v-list-tile-title>Settings</v-list-tile-title>
        </v-list-tile-content>
      </v-list-tile>

    </v-list>
  </v-navigation-drawer>

  <v-toolbar app fixed clipped-left>
    <v-toolbar-side-icon @click.stop="drawer = !drawer"></v-toolbar-side-icon>
    <v-toolbar-title>Candy Bars</v-toolbar-title>
  </v-toolbar>

  <v-content>
    <v-container fluid fill-height>

    <template>
      <v-card>
        <v-card-title>
          Routes
          <v-spacer></v-spacer>
          <v-text-field append-icon="search" label="Search" single-line hide-details v-model="search"></v-text-field>
        </v-card-title>
        <v-data-table v-bind:headers="headers" :items="routes" :search="search" hide-actions class="elevation-1">
          <template slot="items" slot-scope="props">
            <td><router-link :to="{ name: 'route', params: {id: props.item.id}}">{{ props.item.name }}</router-link></td>
            <td>{{ props.item.agency }}</td>
          </template>
        </v-data-table>
      </v-card>
    </template>

    </v-container>
  </v-content>

  <v-footer app fixed>
    <span>© 2017</span>
  </v-footer>

</v-app>
</code>```

答:
Instead of the <template>, wrap the card in a <v-layout child-flex> like so:

```<code>...
<v-content>
  <v-container fluid fill-height>

    <v-layout child-flex>
      <v-card>
        <v-card-title>
          ...
</code>```

child-flex is a class that gives its children (in this case just the card) the css rule flex: 1 1 auto, making them grow to fill available space.

Body:
I have a Vuetify data table that is nested inside a v-card so that I can enable an inline search on the data table, but this is causing it to shrink down and only take up a small amount of the overall container whereas it was filling the entire container when not nested in the v-card.

I have reproduced a minimal example of this on codepen at https://codepen.io/bigtunacan/project/editor/XGRpVL

The main area of concern though is here.

      <v-list-tile @click="">
        <v-list-tile-action>
          <v-icon>dashboard</v-icon>
        </v-list-tile-action>
        <v-list-tile-content>
          <v-list-tile-title>Dashboard</v-list-tile-title>
        </v-list-tile-content>
      </v-list-tile>

      <v-list-tile @click="">
        <v-list-tile-action>
          <v-icon>settings</v-icon>
        </v-list-tile-action>
        <v-list-tile-content>
          <v-list-tile-title>Settings</v-list-tile-title>
        </v-list-tile-content>
      </v-list-tile>

    </v-list>
  </v-navigation-drawer>

  <v-toolbar app fixed clipped-left>
    <v-toolbar-side-icon @click.stop="drawer = !drawer"></v-toolbar-side-icon>
    <v-toolbar-title>Candy Bars</v-toolbar-title>
  </v-toolbar>

  <v-content>
    <v-container fluid fill-height>

    <template>
      <v-card>
        <v-card-title>
          Routes
          <v-spacer></v-spacer>
          <v-text-field append-icon="search" label="Search" single-line hide-details v-model="search"></v-text-field>
        </v-card-title>
        <v-data-table v-bind:headers="headers" :items="routes" :search="search" hide-actions class="elevation-1">
          <template slot="items" slot-scope="props">
            <router-link :to="{ name: 'route', params: {id: props.item.id}}">{{ props.item.name }}</router-link>
            {{ props.item.agency }}
          </template>
        </v-data-table>
      </v-card>
    </template>

    </v-container>
  </v-content>

  <v-footer app fixed>
    © 2017
  </v-footer>

</v-app>

Body:
Instead of the <template>, wrap the card in a <v-layout child-flex> like so:

...
<v-content>
  <v-container fluid fill-height>

    <v-layout child-flex>
      <v-card>
        <v-card-title>
          ...

child-flex is a class that gives its children (in this case just the card) the css rule flex: 1 1 auto, making them grow to fill available space.

ContentLicense: CC BY-SA 4.0


问:
powershell script to delete old backup files more than 6 months old
I'm deleting files manually on my system which are more than 6 months old, want to automate the process, is it possible via powershell? Pretty new to it!

I want to delete files more than 6 months old.
Any help would be much invited!

答:
So Vivek Kumar his line will work, but there is one important note, that why i'm posting it as an answer and not as a comment.

This will work but be careful, if you cut/paste an old file, the creationdate will be pasted as well. So say you cut and paste a file that has been on your harddrive for 2 years, your script will delete it on your first run (and not after your period of six months). If you COPY/paste it, then the creationdate will be the date on which you copy it.


问:
Maven site migration - how to handle it?
Maven sites can discover Maven sites from dependencies using the <url> from the respective pom. These urls are usually hard-coded in the pom or one of its parent poms.

At the moment, we use the Nexus 2.14 site urls which have a path like

```<code>http://somerepo:8081/nexus/...
</code>```

When we migrate to Nexus 3 or Artifactory, these urls will change, meaning that all links between sites of our artifacts will break.

How can we avoid this?

答:
From sonatype help

Finalize migration in Nexus Repository Manager 3

Shutdown Nexus Repository Manager 2

Shutdown Nexus Repository Manager 3

Reconfigure it to run on the original port and context of Nexus
  Repository Manager 2, for example port 8081 and /nexus context.

Start Nexus Repository Manager 3

Congratulations – you are done. Depending on your specific setup e.g.
  usage of an external reverse proxy server around the repository
  manager the detailed config steps will vary a little bit, but the
  general approach is the same.

All external settings.xml, .npmrc and similar config files using
  repository URLs will continue to work in Nexus Repository 3, so you
  wont have to reconfigure any client tools.

That mean that If you configure Nexus 3 correctly, your URLs will be the same and you don't need to change your poms.

Body:
Maven sites can discover Maven sites from dependencies using the <url> from the respective pom. These urls are usually hard-coded in the pom or one of its parent poms.

At the moment, we use the Nexus 2.14 site urls which have a path like

http://somerepo:8081/nexus/...

When we migrate to Nexus 3 or Artifactory, these urls will change, meaning that all links between sites of our artifacts will break.

How can we avoid this?


问:
Shorthand method to count length of array
I have an array like this

```<code>var arr = [{a:1, ...},{a:1, ...},{c:2, ...},{a:3, ...},{a:1, ...}]
</code>```

how can I get the length of array where arr[x].a != 1 .

I know this can be done using for loop and push but I want to follow the best practise as every decent programmer should do.

P.S FYI I am using AngularJS.

EDIT 1
For anyone facing issues with arrow function in sajeetharan's answer because of ES6 script here is the solution

```<code>arr.filter(function(a){return a.a != 1}).length;
</code>```

答:
The most memory efficient way for this is:

```<code>const result = arr.reduce((count,el)=> count+ (el.a!==1)},0)
</code>```

filter creates a complete new array, reduce only creates a new var.
And both of them iterates over the array once.

Body:
I have an array like this

var arr = [{a:1, ...},{a:1, ...},{c:2, ...},{a:3, ...},{a:1, ...}]

how can I get the length of array where arr[x].a != 1 .

I know this can be done using for loop and push but I want to follow the best practise as every decent programmer should do.

P.S FYI I am using AngularJS.

EDIT 1
For anyone facing issues with arrow function in sajeetharan's answer because of ES6 script here is the solution

arr.filter(function(a){return a.a != 1}).length;

Body:
The most memory efficient way for this is:

const result = arr.reduce((count,el)=> count+ (el.a!==1)},0)

filter creates a complete new array, reduce only creates a new var.
And both of them iterates over the array once.


问:
Hibernate 5.2 encrypt configuration properties
In my application build on Hibernate 5.2.11 there are many hibernate configuration file with username, password and connection url.
I would like to encrypt that data.

My configuration file is like this:

```<code><hibernate-configuration>

<session-factory>

    <!-- Database connection settings -->
    <property name="connection.driver_class">oracle.jdbc.driver.OracleDriver</property>

    <property name="connection.url">jdbc:oracle:localhos</property>
    <property name="connection.username">username</property>
    <property name="connection.password">passowrd123</property>

    <!-- JDBC connection pool (use the built-in) -->
    <property name="connection.pool_size">2</property>

    <!-- SQL dialect -->
    <property name="dialect">org.hibernate.dialect.Oracle12cDialect</property>
    <!-- Disable the second-level cache -->
    <property name="cache.provider_class">org.hibernate.cache.internal.NoCacheProvider</property>
    <!-- Echo all executed SQL to stdout -->
    <property name="show_sql">false</property>

</session-factory>

</hibernate-configuration>
</code>```

Any suggestion?

答:
Generally - encrypting/hiding anything what resides on the client's side (workstation/mobile/..) you can consider more like obfuscation or encoding.

In theory - you may set the Hibernate properties programatically (see Setting properties programmatically in Hibernate) reading your data from an encrypted file.

The problem is - where do you put your encryption keys? The keys has to be available to the application anyway somewhere.

Body:
In my application build on Hibernate 5.2.11 there are many hibernate configuration file with username, password and connection url.
I would like to encrypt that data.

My configuration file is like this:

<hibernate-configuration>

<session-factory>

    <property name="connection.driver_class">oracle.jdbc.driver.OracleDriver</property>

    <property name="connection.url">jdbc:oracle:localhos</property>
    <property name="connection.username">username</property>
    <property name="connection.password">passowrd123</property>

    <property name="connection.pool_size">2</property>

    <property name="dialect">org.hibernate.dialect.Oracle12cDialect</property>

    <property name="cache.provider_class">org.hibernate.cache.internal.NoCacheProvider</property>

    <property name="show_sql">false</property>

</session-factory>

</hibernate-configuration>

Any suggestion?


问:
tensorflow: check if a scalar boolean tensor is True
I want to control the execution of a function using a placeholder, but keep getting an error "Using a tf.Tensor as a Python bool is not allowed". Here is the code that produces this error:

```<code>import tensorflow as tf
def foo(c):
  if c:
    print('This is true')
    #heavy code here
    return 10
  else:
    print('This is false')
    #different code here
    return 0

a = tf.placeholder(tf.bool)  #placeholder for a single boolean value
b = foo(a)
sess = tf.InteractiveSession()
res = sess.run(b, feed_dict = {a: True})
sess.close()
</code>```

I changed if c to if c is not None without luck. How can I control foo by turning on and off the placeholder a then?

Update: as @nessuno and @nemo point out, we must use tf.cond instead of if..else. The answer to my question is to re-design my function like this:

```<code>import tensorflow as tf
def foo(c):
  return tf.cond(c, func1, func2)

a = tf.placeholder(tf.bool)  #placeholder for a single boolean value
b = foo(a)
sess = tf.InteractiveSession()
res = sess.run(b, feed_dict = {a: True})
sess.close()
</code>```

答:
A simpler way to tackle it: </p>

```<code>In [50]: a = tf.placeholder(tf.bool)

In [51]: is_true = tf.count_nonzero([a])

In [52]: sess.run(is_true, {a: True})
Out[52]: 1

In [53]: sess.run(is_true, {a: False})
Out[53]: 0
</code>```

Body:
I want to control the execution of a function using a placeholder, but keep getting an error "Using a tf.Tensor as a Python bool is not allowed". Here is the code that produces this error:

import tensorflow as tf
def foo(c):
  if c:
    print('This is true')
    #heavy code here
    return 10
  else:
    print('This is false')
    #different code here
    return 0

a = tf.placeholder(tf.bool)  #placeholder for a single boolean value
b = foo(a)
sess = tf.InteractiveSession()
res = sess.run(b, feed_dict = {a: True})
sess.close()

I changed if c to if c is not None without luck. How can I control foo by turning on and off the placeholder a then?

Update: as @nessuno and @nemo point out, we must use tf.cond instead of if..else. The answer to my question is to re-design my function like this:

import tensorflow as tf
def foo(c):
  return tf.cond(c, func1, func2)

a = tf.placeholder(tf.bool)  #placeholder for a single boolean value
b = foo(a)
sess = tf.InteractiveSession()
res = sess.run(b, feed_dict = {a: True})
sess.close()

Body:
A simpler way to tackle it:

In [50]: a = tf.placeholder(tf.bool)

In [51]: is_true = tf.count_nonzero([a])

In [52]: sess.run(is_true, {a: True})
Out[52]: 1

In [53]: sess.run(is_true, {a: False})
Out[53]: 0


问:
UISplitViewController with iOS 11 large titles broken animation
When using the UISplitViewController in navigating from Master to Detail the navigation bar animation does not work as expected. It "jumps" up instead of a smooth animation.

Steps to Reproduce:
Create project from template "Master detail App" in Xcode 9.
Add the following code into MasterViewController in viewDidLoad:

```<code>navigationController?.navigationBar.prefersLargeTitles = true
navigationItem.largeTitleDisplayMode = .always
</code>```

Add the following code in DetailViewController in viewDidLoad:

```<code>navigationItem.largeTitleDisplayMode = .never
</code>```

Now navigate between Master and Detail in the iPhone simulator and you can see how the Navigation Bar "jumps" up on the DetailViewController instead of a smooth animation.

See video:  https://youtu.be/p90I4VrM2fs

My assumption is that it has something to do with using two UINavigationController with the UISplitViewController. (which is how it is done)

Any ideas how to resolve this? Thanks.

答: I just found out the problem. prefersLargeTitles and largeTitleDisplayMode have to be set in awakeFromNib(), not in viewDidLoad().

Body:
When using the UISplitViewController in navigating from Master to Detail the navigation bar animation does not work as expected. It "jumps" up instead of a smooth animation.

Steps to Reproduce:
Create project from template "Master detail App" in Xcode 9.
Add the following code into MasterViewController in viewDidLoad:

navigationController?.navigationBar.prefersLargeTitles = true
navigationItem.largeTitleDisplayMode = .always

Add the following code in DetailViewController in viewDidLoad:

navigationItem.largeTitleDisplayMode = .never

Now navigate between Master and Detail in the iPhone simulator and you can see how the Navigation Bar "jumps" up on the DetailViewController instead of a smooth animation.

See video:  https://youtu.be/p90I4VrM2fs

My assumption is that it has something to do with using two UINavigationController with the UISplitViewController. (which is how it is done)

Any ideas how to resolve this? Thanks.


问:
Owl carousel "items" not working on 1900 + pixels
I have this code. It's ok to 1899px, but big than 1900px, the items option not working.

```<code>jQuery(document).ready(function () {
    $(".owl-case").owlCarousel({
        autoPlay: 3000,
        items: 3, // THIS IS IMPORTANT
        responsiveClass:true
    });
});
</code>```

First image on 1899px:

Second image on 1900px

Thank for answers!

答:
You are missing loop: true,

```<code>jQuery(document).ready(function () {
    $(".owl-case").owlCarousel({
        autoPlay: 3000,
        items: 3, // THIS IS IMPORTANT
        loop: true,
        responsiveClass:true
    });
});
</code>```

As in my case it is working...

or may be it's the jquery library.

I am using jquery-2.1.4.min.js.

Body:
I have this code. It's ok to 1899px, but big than 1900px, the items option not working.

jQuery(document).ready(function () {
    $(".owl-case").owlCarousel({
        autoPlay: 3000,
        items: 3, // THIS IS IMPORTANT
        responsiveClass:true
    });
});

First image on 1899px:

Second image on 1900px

Thank for answers!

Body:
You are missing loop: true,

jQuery(document).ready(function () {
    $(".owl-case").owlCarousel({
        autoPlay: 3000,
        items: 3, // THIS IS IMPORTANT
        loop: true,
        responsiveClass:true
    });
});

As in my case it is working...

or may be it's the jquery library.

I am using jquery-2.1.4.min.js.


问:
Import CSV file to postgresql
I want to import large csv file its around 1GB of size using copy command.
But the condition is if lets see Column A1  datatype is Numeric and the data of the csv file is also of type numeric but some of the values are in alpha numeric. so its not importing .
What i want is set the non-numeric value of the colum A1 to null and import the data.
All the condition i want in the copy command .
Sample of csv file.

A1
A2
A3

90
91
92

A21
B23
C43

12
13
14

12ddwd3
1yhh53
1dfsf754

12
13
14

```

Table meta data will be A1 numeric,A2 numeric,A3 numeric
I want to import csv file into the table and non numeric value will set to Null.

答:
you cant conditionnaly COPY table from file. what you can do instead:

```<code>create table t (a1 text, a2 text, a3 text);
COPY t from file;
update t set a1 = null where a1 !~ '^\d{1,}$';
alter table t alter column a1 type int using a1::int;
</code>```

Title: Import CSV file to postgresql

Body:
I want to import large csv file its around 1GB of size using copy command.
But the condition is if lets see Column A1  datatype is Numeric and the data of the csv file is also of type numeric but some of the values are in alpha numeric. so its not importing .
What i want is set the non-numeric value of the colum A1 to null and import the data.
All the condition i want in the copy command .
Sample of csv file.

A1
A2
A3

90
91
92

A21
B23
C43

12
13
14

12ddwd3
1yhh53
1dfsf754

12
13
14

Table meta data will be A1 numeric,A2 numeric,A3 numeric
I want to import csv file into the table and non numeric value will set to Null.

Body:
you cant conditionnaly COPY table from file. what you can do instead:

create table t (a1 text, a2 text, a3 text);
COPY t from file;
update t set a1 = null where a1 !~ '^\d{1,}$';
alter table t alter column a1 type int using a1::int;


问:
Xamarin iOS app crashes when I try to access restored CoreBluetooth peripherals
I have a Xamarin Cross-Platform app that uses the bluetooth-central background mode on the iOS side to keep a connection to a bluetooth-to-serial dongle alive. Everything is working well, except I am trying to implement the CBCentralManagerDelegate.WillRestoreState method (see iOS Doc, and the useless Xamarin Doc for details).

From the iOS doc, I can see that the second argument has an element that contains restored peripherals in the CBCentralManager.RestoredStatePeripheralsKey, and that the element is an NSArray of CBPeripherals. So, I've written this method in my class that overrides CBCentralManagerDelegate:

```<code>// Handle state restoration if OS restores CoreBluetooth peripherals
public override void WillRestoreState(CBCentralManager central, NSDictionary state)
{
    NSObject restoredPeripherals = new NSObject();

    if (state.TryGetValue(CBCentralManager.RestoredStatePeripheralsKey, out restoredPeripherals))
    {
        Logger.Debug("Restoring CoreBluetooth Peripherals...");
        NSArray<CBPeripheral> peripherals = restoredPeripherals as NSArray<CBPeripheral>;
        foreach (CBPeripheral peripheral in peripherals)
        {
            Logger.Debug("Loading preexisting peripherals");
            discoveredPeripherals.Add(peripheral.Name, peripheral);
        }
    }

    base.WillRestoreState(central, state);
}
</code>```

The problem is with the line that says: NSArray<CBPeripheral> peripherals = restoredPeripherals as NSArray<CBPeripheral>;

This line leads to a crash. In the extremely rare case that I'm able to catch this in the debugger (it's hard to keep the debugger connected while reproducing this), it says something about this line being an invalid cast.

Here's the log I get from the iPad:

```<code>Nov 15 14:22:58 iPad-Mini Warning 520 MyApp    [Debug]   Restoring CoreBluetooth Peripherals... (
Nov 15 14:22:58 iPad-Mini Warning 520 MyApp
Nov 15 14:22:59 iPad-Mini Warning 520 MyApp    critical:   15  MyApp                    0x00083733 -[Messenger_iOS_TruConnectBLEFactory_ManagerDelegate centralManager:willRestoreState:] + 60
Nov 15 14:22:59 iPad-Mini Warning 520 MyApp    critical:
Nov 15 14:22:59 iPad-Mini Warning 520 MyApp    critical:   21  libdispatch.dylib                   0x20df3b93 <redacted> + 182
Nov 15 14:22:59 iPad-Mini Warning 520 MyApp    critical:   13  libmonosgen-2.0.dylib               0x08d4ff6b mono_runtime_invoke + 138
Nov 15 14:22:59 iPad-Mini Warning 520 MyApp    critical:   4   libxamarin-debug.dylib              0x08fa2360 xamarin_printf + 0
Nov 15 14:22:59 iPad-Mini Warning 520 MyApp    critical:   24  libsystem_pthread.dylib             0x20fadb29 _pthread_wqthread + 1024
Nov 15 14:22:59 iPad-Mini Warning 520 MyApp    critical:   1   libsystem_platform.dylib            0x20faa077 _sigtramp + 42
Nov 15 14:22:59 iPad-Mini Warning 520 MyApp    critical:   2   libsystem_pthread.dylib             0x20fb0733 pthread_kill + 62
Nov 15 14:22:59 iPad-Mini Warning 520 MyApp    critical:   19  libdispatch.dylib                   0x20df6423 <redacted> + 1758
Nov 15 14:22:59 iPad-Mini Warning 520 MyApp    critical:   8   libmonosgen-2.0.dylib               0x08cde29f handle_signal_exception + 42
Nov 15 14:22:59 iPad-Mini Warning 520 MyApp    critical:   12  libmonosgen-2.0.dylib               0x08d4ffd5 do_runtime_invoke + 78
Nov 15 14:22:59 iPad-Mini Warning 520 MyApp    critical:   14  MyApp                    0x0008393b _ZL31native_to_managed_trampoline_55P11objc_objectP13objc_selectorPP11_MonoMethodP16CBCentralManagerP12NSDictionaryj + 516
Nov 15 14:22:59 iPad-Mini Warning 520 MyApp    critical:   16  CoreBluetooth                       0x2637abe3 <redacted> + 2486
Nov 15 14:22:59 iPad-Mini Warning 520 MyApp    critical:
Nov 15 14:22:59 iPad-Mini Warning 520 MyApp    critical:   22  libdispatch.dylib                   0x20df85e9 <redacted> + 1560
Nov 15 14:22:59 iPad-Mini Warning 520 MyApp    critical:   9   ???                                 0x00000000 0x0 + 0
Nov 15 14:22:59 iPad-Mini Warning 520 MyApp    critical:   6   libmonosgen-2.0.dylib               0x08ce6235 mono_handle_exception_internal + 3162
Nov 15 14:22:59 iPad-Mini Warning 520 MyApp    critical:   11  libmonosgen-2.0.dylib               0x08cf10f5 mono_jit_runtime_invoke + 712
Nov 15 14:22:59 iPad-Mini Warning 520 MyApp    Unhandled managed exception:
Nov 15 14:22:59 iPad-Mini Warning 520 MyApp    critical:   25  libsystem_pthread.dylib             0x20fad718 start_wqthread + 8
Nov 15 14:22:59 iPad-Mini Warning 520 MyApp    critical:   7   libmonosgen-2.0.dylib               0x08ce55d7 mono_handle_exception + 30
Nov 15 14:22:59 iPad-Mini Warning 520 MyApp    critical:   5   libmonosgen-2.0.dylib               0x08d1d7cd mono_invoke_unhandled_exception_hook + 100
Nov 15 14:22:59 iPad-Mini Warning 520 MyApp    critical:   18  libdispatch.dylib                   0x20de9823 <redacted> + 10
Nov 15 14:22:59 iPad-Mini Warning 520 MyApp    critical:   3   libsystem_c.dylib                   0x20e9b0ad abort + 108
Nov 15 14:22:59 iPad-Mini Warning 520 MyApp    critical:   17  CoreBluetooth                       0x263869f3 <redacted> + 62
Nov 15 14:22:59 iPad-Mini Warning 520 MyApp    critical:   10  libmscorlib.dll.dylib               0x00d49520 wrapper_runtime_invoke_object_runtime_invoke_dynamic_intptr_intptr_intptr_intptr + 256
Nov 15 14:22:59 iPad-Mini Warning 520 MyApp    critical:   0   libmonosgen-2.0.dylib               0x08ce6637 mono_handle_native_crash + 196
Nov 15 14:22:59 iPad-Mini Warning 520 MyApp    critical: Stacktrace:
Nov 15 14:22:59 iPad-Mini Warning 520 MyApp    critical:   23  libdispatch.dylib                   0x20df7fcd <redacted> + 96
Nov 15 14:22:59 iPad-Mini Warning 520 MyApp    critical:   20  libdispatch.dylib                   0x20df5a61 <redacted> + 284
</code>```

Does anyone have ideas about why this is crashing? Also, if anyone has examples of implementing this method with Xamarin, please share the link. I haven't been able find any. :(

答:
I guess it should be to converted to NSArray instead of NSArray<CBPeripheral>.

Try the following:

```<code>NSArray peripherals = (NSArray) restoredPeripherals;
for (nuint i = 0; i < peripherals.Count; i++)
{
    CBPeripheral peripheral = peripherals.GetItem<CBPeripheral>(i);

    Logger.Debug("Loading preexisting peripherals");
    discoveredPeripherals.Add(peripheral.Name, peripheral);
}
</code>```

Body:
I have a Xamarin Cross-Platform app that uses the bluetooth-central background mode on the iOS side to keep a connection to a bluetooth-to-serial dongle alive. Everything is working well, except I am trying to implement the CBCentralManagerDelegate.WillRestoreState method (see iOS Doc, and the useless Xamarin Doc for details).

From the iOS doc, I can see that the second argument has an element that contains restored peripherals in the CBCentralManager.RestoredStatePeripheralsKey, and that the element is an NSArray of CBPeripherals. So, I've written this method in my class that overrides CBCentralManagerDelegate:

// Handle state restoration if OS restores CoreBluetooth peripherals
public override void WillRestoreState(CBCentralManager central, NSDictionary state)
{
    NSObject restoredPeripherals = new NSObject();

    if (state.TryGetValue(CBCentralManager.RestoredStatePeripheralsKey, out restoredPeripherals))
    {
        Logger.Debug("Restoring CoreBluetooth Peripherals...");
        NSArray<CBPeripheral> peripherals = restoredPeripherals as NSArray<CBPeripheral>;
        foreach (CBPeripheral peripheral in peripherals)
        {
            Logger.Debug("Loading preexisting peripherals");
            discoveredPeripherals.Add(peripheral.Name, peripheral);
        }
    }

    base.WillRestoreState(central, state);
}

The problem is with the line that says: NSArray<CBPeripheral> peripherals = restoredPeripherals as NSArray<CBPeripheral>;

This line leads to a crash. In the extremely rare case that I'm able to catch this in the debugger (it's hard to keep the debugger connected while reproducing this), it says something about this line being an invalid cast.

Here's the log I get from the iPad:

Nov 15 14:22:58 iPad-Mini Warning 520 MyApp    [Debug]   Restoring CoreBluetooth Peripherals... (
Nov 15 14:22:58 iPad-Mini Warning 520 MyApp
Nov 15 14:22:59 iPad-Mini Warning 520 MyApp    critical:   15  MyApp                    0x00083733 -[Messenger_iOS_TruConnectBLEFactory_ManagerDelegate centralManager:willRestoreState:] + 60
Nov 15 14:22:59 iPad-Mini Warning 520 MyApp    critical:
Nov 15 14:22:59 iPad-Mini Warning 520 MyApp    critical:   21  libdispatch.dylib                   0x20df3b93 <redacted> + 182
Nov 15 14:22:59 iPad-Mini Warning 520 MyApp    critical:   13  libmonosgen-2.0.dylib               0x08d4ff6b mono_runtime_invoke + 138
Nov 15 14:22:59 iPad-Mini Warning 520 MyApp    critical:   4   libxamarin-debug.dylib              0x08fa2360 xamarin_printf + 0
Nov 15 14:22:59 iPad-Mini Warning 520 MyApp    critical:   24  libsystem_pthread.dylib             0x20fadb29 _pthread_wqthread + 1024
Nov 15 14:22:59 iPad-Mini Warning 520 MyApp    critical:   1   libsystem_platform.dylib            0x20faa077 _sigtramp + 42
Nov 15 14:22:59 iPad-Mini Warning 520 MyApp    critical:   2   libsystem_pthread.dylib             0x20fb0733 pthread_kill + 62
Nov 15 14:22:59 iPad-Mini Warning 520 MyApp    critical:   19  libdispatch.dylib                   0x20df6423 <redacted> + 1758
Nov 15 14:22:59 iPad-Mini Warning 520 MyApp    critical:   8   libmonosgen-2.0.dylib               0x08cde29f handle_signal_exception + 42
Nov 15 14:22:59 iPad-Mini Warning 520 MyApp    critical:   12  libmonosgen-2.0.dylib               0x08d4ffd5 do_runtime_invoke + 78
Nov 15 14:22:59 iPad-Mini Warning 520 MyApp    critical:   14  MyApp                    0x0008393b _ZL31native_to_managed_trampoline_55P11objc_objectP13objc_selectorPP11_MonoMethodP16CBCentralManagerP12NSDictionaryj + 516
Nov 15 14:22:59 iPad-Mini Warning 520 MyApp    critical:   16  CoreBluetooth                       0x2637abe3 <redacted> + 2486
Nov 15 14:22:59 iPad-Mini Warning 520 MyApp    critical:
Nov 15 14:22:59 iPad-Mini Warning 520 MyApp    critical:   22  libdispatch.dylib                   0x20df85e9 <redacted> + 1560
Nov 15 14:22:59 iPad-Mini Warning 520 MyApp    critical:   9   ???                                 0x00000000 0x0 + 0
Nov 15 14:22:59 iPad-Mini Warning 520 MyApp    critical:   6   libmonosgen-2.0.dylib               0x08ce6235 mono_handle_exception_internal + 3162
Nov 15 14:22:59 iPad-Mini Warning 520 MyApp    critical:   11  libmonosgen-2.0.dylib               0x08cf10f5 mono_jit_runtime_invoke + 712
Nov 15 14:22:59 iPad-Mini Warning 520 MyApp    Unhandled managed exception:
Nov 15 14:22:59 iPad-Mini Warning 520 MyApp    critical:   25  libsystem_pthread.dylib             0x20fad718 start_wqthread + 8
Nov 15 14:22:59 iPad-Mini Warning 520 MyApp    critical:   7   libmonosgen-2.0.dylib               0x08ce55d7 mono_handle_exception + 30
Nov 15 14:22:59 iPad-Mini Warning 520 MyApp    critical:   5   libmonosgen-2.0.dylib               0x08d1d7cd mono_invoke_unhandled_exception_hook + 100
Nov 15 14:22:59 iPad-Mini Warning 520 MyApp    critical:   18  libdispatch.dylib                   0x20de9823 <redacted> + 10
Nov 15 14:22:59 iPad-Mini Warning 520 MyApp    critical:   3   libsystem_c.dylib                   0x20e9b0ad abort + 108
Nov 15 14:22:59 iPad-Mini Warning 520 MyApp    critical:   17  CoreBluetooth                       0x263869f3 <redacted> + 62
Nov 15 14:22:59 iPad-Mini Warning 520 MyApp    critical:   10  libmscorlib.dll.dylib               0x00d49520 wrapper_runtime_invoke_object_runtime_invoke_dynamic_intptr_intptr_intptr_intptr + 256
Nov 15 14:22:59 iPad-Mini Warning 520 MyApp    critical:   0   libmonosgen-2.0.dylib               0x08ce6637 mono_handle_native_crash + 196
Nov 15 14:22:59 iPad-Mini Warning 520 MyApp    critical: Stacktrace:
Nov 15 14:22:59 iPad-Mini Warning 520 MyApp    critical:   23  libdispatch.dylib                   0x20df7fcd <redacted> + 96
Nov 15 14:22:59 iPad-Mini Warning 520 MyApp    critical:   20  libdispatch.dylib                   0x20df5a61 <redacted> + 284

Does anyone have ideas about why this is crashing? Also, if anyone has examples of implementing this method with Xamarin, please share the link. I haven't been able find any. :(

Body:
I guess it should be to converted to NSArray instead of NSArray<CBPeripheral>.

Try the following:

NSArray peripherals = (NSArray) restoredPeripherals;
for (nuint i = 0; i < peripherals.Count; i++)
{
    CBPeripheral peripheral = peripherals.GetItem<CBPeripheral>(i);

    Logger.Debug("Loading preexisting peripherals");
    discoveredPeripherals.Add(peripheral.Name, peripheral);
}