答:
Your example DataFrame, ensuring the index is a datetime  dtype

```<code>#imports excluded
d = {'mean':{'1901-01-31': 0.60847, '1901-02-28': 0.75183, '1901-03-31': 0.05098,
             '1901-04-30': 0.22906, '1901-05-31': 0.24698, '1901-11-30': 0.93659,
             '1901-12-31': 0.08592, '1902-07-31': 0.7869, '1902-08-31': 0.77402,
             '1902-12-31': 0.60236, '1903-01-31': 0.8055, '1903-02-28': 0.6045,
             '1903-03-31': 0.99139, '1903-04-30': 0.77478, '1903-05-31': 0.88022,
             '1903-06-30': 0.73554},
     'count': {'1901-01-31': 3, '1901-02-28': 6, '1901-03-31': 6, '1901-04-30': 2,
               '1901-05-31': 4, '1901-11-30': 8, '1901-12-31': 1, '1902-07-31': 0,
               '1902-08-31': 9, '1902-12-31': 6, '1903-01-31': 4, '1903-02-28': 7,
               '1903-03-31': 2, '1903-04-30': 1, '1903-05-31': 9, '1903-06-30': 1}}

df = pd.DataFrame(d)
df.index = pd.to_datetime(df.index)
#df = df.set_index(pd.to_datetime(df.index))
</code>```

Axes.annotate's xy argument expects a tuple of two floats. After grouping by year and month; iterating over the rows  produces a ((year,month),float) tuple because of the multi-index - annotate doesn't like that.

I haven't figured out how to make your groupby solution work - I think it would involve translating/transforming the (year,month) tuple into a coordinate the plot/axes understands or specifying an x coordinate system that can use that tuple.

Resampling by month, plotting and annotating works

```<code>data = df.resample('M').mean()
# or maybe it should be
#data = df.resample('M').agg({'mean':'mean','count':'sum'})

ax = data['mean'].plot()

for x,y,count in zip(data.index,data['mean'],data['count']):
    ax.annotate(f'{count:.0f}',xy=(x,y), ha='center',clip_on=True)

# or
for (x,(y,count)) in data.iterrows():
    ax.annotate(f'{count:.0f}',xy=(x,y), ha='center',clip_on=True)

plt.show()
plt.close()
</code>```

There were missing months in the example DataFrame so this plot has discontinuities.

Title: TypeError: float() argument must be a string or a number, not 'tuple' with annotate and iterrows

Body:
I want to plot the mean based on month/year

here is a sample of my data and date as index

               mean   count
date
1901-01-31  0.608475    3
1901-02-28  0.751826    6
1901-03-31  0.050980    6
1901-04-30  0.229060    2
1901-05-31  0.246976    4
1901-11-30  0.936585    8
1901-12-31  0.085918    1
1902-07-31  0.786897    0
1902-08-31  0.774024    9
1902-12-31  0.602361    6
1903-01-31  0.805497    4
1903-02-28  0.604498    7
1903-03-31  0.991389    2
1903-04-30  0.774783    1
1903-05-31  0.880222    9
1903-06-30  0.735544    1

so I wrote this code to groupby by month/year

data=df.groupby([df.index.year.rename('year'),df.index.month.rename('month')]).mean()

and here is a sample of data after group by

               mean   count
date    date
1901    1   0.468082    7
        2   0.378744    8
        3   0.668791    3
        4   0.563842    7
        5   0.764414    2
        6   0.530849    3
        7   0.703855    7
        8   0.604860    9
        9   0.766420    0
       10   0.752520    8
       11   0.361177    3
       12   0.502622    1
1902    1   0.694125    0
        2   0.661784    0
        3   0.491230    2
        4   0.074626    7
        5   0.291552    4
        6   0.376639    6
        7   0.681985    8
        8   0.381116    6
        9   0.895843    3
       10   0.378515    8
       11   0.803789    8
       12   0.616002    7
   1903 1   0.372718    4
        2   0.992567    9
        3   0.746151    9
        4   0.970088    7
        5   0.053416    1
        6   0.959746    4
        7   0.604006    0
        8   0.894918    0
        9   0.716278    3
       10   0.420532    6
       11   0.161469    7

then I have plot

import matplotlib.pyplot as plt
plt.figure()
ax = data['mean'].plot(figsize=(20,10),linewidth=0.8)
for d,row in data.iterrows():
    ax.annotate('{:.0f}'.format(row['count']), xy=(d,row['mean']), ha='center',clip_on=True)

but I got this error

Error in callback <function install_repl_displayhook.<locals>.post_execute at 0x00000250AD5FDD08> (for post_execute):
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
~\Anaconda3\lib\site-packages\matplotlib\pyplot.py in post_execute()
    107             def post_execute():
    108                 if matplotlib.is_interactive():
--> 109                     draw_all()
    110
    111             # IPython >= 2

~\Anaconda3\lib\site-packages\matplotlib\_pylab_helpers.py in draw_all(cls, force)
    126         for f_mgr in cls.get_all_fig_managers():
    127             if force or f_mgr.canvas.figure.stale:
--> 128                 f_mgr.canvas.draw_idle()
    129
    130 atexit.register(Gcf.destroy_all)

~\Anaconda3\lib\site-packages\matplotlib\backend_bases.py in draw_idle(self, *args, **kwargs)
   1905         if not self._is_idle_drawing:
   1906             with self._idle_draw_cntx():
-> 1907                 self.draw(*args, **kwargs)
   1908
   1909     def draw_cursor(self, event):

~\Anaconda3\lib\site-packages\matplotlib\backends\backend_agg.py in draw(self)
    386         self.renderer = self.get_renderer(cleared=True)
    387         with RendererAgg.lock:
--> 388             self.figure.draw(self.renderer)
    389             # A GUI class may be need to update a window using this draw, so
    390             # don't forget to call the superclass.

~\Anaconda3\lib\site-packages\matplotlib\artist.py in draw_wrapper(artist, renderer, *args, **kwargs)
     36                 renderer.start_filter()
     37
---> 38             return draw(artist, renderer, *args, **kwargs)
     39         finally:
     40             if artist.get_agg_filter() is not None:

~\Anaconda3\lib\site-packages\matplotlib\figure.py in draw(self, renderer)
   1707             self.patch.draw(renderer)
   1708             mimage._draw_list_compositing_images(
-> 1709                 renderer, self, artists, self.suppressComposite)
   1710
   1711             renderer.close_group('figure')

~\Anaconda3\lib\site-packages\matplotlib\image.py in _draw_list_compositing_images(renderer, parent, artists, suppress_composite)
    133     if not_composite or not has_images:
    134         for a in artists:
--> 135             a.draw(renderer)
    136     else:
    137         # Composite any adjacent images together

~\Anaconda3\lib\site-packages\matplotlib\artist.py in draw_wrapper(artist, renderer, *args, **kwargs)
     36                 renderer.start_filter()
     37
---> 38             return draw(artist, renderer, *args, **kwargs)
     39         finally:
     40             if artist.get_agg_filter() is not None:

~\Anaconda3\lib\site-packages\matplotlib\axes\_base.py in draw(self, renderer, inframe)
   2643             renderer.stop_rasterizing()
   2644
-> 2645         mimage._draw_list_compositing_images(renderer, self, artists)
   2646
   2647         renderer.close_group('axes')

~\Anaconda3\lib\site-packages\matplotlib\image.py in _draw_list_compositing_images(renderer, parent, artists, suppress_composite)
    133     if not_composite or not has_images:
    134         for a in artists:
--> 135             a.draw(renderer)
    136     else:
    137         # Composite any adjacent images together

~\Anaconda3\lib\site-packages\matplotlib\artist.py in draw_wrapper(artist, renderer, *args, **kwargs)
     36                 renderer.start_filter()
     37
---> 38             return draw(artist, renderer, *args, **kwargs)
     39         finally:
     40             if artist.get_agg_filter() is not None:

~\Anaconda3\lib\site-packages\matplotlib\text.py in draw(self, renderer)
   2353             return
   2354
-> 2355         xy_pixel = self._get_position_xy(renderer)
   2356         if not self._check_xy(renderer, xy_pixel):
   2357             return

~\Anaconda3\lib\site-packages\matplotlib\text.py in _get_position_xy(self, renderer)
   1903         "Return the pixel position of the annotated point."
   1904         x, y = self.xy
-> 1905         return self._get_xy(renderer, x, y, self.xycoords)
   1906
   1907     def _check_xy(self, renderer, xy_pixel):

~\Anaconda3\lib\site-packages\matplotlib\text.py in _get_xy(self, renderer, x, y, s)
   1757
   1758         if s1 == 'data':
-> 1759             x = float(self.convert_xunits(x))
   1760         if s2 == 'data':
   1761             y = float(self.convert_yunits(y))

TypeError: float() argument must be a string or a number, not 'tuple'

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
~\Anaconda3\lib\site-packages\IPython\core\formatters.py in __call__(self, obj)
    339                 pass
    340             else:
--> 341                 return printer(obj)
    342             # Finally look for special method names
    343             method = get_real_method(obj, self.print_method)

~\Anaconda3\lib\site-packages\IPython\core\pylabtools.py in <lambda>(fig)
    242
    243     if 'png' in formats:
--> 244         png_formatter.for_type(Figure, lambda fig: print_figure(fig, 'png', **kwargs))
    245     if 'retina' in formats or 'png2x' in formats:
    246         png_formatter.for_type(Figure, lambda fig: retina_figure(fig, **kwargs))

~\Anaconda3\lib\site-packages\IPython\core\pylabtools.py in print_figure(fig, fmt, bbox_inches, **kwargs)
    126
    127     bytes_io = BytesIO()
--> 128     fig.canvas.print_figure(bytes_io, **kw)
    129     data = bytes_io.getvalue()
    130     if fmt == 'svg':

~\Anaconda3\lib\site-packages\matplotlib\backend_bases.py in print_figure(self, filename, dpi, facecolor, edgecolor, orientation, format, bbox_inches, **kwargs)
   2054                         orientation=orientation,
   2055                         dryrun=True,
-> 2056                         **kwargs)
   2057                     renderer = self.figure._cachedRenderer
   2058                     bbox_artists = kwargs.pop("bbox_extra_artists", None)

~\Anaconda3\lib\site-packages\matplotlib\backends\backend_agg.py in print_png(self, filename_or_obj, metadata, pil_kwargs, *args, **kwargs)
    525
    526         else:
--> 527             FigureCanvasAgg.draw(self)
    528             renderer = self.get_renderer()
    529             with cbook._setattr_cm(renderer, dpi=self.figure.dpi), \

~\Anaconda3\lib\site-packages\matplotlib\backends\backend_agg.py in draw(self)
    386         self.renderer = self.get_renderer(cleared=True)
    387         with RendererAgg.lock:
--> 388             self.figure.draw(self.renderer)
    389             # A GUI class may be need to update a window using this draw, so
    390             # don't forget to call the superclass.

~\Anaconda3\lib\site-packages\matplotlib\artist.py in draw_wrapper(artist, renderer, *args, **kwargs)
     36                 renderer.start_filter()
     37
---> 38             return draw(artist, renderer, *args, **kwargs)
     39         finally:
     40             if artist.get_agg_filter() is not None:

~\Anaconda3\lib\site-packages\matplotlib\figure.py in draw(self, renderer)
   1707             self.patch.draw(renderer)
   1708             mimage._draw_list_compositing_images(
-> 1709                 renderer, self, artists, self.suppressComposite)
   1710
   1711             renderer.close_group('figure')

~\Anaconda3\lib\site-packages\matplotlib\image.py in _draw_list_compositing_images(renderer, parent, artists, suppress_composite)
    133     if not_composite or not has_images:
    134         for a in artists:
--> 135             a.draw(renderer)
    136     else:
    137         # Composite any adjacent images together

~\Anaconda3\lib\site-packages\matplotlib\artist.py in draw_wrapper(artist, renderer, *args, **kwargs)
     36                 renderer.start_filter()
     37
---> 38             return draw(artist, renderer, *args, **kwargs)
     39         finally:
     40             if artist.get_agg_filter() is not None:

~\Anaconda3\lib\site-packages\matplotlib\axes\_base.py in draw(self, renderer, inframe)
   2643             renderer.stop_rasterizing()
   2644
-> 2645         mimage._draw_list_compositing_images(renderer, self, artists)
   2646
   2647         renderer.close_group('axes')

~\Anaconda3\lib\site-packages\matplotlib\image.py in _draw_list_compositing_images(renderer, parent, artists, suppress_composite)
    133     if not_composite or not has_images:
    134         for a in artists:
--> 135             a.draw(renderer)
    136     else:
    137         # Composite any adjacent images together

~\Anaconda3\lib\site-packages\matplotlib\artist.py in draw_wrapper(artist, renderer, *args, **kwargs)
     36                 renderer.start_filter()
     37
---> 38             return draw(artist, renderer, *args, **kwargs)
     39         finally:
     40             if artist.get_agg_filter() is not None:

~\Anaconda3\lib\site-packages\matplotlib\text.py in draw(self, renderer)
   2353             return
   2354
-> 2355         xy_pixel = self._get_position_xy(renderer)
   2356         if not self._check_xy(renderer, xy_pixel):
   2357             return

~\Anaconda3\lib\site-packages\matplotlib\text.py in _get_position_xy(self, renderer)
   1903         "Return the pixel position of the annotated point."
   1904         x, y = self.xy
-> 1905         return self._get_xy(renderer, x, y, self.xycoords)
   1906
   1907     def _check_xy(self, renderer, xy_pixel):

~\Anaconda3\lib\site-packages\matplotlib\text.py in _get_xy(self, renderer, x, y, s)
   1757
   1758         if s1 == 'data':
-> 1759             x = float(self.convert_xunits(x))
   1760         if s2 == 'data':
   1761             y = float(self.convert_yunits(y))

TypeError: float() argument must be a string or a number, not 'tuple'

and think maybe the error because of the (group by), if I don't (group by) the data by month and year then plot it as days like this format (1901-01-31) it's worked

so I had tried to ungroup by use .reset_index() but the X label was the indexes of the data and what I want is month/year.

also, I had tried to merge the MultiIndex into one index by use
data.index = ['{}-{}'.format(i, j) for i, j in data.index]
but i got this erorr
ConversionError: Failed to convert value(s) to axis units: '1901-1'

the expected result is similar this but by months/years, not days

any help?

Body:
Your example DataFrame, ensuring the index is a datetime  dtype

#imports excluded
d = {'mean':{'1901-01-31': 0.60847, '1901-02-28': 0.75183, '1901-03-31': 0.05098,
             '1901-04-30': 0.22906, '1901-05-31': 0.24698, '1901-11-30': 0.93659,
             '1901-12-31': 0.08592, '1902-07-31': 0.7869, '1902-08-31': 0.77402,
             '1902-12-31': 0.60236, '1903-01-31': 0.8055, '1903-02-28': 0.6045,
             '1903-03-31': 0.99139, '1903-04-30': 0.77478, '1903-05-31': 0.88022,
             '1903-06-30': 0.73554},
     'count': {'1901-01-31': 3, '1901-02-28': 6, '1901-03-31': 6, '1901-04-30': 2,
               '1901-05-31': 4, '1901-11-30': 8, '1901-12-31': 1, '1902-07-31': 0,
               '1902-08-31': 9, '1902-12-31': 6, '1903-01-31': 4, '1903-02-28': 7,
               '1903-03-31': 2, '1903-04-30': 1, '1903-05-31': 9, '1903-06-30': 1}}

df = pd.DataFrame(d)
df.index = pd.to_datetime(df.index)
#df = df.set_index(pd.to_datetime(df.index))

Axes.annotate's xy argument expects a tuple of two floats. After grouping by year and month; iterating over the rows  produces a ((year,month),float) tuple because of the multi-index - annotate doesn't like that.

I haven't figured out how to make your groupby solution work - I think it would involve translating/transforming the (year,month) tuple into a coordinate the plot/axes understands or specifying an x coordinate system that can use that tuple.

Resampling by month, plotting and annotating works

data = df.resample('M').mean()
# or maybe it should be
#data = df.resample('M').agg({'mean':'mean','count':'sum'})

ax = data['mean'].plot()

for x,y,count in zip(data.index,data['mean'],data['count']):
    ax.annotate(f'{count:.0f}',xy=(x,y), ha='center',clip_on=True)

# or
for (x,(y,count)) in data.iterrows():
    ax.annotate(f'{count:.0f}',xy=(x,y), ha='center',clip_on=True)

plt.show()
plt.close()

There were missing months in the example DataFrame so this plot has discontinuities.


来源: stackexchange

问:
Create special binary search tree using C++
I want to create a Binary search tree which has special Nodes. There should be three classes of Nodes, Internal Node, External Node and Root node, each inheriting a common parent Node and each type of node will have some unique function. Is it possible to create such a BST. The problem I am facing is suppose the first node I insert into the tree becomes the root node. The next node I insert will become External Node. Now if I insert another node then the external node has to become a internal node and the new node will become the external node. Also I cannot find a way to navigate through the tree from one node to another as the nodes will be of different types. Can a tree of this type be created. If yes then give me some suggestions of how this can be done.</p>

答:
You could use basic inheritance some type enum and recursive calls.
This could be a starting point:

```<code>enum NodeType
{
    eRoot,
    eInternal,
    eExternal
};

class BinaryNode
{
public:
   virtual NodeType GetType() = 0;
   virtual void UpdateTree() = 0;

protected:
   BinaryNode* ChildLeft;
   BinaryNode* ChildRight;
   BinaryNode* Parent;
};

class ExternalNode : public BinaryNode
{
   NodeType GetType() override { return eExternal; }
   void UpdateTree() override
   {
      //... Replace node instances here(e.g. delete this node and construct the correct new one given this sub tree. call new InternalNode(this) for example)
      // Call this towards the parent node so the tree will be transformed accordingly
   }
}
class InternalNode : public BinaryNode
{
   NodeType GetType() override { return eInternal; }
   void UpdateTree() override { //... }
}
class RootNode : public BinaryNode
{
   NodeType GetType() override { return eRoot; }
   void UpdateTree() override { //... }
}

</code>```

This is just to give you an idea where to start. You can check the node type at runtime via GetType() and do some checks based on that.

Be aware that this kind of transformation is not particularly fast.
If you want this to be fast, don't use different types and virtual function calls and pointers.

Place your binary tree inside an array and use binary indexing, so at a given index "n" use 2*n+1 to get the left child and 2*n+2 to get the right child. Then use some flags (root, external, internal etc.) to determine which functions you want to call on the binary node. I wouldn't use inheritance like in my code example to be fast or more readable. In fact, deciding externally what functions to call on a node can be much more readable and less error-prone.

ContentLicense: CC BY-SA 4.0

Body:
You could use basic inheritance some type enum and recursive calls.
This could be a starting point:

enum NodeType
{
    eRoot,
    eInternal,
    eExternal
};

class BinaryNode
{
public:
   virtual NodeType GetType() = 0;
   virtual void UpdateTree() = 0;

protected:
   BinaryNode* ChildLeft;
   BinaryNode* ChildRight;
   BinaryNode* Parent;
};

class ExternalNode : public BinaryNode
{
   NodeType GetType() override { return eExternal; }
   void UpdateTree() override
   {
      //... Replace node instances here(e.g. delete this node and construct the correct new one given this sub tree. call new InternalNode(this) for example)
      // Call this towards the parent node so the tree will be transformed accordingly
   }
}
class InternalNode : public BinaryNode
{
   NodeType GetType() override { return eInternal; }
   void UpdateTree() override { //... }
}
class RootNode : public BinaryNode
{
   NodeType GetType() override { return eRoot; }
   void UpdateTree() override { //... }
}

This is just to give you an idea where to start. You can check the node type at runtime via GetType() and do some checks based on that.

Be aware that this kind of transformation is not particularly fast.
If you want this to be fast, don't use different types and virtual function calls and pointers.

Place your binary tree inside an array and use binary indexing, so at a given index "n" use 2*n+1 to get the left child and 2*n+2 to get the right child. Then use some flags (root, external, internal etc.) to determine which functions you want to call on the binary node. I wouldn't use inheritance like in my code example to be fast or more readable. In fact, deciding externally what functions to call on a node can be much more readable and less error-prone.


问:
How is SHA unique?
I am trying to understand SHA uniqueness in simple terms.
For example let us assume there are only messages with maximum length of 4 bits (binery) in whole world. Number of possible messages with different lengths is

2 for single bit length

2^2 for double bit length

2^3 for 3 bit length

2^4 for 4 bit length

that would be 2+4+8+16 = 30 (31 if we consider empty message 2^0 = 1)

Lets us consider SHA3(for example) with output length of 3bits (binery), so maximum possible number of digest are 8.
How can a digest be unique if we need to map 30 messages to 8, or why is it hard to find digest collision for 2 unique messages

答:
Any SHA3 variant will have digests with more than 100 bits. The terminology has probably confused you, because SHA256 has 256 bits, while SHA3 is considered the third generation of SHA algorithms (and does NOT have 3 bits of lenght). </p>

<p>Generally speaking it's not hard to find a hash collision by brute-forcing (alas, it's time-consuming), what is difficult is producing a collision that is also meaningful in its context. For example, assume you have a source file for an important application, that hashes to a digest. If an attacker tried to alter the source file in a way to introduce a vulnerability, while also hashing to the same digest, he'd have to introduce a lot of random gibberish, making the attack obvious. </p>

Title: How is SHA unique?

Body:
Any SHA3 variant will have digests with more than 100 bits. The terminology has probably confused you, because SHA256 has 256 bits, while SHA3 is considered the third generation of SHA algorithms (and does NOT have 3 bits of lenght).

Generally speaking it's not hard to find a hash collision by brute-forcing (alas, it's time-consuming), what is difficult is producing a collision that is also meaningful in its context. For example, assume you have a source file for an important application, that hashes to a digest. If an attacker tried to alter the source file in a way to introduce a vulnerability, while also hashing to the same digest, he'd have to introduce a lot of random gibberish, making the attack obvious.


问:
Java: difference between < and <= for long integer for 9223372036854775807L
When I run the following code in JVM, I am unable to understand why it behaves like this.
As per my understanding, < x operator should go till x-1.

```<code>  public class LongQuestion {

  public static void main(String[] args) {

        if(9223372036854775807L < Math.pow(2,63)) {
            System.out.println("True");                            // DOES NOT GET PRINTED
        }

         if(9223372036854775807L <= Math.pow(2,63) - 1 ) {
            System.out.println("Also True");                       // THIS GETS PRINTED
        }

    }

}
</code>```

I want to understand why Java behaves like this.

Body:
When I run the following code in JVM, I am unable to understand why it behaves like this.
As per my understanding, < x operator should go till x-1.

  public class LongQuestion {

  public static void main(String[] args) {

        if(9223372036854775807L < Math.pow(2,63)) {
            System.out.println("True");                            // DOES NOT GET PRINTED
        }

         if(9223372036854775807L <= Math.pow(2,63) - 1 ) {
            System.out.println("Also True");                       // THIS GETS PRINTED
        }

    }

}

I want to understand why Java behaves like this.

Body:
The following code will help you understand it:

public class Main {
    public static void main(String[] args) {
        System.out.println("Long.MAX_VALUE is " + Long.MAX_VALUE);
        System.out.println("Math.pow(2, 63) is " + Math.pow(2, 63));
        System.out.println("Math.pow(2, 63) - 1 is " + (Math.pow(2, 63) - 1));
        System.out.println("(long)Math.pow(2, 63) is " + (long) Math.pow(2, 63));
        System.out.println("(long)(Math.pow(2, 63) - 1) is " + (long) (Math.pow(2, 63) - 1));

        if (9223372036854775807L < Math.pow(2, 63)) {
            System.out.println("9223372036854775807L < Math.pow(2, 63)");
        }

        if (9223372036854775807L <= Math.pow(2, 63)) {
            System.out.println("9223372036854775807L <= Math.pow(2, 63)");
        }

        if (9223372036854775807L <= Math.pow(2, 63) - 1) {
            System.out.println("9223372036854775807L <= Math.pow(2, 63) - 1");
        }

        if (9223372036854775807L < (long) Math.pow(2, 63)) {
            System.out.println("9223372036854775807L < (long)Math.pow(2, 63)");
        }

        if (9223372036854775807L <= (long) Math.pow(2, 63)) {
            System.out.println("9223372036854775807L <= (long)Math.pow(2, 63)");
        }

        if (9223372036854775807L <= (long) Math.pow(2, 63) - 1) {
            System.out.println("9223372036854775807L <= (long)Math.pow(2, 63) - 1");
        }

        if (9223372036854775807L <= (long) (Math.pow(2, 63) - 1)) {
            System.out.println("9223372036854775807L <= (long)(Math.pow(2, 63) - 1)");
        }
    }
}

Output:

Long.MAX_VALUE is 9223372036854775807
Math.pow(2, 63) is 9.223372036854776E18
Math.pow(2, 63) - 1 is 9.223372036854776E18
(long)Math.pow(2, 63) is 9223372036854775807
(long)(Math.pow(2, 63) - 1) is 9223372036854775807
9223372036854775807L <= Math.pow(2, 63)
9223372036854775807L <= Math.pow(2, 63) - 1
9223372036854775807L <= (long)Math.pow(2, 63)
9223372036854775807L <= (long)(Math.pow(2, 63) - 1)


问:
Passing an *os.File as an *io.Reader
If there's a function that takes a *io.Reader, how would one pass an *io.File?  This doesn't work:

```<code>func somefunc(r *io.Reader){
}

func Test_FileReader(t *testing.T){
    f, err := os.Open("xyz")
    assert.NoError(t, err)

    somefunc(&f)
}
</code>```

It gives this error:

Cannot use '&f' (type **File) as type *io.Reader

Then, changing *io.Reader->io.Reader and &f->f, it compiles just fine:

```<code>func somefunc(r io.Reader){
}

func Test_FileReader(t *testing.T){
    f, err := os.Open("xyz")
    assert.NoError(t, err)

    somefunc(f)
}
</code>```

Is it even possible to pass an *os.File as an *io.Reader??

答:
*io.Reader is a pointer to an interface. That is almost always unnecessary.

While *File is an io.Reader, **File is not *io.Reader. When the compiler passes a struct in place of an interface, it constructs an interface that contains the type and the value of the underlying value. However, *io.Reader is not an interface. So if you really want to pass a pointer to an interface, you have to first create an interface, and pass the address of it:

```<code>var intf io.Reader
intf=f
someFunc(&f)
</code>```

But then, passing a pointer to an interface is only necessary if the function sets the interface value to something else.

Title: Passing an *os.File as an *io.Reader

Body:
If there's a function that takes a *io.Reader, how would one pass an *io.File?  This doesn't work:

func somefunc(r *io.Reader){
}

func Test_FileReader(t *testing.T){
    f, err := os.Open("xyz")
    assert.NoError(t, err)

    somefunc(&f)
}

It gives this error:

Cannot use '&f' (type **File) as type *io.Reader

Then, changing *io.Reader->io.Reader and &f->f, it compiles just fine:

func somefunc(r io.Reader){
}

func Test_FileReader(t *testing.T){
    f, err := os.Open("xyz")
    assert.NoError(t, err)

    somefunc(f)
}

Is it even possible to pass an *os.File as an *io.Reader??

Body:
*io.Reader is a pointer to an interface. That is almost always unnecessary.

While *File is an io.Reader, **File is not *io.Reader. When the compiler passes a struct in place of an interface, it constructs an interface that contains the type and the value of the underlying value. However, *io.Reader is not an interface. So if you really want to pass a pointer to an interface, you have to first create an interface, and pass the address of it:

var intf io.Reader
intf=f
someFunc(&f)

But then, passing a pointer to an interface is only necessary if the function sets the interface value to something else.


问:
SwiftUI on macOS: How to enable UI for onDelete (deletion from List)
Perhaps I'm particularly dense this morning but I'm trying to delete a row from a List in SwiftUI on macOS.

The issue is that there is no UI exposed to perform the delete. By that I mean that the List does not respond to delete key presses, has no right click menu nor supports any other gestures like swipe to delete (which would be odd on macOS anyway).

Here's the example I'm using:

```<code>import SwiftUI

struct ContentView: View {
    @State var items = ["foo", "bar", "baz"]
    @State var selection: String? = nil

    var body: some View {
        List(selection: $selection) {
            ForEach(items, id: \.self) { Text($0) }
                .onDelete { self.items.remove(atOffsets: $0)}
        }
        .frame(maxWidth: .infinity, maxHeight: .infinity)
    }
}
</code>```

The exact same code on iOS gives me a table view with the standard "swipe left to delete" UI. On macOS there is just nothing.

I tried adding

```<code>    .onDeleteCommand(perform: {
        if let sel = self.selection, let idx = self.items.firstIndex(of: sel) {
            self.items.remove(at: idx)
        }
    })
</code>```

to the List but still no response to delete key presses.

How does one enable List row deletion on macOS?

答:
This code enables the "Delete" menu and removes the selected item when I select Edit > Delete (without manually wiring up the menu):

```<code>struct ContentView: View {
    @State var items = ["foo", "bar", "baz"]
    @State var selection: String? = nil

    var body: some View {
        List(selection: $selection) {
            ForEach(items, id: \.self) { Text($0) }
        }
        .onDeleteCommand {
            if
                let sel = self.selection,
                let idx = self.items.firstIndex(of: sel) {
                print("delete item: \(sel)")
                self.items.remove(at: idx)
            }
        }
        .frame(maxWidth: .infinity, maxHeight: .infinity)
        .animation(.default)
    }
}
</code>```

Then, to make the delete key work, make it the keyboard equivalent for the Delete menu option:
- Edit Main.storyboard
- Select Edit > Delete
- Click in the "Key Equivalent" field
- Hit the delete key.

Run the app, select an item, hit the delete key, and your item should disappear.

Body:
Perhaps I'm particularly dense this morning but I'm trying to delete a row from a List in SwiftUI on macOS.

The issue is that there is no UI exposed to perform the delete. By that I mean that the List does not respond to delete key presses, has no right click menu nor supports any other gestures like swipe to delete (which would be odd on macOS anyway).

Here's the example I'm using:

import SwiftUI

struct ContentView: View {
    @State var items = ["foo", "bar", "baz"]
    @State var selection: String? = nil

    var body: some View {
        List(selection: $selection) {
            ForEach(items, id: \.self) { Text($0) }
                .onDelete { self.items.remove(atOffsets: $0)}
        }
        .frame(maxWidth: .infinity, maxHeight: .infinity)
    }
}

The exact same code on iOS gives me a table view with the standard "swipe left to delete" UI. On macOS there is just nothing.

I tried adding

    .onDeleteCommand(perform: {
        if let sel = self.selection, let idx = self.items.firstIndex(of: sel) {
            self.items.remove(at: idx)
        }
    })

to the List but still no response to delete key presses.

How does one enable List row deletion on macOS?

Body:
This code enables the "Delete" menu and removes the selected item when I select Edit > Delete (without manually wiring up the menu):

struct ContentView: View {
    @State var items = ["foo", "bar", "baz"]
    @State var selection: String? = nil

    var body: some View {
        List(selection: $selection) {
            ForEach(items, id: \.self) { Text($0) }
        }
        .onDeleteCommand {
            if
                let sel = self.selection,
                let idx = self.items.firstIndex(of: sel) {
                print("delete item: \(sel)")
                self.items.remove(at: idx)
            }
        }
        .frame(maxWidth: .infinity, maxHeight: .infinity)
        .animation(.default)
    }
}

Then, to make the delete key work, make it the keyboard equivalent for the Delete menu option:
- Edit Main.storyboard
- Select Edit > Delete
- Click in the "Key Equivalent" field
- Hit the delete key.

Run the app, select an item, hit the delete key, and your item should disappear.


问:
What is the easiest and least boring way to learn CakePHP?
I am trying to actually learn CakePHP and be able to make a simple website with it, but the shere size of the documentation and people telling me I should have read at least 100 pages, has kept me away from CakePHP after having worked with it for a month.

I just get a little bored when I have to read a full manual page with references, half of the used terms I have not yet known before, so it's not very effective.

I have successfully completed the blog-tutorial and read about the MVC model, I am however not ready to make a simple website. Half the time of my first attempt I ended up copy-pasting and using trial and error.

答: CakeFest is in September :)</p>

ContentLicense: CC BY-SA 3.0

Body: CakeFest is in September :)


问:
Why TApplication.MessageBox closes automatically?
I have an app that takes a few seconds to load (lots of initializations). The GUI freezes during startup. So I want to create a splash screen that fades in and out as the application loads.
I use TBackgroundWorker component to do the animation in a background thread.

However, something strange happens when I use this component: when it signals "work complete" (see BackgroundWorkerWorkComplete) a message dialog that I open meanwhile is automatically closed.

```<code>procedure TMainForm.ButtonStartSplashClick(Sender: TObject);
VAR
  frmSplash: TfrmSplash;
begin
 frmSplash:= TfrmSplash.Create(NIL);
 frmSplash.StartAnimation;

 //MessageBox(Handle, 'Hi', nil, MB_OK);   // This remains on screen
 Application.MessageBox(PChar('Hi'), PChar('Box'), MB_ICONINFORMATION); // This is automatically closed when the background thread is done
end;
</code>```

And this is the splash screen:

```<code>procedure TfrmSplash.StartAnimation;
begin
 Show;
 BackgroundWorker.Execute;
end;

procedure TfrmSplash.FormClose(Sender: TObject; var Action: TCloseAction);
begin
 Action:= caFree;
end;

procedure TfrmSplash.BackgroundWorkerWork(Worker: TBackgroundWorker);
VAR i: Integer;
begin
  for i:= 1 to 255 DO
   begin
    AlphaBlendValue:= i; // do not access GUI directly from thread
    Sleep(30);
   end;
end;

procedure TfrmSplash.BackgroundWorkerWorkComplete(Worker: TBackgroundWorker; Cancelled: Boolean);
begin
 Close; // At this point, the msg box will be closed also
end;
</code>```

What I find strange is that MessageBox remains on screen while Application.MessageBox does not (is automatically closed).

Why closing TfrmSplash will close the message box also?

答:
TApplication.MessageBox is a wrapper around the WinAPI MessageBox function.  The code for the former shows you how it's called :

```<code>function TApplication.MessageBox(const Text, Caption: PChar; Flags: Longint): Integer;
var
  ActiveWindow, TaskActiveWindow: HWnd;
  MBMonitor, AppMonitor: HMonitor;
  MonInfo: TMonitorInfo;
  Rect: TRect;
  FocusState: TFocusState;
  WindowList: TTaskWindowList;
begin
  ActiveWindow := ActiveFormHandle;
  if ActiveWindow = 0 then
    TaskActiveWindow := Handle
  else
    TaskActiveWindow := ActiveWindow;

   {  ... }

  try
    Result := Winapi.Windows.MessageBox(TaskActiveWindow, Text, Caption, Flags);
  finally
</code>```

Notice that the HWND passed to the WinAPI call is TaskActiveWindow, which is taken as the active window at the time the call is made (unless there is none, in which case the application's handle is used instead).  Since you've just created your TFrmSplash, it will be the active window and the message box will be disposed when its parent (your splash window) is closed.

When you simply call MessageBox directly :

```<code> MessageBox(Handle, 'Hi', nil, MB_OK);   // This remains on screen
</code>```

You are passing Handle, which is implicitly the handle of the form from which you're calling the code, in this case your TMainForm, so the main form becomes the owner in this case and has no relation to the splash screen.

Body:
I have an app that takes a few seconds to load (lots of initializations). The GUI freezes during startup. So I want to create a splash screen that fades in and out as the application loads.
I use TBackgroundWorker component to do the animation in a background thread.

However, something strange happens when I use this component: when it signals "work complete" (see BackgroundWorkerWorkComplete) a message dialog that I open meanwhile is automatically closed.

procedure TMainForm.ButtonStartSplashClick(Sender: TObject);
VAR
  frmSplash: TfrmSplash;
begin
 frmSplash:= TfrmSplash.Create(NIL);
 frmSplash.StartAnimation;

 //MessageBox(Handle, 'Hi', nil, MB_OK);   // This remains on screen
 Application.MessageBox(PChar('Hi'), PChar('Box'), MB_ICONINFORMATION); // This is automatically closed when the background thread is done
end;

And this is the splash screen:

procedure TfrmSplash.StartAnimation;
begin
 Show;
 BackgroundWorker.Execute;
end;

procedure TfrmSplash.FormClose(Sender: TObject; var Action: TCloseAction);
begin
 Action:= caFree;
end;

procedure TfrmSplash.BackgroundWorkerWork(Worker: TBackgroundWorker);
VAR i: Integer;
begin
  for i:= 1 to 255 DO
   begin
    AlphaBlendValue:= i; // do not access GUI directly from thread
    Sleep(30);
   end;
end;

procedure TfrmSplash.BackgroundWorkerWorkComplete(Worker: TBackgroundWorker; Cancelled: Boolean);
begin
 Close; // At this point, the msg box will be closed also
end;

What I find strange is that MessageBox remains on screen while Application.MessageBox does not (is automatically closed).

Why closing TfrmSplash will close the message box also?

Body:
TApplication.MessageBox is a wrapper around the WinAPI MessageBox function.  The code for the former shows you how it's called :

function TApplication.MessageBox(const Text, Caption: PChar; Flags: Longint): Integer;
var
  ActiveWindow, TaskActiveWindow: HWnd;
  MBMonitor, AppMonitor: HMonitor;
  MonInfo: TMonitorInfo;
  Rect: TRect;
  FocusState: TFocusState;
  WindowList: TTaskWindowList;
begin
  ActiveWindow := ActiveFormHandle;
  if ActiveWindow = 0 then
    TaskActiveWindow := Handle
  else
    TaskActiveWindow := ActiveWindow;

   {  ... }

  try
    Result := Winapi.Windows.MessageBox(TaskActiveWindow, Text, Caption, Flags);
  finally

Notice that the HWND passed to the WinAPI call is TaskActiveWindow, which is taken as the active window at the time the call is made (unless there is none, in which case the application's handle is used instead).  Since you've just created your TFrmSplash, it will be the active window and the message box will be disposed when its parent (your splash window) is closed.

When you simply call MessageBox directly :

 MessageBox(Handle, 'Hi', nil, MB_OK);   // This remains on screen

You are passing Handle, which is implicitly the handle of the form from which you're calling the code, in this case your TMainForm, so the main form becomes the owner in this case and has no relation to the splash screen.


问:
Setting Azure Function Service Bus Topic and Subscription Output Binding via C#
I have a simple HTTP trigger Azure Function with multiple Service Bus output bindings. All the bindings are pointing to the same Topic, but they have different Subscriptions. If I was to set this function app  through function.json it is pretty straightforward:

```<code>{
  "bindings": [
    {
      "authLevel": "function",
      "name": "req",
      "type": "httpTrigger",
      "direction": "in",
      "methods": [
        "get",
        "post"
      ]
    },
    {
      "name": "$return",
      "type": "http",
      "direction": "out"
    },
    {
      "type": "serviceBus",
      "connection": "SERVICEBUS",
      "name": "output",
      "topicName": "outtopic",
      "subscriptionName": "sub",
      "direction": "out"
    },
    {
      "type": "serviceBus",
      "connection": "SERVICEBUS",
      "name": "output",
      "topicName": "outtopic",
      "subscriptionName": "sub2",
      "direction": "out"
    }
  ],
  "disabled": false
}
</code>```

But I publish my functions via Visual Studio and therefore my Azure Functions are read only in the portal and function.json is automatically generated by VS upon publishing.
The problem is that I cannot figure out how do I setup multiple output bindings pointing to different subscriptions. Currently I have something like this:

```<code>[FunctionName("Function2")]
public static async Task<IActionResult> Run(
    [HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequest req,
    [ServiceBus("outtopic", entityType:EntityType.Topic)] IAsyncCollector<string> output,
    [ServiceBus("outtopic", entityType: EntityType.Topic)] IAsyncCollector<string> output2,
    ILogger log)
{
    log.LogInformation("C# HTTP trigger function processed a request.");

    string requestBody = await new StreamReader(req.Body).ReadToEndAsync();

    await output.AddAsync(requestBody);

    return new OkObjectResult("OK");
}
</code>```

As you can see output and output2 are pointing to the same Topic, but there is no option to specify Subscription.
At this point I am pretty confident that this has not been implemented yet. But I hope there is a workaround maybe?

答:
It is not possible to directly put messages into a Topic Subscription, rather every message has to come through a Topic.

To make sure only a particular subscription receives a message, you need to configure the Topic Subscription rule. You can read more about rules in the blog post here.

Body:
I have a simple HTTP trigger Azure Function with multiple Service Bus output bindings. All the bindings are pointing to the same Topic, but they have different Subscriptions. If I was to set this function app  through function.json it is pretty straightforward:

{
  "bindings": [
    {
      "authLevel": "function",
      "name": "req",
      "type": "httpTrigger",
      "direction": "in",
      "methods": [
        "get",
        "post"
      ]
    },
    {
      "name": "$return",
      "type": "http",
      "direction": "out"
    },
    {
      "type": "serviceBus",
      "connection": "SERVICEBUS",
      "name": "output",
      "topicName": "outtopic",
      "subscriptionName": "sub",
      "direction": "out"
    },
    {
      "type": "serviceBus",
      "connection": "SERVICEBUS",
      "name": "output",
      "topicName": "outtopic",
      "subscriptionName": "sub2",
      "direction": "out"
    }
  ],
  "disabled": false
}

But I publish my functions via Visual Studio and therefore my Azure Functions are read only in the portal and function.json is automatically generated by VS upon publishing.
The problem is that I cannot figure out how do I setup multiple output bindings pointing to different subscriptions. Currently I have something like this:

[FunctionName("Function2")]
public static async Task<IActionResult> Run(
    [HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequest req,
    [ServiceBus("outtopic", entityType:EntityType.Topic)] IAsyncCollector<string> output,
    [ServiceBus("outtopic", entityType: EntityType.Topic)] IAsyncCollector<string> output2,
    ILogger log)
{
    log.LogInformation("C# HTTP trigger function processed a request.");

    string requestBody = await new StreamReader(req.Body).ReadToEndAsync();

    await output.AddAsync(requestBody);

    return new OkObjectResult("OK");
}

As you can see output and output2 are pointing to the same Topic, but there is no option to specify Subscription.
At this point I am pretty confident that this has not been implemented yet. But I hope there is a workaround maybe?


问:
Count lines with integers in them using bash and wc -l
A utility on my Linux machine outputs a log to 'stdout'.
In each line, there is either a String or an Integer, it looks like the following:

```<code>[ERROR] resource busy, retrying
0989282882
[DEBUG] starting process with pid 4028
7918361566
1037491392
[DEBUG] starting process with pid 4056
2873187983
7853738301
1290312037
[DEBUG] done with init
1872989829
[DEBUG] cleaning up
8917982882
</code>```

(In reality it is way longer)

I want to count the lines that have integers in them.

I already used: program | grep DEBUG | wc -l to get the debug count (same for ERROR)

But how can I count the integers? They don't have anything static like the strings, that I could grep...

答:
You do not need wc  for this, grep has -c

```<code>program |  grep -c -E -x '[[:digit:]]+'
</code>```

-c print only a count of selected lines

-E extended regexp (you can omit it and use the pattern [0-9]\+)

-x match the entire line not just part of it

See POSIX grep manual

Alternatively, since you mentioned also [DEBUG], you can use awk for a single pass (especialy if your program is not idempotent)

```<code>program | awk  '/^[0-9]+$/ { numbers++ } /^\[DEBUG\]/ {debugs++} END { print numbers,debugs }'
</code>```

See POSIX awk manual

Body:
A utility on my Linux machine outputs a log to 'stdout'.
In each line, there is either a String or an Integer, it looks like the following:

[ERROR] resource busy, retrying
0989282882
[DEBUG] starting process with pid 4028
7918361566
1037491392
[DEBUG] starting process with pid 4056
2873187983
7853738301
1290312037
[DEBUG] done with init
1872989829
[DEBUG] cleaning up
8917982882

(In reality it is way longer)

I want to count the lines that have integers in them.

I already used: program | grep DEBUG | wc -l to get the debug count (same for ERROR)

But how can I count the integers? They don't have anything static like the strings, that I could grep...

Body:
You do not need wc  for this, grep has -c

program |  grep -c -E -x '[[:digit:]]+'

-c print only a count of selected lines

-E extended regexp (you can omit it and use the pattern [0-9]\+)

-x match the entire line not just part of it

See POSIX grep manual

Alternatively, since you mentioned also [DEBUG], you can use awk for a single pass (especialy if your program is not idempotent)

program | awk  '/^[0-9]+$/ { numbers++ } /^\[DEBUG\]/ {debugs++} END { print numbers,debugs }'

See POSIX awk manual


问:
Set MySQL timestamp to random time within past 24 hours
I have a timestamp column in my MySQL table.

I'm wanting to set this timestamp to a random time within the past 24 hours for all rows in the table.

I know I can update all the rows doing this:

```<code>UPDATE table SET timestamp =
</code>```

But I can't find if there's a way to set a random timestamp that's occurred within the past 24 hours so that each row has a different time.

答:
You can try:  </p>

```<code>Update table set timestamp = select(cast((sysdate() - floor(rand()*24)) AS Datetime));
</code>```

Body:
I have a timestamp column in my MySQL table.

I'm wanting to set this timestamp to a random time within the past 24 hours for all rows in the table.

I know I can update all the rows doing this:

UPDATE table SET timestamp =

But I can't find if there's a way to set a random timestamp that's occurred within the past 24 hours so that each row has a different time.

Body:
You can try:

Update table set timestamp = select(cast((sysdate() - floor(rand()*24)) AS Datetime));


问:
How can I properly format SQL files without faulty indentation?
I'm trying a myriad of online recommended packages for formatting SQL files and can't seem to get anything working. The output is always skewed. Does anyone have recommendations? I'm trying to pipe the file into a CLI tool while I'm writing statements/queries in VIM.

Example command: sqlformat --reindent=true tables.sql

```<code>sqlformat --reindent tables.sql                                                                                 2 ✘  11:36:17
CREATE TABLE users (id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
                                                         name VARCHAR(255),
                                                              email VARCHAR(255));
</code>```

Ideal Output:

```<code>CREATE TABLE users (
  id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
  name VARCHAR(255),
  email VARCHAR(255)
);
</code>```

答:
I did the following in my nvim init file

```<code>  115 "SQL Formatting
  116 nnoremap <leader>sql :%!sql-formatter-cli .<CR>
  117 inoremap <leader>sql :%!sql-formatter-cli .<CR>
</code>```

after running npm i -g sql-formatter-cli

Body:
I'm trying a myriad of online recommended packages for formatting SQL files and can't seem to get anything working. The output is always skewed. Does anyone have recommendations? I'm trying to pipe the file into a CLI tool while I'm writing statements/queries in VIM.

Example command: sqlformat --reindent=true tables.sql

sqlformat --reindent tables.sql                                                                                 2 ✘  11:36:17
CREATE TABLE users (id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
                                                         name VARCHAR(255),
                                                              email VARCHAR(255));

Ideal Output:

CREATE TABLE users (
  id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
  name VARCHAR(255),
  email VARCHAR(255)
);

Body:
I did the following in my nvim init file

  115 "SQL Formatting
  116 nnoremap <leader>sql :%!sql-formatter-cli .<CR>
  117 inoremap <leader>sql :%!sql-formatter-cli .<CR>

after running npm i -g sql-formatter-cli


问:
Angular <mat-select> component is not working on a FormGroup
I'm trying to use  inside a formGroup but although it builds the component and I can navigate through options, I couldn't select any of them. When the page is loaded I can see this error :

ERROR TypeError: "this._selectionModel.onChange is undefined"

Here's my component.ts :

```<code>@Component({
  selector: 'app-agent',
  templateUrl: './agent.component.html',
  styleUrls: ['./agent.component.css']
})
export class AgentComponent implements OnInit {

  agents = [];
  durationInSeconds = 5;
  statusList = ['AVAILABLE', 'NOT_AVAILABLE'];
  agentForm = new FormGroup ({
    name: new FormControl(),
    status: new FormControl(this.statusList[0]),
  });
  searchForm = new FormGroup(
    {key: new FormControl()}
  );

  constructor(private agentService: AgentService) { }

  ngOnInit(): void {
    this.getAll();
  }

  filter(): void {
    if (this.searchForm.value.key) {
      this.getOne();
    } else {
      this.getAll();
    }
  }

  save(): void {
    this.agentService.save(new AgentData(this.agentForm.value.name, this.agentForm.value.status)).subscribe((data) => {
      this.agentForm.value.name = data.name;
      this.agentForm.value.status = data.status;
    }
    );
  }
}
</code>```

And this is the component html part :

```<code>        <form [formGroup]="agentForm" (submit)="save()">
          <table class="form-group" style="width: 100%; ">
            <div class="row" >
              <mat-form-field style="width: 100%; ">
                <mat-label>Agent name</mat-label>
                <input matInput placeholder="Ex. fferchichi" formControlName="name">
              </mat-form-field>
            </div>

            <div class="row">
              <mat-form-field style="width: 100%;">
                <mat-label>Status</mat-label>
                <mat-select formControlName="status">
                  <mat-option *ngFor="let status of statusList" [value]="status">
                    {{status | labelit}}
                  </mat-option>
                </mat-select>
                <mat-error *ngIf="agentForm.hasError('required')">Please choose a Status</mat-error>
              </mat-form-field>
            </div>

            <div class="row" style="text-align: right;">
              <input type="submit" class="btn btn-default" value="Save"/>
            </div>

          </table>
        </form>
</code>```

It feels like the binding with formControl is read-only but I can't find out why or how to fix it.

答:
you cannot simply assign values to formcontrol using '=' symbol,
You have to options, i.e., eitheir you have to use setValue method or patchValue method,
I'd suggest you to use patchValue method because, when you use setValue method you have to change every formcontrol in your form.
so you try something like this...</p>
```<code>this.searchForm.patchValue({
    name: data.name,
    status: data.status
});`
</code>```

Body:
I'm trying to use  inside a formGroup but although it builds the component and I can navigate through options, I couldn't select any of them. When the page is loaded I can see this error :

ERROR TypeError: "this._selectionModel.onChange is undefined"

Here's my component.ts :

@Component({
  selector: 'app-agent',
  templateUrl: './agent.component.html',
  styleUrls: ['./agent.component.css']
})
export class AgentComponent implements OnInit {

  agents = [];
  durationInSeconds = 5;
  statusList = ['AVAILABLE', 'NOT_AVAILABLE'];
  agentForm = new FormGroup ({
    name: new FormControl(),
    status: new FormControl(this.statusList[0]),
  });
  searchForm = new FormGroup(
    {key: new FormControl()}
  );

  constructor(private agentService: AgentService) { }

  ngOnInit(): void {
    this.getAll();
  }

  filter(): void {
    if (this.searchForm.value.key) {
      this.getOne();
    } else {
      this.getAll();
    }
  }

  save(): void {
    this.agentService.save(new AgentData(this.agentForm.value.name, this.agentForm.value.status)).subscribe((data) => {
      this.agentForm.value.name = data.name;
      this.agentForm.value.status = data.status;
    }
    );
  }
}

And this is the component html part :

        <form [formGroup]="agentForm" (submit)="save()">

              <mat-form-field style="width: 100%; ">
                <mat-label>Agent name</mat-label>
                <input matInput placeholder="Ex. fferchichi" formControlName="name">
              </mat-form-field>

              <mat-form-field style="width: 100%;">
                <mat-label>Status</mat-label>
                <mat-select formControlName="status">
                  <mat-option *ngFor="let status of statusList" [value]="status">
                    {{status | labelit}}
                  </mat-option>
                </mat-select>
                <mat-error *ngIf="agentForm.hasError('required')">Please choose a Status</mat-error>
              </mat-form-field>

              <input type="submit" class="btn btn-default" value="Save"/>

        </form>

It feels like the binding with formControl is read-only but I can't find out why or how to fix it.

Body:
you cannot simply assign values to formcontrol using '=' symbol,
You have to options, i.e., eitheir you have to use setValue method or patchValue method,
I'd suggest you to use patchValue method because, when you use setValue method you have to change every formcontrol in your form.
so you try something like this...

this.searchForm.patchValue({
    name: data.name,
    status: data.status
});`


问:
matrix multiplication without losing xts properties
I have an xts object, and I wish to create weighted sums of the columns (and do this a LOT).  By far the easiest way is matrix multiplication, but then the result loses the nice xts qualities.

It's easy to add them back by creating a new xts object -- but it's both slow and tedious.

For example:

```<code>dd <- xts(matrix(rnorm(200), ncol=2), Sys.Date() + 1:100)
w_sum <- dd %*% c(-1, 1)
</code>```

... and the problem is:

```<code>> tail(w_sum)
             [,1]
 [95,]  0.1758262
 [96,] -0.3310975
 [97,] -0.1204836
 [98,] -1.2242001
 [99,] -1.7333222
[100,]  1.1216603
</code>```

The fix is:

```<code>w_sumx <- xts(dd %*% c(-1, 1), index(dd))
</code>```

But not only is it bothersome, it's slow. Also, i note with interest that xts is really fast for subtraction. Is there a way to do this which leverages the fast internals of xts?

```<code>f1 <- function() xts(dd %*% c(-1, 1), index(dd))
f2 <- function() dd[,2] - dd[,1]

> microbenchmark::microbenchmark(f1(), f2(), times = 1000)
Unit: microseconds
 expr  min   lq     mean median     uq    max neval cld
 f1() 83.7 97.3 114.1294 104.65 115.00 6688.4  1000   b
 f2() 26.3 34.0  40.6202  38.85  45.15  155.4  1000  a
</code>```

答:
A few simple alternatives exists. Obviously you could rewrite the method in Rcpp as suggested, but a simpler alternative is just to overwrite the attributes after performing matrix regular multiplication.

```<code>dd_new <- dd %*% c(-1, 1)
att <- attributes(dd)
att$dim <- dim(dd_new)
attributes(dd_new) <- att
</code>```

This is not as fast as pure matrix multiplication, but is about 10 - 13x faster than subsetting the time series itself.

```<code>microbenchmark::microbenchmark(xts = dd[, 1] - dd[, 2],
                               matmult = dd %*% c(1, -1),
                               xtsmatmult = xts(dd %*% c(1, -1), index(dd)),
                               "%.%" = dd %.% c(1, -1),
                               "%-%" = dd %-% c(1, -1),
                               times = 1e5)
Unit: milliseconds
       expr    min     lq    mean median     uq    max neval
        xts 0.0396 0.0685 0.11200 0.0998 0.1170  15.40 1e+05
    matmult 0.0008 0.0021 0.00352 0.0028 0.0040   7.71 1e+05
 xtsmatmult 0.0853 0.1380 0.22900 0.2100 0.2300 117.00 1e+05
        %.% 0.0025 0.0055 0.00905 0.0076 0.0099   8.97 1e+05
        %-% 0.0096 0.0183 0.03030 0.0268 0.0318 101.00 1e+05
</code>```

In the above %.% is a barebone function leaving only doing the matrix multiplication and overwriting the attributes, while %-% adds some simple input-checks, to ensure that dimensions are acceptable, and using S3 class style, in order to simplify generalizations.

Functions:

note that the compiler::cmpfun function has been used to byte-compile the functions (similar to a package function). In this case the effect is insignificant.

```<code>`%.%` <- compiler::cmpfun(function(x, z){
    x2 <- x %*% z
    att <- attributes(x)
    att$dim <- dim(x2)
    attributes(x2) <- att
    x2
})
`%-%` <- function(x, z)
    UseMethod('%-%')
`%-%.xts` <- compiler::cmpfun(function(x, z){
    ##
    if(!is.xts(x))
        stop('x must be an xts object')
    if(!is.numeric(z) || !(n <- length(z)) == ncol(x) || n == 0)
        stop('z must be an index vector')
    x2 <- x %*% z
    att <- attributes(x)
    att$dim <- dim(x2)
    attributes(x2) <- att
    x2
})
</code>```

Body:
I have an xts object, and I wish to create weighted sums of the columns (and do this a LOT).  By far the easiest way is matrix multiplication, but then the result loses the nice xts qualities.

It's easy to add them back by creating a new xts object -- but it's both slow and tedious.

For example:

dd <- xts(matrix(rnorm(200), ncol=2), Sys.Date() + 1:100)
w_sum <- dd %*% c(-1, 1)

... and the problem is:

> tail(w_sum)
             [,1]
 [95,]  0.1758262
 [96,] -0.3310975
 [97,] -0.1204836
 [98,] -1.2242001
 [99,] -1.7333222
[100,]  1.1216603

The fix is:

w_sumx <- xts(dd %*% c(-1, 1), index(dd))

But not only is it bothersome, it's slow. Also, i note with interest that xts is really fast for subtraction. Is there a way to do this which leverages the fast internals of xts?

f1 <- function() xts(dd %*% c(-1, 1), index(dd))
f2 <- function() dd[,2] - dd[,1]

> microbenchmark::microbenchmark(f1(), f2(), times = 1000)
Unit: microseconds
 expr  min   lq     mean median     uq    max neval cld
 f1() 83.7 97.3 114.1294 104.65 115.00 6688.4  1000   b
 f2() 26.3 34.0  40.6202  38.85  45.15  155.4  1000  a

Body:
A few simple alternatives exists. Obviously you could rewrite the method in Rcpp as suggested, but a simpler alternative is just to overwrite the attributes after performing matrix regular multiplication.

dd_new <- dd %*% c(-1, 1)
att <- attributes(dd)
att$dim <- dim(dd_new)
attributes(dd_new) <- att

This is not as fast as pure matrix multiplication, but is about 10 - 13x faster than subsetting the time series itself.

microbenchmark::microbenchmark(xts = dd[, 1] - dd[, 2],
                               matmult = dd %*% c(1, -1),
                               xtsmatmult = xts(dd %*% c(1, -1), index(dd)),
                               "%.%" = dd %.% c(1, -1),
                               "%-%" = dd %-% c(1, -1),
                               times = 1e5)
Unit: milliseconds
       expr    min     lq    mean median     uq    max neval
        xts 0.0396 0.0685 0.11200 0.0998 0.1170  15.40 1e+05
    matmult 0.0008 0.0021 0.00352 0.0028 0.0040   7.71 1e+05
 xtsmatmult 0.0853 0.1380 0.22900 0.2100 0.2300 117.00 1e+05
        %.% 0.0025 0.0055 0.00905 0.0076 0.0099   8.97 1e+05
        %-% 0.0096 0.0183 0.03030 0.0268 0.0318 101.00 1e+05

In the above %.% is a barebone function leaving only doing the matrix multiplication and overwriting the attributes, while %-% adds some simple input-checks, to ensure that dimensions are acceptable, and using S3 class style, in order to simplify generalizations.

Functions:

note that the compiler::cmpfun function has been used to byte-compile the functions (similar to a package function). In this case the effect is insignificant.

`%.%` <- compiler::cmpfun(function(x, z){
    x2 <- x %*% z
    att <- attributes(x)
    att$dim <- dim(x2)
    attributes(x2) <- att
    x2
})
`%-%` <- function(x, z)
    UseMethod('%-%')
`%-%.xts` <- compiler::cmpfun(function(x, z){
    ##
    if(!is.xts(x))
        stop('x must be an xts object')
    if(!is.numeric(z) || !(n <- length(z)) == ncol(x) || n == 0)
        stop('z must be an index vector')
    x2 <- x %*% z
    att <- attributes(x)
    att$dim <- dim(x2)
    attributes(x2) <- att
    x2
})


问:
Kubernetes - What exactly is imperative Vs Declarative
I am seeing multiple and different explanations for imperative Vs Declarative for Kubernetes - something like Imperative means when we use yaml files to create the resources to describe the state and declarative vice versa.

what is the real and clear difference between these two. I would really appreciate if you can put the group of commands fall under the same - like Create under imperative way etc ..

答:
"Imperative" is a command - like "create 42 widgets".

"Declarative" is a statement of the desired end result - like "I want 42 widgets to exist".

Typically, your yaml file will be declarative in nature: it will say that you want 42 widgets to exist.  You'll give that to Kubernetes, and it will execute the steps necessary to end up with having 42 widgets.

"Create" is itself an imperative command, but what you're creating is a Kubernetes cluster.  What the cluster should look like is determined by the declarations in the yaml file.


问:
Understanding GraphQL
I started experimenting with the GraphQL wp api.

I am querying the menus. As for the documentation, the query is very long

I would expect that querying

```<code>{
    menus
}
</code>```

only would bring about all the data nested in menus, it does not.

Why is this? What is the way to getting all nested data in an object as to see what's in there?

Thank you for your time

答: That is the main feature of GraphQL, you can specify what data you need from a query. And because of that, you can't just query menus in that way, you need to specify every nested field in menus you need and only then it'll work :)

Title: Understanding GraphQL

Body:
I started experimenting with the GraphQL wp api.

I am querying the menus. As for the documentation, the query is very long

I would expect that querying

{
    menus
}

only would bring about all the data nested in menus, it does not.

Why is this? What is the way to getting all nested data in an object as to see what's in there?

Thank you for your time


问:
PHP removing a certain string in a string once
I recently have played around with the use of preg_replace in PHP to specifically remove a string once.

However I have a list of numbers (345, 346 and wanting to remove ", 346" for example) and I have kept on running into the same problem how it removes the whole string and leaves it empty.

Desired results are

```<code>345, 346
Removing ", 346"
Turns to
345
And also
345, 346, 347 removing ", 346"
Turns to
345, 347
</code>```

Code:

```<code>$oldpost = ", ".$_GET['id'];

$newposts = preg_replace($oldpost, "", $row['posts']);

</code>```

I tried this previously and haven't found anything that seems to do a better job.

答:
Documentation is here for preg_replace:
https://www.php.net/manual/en/function.preg-replace.php

Try adding a value for the "limit" parameter.

limit:
The maximum possible replacements for each pattern in each subject string. Defaults to -1 (no limit).

Body:
I recently have played around with the use of preg_replace in PHP to specifically remove a string once.

However I have a list of numbers (345, 346 and wanting to remove ", 346" for example) and I have kept on running into the same problem how it removes the whole string and leaves it empty.

Desired results are

345, 346
Removing ", 346"
Turns to
345
And also
345, 346, 347 removing ", 346"
Turns to
345, 347

Code:

$oldpost = ", ".$_GET['id'];

$newposts = preg_replace($oldpost, "", $row['posts']);

I tried this previously and haven't found anything that seems to do a better job.


问:
Intel Edison no longer supported?
Last year I got pretty excited with Android things and bought an Intel Edison to try it on. I recently found some time to work on it and realized it is no longer a supported hardware and I am not able to do any thing with it. :(

Any help would be appreciated!

答: Intel has stopped support, but there is still community activity: there is a Yocto image builder that currently builds Yocto Warrior and Debian Buster with kernel v5.4 here: https://edison-fw.github.io/meta-intel-edison/</p>

Title: Intel Edison no longer supported?


问:
Trying to get input from a .txt file, and put it in a doubly linked list
I'm trying to get input from a .txt file, and put it in a doubly linked list in alphabetical order. However some of the names of the .txt file eventually do go in and somehow disappear from the doubly linkedlist? the .sort() function in the insert function in the main is supposed to sort the names in alphabetical order, and yet sometimes it doesn't put the names in Alphabetical order. How can I solve this issue?

Thank you :)

Main method

```<code>import java.util.*;
import java.io.*;
class Main
{
  public static void main(String[] args) throws FileNotFoundException
  {
    DLL dub = new DLL();
    dub=insert("input.txt");
    dub.traverse();
  }
  public static DLL insert(String fileName) throws FileNotFoundException // gets input from .txt file
  {
    DLL list = new DLL();
    try(Scanner file = new Scanner(new File(fileName)))
    {
      while(file.hasNextLine())
      {
        String line = file.nextLine();
        if(line.startsWith("delete ")) // if .txt contains delete then delete then find the word from the DLL, and remove it
        {
          String element = line.substring("delete ".length());
          list.remove(element);
          continue;
        }
        list.add(line);
      }
      list.sort();
    }
    return list;
  }
}
</code>```

Doubly Linked List Class #

```<code>import java.io.*;
import java.util.*;
public class DLL
{
  private Node head;
  private Node tail;
  /******************************************************************/
  public void traverse() // this method displays the DLL traversing forward and backward
  {
    System.out.println();
    for(Node n=head; n!=null; n=n.getNext()) // traverses forwards
    {
      System.out.println(n.getValue());
    }
    System.out.println("==========");
    for(Node n=tail; n!=null; n=n.getPrev()) // traverses backwards
    {
      System.out.println(n.getValue());
    }
  }
  /******************************************************************/
  public void add(String line) // this method adds a name into the doubly linked list
  {
    Node newNode = new Node(line); // creates a new node
    if(head==null) //if the head is null set the head and tail equal to the new node
    {
      head=newNode;
      tail=newNode;
    }
    else // otherwise, add the tail at the end
    {
      newNode.setPrev(tail);
      tail.setNext(newNode);
      tail=newNode;
    }
  }
  /******************************************************************/
  public void remove(String line) // removes a node
  {
    Node nodeToDelete = find(line); // checks to see if node is available
    removeNode(nodeToDelete); // remove the node
  }
  /******************************************************************/
  private Node find(String element) // this method checks to see if the name is available
  {
    Node curr = head;
    if(curr==null) // if the node is empty, then make the program crash
    {
      throw new IllegalStateException("LinkedList is empty.");
    }
    while(curr!=null) // otherwise, traverse through the program
    {
      if(curr.getValue().equals(element))
      {
        return curr;
      }
      curr=curr.getNext();
    }
    if(curr==null) // if element cant be found then throw an exception
    {
      throw new IllegalStateException("Element was not found.");
    }
    return null; // returns nothing
  }
  /******************************************************************/
  public Node findSmallest() // this method finds
  {
    Node curr = head;
    if(curr==null)
    {
      throw new IllegalStateException("LinkedList is empty.");
    }
   String smallestElement = curr.getValue();
   Node smallestNode=curr;
   while(curr!=null)
   {
      if(smallestElement.compareTo(curr.getValue())<0)
      {
        smallestNode=curr;
        smallestElement = smallestNode.getValue();
      }
      curr=curr.getNext();
   }
    return smallestNode;
  }
  /******************************************************************/
  public void removeNode(Node nodeToDelete)
  {
    Node prev = nodeToDelete.getPrev();
    Node next = nodeToDelete.getNext();

    if(prev == null && next == null) // case to remove an item with no previous or next
    {
      head=null;
      tail=null;
    }
    else if(prev==null) // case to remove a name that happens to be at the head
    {
      head=next;
      head.setPrev(null);
    }
    else if(tail.getNext()==null) // case to remove a name that happens to be at the tail
    {
      tail=prev;
      tail.setNext(null);
    }
    else // otherwise remove the node in-between
    {
      prev.setNext(next);
      next.setPrev(prev);
    }
  }
  /******************************************************************/
  public boolean isEmpty()
  {
    return head==null;
  }
  /******************************************************************/
  public void sort()
  {
    DLL sorted = new DLL();
    if(isEmpty())
    {
      return;
    }
    while (!isEmpty())
    {
      Node smallest = findSmallest();
      sorted.add(smallest.getValue());
      remove(smallest.getValue());
    }
    head = sorted.head;
    tail = sorted.tail;
  }
}
</code>```

Node Class #

```<code>public class Node
{
  private Node prev;
  private Node next;
  private String name;
  Node(String name) // constructor
  {
    this.name=name;
  }
  public String getValue() // this function returns the name
  {
    return this.name;
  }
  public void setValue(String name) // this function changes the value
  {
    this.name=name;
  }
  public Node getNext() // this function returns the previous node
  {
    return this.next;
  }
  public Node getPrev() // this function returns the previous node
  {
    return this.prev;
  }

  public void setNext(Node next) // this function sets the next node
  {
    this.next=next;
  }

  public void setPrev(Node prev) // this function sets the previous node
  {
    this.prev=prev;
  }
}
</code>```

input.txt file #

```<code>Jim
Jill
John
Louis
delete Jill
Bob
Jack
delete Jim
</code>```

Output I get #

```<code>Jack
Bob
=========
Bob
Jack

</code>```

Output I expect

```<code>Bob
Jack
John
Louis
=========
Louis
John
Jack
Bob
</code>```

答:
Notice this line in the DLL:

```<code>else if(tail.getNext()==null)
</code>```

That condition is always true as the tail never has a node after it.

Maybe you wanted this?

```<code>else if (next == null)
</code>```

Body:
I'm trying to get input from a .txt file, and put it in a doubly linked list in alphabetical order. However some of the names of the .txt file eventually do go in and somehow disappear from the doubly linkedlist? the .sort() function in the insert function in the main is supposed to sort the names in alphabetical order, and yet sometimes it doesn't put the names in Alphabetical order. How can I solve this issue?

Thank you :)

Main method

import java.util.*;
import java.io.*;
class Main
{
  public static void main(String[] args) throws FileNotFoundException
  {
    DLL dub = new DLL();
    dub=insert("input.txt");
    dub.traverse();
  }
  public static DLL insert(String fileName) throws FileNotFoundException // gets input from .txt file
  {
    DLL list = new DLL();
    try(Scanner file = new Scanner(new File(fileName)))
    {
      while(file.hasNextLine())
      {
        String line = file.nextLine();
        if(line.startsWith("delete ")) // if .txt contains delete then delete then find the word from the DLL, and remove it
        {
          String element = line.substring("delete ".length());
          list.remove(element);
          continue;
        }
        list.add(line);
      }
      list.sort();
    }
    return list;
  }
}

Doubly Linked List Class #

import java.io.*;
import java.util.*;
public class DLL
{
  private Node head;
  private Node tail;
  /******************************************************************/
  public void traverse() // this method displays the DLL traversing forward and backward
  {
    System.out.println();
    for(Node n=head; n!=null; n=n.getNext()) // traverses forwards
    {
      System.out.println(n.getValue());
    }
    System.out.println("==========");
    for(Node n=tail; n!=null; n=n.getPrev()) // traverses backwards
    {
      System.out.println(n.getValue());
    }
  }
  /******************************************************************/
  public void add(String line) // this method adds a name into the doubly linked list
  {
    Node newNode = new Node(line); // creates a new node
    if(head==null) //if the head is null set the head and tail equal to the new node
    {
      head=newNode;
      tail=newNode;
    }
    else // otherwise, add the tail at the end
    {
      newNode.setPrev(tail);
      tail.setNext(newNode);
      tail=newNode;
    }
  }
  /******************************************************************/
  public void remove(String line) // removes a node
  {
    Node nodeToDelete = find(line); // checks to see if node is available
    removeNode(nodeToDelete); // remove the node
  }
  /******************************************************************/
  private Node find(String element) // this method checks to see if the name is available
  {
    Node curr = head;
    if(curr==null) // if the node is empty, then make the program crash
    {
      throw new IllegalStateException("LinkedList is empty.");
    }
    while(curr!=null) // otherwise, traverse through the program
    {
      if(curr.getValue().equals(element))
      {
        return curr;
      }
      curr=curr.getNext();
    }
    if(curr==null) // if element cant be found then throw an exception
    {
      throw new IllegalStateException("Element was not found.");
    }
    return null; // returns nothing
  }
  /******************************************************************/
  public Node findSmallest() // this method finds
  {
    Node curr = head;
    if(curr==null)
    {
      throw new IllegalStateException("LinkedList is empty.");
    }
   String smallestElement = curr.getValue();
   Node smallestNode=curr;
   while(curr!=null)
   {
      if(smallestElement.compareTo(curr.getValue())<0)
      {
        smallestNode=curr;
        smallestElement = smallestNode.getValue();
      }
      curr=curr.getNext();
   }
    return smallestNode;
  }
  /******************************************************************/
  public void removeNode(Node nodeToDelete)
  {
    Node prev = nodeToDelete.getPrev();
    Node next = nodeToDelete.getNext();

    if(prev == null && next == null) // case to remove an item with no previous or next
    {
      head=null;
      tail=null;
    }
    else if(prev==null) // case to remove a name that happens to be at the head
    {
      head=next;
      head.setPrev(null);
    }
    else if(tail.getNext()==null) // case to remove a name that happens to be at the tail
    {
      tail=prev;
      tail.setNext(null);
    }
    else // otherwise remove the node in-between
    {
      prev.setNext(next);
      next.setPrev(prev);
    }
  }
  /******************************************************************/
  public boolean isEmpty()
  {
    return head==null;
  }
  /******************************************************************/
  public void sort()
  {
    DLL sorted = new DLL();
    if(isEmpty())
    {
      return;
    }
    while (!isEmpty())
    {
      Node smallest = findSmallest();
      sorted.add(smallest.getValue());
      remove(smallest.getValue());
    }
    head = sorted.head;
    tail = sorted.tail;
  }
}

Node Class #

public class Node
{
  private Node prev;
  private Node next;
  private String name;
  Node(String name) // constructor
  {
    this.name=name;
  }
  public String getValue() // this function returns the name
  {
    return this.name;
  }
  public void setValue(String name) // this function changes the value
  {
    this.name=name;
  }
  public Node getNext() // this function returns the previous node
  {
    return this.next;
  }
  public Node getPrev() // this function returns the previous node
  {
    return this.prev;
  }

  public void setNext(Node next) // this function sets the next node
  {
    this.next=next;
  }

  public void setPrev(Node prev) // this function sets the previous node
  {
    this.prev=prev;
  }
}

input.txt file #

Jim
Jill
John
Louis
delete Jill
Bob
Jack
delete Jim

Output I get #

Jack
Bob
=========
Bob
Jack

Output I expect

Bob
Jack
John
Louis
=========
Louis
John
Jack
Bob

Body:
Notice this line in the DLL:

else if(tail.getNext()==null)

That condition is always true as the tail never has a node after it.

Maybe you wanted this?

else if (next == null)


问:
How to transform nested XML to CSV?
While not strictly XML at this point, looking to transform a "list" into something which would work for XML shredding, so something more like a table.  Suitable for import to a spreadsheet or a table in a SQL database.

How would this input:

people

joe

phone1

phone2

phone3

sue

cell4

home5

alice

atrib6

x7

y9

z10

get transformed to a structure like:

```<code>joe phone1 phone2 phone3
sue cell4 home5
alice atrib6 x7 y9 z10
</code>```

It only matters that the "names" are in the first column, other "attributes" in any of following columns of CSV or similar, or something exportable as such CSV.  It doesn't have to be CSV, perhaps just convertible to such a structure because BaseX exports to CSV quite nicely through the GUI.

or, perhaps:

```<code>joe phone1
joe phone2
joe phone3
sue cell4
sue home5
alice atrib6
alice x7
alice y9
alice z10
</code>```

Although I prefer the former for this specific data.

答:
I think in another question you already got the suggestion to use windowing:

```<code>declare namespace output = "http://www.w3.org/2010/xslt-xquery-serialization";

declare option output:method 'text';
declare option output:item-separator '
';

for tumbling window $group in ul/*
start $s next $n when $s[self::li] and $n[self::ul]
return
    tail($group) ! ($s || ',' || .)
</code>```

https://xqueryfiddle.liberty-development.net/6qVSgeS

Title: How to transform nested XML to CSV?

Body:
While not strictly XML at this point, looking to transform a "list" into something which would work for XML shredding, so something more like a table.  Suitable for import to a spreadsheet or a table in a SQL database.

How would this input:

people

joe

phone1

phone2

phone3

sue

cell4

home5

alice

atrib6

x7

y9

z10

get transformed to a structure like:

joe phone1 phone2 phone3
sue cell4 home5
alice atrib6 x7 y9 z10

It only matters that the "names" are in the first column, other "attributes" in any of following columns of CSV or similar, or something exportable as such CSV.  It doesn't have to be CSV, perhaps just convertible to such a structure because BaseX exports to CSV quite nicely through the GUI.

or, perhaps:

joe phone1
joe phone2
joe phone3
sue cell4
sue home5
alice atrib6
alice x7
alice y9
alice z10

Although I prefer the former for this specific data.

Body:
I think in another question you already got the suggestion to use windowing:

declare namespace output = "http://www.w3.org/2010/xslt-xquery-serialization";

declare option output:method 'text';
declare option output:item-separator '&#10;';

for tumbling window $group in ul/*
start $s next $n when $s[self::li] and $n[self::ul]
return
    tail($group) ! ($s || ',' || .)

https://xqueryfiddle.liberty-development.net/6qVSgeS


问:
api response unreadable
I am getting an unreadable format of data when I called the api in android. But my actual response via postman as follows.

When I debug the code response is as follows.

Why the data response is showing like so? How can I get the data as in postman response?

答: You need right click data and select inspection  .. Then click view text </p>

Title: api response unreadable


问:
Best way to return the nth digit in a number?
I have a solution but it looks messy and was hoping there was a better way:

Write a function that returns the nth digit of a number

/*
Write a function that returns the nth digit of a number
digitN(498, 1)  // 8
digitN(498, 10) // 9
digitN(498, 100) // 4
*/

function digitN(number, base){
  if(base === 1){
    return number % 10;
  }
  if(base === 10){
    return Math.floor((number % 100) / 10);
  }
  if(base === 100){
    return Math.floor((number % 1000) / 100);
  }
}

console.log(digitN(498, 100))```

答:
The trick is to do it with fewer operations and function calls.

```<code>function digitN(N, base) {
    return Math.floor(N / base % 10);
}
</code>```

Or if you are a cool cat:

```<code>const digitN(N, base) => Math.floor(N / base % 10);
</code>```

Body:
The trick is to do it with fewer operations and function calls.

function digitN(N, base) {
    return Math.floor(N / base % 10);
}

Or if you are a cool cat:

const digitN(N, base) => Math.floor(N / base % 10);


问:
Using PHP to check for mysql DB changes
I'm creating a new web application and I only want to update certain tables when the db is changed, this will be done by firing off a PHP script in a JavaScript setInterval.

My issue is that I am having a hard time trying to find a way to easily determine if certain rows in the database table have changed. In other instances I have used "show table status" and compared that against the last update_time that I had already stored.

In this case though, I don't want to look at the entire table, I just need to know if the rows in my query have changed. I originally tried to md5 the array, as well as md5 on the serialization of the array. It seems that neither of them work and return the same md5 hash each time.

Just for example, here is my query:

```<code>$getUserTable = mysql_query("select * from uct_admin.resources where teamID='62' order by ResourceName");
</code>```

Solution that I came up with after reading the answers:

```<code>$getUserTable = mysql_query("select * from uct_admin.resources where teamID='62' order by csiname");
while ($row = mysql_fetch_assoc($getUserTable)) {
    $arrayTest[] = $row;
}
$hash = md5(http_build_query($arrayTest, 'flags_'));
</code>```

This works perfectly due to the nested array returned from the query.

答:
I'd create a table to log all changes, called dbLogTable.  ID (foreign key) and timeStamp would be its columns.  Each time your PHP script runs, use truncate table dbLogTable in order to clear the table.  Your PHP script could detect any changes by running COUNT(*) FROM dbLogTable, which would be zero if there were no changes and nonzero if there were changes.  All changes could then be accessed via the foreign key, ID.

Disclaimer: I'm a noob when it comes to DB work, so while this may be how I would do it, it might not be the best way to do it.

Title: Using PHP to check for mysql DB changes

Body:
I'm creating a new web application and I only want to update certain tables when the db is changed, this will be done by firing off a PHP script in a JavaScript setInterval.

My issue is that I am having a hard time trying to find a way to easily determine if certain rows in the database table have changed. In other instances I have used "show table status" and compared that against the last update_time that I had already stored.

In this case though, I don't want to look at the entire table, I just need to know if the rows in my query have changed. I originally tried to md5 the array, as well as md5 on the serialization of the array. It seems that neither of them work and return the same md5 hash each time.

Just for example, here is my query:

$getUserTable = mysql_query("select * from uct_admin.resources where teamID='62' order by ResourceName");

Solution that I came up with after reading the answers:

$getUserTable = mysql_query("select * from uct_admin.resources where teamID='62' order by csiname");
while ($row = mysql_fetch_assoc($getUserTable)) {
    $arrayTest[] = $row;
}
$hash = md5(http_build_query($arrayTest, 'flags_'));

This works perfectly due to the nested array returned from the query.


问:
Youtube Live Streaming API for WebRTC
I made a simple webRTC web page with javascript and Signal server for it.
And, I would like to post a part of screen on Youtube Live Streaming.
is it possible to do it?
if so, I want to know how to do it.

thanks.

答:
Well, afaik, so far there is no standard interface for YouTube Live-WebRTC. It seems internally that they do use WebRTC for some things (camera capture), but they don't seem to provide an interface for third-party to do this and the solutions you have are hacks. They may not work in production environment and you can't rely on them.

There are some intermediate tools that convert WebRTC video to formats that YouTube Live accepts. One of them is Flashphoner. You can take a look at that.

Title: Youtube Live Streaming API for WebRTC


问:
How to stop Visual Studio from moving and/or resizing controls when opening a project?
I have a certain project that's been problematic in visual studio. The main form has a TabControl with four tab pages, and during initial development, the entire contents of the third tab page would shift down each time the project was opened. (It got really bad if you didn't look at that page for a few days, and the next time you ran the program, you had to scroll down past all the blank space that had built up before getting to any content.) That was relatively easy to work around by selecting everything and dragging it back up to the top.

Since the project has gone into maintenance/enhancement mode, the third tab page hasn't had any problems, but several controls on the fourth tab page are being re-sized (a small increase in width) or shifted left (a large decrease in X-position). Again, these same controls are affected each time the project is opened, so if you don't fix them each time, they'll continue to get further away from their correct settings.

The problem description is a lot like this other question; one notable difference is that the designer source file is not changed, i.e., I can open the designer source file in a separate text editor and see the correct values for location and position of all the affected controls, while at the same time I have the project open in Visual Studio and see the incorrect values in the Properties window. (Doing a "Save" or "Save All" doesn't affect the designer source file after just opening the project, but changing anything on the form and then saving it will make the source file match the incorrect values from Visual Studio.)

Any ideas about why Visual Studio is displaying the form incorrectly? I'd really like to avoid having to spend the extra time to fix it every day. And I'm not keen on adding code to the constructor to re-set those properties, as suggested elsewhere (violation of SPOT/DRY rule, you know--fraught with peril).

答:
I finally found a way to get around this.  When I set the affected form's Minimum Size property in the designer to something other than 0,0 (such as the current size of the form)  some of the controls relocate themselves the next time I open the form.  Setting Minimum Size back to 0,0 resolves it. The affected controls either have no Anchor setting or have Anchor set to Bottom.

So its seems the combination of Anchor Bottom and non-zero Minimum Size is what makes this unwanted movement happen.

ContentLicense: CC BY-SA 2.5


问:
How force remove network interfaces? AWS - Error detaching network interface
I created stack with nested stacks, there is some network interfaces, VPC etc.
I try to remove network interface but I can't because I'm getting an error

```<code>Error detaching network interface
eni-0d3be6d4c7869686a: You are not allowed to manage 'ela-attach' attachments.
</code>```

Do you have any ideas how to force remove?

答:
Find the resource that the ENI is attached to. It could be a Lambda function or ELB, for example. Was that resource created outside of your CloudFormation stack? If so, you'll need to delete that resource. If it was created within the CloudFormation stack, then you might just need to wait and retry (e.g. if a warm Lambda function was holding on to the ENI).

Steps are described in more detail here. Other ideas here.

Body:
I created stack with nested stacks, there is some network interfaces, VPC etc.
I try to remove network interface but I can't because I'm getting an error

Error detaching network interface
eni-0d3be6d4c7869686a: You are not allowed to manage 'ela-attach' attachments.

Do you have any ideas how to force remove?


问:
Regex are "(" and ")" necessary?
Do I only have to use (and ) if the pattern consists of multiple groups?

So if the pattern is true|false it doesn't matter if I add parenthesis or not, right?
Then again, if the pattern is POINT_PATTERN("\\((\\d+),(\\d+)\\)") it does make a difference because I want to get two different values from it.

Can I write my current patterns, which are:

```<code>NUMBER_PATTERN("(?!(0[0-9]))[0-9]+"),
BOOLEAN_PATTERN("(true|false)"),
STRING_PATTERN("(\\w+)"),
INTEGER_PATTERN("/^([+-]?[1-9]\\d*|0)$/"),
</code>```

as

```<code>NUMBER_PATTERN("(?!0[0-9])[0-9]+"),
BOOLEAN_PATTERN("true|false"),
STRING_PATTERN("\\w+"),
INTEGER_PATTERN("^[+-]?[1-9]\\d*|0$");
</code>```

without any loss?

I am particularly unsure about NUMER_PATTERN and INTEGER_PATTERN. Is there any other reason why I shouldn't do this (bad coding style, ...)?

答:
Yes, a sequence of characters or character classes is the default, and it is of higher precedence than the OR operator |. So if you don't have anything in front or behind your sequence (clearly displayed in your cases of true|false) then you don't need them.

However, if you want to use e.g. this is true|false for "this is true" or "this is false" then the precedence will fail for "this is false" and you need to group the true|false, for instance using a non-capturing group, e.g. this is (?:true|false).

I don't see any problems with your expressions where you removed some of the parentheses. However, if you want to check them, then simply put them into an (online) checker that shows the precedence (e.g. this one) and check if the resulting "explanation" changes. The various IDE plugings for regexp testing will hopefully also provide a similar tree view for you.

Beware that you are sometimes using boundary matchers (^ and $) and sometimes you are not. I'd expect those to be either used or not used.

Title: Regex are "(" and ")" necessary?

Body:
Do I only have to use (and ) if the pattern consists of multiple groups?

So if the pattern is true|false it doesn't matter if I add parenthesis or not, right?
Then again, if the pattern is POINT_PATTERN("\\((\\d+),(\\d+)\\)") it does make a difference because I want to get two different values from it.

Can I write my current patterns, which are:

NUMBER_PATTERN("(?!(0[0-9]))[0-9]+"),
BOOLEAN_PATTERN("(true|false)"),
STRING_PATTERN("(\\w+)"),
INTEGER_PATTERN("/^([+-]?[1-9]\\d*|0)$/"),

as

NUMBER_PATTERN("(?!0[0-9])[0-9]+"),
BOOLEAN_PATTERN("true|false"),
STRING_PATTERN("\\w+"),
INTEGER_PATTERN("^[+-]?[1-9]\\d*|0$");

without any loss?

I am particularly unsure about NUMER_PATTERN and INTEGER_PATTERN. Is there any other reason why I shouldn't do this (bad coding style, ...)?


问:
Typescript alias for builtin type
How can i make alias for built in type such as from utility-types, i have definition which have the same name as builtin types, and happen to use type with the same name from builtin types, example :

```<code>interface Record { // <-- my definition

   toObject() : Record<string, object> // <-- built in definition
}
</code>```

does not work

```<code>type TsRecord<K,V> = Record<K, V>
</code>```

if there is an import method, i cant find the reference

```<code>import {Record as TsRecord} from ?
</code>```

答:
Not sure why you have to use the name Record for your own definition but you could reuse the source for the record utility type for the custom TsRecord type:

```<code>type TsRecord<K extends keyof any, T> = {
  [P in K]: T;
};

interface Record {
  // <-- my definition
  toObject(): TsRecord<string, object>;
}
</code>```

Or rename your own definition:

```<code>interface TsRecord {
  // <-- my definition
  toObject(): Record<string, object>;
}
</code>```

Title: Typescript alias for builtin type

Body:
How can i make alias for built in type such as from utility-types, i have definition which have the same name as builtin types, and happen to use type with the same name from builtin types, example :

interface Record { // <-- my definition

   toObject() : Record<string, object> // <-- built in definition
}

does not work

type TsRecord<K,V> = Record<K, V>

if there is an import method, i cant find the reference

import {Record as TsRecord} from ?

Body:
Not sure why you have to use the name Record for your own definition but you could reuse the source for the record utility type for the custom TsRecord type:

type TsRecord<K extends keyof any, T> = {
  [P in K]: T;
};

interface Record {
  // <-- my definition
  toObject(): TsRecord<string, object>;
}

Or rename your own definition:

interface TsRecord {
  // <-- my definition
  toObject(): Record<string, object>;
}


问:
ETL batch processing
I'm looking for some open source technology that will allow me to create scheduled batch processing (e.g. Query every 1 hour some SQL DB like Oracle, and insert to Kafka. It is possible that some transformation will be done to the data between). The thing is that I need to be able to transport large amount of data ("big data" - Oracle queries could return 10GB or more).

I read about Apache Airflow for example, but it does not seem to fit for large amount of data.

What other technologies can I use for that purpose?

答:
Your understanding of Apache Airflow is slightly misleading. It is meant to be used for programmatically authoring, scheduling and monitoring workflows.

You can use various techs to do the ETL job you intend to do. Airflow is meant to be orchestrator. It can do

Monitoring Cron jobs

Transferring data from one place to other (which might include periodically fetching data from multiple sources)

Machine Learning Pipelines.

Airflow has integration with all major cloud vendors as well. MS Azure, GCP, AWS. See this. It can work well with Qubole, Spark and others.

I would urge you to look at 2 separate things in 2 separate lights. Doing actual ETL job might require it's own setup and running it in a scheduled way is where Airflow comes into picture. Airflow can also help you with the devops aspect of your job.

Title: ETL batch processing