问:
Compiling with Intel Threading Building Blocks: error operands to ?:
Currently, I try to compile OpenVDB, which depends on Threading Building Blocks. I get the following error:

```<code>In file included from /usr/include/tbb/enumerable_thread_specific.h:32:0,
             from ../openvdb/tools/Morphology.h:59,
             from ../openvdb/tools/MultiResGrid.h:64,
             from cmd/openvdb_lod/main.cc:32:
/usr/include/tbb/concurrent_vector.h: In member function ‘tbb::concurrent_vector<T, A>::iterator tbb::concurrent_vector<T, A>::grow_by(tbb::concurrent_vector<T, A>::size_type)’:
/usr/include/tbb/concurrent_vector.h:667:38: error: operands to ?: have different types ‘tbb::internal::concurrent_vector_base_v3::size_type {aka long unsigned int}’ and ‘tbb::atomic<long unsigned int>’
     return iterator(*this, delta ? internal_grow_by( delta, sizeof(T), &initialize_array, NULL ) : my_early_size);
                            ~~~~~~^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
/usr/include/tbb/concurrent_vector.h:667:38: note:   and each type can be converted to the other
/usr/include/tbb/concurrent_vector.h: In member function ‘tbb::concurrent_vector<T, A>::iterator tbb::concurrent_vector<T, A>::grow_by(tbb::concurrent_vector<T, A>::size_type, tbb::concurrent_vector<T, A>::const_reference)’:
/usr/include/tbb/concurrent_vector.h:680:38: error: operands to ?: have different types ‘tbb::internal::concurrent_vector_base_v3::size_type {aka long unsigned int}’ and ‘tbb::atomic<long unsigned int>’
     return iterator(*this, delta ? internal_grow_by( delta, sizeof(T), &initialize_array_by, static_cast<const void*>(&t) ) : my_early_size);
                            ~~~~~~^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
/usr/include/tbb/concurrent_vector.h:680:38: note:   and each type can be converted to the other
make: *** [vdb_lod] Error 1
</code>```

In short, as second and third argument, the ?: operator gets one base type and the same base type wrapped in tbb::atomic, with the compiler not knowing which type to use as return value.

Needless to say, I have no intentions of changing that source code. Since they are established products, it's safe to say that I do something wrong at compiling.

The TBB library file seems to be build with rather old versions of GCC, that is 4.7. I originally thought that the problem might be that I used GCC 7.2.0, therefore I tried out different versions, like GCC 4.8.5, but the error persists.

I haven't tried out 4.7 in particular since I work in a company where I don't have admin rights, and I try to avoid a local installation of GCC. Especially since I don't know if GCC is even the issue here.

Does anyone know a fix to that?

Edit: https://software.intel.com/en-us/forums/intel-threading-building-blocks/topic/417161 seems to be about the same problem, and an employee from Intel noted it for change in there. However, that post was from 2013 and since people used TBB in-between, there must be something I do different in general.

答:
It looks like that an outdated TBB version is used.
See the similar question on the TBB forum.</p>

Body:
Currently, I try to compile OpenVDB, which depends on Threading Building Blocks. I get the following error:

In file included from /usr/include/tbb/enumerable_thread_specific.h:32:0,
             from ../openvdb/tools/Morphology.h:59,
             from ../openvdb/tools/MultiResGrid.h:64,
             from cmd/openvdb_lod/main.cc:32:
/usr/include/tbb/concurrent_vector.h: In member function ‘tbb::concurrent_vector<T, A>::iterator tbb::concurrent_vector<T, A>::grow_by(tbb::concurrent_vector<T, A>::size_type)’:
/usr/include/tbb/concurrent_vector.h:667:38: error: operands to ?: have different types ‘tbb::internal::concurrent_vector_base_v3::size_type {aka long unsigned int}’ and ‘tbb::atomic<long unsigned int>’
     return iterator(*this, delta ? internal_grow_by( delta, sizeof(T), &initialize_array, NULL ) : my_early_size);
                            ~~~~~~^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
/usr/include/tbb/concurrent_vector.h:667:38: note:   and each type can be converted to the other
/usr/include/tbb/concurrent_vector.h: In member function ‘tbb::concurrent_vector<T, A>::iterator tbb::concurrent_vector<T, A>::grow_by(tbb::concurrent_vector<T, A>::size_type, tbb::concurrent_vector<T, A>::const_reference)’:
/usr/include/tbb/concurrent_vector.h:680:38: error: operands to ?: have different types ‘tbb::internal::concurrent_vector_base_v3::size_type {aka long unsigned int}’ and ‘tbb::atomic<long unsigned int>’
     return iterator(*this, delta ? internal_grow_by( delta, sizeof(T), &initialize_array_by, static_cast<const void*>(&t) ) : my_early_size);
                            ~~~~~~^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
/usr/include/tbb/concurrent_vector.h:680:38: note:   and each type can be converted to the other
make: *** [vdb_lod] Error 1

In short, as second and third argument, the ?: operator gets one base type and the same base type wrapped in tbb::atomic, with the compiler not knowing which type to use as return value.

Needless to say, I have no intentions of changing that source code. Since they are established products, it's safe to say that I do something wrong at compiling.

The TBB library file seems to be build with rather old versions of GCC, that is 4.7. I originally thought that the problem might be that I used GCC 7.2.0, therefore I tried out different versions, like GCC 4.8.5, but the error persists.

I haven't tried out 4.7 in particular since I work in a company where I don't have admin rights, and I try to avoid a local installation of GCC. Especially since I don't know if GCC is even the issue here.

Does anyone know a fix to that?

Edit: https://software.intel.com/en-us/forums/intel-threading-building-blocks/topic/417161 seems to be about the same problem, and an employee from Intel noted it for change in there. However, that post was from 2013 and since people used TBB in-between, there must be something I do different in general.


来源: stackexchange

问:
How to find minimum of BigDecimal field in collection with java streams?
I want to use java streams to iterate a list and find the BigDecimal minimum price. The following illustrates, but does not work (because min() cannot accept BigDecimal.

```<code>class Product {
    public BigDecimal price;
}

List<Product> products;
products.stream().min((Product) p -> p.price);
</code>```

答:
Did you try :</p>

```<code>Product minProductPrice = producs.stream()
        .min((o1, o2) -> o1.price.compareTo(o2.price)).get();
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I want to use java streams to iterate a list and find the BigDecimal minimum price. The following illustrates, but does not work (because min() cannot accept BigDecimal.

class Product {
    public BigDecimal price;
}

List<Product> products;
products.stream().min((Product) p -> p.price);

Body:
Did you try :

Product minProductPrice = producs.stream()
        .min((o1, o2) -> o1.price.compareTo(o2.price)).get();


问:
Sharing large datasets between Matlab and R
I need a relatively efficient way to share data between Matlab and R.

I have checked SaveR and MATLAB R-link, but SaveR formats Matlab's binary data as text strings first and then prints them to an ASCII file, which is not efficient for large datasets, and MATLAB R-link only works on Windows (it uses a COM-based interface).

Update:

Dirk has posted a list of what seem to be better solutions to this problem than SaveR and Matlab R-link. I also learned recently about RAM disks (see here and here for some implementation examples), and thought that they might facilitate the task of sharing large datasets between Matlab and R (or similar computational environments) further. This leads me to the following questions:

Assumming that the data fits in the machines' memory in Matlab's or R's native data containers:

Are any of the solutions listed so
far a better fit for RAM disks?

Are there any additional
considerations to be taken into
account when dealing with RAM disks
instead of with secundary-storage
solutions?

Thanks!

答: Matlab use HDF5 natively in last versions ("save" and "load"). There is a package for R. Then HDF5 might be a good solution.</p>

ContentLicense: CC BY-SA 2.5


问:
COM interop - event and property with same name
I have an old COM object implemented in C++/ATL. The object has an event and a property with the same name. This is not a problem in COM.

In C#, the property effectively hides the event, so it doesn't seem possible to add an event handler.

Is there a solution to this problem in C#?

(Interestingly, you can handle it in VB.NET using the WithEvents and Handles mechanism, but that doesn't help me in C#).

Update

This is the definition of the event interface (IDL).

```<code>// Event interface to be implemented by channel objects.
[
  uuid(FF34BE60-C584-4f45-B3A1-231F0E08BE83),
  helpstring("IChannelEvents Interface"),
]
dispinterface IChannelEvents
{
  properties:
  methods:
  [id(1), helpstring("")]
  void OnlineValue ( [in] double        dValue,
                     [in] double        dMax,
                     [in] double        dMin,
                     [in] BSTR          Unit,
                     [in] VARIANT_BOOL  bOverloaded );

  [id(2), helpstring("")]
  void MeasuredExcitation ( [in] double        dValue,
                            [in] VARIANT_BOOL  bValueValid,
                            [in] VARIANT_BOOL  bInRange );

  [id(3), helpstring("")]
  void MultipleOnlineValues ( [in] VARIANT        Values,
                              [in] BSTR           Unit );
} ;
</code>```

This it the definition of the COM object (IDL)

```<code>[
  uuid(2B725FC4-6FE6-4D53-9528-F098F04E98EE),
  helpstring("Channel Class")
]
coclass Channel
{
  [default] interface IChannel;
  [default, source ] dispinterface IChannelEvents ;
};
</code>```

The interface IChannel contains a property named OnlineValue. I don't think the exact definition is important.

Hans seems to be suggesting something like this:

```<code>class EventTest
{
  void Test()
  {
    Channel         c  = null ;
    IChannelEvents  ce = c as IChannelEvents ;
    ce.OnlineValue += this.OnlineValue ;
  }

  void OnlineValue ( double        dValue,
                     double        dMax,
                     double        dMin,
                     string        Unit,
                     bool          bOverloaded )
  {
  }
}
</code>```

This generates the error

```<code>Error CS1656
Cannot assign to 'OnlineValue' because it is a 'method group'
</code>```

This code doesn't really make sense to me, because - as Hans says - the channel object does not implements the event interface, so why would the cast from Channel to IChannelEvents work?

答:
I have found a solution, which is probably what Hans Passant was suggesting.

The event interface is named IChannelEvents. The type library importer generates an interface named IChannelEvents_Event.

Disassembled, the interface definition is as follows:

```<code>[ComEventInterface(typeof(IChannelEvents), typeof(IChannelEvents_EventProvider)), ComVisible(false), TypeLibType(16)]
public interface IChannelEvents_Event
{
  event IChannelEvents_OnlineValueEventHandler OnlineValue;
  event IChannelEvents_MeasuredExcitationEventHandler MeasuredExcitation;
  event IChannelEvents_MultipleOnlineValuesEventHandler MultipleOnlineValues;
}
</code>```

I can cast the COM object to this interface and add an event handler as shown below.

```<code>class EventTest
{
  void Test()
  {
    Channel              c  = null ;
    IChannelEvents_Event ee = c as IChannelEvents_Event ;

    ee.OnlineValue += OnlineValue ;
  }

  void OnlineValue ( double        dValue,
                     double        dMax,
                     double        dMin,
                     string        Unit,
                     bool          bOverloaded )
  {
  }
}
</code>```

This interface does not show up in intellisense, but after entering it, visual Studio sets the text color to indicate that it recognizes the type.

Body:
I have an old COM object implemented in C++/ATL. The object has an event and a property with the same name. This is not a problem in COM.

In C#, the property effectively hides the event, so it doesn't seem possible to add an event handler.

Is there a solution to this problem in C#?

(Interestingly, you can handle it in VB.NET using the WithEvents and Handles mechanism, but that doesn't help me in C#).

Update

This is the definition of the event interface (IDL).

// Event interface to be implemented by channel objects.
[
  uuid(FF34BE60-C584-4f45-B3A1-231F0E08BE83),
  helpstring("IChannelEvents Interface"),
]
dispinterface IChannelEvents
{
  properties:
  methods:
  [id(1), helpstring("")]
  void OnlineValue ( [in] double        dValue,
                     [in] double        dMax,
                     [in] double        dMin,
                     [in] BSTR          Unit,
                     [in] VARIANT_BOOL  bOverloaded );

  [id(2), helpstring("")]
  void MeasuredExcitation ( [in] double        dValue,
                            [in] VARIANT_BOOL  bValueValid,
                            [in] VARIANT_BOOL  bInRange );

  [id(3), helpstring("")]
  void MultipleOnlineValues ( [in] VARIANT        Values,
                              [in] BSTR           Unit );
} ;

This it the definition of the COM object (IDL)

[
  uuid(2B725FC4-6FE6-4D53-9528-F098F04E98EE),
  helpstring("Channel Class")
]
coclass Channel
{
  [default] interface IChannel;
  [default, source ] dispinterface IChannelEvents ;
};

The interface IChannel contains a property named OnlineValue. I don't think the exact definition is important.

Hans seems to be suggesting something like this:

class EventTest
{
  void Test()
  {
    Channel         c  = null ;
    IChannelEvents  ce = c as IChannelEvents ;
    ce.OnlineValue += this.OnlineValue ;
  }

  void OnlineValue ( double        dValue,
                     double        dMax,
                     double        dMin,
                     string        Unit,
                     bool          bOverloaded )
  {
  }
}

This generates the error

Error CS1656
Cannot assign to 'OnlineValue' because it is a 'method group'

This code doesn't really make sense to me, because - as Hans says - the channel object does not implements the event interface, so why would the cast from Channel to IChannelEvents work?

Body:
I have found a solution, which is probably what Hans Passant was suggesting.

The event interface is named IChannelEvents. The type library importer generates an interface named IChannelEvents_Event.

Disassembled, the interface definition is as follows:

[ComEventInterface(typeof(IChannelEvents), typeof(IChannelEvents_EventProvider)), ComVisible(false), TypeLibType(16)]
public interface IChannelEvents_Event
{
  event IChannelEvents_OnlineValueEventHandler OnlineValue;
  event IChannelEvents_MeasuredExcitationEventHandler MeasuredExcitation;
  event IChannelEvents_MultipleOnlineValuesEventHandler MultipleOnlineValues;
}

I can cast the COM object to this interface and add an event handler as shown below.

class EventTest
{
  void Test()
  {
    Channel              c  = null ;
    IChannelEvents_Event ee = c as IChannelEvents_Event ;

    ee.OnlineValue += OnlineValue ;
  }

  void OnlineValue ( double        dValue,
                     double        dMax,
                     double        dMin,
                     string        Unit,
                     bool          bOverloaded )
  {
  }
}

This interface does not show up in intellisense, but after entering it, visual Studio sets the text color to indicate that it recognizes the type.


问:
Javascript - code and decode from base64 using atob() and btoa() functions
I am trying some simple code - decode logic using the standard browser functionalities atob() and btoa() and I am encountering behaviors I can not fully understand.

I have written a very simple test case

```<code> it('converts from base64 to ascii', () => {
    const stringA = 'I am Enrico in Asci';
    const stringB = atob(stringA);
    const stringA1 = btoa(stringB);
    console.log('My ASCCI to binary and viceversa', stringA1);
    expect(stringA1).toBe(stringA);
  });
</code>```

The test case fails. What I see on the console of Chrome is

```<code>Expected 'IamEnricoinAscg=' to be 'I am Enrico in Asci'.
</code>```

Apparently all spaces have gone and end character is wrong.
Any help is appreciated.

答:
```<code>const stringA1 = btoa(stringB);
</code>```

<p>you define constant , there must be var </p>

```<code>var stringA1 = btoa(stringB);
</code>```

Body:
I am trying some simple code - decode logic using the standard browser functionalities atob() and btoa() and I am encountering behaviors I can not fully understand.

I have written a very simple test case

 it('converts from base64 to ascii', () => {
    const stringA = 'I am Enrico in Asci';
    const stringB = atob(stringA);
    const stringA1 = btoa(stringB);
    console.log('My ASCCI to binary and viceversa', stringA1);
    expect(stringA1).toBe(stringA);
  });

The test case fails. What I see on the console of Chrome is

Expected 'IamEnricoinAscg=' to be 'I am Enrico in Asci'.

Apparently all spaces have gone and end character is wrong.
Any help is appreciated.

Body:
const stringA1 = btoa(stringB);

you define constant , there must be var

var stringA1 = btoa(stringB);


问:
rstrip on python behaving awkwardly: 'HelloWorld'.rstrip('World') deletes everything after 'He'

I had started learning python recently, and I have encountered a awkward behavior with rstrip.

My understanding is that the str.rstrip() will delete all characters as soon as it encounters one of the character it took in an argument.

```<code>>>> a = 'HelloWorld'
>>> a.rstrip('l')
'HelloWorld'
>>> a = 'HelloWorld'
>>> a.rstrip('World')
'He'
</code>```

I'm totally confused by the result I've got.

Shouldn't the first code supposed be producing 'He' instead?

答: It seems to start from the right and stop as soon as it encounters a character that is not in the set you passed as argument.</p>

Body:
I had started learning python recently, and I have encountered a awkward behavior with rstrip.

My understanding is that the str.rstrip() will delete all characters as soon as it encounters one of the character it took in an argument.

>>> a = 'HelloWorld'
>>> a.rstrip('l')
'HelloWorld'
>>> a = 'HelloWorld'
>>> a.rstrip('World')
'He'

I'm totally confused by the result I've got.

Shouldn't the first code supposed be producing 'He' instead?


问:
Cut after the closest word boundary after specific length
Input

```<code><items>
    <item>Lorem ipsum dolor sit amet, sed diam nonumy tempor magna aliquyam erat. Ssed diam voluptua.</item>
    <item>Lorem ipsum dolor sit amet, sed diam nonumy<br/>tempor magna aliquyam erat. Ssed diam voluptua.</item>
    <item>Lorem ipsum dolor sit amet, sed diam nonumy <b>tempor magna aliquyam erat</b>. Ssed diam voluptua.</item>
    <item>Lorem ipsum dolor sit amet, sed diam nonumy <b>tempor <i>magna</i> aliquyam erat</b>. Ssed diam voluptua.</item>
    <item>Lorem ipsum dolor sit amet.</item>
</items>
</code>```

Requirements

"Cut" after the closest word after a specific length, e.g. 25 characters (incl. whitespaces)

All nodes() before that position are untouched

All * after that position get a attribute foo="bar"

All text() after that position are processed by a template with mode='xy' (this template will uglify the text); the template wraps all adjacent text()-nodes in a <o foo="bar"> + itself as '#'

IF text()-nodes are in a particial readable/uglified *, these text()-nodes are wrapped within a new element <o foo="bar"> [see item[4] => "aliquyam erat"] + itself as '#'

IF string-length(text()) le $visibleChars THEN nothing happens

Output

```<code><!-- middle of word "temppor" -->
<xsl:variable name="visibleChars" select="number(48)"/>
<items>
    <item>Lorem ipsum dolor sit amet, sed diam nonumy tempor<o foo="bar"> #</o></item>
    <item>Lorem ipsum dolor sit amet, sed diam nonumy<br/>tempor<o foo="bar"> #</o></item>
    <item>Lorem ipsum dolor sit amet, sed diam nonumy <b>tempor<o foo="bar">#</o></b><o foo="bar">#</o></item>
    <item>Lorem ipsum dolor sit amet, sed diam nonumy <b>tempor <i foo="bar">#</i><o foo="bar"> #</o></b><o foo="bar">#</o></item>
    <item>Lorem ipsum dolor sit amet.</item>
</items>
</code>```

Failed pseudo xslt

```<code><xsl:templates match="item">
  WHEN count(text()) eq count(node())
  THEN
     Create a $temp of <item> AND insert a <cut/> at position ($visibleChars + CharsTillNextDelimiter)
     <!-- chars to stay visible -->
     <xsl:apply-templates select="$temp/text()[following-sibling::cut]"/>
     <!-- chars to uglify -->
     <xsl:apply-templates select="$temp/text()[preceding-sibling::cut]" mode="xy"/>

  WHEN (*)
  THEN
     NoIDEAToTackleMixedContentFields

...
<xsl:template match="text()" mode="xy">

    <xsl:analyze-string select="." regex="[a-zA-Z0-9]">
        <xsl:matching-substring>
            <xsl:text>#</xsl:text>
        </xsl:matching-substring>
        <xsl:non-matching-substring>
            <xsl:value-of select="."/>
        </xsl:non-matching-substring>
    </xsl:analyze-string>
</xsl:template>
...
</code>```

I don't have a running minified xslt, nevertheless someone might show me a way to fulfill the requirements. Any help is appreciated and I hope I covered all possible circumstances in my example.

答:
I have managed to insert the cut element and to then process the modified item as follows:

```<code><?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:functx="http://www.functx.com"
    exclude-result-prefixes="xs functx" version="2.0">

    <xsl:param name="length" select="48"/>

    <xsl:function name="functx:escape-for-regex" as="xs:string">
        <xsl:param name="arg" as="xs:string?"/>

        <xsl:sequence
            select="
                replace($arg,
                '(\.|\[|\]|\\|\||\-|\^|\$|\?|\*|\+|\{|\}|\(|\))', '\\$1')
                "/>

    </xsl:function>

    <xsl:template match="@* | node()" mode="#all">
        <xsl:copy>
            <xsl:apply-templates select="@* | node()" mode="#current"/>
        </xsl:copy>
    </xsl:template>

    <xsl:template match="item[string-length() gt $length]">
        <xsl:variable name="head" as="xs:string" select="substring(., 1, $length)"/>
        <xsl:variable name="head-pattern" as="xs:string"
            select="concat('^', functx:escape-for-regex($head), '\S*')"/>
        <xsl:variable name="text-to-cut" as="text()"
            select="descendant::text()[matches(string-join((preceding::text()[. >> current()], .), ''), $head-pattern)][1]"/>
        <xsl:variable name="splitted-text" as="xs:string*">
            <xsl:analyze-string select="$text-to-cut"
                regex="{if ($text-to-cut is (current()//text())[1]) then $head-pattern else '^\S+'}">
                <xsl:matching-substring>
                    <xsl:sequence select="."/>
                </xsl:matching-substring>
                <xsl:non-matching-substring>
                    <xsl:sequence select="."/>
                </xsl:non-matching-substring>
            </xsl:analyze-string>
        </xsl:variable>
        <xsl:variable name="modified-copy" as="element(item)">
            <xsl:copy>
                <xsl:apply-templates mode="modify">
                    <xsl:with-param name="text-to-cut" as="text()" select="$text-to-cut"
                        tunnel="yes"/>
                    <xsl:with-param name="splitted-text" as="xs:string*" select="$splitted-text"
                        tunnel="yes"/>
                </xsl:apply-templates>
            </xsl:copy>
        </xsl:variable>
        <xsl:message select="'modified-copy', $modified-copy"/>
        <xsl:apply-templates select="$modified-copy" mode="cut"/>
    </xsl:template>

    <xsl:template match="item//text()" mode="modify">
        <xsl:param name="text-to-cut" as="text()" tunnel="yes"/>
        <xsl:param name="splitted-text" as="xs:string*" tunnel="yes"/>
        <xsl:choose>
            <xsl:when test=". is $text-to-cut">
                <xsl:value-of select="$splitted-text[1]"/>
                <cut/>
                <xsl:value-of select="$splitted-text[2]"/>
            </xsl:when>
            <xsl:otherwise>
                <xsl:next-match/>
            </xsl:otherwise>
        </xsl:choose>
    </xsl:template>

    <xsl:template match="cut" mode="cut"/>

    <xsl:template match="*[preceding-sibling::cut]" mode="cut">
        <xsl:copy>
            <xsl:attribute name="foo">bar</xsl:attribute>
            <xsl:apply-templates mode="#current"/>
        </xsl:copy>
    </xsl:template>

    <xsl:template match="text()[preceding::cut]" mode="cut">
        <o foo="bar">
            <xsl:analyze-string select="." regex="[a-zA-Z0-9]+">
                <xsl:matching-substring>
                    <xsl:text>#</xsl:text>
                </xsl:matching-substring>
                <xsl:non-matching-substring>
                    <xsl:value-of select="."/>
                </xsl:non-matching-substring>
            </xsl:analyze-string>
        </o>
    </xsl:template>

</xsl:stylesheet>
</code>```

The result I get for your input is not quite what you posted but close so I hope you can adapt that:

```<code><items>
    <item>Lorem ipsum dolor sit amet, sed diam nonumy tempor<o foo="bar"> # # #. # # #.</o></item>
    <item>Lorem ipsum dolor sit amet, sed diam nonumy<br/>tempor<o foo="bar"> # # #. # # #.</o></item>
    <item>Lorem ipsum dolor sit amet, sed diam nonumy <b>tempor<o foo="bar"> # # #</o></b><o foo="bar">. # # #.</o></item>
    <item>Lorem ipsum dolor sit amet, sed diam nonumy <b>tempor<o foo="bar"> </o><i foo="bar"><o foo="bar">#</o></i><o foo="bar"> # #</o></b><o foo="bar">. # # #.</o></item>
    <item>Lorem ipsum dolor sit amet.</item>
</items>
</code>```

Body:
Input

<items>
    <item>Lorem ipsum dolor sit amet, sed diam nonumy tempor magna aliquyam erat. Ssed diam voluptua.</item>
    <item>Lorem ipsum dolor sit amet, sed diam nonumy
tempor magna aliquyam erat. Ssed diam voluptua.</item>
    <item>Lorem ipsum dolor sit amet, sed diam nonumy tempor magna aliquyam erat. Ssed diam voluptua.</item>
    <item>Lorem ipsum dolor sit amet, sed diam nonumy tempor magna aliquyam erat. Ssed diam voluptua.</item>
    <item>Lorem ipsum dolor sit amet.</item>
</items>

Requirements

"Cut" after the closest word after a specific length, e.g. 25 characters (incl. whitespaces)

All nodes() before that position are untouched

All * after that position get a attribute foo="bar"

All text() after that position are processed by a template with mode='xy' (this template will uglify the text); the template wraps all adjacent text()-nodes in a <o foo="bar"> + itself as '#'

IF text()-nodes are in a particial readable/uglified *, these text()-nodes are wrapped within a new element <o foo="bar"> [see item[4] => "aliquyam erat"] + itself as '#'

IF string-length(text()) le $visibleChars THEN nothing happens

Output

<xsl:variable name="visibleChars" select="number(48)"/>
<items>
    <item>Lorem ipsum dolor sit amet, sed diam nonumy tempor<o foo="bar"> #</o></item>
    <item>Lorem ipsum dolor sit amet, sed diam nonumy
tempor<o foo="bar"> #</o></item>
    <item>Lorem ipsum dolor sit amet, sed diam nonumy tempor<o foo="bar">#</o><o foo="bar">#</o></item>
    <item>Lorem ipsum dolor sit amet, sed diam nonumy tempor #<o foo="bar"> #</o><o foo="bar">#</o></item>
    <item>Lorem ipsum dolor sit amet.</item>
</items>

Failed pseudo xslt

<xsl:templates match="item">
  WHEN count(text()) eq count(node())
  THEN
     Create a $temp of <item> AND insert a <cut/> at position ($visibleChars + CharsTillNextDelimiter)

     <xsl:apply-templates select="$temp/text()[following-sibling::cut]"/>

     <xsl:apply-templates select="$temp/text()[preceding-sibling::cut]" mode="xy"/>

  WHEN (*)
  THEN
     NoIDEAToTackleMixedContentFields

...
<xsl:template match="text()" mode="xy">

    <xsl:analyze-string select="." regex="[a-zA-Z0-9]">
        <xsl:matching-substring>
            <xsl:text>#</xsl:text>
        </xsl:matching-substring>
        <xsl:non-matching-substring>
            <xsl:value-of select="."/>
        </xsl:non-matching-substring>
    </xsl:analyze-string>
</xsl:template>
...

I don't have a running minified xslt, nevertheless someone might show me a way to fulfill the requirements. Any help is appreciated and I hope I covered all possible circumstances in my example.

Body:
I have managed to insert the cut element and to then process the modified item as follows:

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:functx="http://www.functx.com"
    exclude-result-prefixes="xs functx" version="2.0">

    <xsl:param name="length" select="48"/>

    <xsl:function name="functx:escape-for-regex" as="xs:string">
        <xsl:param name="arg" as="xs:string?"/>

        <xsl:sequence
            select="
                replace($arg,
                '(\.|\[|\]|\\|\||\-|\^|\$|\?|\*|\+|\{|\}|\(|\))', '\\$1')
                "/>

    </xsl:function>

    <xsl:template match="@* | node()" mode="#all">
        <xsl:copy>
            <xsl:apply-templates select="@* | node()" mode="#current"/>
        </xsl:copy>
    </xsl:template>

    <xsl:template match="item[string-length() gt $length]">
        <xsl:variable name="head" as="xs:string" select="substring(., 1, $length)"/>
        <xsl:variable name="head-pattern" as="xs:string"
            select="concat('^', functx:escape-for-regex($head), '\S*')"/>
        <xsl:variable name="text-to-cut" as="text()"
            select="descendant::text()[matches(string-join((preceding::text()[. >> current()], .), ''), $head-pattern)][1]"/>
        <xsl:variable name="splitted-text" as="xs:string*">
            <xsl:analyze-string select="$text-to-cut"
                regex="{if ($text-to-cut is (current()//text())[1]) then $head-pattern else '^\S+'}">
                <xsl:matching-substring>
                    <xsl:sequence select="."/>
                </xsl:matching-substring>
                <xsl:non-matching-substring>
                    <xsl:sequence select="."/>
                </xsl:non-matching-substring>
            </xsl:analyze-string>
        </xsl:variable>
        <xsl:variable name="modified-copy" as="element(item)">
            <xsl:copy>
                <xsl:apply-templates mode="modify">
                    <xsl:with-param name="text-to-cut" as="text()" select="$text-to-cut"
                        tunnel="yes"/>
                    <xsl:with-param name="splitted-text" as="xs:string*" select="$splitted-text"
                        tunnel="yes"/>
                </xsl:apply-templates>
            </xsl:copy>
        </xsl:variable>
        <xsl:message select="'modified-copy', $modified-copy"/>
        <xsl:apply-templates select="$modified-copy" mode="cut"/>
    </xsl:template>

    <xsl:template match="item//text()" mode="modify">
        <xsl:param name="text-to-cut" as="text()" tunnel="yes"/>
        <xsl:param name="splitted-text" as="xs:string*" tunnel="yes"/>
        <xsl:choose>
            <xsl:when test=". is $text-to-cut">
                <xsl:value-of select="$splitted-text[1]"/>
                <cut/>
                <xsl:value-of select="$splitted-text[2]"/>
            </xsl:when>
            <xsl:otherwise>
                <xsl:next-match/>
            </xsl:otherwise>
        </xsl:choose>
    </xsl:template>

    <xsl:template match="cut" mode="cut"/>

    <xsl:template match="*[preceding-sibling::cut]" mode="cut">
        <xsl:copy>
            <xsl:attribute name="foo">bar</xsl:attribute>
            <xsl:apply-templates mode="#current"/>
        </xsl:copy>
    </xsl:template>

    <xsl:template match="text()[preceding::cut]" mode="cut">
        <o foo="bar">
            <xsl:analyze-string select="." regex="[a-zA-Z0-9]+">
                <xsl:matching-substring>
                    <xsl:text>#</xsl:text>
                </xsl:matching-substring>
                <xsl:non-matching-substring>
                    <xsl:value-of select="."/>
                </xsl:non-matching-substring>
            </xsl:analyze-string>
        </o>
    </xsl:template>

</xsl:stylesheet>

The result I get for your input is not quite what you posted but close so I hope you can adapt that:

<items>
    <item>Lorem ipsum dolor sit amet, sed diam nonumy tempor<o foo="bar"> # # #. # # #.</o></item>
    <item>Lorem ipsum dolor sit amet, sed diam nonumy<br/>tempor<o foo="bar"> # # #. # # #.</o></item>
    <item>Lorem ipsum dolor sit amet, sed diam nonumy <b>tempor<o foo="bar"> # # #</o></b><o foo="bar">. # # #.</o></item>
    <item>Lorem ipsum dolor sit amet, sed diam nonumy <b>tempor<o foo="bar"> </o><i foo="bar"><o foo="bar">#</o></i><o foo="bar"> # #</o></b><o foo="bar">. # # #.</o></item>
    <item>Lorem ipsum dolor sit amet.</item>
</items>


问:
Angular 5 : View not updating
In my view i'm rendering a list of skills, using an observable and *ngFor

I retrieve the skills with the following code:

```<code>getSkills(): void {
    this.skillsDataService.getSkills()
        .subscribe(
            skills => this.skills = skills.sort( this.skillSort )
        );
}
</code>```

However i've learned that it's better to use named functions and not too much nesting. So i changed the code to this:

```<code>getSkills(): void {
    this.skillsDataService.getSkills()
        .subscribe(
            this.processSkills
        );
}

processSkills(skills: Skill[]): void {
    this.skills = skills.sort( this.skillSort );
}
</code>```

And now the view doesn't update, eventhough this.skills is filled.

答:
Your "this" in processSkills will not be the controller when you call it like that. In order to understand what i mean you should just log out "this" inside of processSkills and take a course on how "this" works in JavaScript.
In order to make your code work, try this instead:</p>

```<code>.subscribe(
        this.processSkills.bind(this)
    );
</code>```

Title: Angular 5 : View not updating

Body:
In my view i'm rendering a list of skills, using an observable and *ngFor

I retrieve the skills with the following code:

getSkills(): void {
    this.skillsDataService.getSkills()
        .subscribe(
            skills => this.skills = skills.sort( this.skillSort )
        );
}

However i've learned that it's better to use named functions and not too much nesting. So i changed the code to this:

getSkills(): void {
    this.skillsDataService.getSkills()
        .subscribe(
            this.processSkills
        );
}

processSkills(skills: Skill[]): void {
    this.skills = skills.sort( this.skillSort );
}

And now the view doesn't update, eventhough this.skills is filled.

Body:
Your "this" in processSkills will not be the controller when you call it like that. In order to understand what i mean you should just log out "this" inside of processSkills and take a course on how "this" works in JavaScript.
In order to make your code work, try this instead:

.subscribe(
        this.processSkills.bind(this)
    );


问:
JFoenix: JFXTabPane tab-selected-line color and width
I work with the JFoenix-Library and have a problem.

How can I change the width of the tab-selected-line. I tried the following code but it doesnt work:

```<code>.jfx-tab-pane .tab-selected-line {
-fx-border-color: green;
-fx-stroke-width: 3px;
}
</code>```

I can set the color of the selected line but the width wont work. So i tested it on another way.

I set the border-width and the border-color of the tab like this:

```<code>.jfx-tab-pane .tab:selected {
-fx-border-width: 0 0 4 0;
-fx-border-color: green;
}
</code>```

But after that, I cant set the selected-line color. It takes the default color.
enter image description here

答:
For change stroke color must use -fx-stroke
You can use this:

```<code>.jfx-tab-pane .tab-selected-line {
    -fx-stroke: green;
    -fx-stroke-width: 5pt;
}
</code>```

Body:
I work with the JFoenix-Library and have a problem.

How can I change the width of the tab-selected-line. I tried the following code but it doesnt work:

.jfx-tab-pane .tab-selected-line {
-fx-border-color: green;
-fx-stroke-width: 3px;
}

I can set the color of the selected line but the width wont work. So i tested it on another way.

I set the border-width and the border-color of the tab like this:

.jfx-tab-pane .tab:selected {
-fx-border-width: 0 0 4 0;
-fx-border-color: green;
}

But after that, I cant set the selected-line color. It takes the default color.
enter image description here

Body:
For change stroke color must use -fx-stroke
You can use this:

.jfx-tab-pane .tab-selected-line {
    -fx-stroke: green;
    -fx-stroke-width: 5pt;
}


问:
PHPMailer & STARTTLS not sending email
Message not sending with such settings

```<code>$mail = new PHPMailer;
$mail->SMTPDebug = 4;
$mail->isSMTP();
$mail->Host = "domain.com";
$mail->SMTPAuth = true;
$mail->Username = "login";
$mail->Password = "pasw";
$mail->SMTPSecure = "tls";
$mail->Port = 2525;
$mail->CharSet = 'UTF-8';
</code>```

openssl extension is loaded. Dеbug output is here
https://justpaste.it/1ecjw
First problem line there is
2017-12-08 09:48:53 SMTP -> get_lines(): $str is "502 5.5.1 command not supported in "STARTTLS""

telnet says that there is  ESMTP service.
I don't know what to investigate next...

答:
Not too complicated - your mail server does not support STARTTLS. If it did it would appear in the list of capabilities after the first EHLO command, which is this:

```<code>250-ENHANCEDSTATUSCODES
250-PIPELINING
250-CHUNKING
250-8BITMIME
250-AUTH CRAM-MD5 PLAIN LOGIN
250-AUTH=CRAM-MD5 PLAIN LOGIN
250-XACK
250-SIZE 0
250-VERP
250 DSN
</code>```

STARTTLS is not in that list. It may still support encryption via SMTPSecure = 'ssl' and Port = 465, but otherwise you'll need to fall back to the most secure auth option over this unencrypted channel, which is AuthType = 'CRAM-MD5'.

ESMTP just means that it supports "Extended SMTP" with EHLO (and all that that implies), not just basic SMTP HELO.

BTW - SMTPDebug = 4 is too noisy for this level of problem, you need 3 at most. Also, you're using an old version of PHPMailer, upgrade.

Title: PHPMailer & STARTTLS not sending email

Body:
Message not sending with such settings

$mail = new PHPMailer;
$mail->SMTPDebug = 4;
$mail->isSMTP();
$mail->Host = "domain.com";
$mail->SMTPAuth = true;
$mail->Username = "login";
$mail->Password = "pasw";
$mail->SMTPSecure = "tls";
$mail->Port = 2525;
$mail->CharSet = 'UTF-8';

openssl extension is loaded. Dеbug output is here
https://justpaste.it/1ecjw
First problem line there is
2017-12-08 09:48:53 SMTP -> get_lines(): $str is "502 5.5.1 command not supported in "STARTTLS""

telnet says that there is  ESMTP service.
I don't know what to investigate next...

Body:
Not too complicated - your mail server does not support STARTTLS. If it did it would appear in the list of capabilities after the first EHLO command, which is this:

250-ENHANCEDSTATUSCODES
250-PIPELINING
250-CHUNKING
250-8BITMIME
250-AUTH CRAM-MD5 PLAIN LOGIN
250-AUTH=CRAM-MD5 PLAIN LOGIN
250-XACK
250-SIZE 0
250-VERP
250 DSN

STARTTLS is not in that list. It may still support encryption via SMTPSecure = 'ssl' and Port = 465, but otherwise you'll need to fall back to the most secure auth option over this unencrypted channel, which is AuthType = 'CRAM-MD5'.

ESMTP just means that it supports "Extended SMTP" with EHLO (and all that that implies), not just basic SMTP HELO.

BTW - SMTPDebug = 4 is too noisy for this level of problem, you need 3 at most. Also, you're using an old version of PHPMailer, upgrade.


问:
Trying to write csv file to R variable
My intention is to format a simple matrix in csv format. As I need to further process the formatted lines, I don't want to write the formatted string to a file.

I already tried using textConnection, which seems to be the right approach.

```<code>m<-matrix(c(1,2,3,4), nrow=2)
result<-write.csv(m, file=textConnection(csvData), row.names=FALSE, col.names=FALSE)
</code>```

I'm expecting csvData to contain the contents of the formatted csv (file) as a vector containing the lines.

I get the error:

```<code>Error in textConnection(csvData) : invalid 'text' argument
</code>```

What is the proper usage of textConnection?

Revised question

After some trying and cleaning all variables I ended up with

```<code>rm(list = ls())
m<-matrix(c(1,2,3,4), nrow=2)
result<-write.csv(m, file=textConnection("csvData", "w"), row.names=FALSE, col.names=FALSE)
</code>```

This produces at least no errors, but I ended with a warning that col.names are ignored. The content of csvData is also not what I expected

```<code>> csvData
[1] "\"V1\",\"V2\"" "1,3"           "2,4"
</code>```

How to remove the header?

My solution

After trying I found, that write.csv should be replaced by write.table.

```<code>rm(list = ls())
m<-matrix(c(1,2,3,4), nrow=2)
result<-write.table(m, file=textConnection("csvData", "w"), row.names=FALSE, col.names=FALSE, sep=";")
</code>```

答:
Try write.csv() from MASS

```<code>MASS::write.matrix(m, file = textConnection("csvData", "w"), sep = ";")
</code>```

Title: Trying to write csv file to R variable

Body:
My intention is to format a simple matrix in csv format. As I need to further process the formatted lines, I don't want to write the formatted string to a file.

I already tried using textConnection, which seems to be the right approach.

m<-matrix(c(1,2,3,4), nrow=2)
result<-write.csv(m, file=textConnection(csvData), row.names=FALSE, col.names=FALSE)

I'm expecting csvData to contain the contents of the formatted csv (file) as a vector containing the lines.

I get the error:

Error in textConnection(csvData) : invalid 'text' argument

What is the proper usage of textConnection?

Revised question

After some trying and cleaning all variables I ended up with

rm(list = ls())
m<-matrix(c(1,2,3,4), nrow=2)
result<-write.csv(m, file=textConnection("csvData", "w"), row.names=FALSE, col.names=FALSE)

This produces at least no errors, but I ended with a warning that col.names are ignored. The content of csvData is also not what I expected

> csvData
[1] "\"V1\",\"V2\"" "1,3"           "2,4"

How to remove the header?

My solution

After trying I found, that write.csv should be replaced by write.table.

rm(list = ls())
m<-matrix(c(1,2,3,4), nrow=2)
result<-write.table(m, file=textConnection("csvData", "w"), row.names=FALSE, col.names=FALSE, sep=";")

Body:
Try write.csv() from MASS

MASS::write.matrix(m, file = textConnection("csvData", "w"), sep = ";")


问:
How to setup and use VSTS for five user
Our office uses VSS as source control. Just come to know that VSTS is free for five users and our team is very small with 5 devs.

I have never use VSTS. so i have few questions. please answer pointwise and with detail along with images if possible.

how to create an account for VSTS?

how to upload our local project exist on my pc to VSTS

how could I send an invitation to other 4 developers in our team, as a result, they can clone our uploaded project on their own pc and start working?

I got one link which is showing how to Add Local Project to GIT in VSTS but I need to know how to add a project to TFVC in VSTS.

答:
Create an account

Go to VisualStudio.com, log in using MSA, pick an available account name and register. If you have an Azure subscription and an Azure Active Directory, you can also create the account from the Azure portal, that way you can use your company-account to log on.

Upload local project

When you create your first project you get to choose whether you want TFVC or Git. Once the project is created, getting your sources in differs depending on your choice.

If you pick TFVC you must create a local workspace on your machine, copy the sources into that directory, then check them in.

Invite other users

To add other users to VSTS they need to have an MSA account or to be part of your AAD (depending on how you setup your account). Then go to the Users hub in the VSTS admin panel and add them to your account. The first 5 basic users are free. If users have an MSDN account (pro or higher) they do not count towards the free user limit as VSTS access is included in the subscription.

Title: How to setup and use VSTS for five user

ContentLicense: CC BY-SA 4.0


问:
How to convert messages from socket streaming source to custom domain object?
I'm very new to spark streaming. I have a Spark Standalone 2.2 running with one worker. I'm using a socket source and trying to read the incoming stream into an object called MicroserviceMessage.

val message = spark.readStream
  .format("socket")
  .option("host", host)
  .option("port", port)
  .load()

val df = message.as[MicroserviceMessage].flatMap(microserviceMessage =>
    microserviceMessage.DataPoints.map(datapoint => (datapoint, microserviceMessage.ServiceProperties, datapoint.EpochUTC)))
  .toDF("datapoint", "properties", "timestamp")
```

<p>I'm hoping this will a DataFrame with columns of "datapoint", "properties" and "timestamp"</p>

<p>The data i'm pasting into my netcat terminal looks like this (this is what I'm trying to read in as MicroserviceMessage):</p>

<pre class="lang-scala prettyprint-override"><code>{
  "SystemType": "mytype",
  "SystemGuid": "6c84fb90-12c4-11e1-840d-7b25c5ee775a",
  "TagType": "Raw Tags",
  "ServiceType": "FILTER",
  "DataPoints": [
    {
      "TagName": "013FIC003.PV",
      "EpochUTC": 1505247956001,
      "ItemValue": 25.47177,
      "ItemValueStr": "NORMAL",
      "Quality": "Good",
      "TimeOffset": "P0000"
    },
    {
      "TagName": "013FIC003.PV",
      "EpochUTC": 1505247956010,
      "ItemValue": 26.47177,
      "ItemValueStr": "NORMAL",
      "Quality": "Good",
      "TimeOffset": "P0000"
    }
  ],
  "ServiceProperties": [
    {
      "Key": "OutputTagName",
      "Value": "FI12102.PV_CL"
    },
    {
      "Key": "OutputTagType",
      "Value": "Cleansing Flow Tags"
    }
  ]
}
</code>```

Instead what I see is:

Exception in thread "main" org.apache.spark.sql.AnalysisException: cannot resolve '`SystemType`' given input columns: [value];
```

<p>MicroserviceMessage case class looks like this:</p>

<pre class="lang-scala prettyprint-override"><code>case class DataPoints
(
  TagName: String,
  EpochUTC: Double,
  ItemValue: Double,
  ItemValueStr: String,
  Quality: String,
  TimeOffset: String
)

case class ServiceProperties
(
  Key: String,
  Value: String
)

case class MicroserviceMessage
(
  SystemType: String,
  SystemGuid: String,
  TagType: String,
  ServiceType: String,
  DataPoints: List[DataPoints],
  ServiceProperties: List[ServiceProperties]
)
</code>```

EDIT:
After reading this post I was able to start the job by doing

val messageEncoder = Encoders.bean(classOf[MicroserviceMessage])

val df = message.select($"value").as(messageEncoder).map(
  msmg => (msmg.ServiceType, msmg.SystemGuid)
).toDF("service", "guid")
```

<p>But this causes issues when I start sending data.</p>

<pre class="lang-scala prettyprint-override"><code>Caused by: java.lang.BootstrapMethodError: java.lang.NoClassDefFoundError: scala/runtime/LambdaDeserialize
</code>```

Full stacktrace

答:
The reason for the exception

Caused by: java.lang.BootstrapMethodError: java.lang.NoClassDefFoundError: scala/runtime/LambdaDeserialize

is that you compiled your Spark Structured Streaming application using Scala 2.12.4 (or any other in 2.12 stream) which is unsupported in Spark 2.2.

From the scaladoc of scala.runtime.LambdaDeserializer:

This class is only intended to be called by synthetic $deserializeLambda$ method that the Scala 2.12 compiler will add to classes hosting lambdas.

Spark 2.2 supports up to and including Scala 2.11.12 with 2.11.8 being the most "blessed" version.

Body:
I'm very new to spark streaming. I have a Spark Standalone 2.2 running with one worker. I'm using a socket source and trying to read the incoming stream into an object called MicroserviceMessage.

val message = spark.readStream
  .format("socket")
  .option("host", host)
  .option("port", port)
  .load()

val df = message.as[MicroserviceMessage].flatMap(microserviceMessage =>
    microserviceMessage.DataPoints.map(datapoint => (datapoint, microserviceMessage.ServiceProperties, datapoint.EpochUTC)))
  .toDF("datapoint", "properties", "timestamp")

I'm hoping this will a DataFrame with columns of "datapoint", "properties" and "timestamp"

The data i'm pasting into my netcat terminal looks like this (this is what I'm trying to read in as MicroserviceMessage):

{
  "SystemType": "mytype",
  "SystemGuid": "6c84fb90-12c4-11e1-840d-7b25c5ee775a",
  "TagType": "Raw Tags",
  "ServiceType": "FILTER",
  "DataPoints": [
    {
      "TagName": "013FIC003.PV",
      "EpochUTC": 1505247956001,
      "ItemValue": 25.47177,
      "ItemValueStr": "NORMAL",
      "Quality": "Good",
      "TimeOffset": "P0000"
    },
    {
      "TagName": "013FIC003.PV",
      "EpochUTC": 1505247956010,
      "ItemValue": 26.47177,
      "ItemValueStr": "NORMAL",
      "Quality": "Good",
      "TimeOffset": "P0000"
    }
  ],
  "ServiceProperties": [
    {
      "Key": "OutputTagName",
      "Value": "FI12102.PV_CL"
    },
    {
      "Key": "OutputTagType",
      "Value": "Cleansing Flow Tags"
    }
  ]
}

Instead what I see is:

Exception in thread "main" org.apache.spark.sql.AnalysisException: cannot resolve '`SystemType`' given input columns: [value];

MicroserviceMessage case class looks like this:

case class DataPoints
(
  TagName: String,
  EpochUTC: Double,
  ItemValue: Double,
  ItemValueStr: String,
  Quality: String,
  TimeOffset: String
)

case class ServiceProperties
(
  Key: String,
  Value: String
)

case class MicroserviceMessage
(
  SystemType: String,
  SystemGuid: String,
  TagType: String,
  ServiceType: String,
  DataPoints: List[DataPoints],
  ServiceProperties: List[ServiceProperties]
)

EDIT:
After reading this post I was able to start the job by doing

val messageEncoder = Encoders.bean(classOf[MicroserviceMessage])

val df = message.select($"value").as(messageEncoder).map(
  msmg => (msmg.ServiceType, msmg.SystemGuid)
).toDF("service", "guid")

But this causes issues when I start sending data.

Caused by: java.lang.BootstrapMethodError: java.lang.NoClassDefFoundError: scala/runtime/LambdaDeserialize

Full stacktrace


问:
How to resolve "Error: No provider for AngularFireDatabase"
I'm trying to build a proto chat application using Angular & Firebase.

the foll are my routes:

```<code>export const appRoutes: Routes = [
    { path: 'signup', component: SignupFormComponent },
    { path: 'login', component: LoginFormComponent },
    { path: 'chat', component: ChatroomComponent },
    { path: '', redirectTo: '/login', pathMatch: 'full'},
];
</code>```

But when i route to /chat, i get the foll error. I'm not sure what is it that i am missing here in order to fix this error. any guidance is appreciated.

I have looked at the foll link, but i have included all the import stated in the answers:
No provider for AngularFireDatabase, AngularFireAuth

```<code>ERROR Error: Uncaught (in promise): Error: StaticInjectorError[AngularFireDatabase]:
  StaticInjectorError[AngularFireDatabase]:
    NullInjectorError: No provider for AngularFireDatabase!
Error: StaticInjectorError[AngularFireDatabase]:
  StaticInjectorError[AngularFireDatabase]:
    NullInjectorError: No provider for AngularFireDatabase!
</code>```

the foll is my chat-service.ts file:

```<code>import { Injectable } from '@angular/core';
import { AngularFireDatabase, FirebaseListObservable } from 'angularfire2/database-deprecated';
import { AngularFireAuth } from 'angularfire2/auth';
import { Observable } from 'rxjs/Observable';
import { AuthService } from '../services/auth.service';
import * as firebase from 'firebase/app';

import { ChatMessage } from '../models/chat-message.model';

@Injectable()
export class ChatService {
  user: firebase.User;
  chatMessages: FirebaseListObservable<ChatMessage[]>;
  chatMessage: ChatMessage;
  userName: Observable<string>;

  constructor(
    private db: AngularFireDatabase,
    private afAuth: AngularFireAuth
    ) {
        /*this.afAuth.authState.subscribe(auth => {
          if (auth !== undefined && auth !== null) {
            this.user = auth; // the user object is only going to be set if we are authenticated
          }

        });*/
    }

   sendMessage(msg: string) { //per all the properties defined in the chat-message model
    const timestamp = this.getTimeStamp();
  //  const email = this.user.email;
    const email = "test@gmail.com";
    this.chatMessages = this.getMessages();
    this.chatMessages.push({
      message: msg,
      timeSent: timestamp,
      //userName: this.userName,
      userName: "test-user",
      email: email });

      console.log('called send');
  }

  getMessages(): FirebaseListObservable<ChatMessage[]> {
    // query to create our message feed binding
    return this.db.list('messages', {
      query: {
        limitToLast: 25,
        orderByKey: true
      }
    });
  }

  getTimeStamp() {
    const now = new Date();
    const date = now.getUTCFullYear() + '/' +
                 (now.getUTCMonth() + 1) + '/' +
                 now.getUTCDate();
    const time = now.getUTCHours() + ':' +
                 now.getUTCMinutes() + ':' +
                 now.getUTCSeconds();

    return (date + ' ' + time);
  }
}
</code>```

the foll is my app.module.ts file:

```<code>import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { HttpModule } from '@angular/http';
import { RouterModule } from '@angular/router';
import { AngularFireModule } from 'angularfire2';
import { AngularFireDatabaseModule } from 'angularfire2/database';
import { AngularFireAuthModule } from 'angularfire2/auth';

import { AppComponent } from './app.component';
import { ChatFormComponent } from './chat-form/chat-form.component';
import { ChatroomComponent } from './chatroom/chatroom.component';
import { FeedComponent } from './feed/feed.component';
import { MessageComponent } from './message/message.component';
import { LoginFormComponent } from './login-form/login-form.component';
import { SignupFormComponent } from './signup-form/signup-form.component';
import { NavbarComponent } from './navbar/navbar.component';
import { UserListComponent } from './user-list/user-list.component';
import { UserItemComponent } from './user-item/user-item.component';

import { appRoutes } from '../routes';
import { ChatService } from './services/chat.service';
import { AuthService } from './services/auth.service';

import { environment } from '../environments/environment';

@NgModule({
  declarations: [
    AppComponent,
    ChatFormComponent,
    ChatroomComponent,
    FeedComponent,
    MessageComponent,
    LoginFormComponent,
    SignupFormComponent,
    NavbarComponent,
    UserListComponent,
    UserItemComponent
  ],
  imports: [
    BrowserModule,
    FormsModule,
    RouterModule.forRoot(appRoutes),
    HttpModule,
    AngularFireModule,
    AngularFireDatabaseModule,
    AngularFireAuthModule,
    AngularFireModule.initializeApp(environment.firebase),

  ],
  providers: [AuthService, ChatService],
  bootstrap: [AppComponent]
})
export class AppModule { }
</code>```

答: Please remove -deprecated from import { AngularFireDatabase, FirebaseListObservable } from 'angularfire2/database-deprecated' in your chat-service file.

Body:
I'm trying to build a proto chat application using Angular & Firebase.

the foll are my routes:

export const appRoutes: Routes = [
    { path: 'signup', component: SignupFormComponent },
    { path: 'login', component: LoginFormComponent },
    { path: 'chat', component: ChatroomComponent },
    { path: '', redirectTo: '/login', pathMatch: 'full'},
];

But when i route to /chat, i get the foll error. I'm not sure what is it that i am missing here in order to fix this error. any guidance is appreciated.

I have looked at the foll link, but i have included all the import stated in the answers:
No provider for AngularFireDatabase, AngularFireAuth

ERROR Error: Uncaught (in promise): Error: StaticInjectorError[AngularFireDatabase]:
  StaticInjectorError[AngularFireDatabase]:
    NullInjectorError: No provider for AngularFireDatabase!
Error: StaticInjectorError[AngularFireDatabase]:
  StaticInjectorError[AngularFireDatabase]:
    NullInjectorError: No provider for AngularFireDatabase!

the foll is my chat-service.ts file:

import { Injectable } from '@angular/core';
import { AngularFireDatabase, FirebaseListObservable } from 'angularfire2/database-deprecated';
import { AngularFireAuth } from 'angularfire2/auth';
import { Observable } from 'rxjs/Observable';
import { AuthService } from '../services/auth.service';
import * as firebase from 'firebase/app';

import { ChatMessage } from '../models/chat-message.model';

@Injectable()
export class ChatService {
  user: firebase.User;
  chatMessages: FirebaseListObservable<ChatMessage[]>;
  chatMessage: ChatMessage;
  userName: Observable<string>;

  constructor(
    private db: AngularFireDatabase,
    private afAuth: AngularFireAuth
    ) {
        /*this.afAuth.authState.subscribe(auth => {
          if (auth !== undefined && auth !== null) {
            this.user = auth; // the user object is only going to be set if we are authenticated
          }

        });*/
    }

   sendMessage(msg: string) { //per all the properties defined in the chat-message model
    const timestamp = this.getTimeStamp();
  //  const email = this.user.email;
    const email = "test@gmail.com";
    this.chatMessages = this.getMessages();
    this.chatMessages.push({
      message: msg,
      timeSent: timestamp,
      //userName: this.userName,
      userName: "test-user",
      email: email });

      console.log('called send');
  }

  getMessages(): FirebaseListObservable<ChatMessage[]> {
    // query to create our message feed binding
    return this.db.list('messages', {
      query: {
        limitToLast: 25,
        orderByKey: true
      }
    });
  }

  getTimeStamp() {
    const now = new Date();
    const date = now.getUTCFullYear() + '/' +
                 (now.getUTCMonth() + 1) + '/' +
                 now.getUTCDate();
    const time = now.getUTCHours() + ':' +
                 now.getUTCMinutes() + ':' +
                 now.getUTCSeconds();

    return (date + ' ' + time);
  }
}

the foll is my app.module.ts file:

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { HttpModule } from '@angular/http';
import { RouterModule } from '@angular/router';
import { AngularFireModule } from 'angularfire2';
import { AngularFireDatabaseModule } from 'angularfire2/database';
import { AngularFireAuthModule } from 'angularfire2/auth';

import { AppComponent } from './app.component';
import { ChatFormComponent } from './chat-form/chat-form.component';
import { ChatroomComponent } from './chatroom/chatroom.component';
import { FeedComponent } from './feed/feed.component';
import { MessageComponent } from './message/message.component';
import { LoginFormComponent } from './login-form/login-form.component';
import { SignupFormComponent } from './signup-form/signup-form.component';
import { NavbarComponent } from './navbar/navbar.component';
import { UserListComponent } from './user-list/user-list.component';
import { UserItemComponent } from './user-item/user-item.component';

import { appRoutes } from '../routes';
import { ChatService } from './services/chat.service';
import { AuthService } from './services/auth.service';

import { environment } from '../environments/environment';

@NgModule({
  declarations: [
    AppComponent,
    ChatFormComponent,
    ChatroomComponent,
    FeedComponent,
    MessageComponent,
    LoginFormComponent,
    SignupFormComponent,
    NavbarComponent,
    UserListComponent,
    UserItemComponent
  ],
  imports: [
    BrowserModule,
    FormsModule,
    RouterModule.forRoot(appRoutes),
    HttpModule,
    AngularFireModule,
    AngularFireDatabaseModule,
    AngularFireAuthModule,
    AngularFireModule.initializeApp(environment.firebase),

  ],
  providers: [AuthService, ChatService],
  bootstrap: [AppComponent]
})
export class AppModule { }


答:
Take a look at the documentation.

rstrip removes all of the characters in its argument that are in the right side of the string you modify. So since "lloWorld" are all made up of characters in "World", those get removed; e isn't, so it stops there.

On the other hand, in the first call, l isn't actually on the right side (rstrip) of the string, so nothing is removed.

Title: rstrip on python behaving awkwardly: 'HelloWorld'.rstrip('World') deletes everything after 'He'


问:
How to use PyCharm as a GIT diff tool from the command line?
On the PyCharm Help Website I see you can use PyCharm as a diff tool from the Command Line to compare two files. That's awesome! However is there a way to take it a step further and use it as a git diff tool.

So I can just type pycharm diff file_name.py and get the GIT differences same way you would if you were on PyCharm have setup the GIT integration and press CTRL + D to see the differences.

答:
Yes you can.

First you need to enable the command-line launcher:

To enable invoking PyCharm operations from the command line, follow
  these steps

On macOS or UNIX:

Make sure PyCharm is running.

On the
  main menu, choose Tools | Create Command-line Launcher. The dialog box
  Create Launcher Script opens, with the suggested path and name of the
  launcher script. You can accept default, or specify your own path.
  Make notice of it, as you'll need it later.

Outside of PyCharm, add the path and name of the launcher script to your path.

On Windows:

Specify the location of the PyCharm executable
  in the Path system environment variable. In this case, you will be
  able to invoke the PyCharm executable and other PyCharm commands from
  any directory.

https://www.jetbrains.com/help/pycharm/running-pycharm-as-a-diff-or-merge-command-line-tool.html

Then add the following lines to your ~/.gitconfig:

```<code>[diff]
        tool = pycharm
[difftool "pycharm"]
        cmd = /usr/local/bin/charm diff "$LOCAL" "$REMOTE" && echo "Press enter to continue..." && read
[merge]
        tool = pycharm
[mergetool "pycharm"]
        cmd = /usr/local/bin/charm merge "$LOCAL" "$REMOTE" "$BASE" "$MERGED"
        keepBackup = false
</code>```

(for Windows users these details might be slightly different)

Body:
Yes you can.

First you need to enable the command-line launcher:

To enable invoking PyCharm operations from the command line, follow
  these steps

On macOS or UNIX:

Make sure PyCharm is running.

On the
  main menu, choose Tools | Create Command-line Launcher. The dialog box
  Create Launcher Script opens, with the suggested path and name of the
  launcher script. You can accept default, or specify your own path.
  Make notice of it, as you'll need it later.

Outside of PyCharm, add the path and name of the launcher script to your path.

On Windows:

Specify the location of the PyCharm executable
  in the Path system environment variable. In this case, you will be
  able to invoke the PyCharm executable and other PyCharm commands from
  any directory.

https://www.jetbrains.com/help/pycharm/running-pycharm-as-a-diff-or-merge-command-line-tool.html

Then add the following lines to your ~/.gitconfig:

[diff]
        tool = pycharm
[difftool "pycharm"]
        cmd = /usr/local/bin/charm diff "$LOCAL" "$REMOTE" && echo "Press enter to continue..." && read
[merge]
        tool = pycharm
[mergetool "pycharm"]
        cmd = /usr/local/bin/charm merge "$LOCAL" "$REMOTE" "$BASE" "$MERGED"
        keepBackup = false

(for Windows users these details might be slightly different)


问:
Verilog Iteration error
Hi I am trying to execute this piece of code in Vivado 2017.2.1 and I keep getting this error

[Synth 8-3380] loop condition does not converge after 2000 iterations

```<code>while (side == 1)
  begin
  ball_x<=ball_x - 11'd10;
  end
while (side == 0)
  begin
  ball_x<=ball_x + 11'd10;
  end

if (ball_x <14)
begin
side=0;
end
else if (ball_x>1394)
begin
side=1;
end
</code>```

this code is to get a ball to change directions when it has hit the 10px wide border. I googled it online and apparently Vivado did not support a while loop a few versions back but has added support recently and so this should work?

答:
Your code does not seem to be written to be synthesizable at all, and you need to understand how the FPGA is intended to work.

Your first step should be to introduce a clock in your design, and understand how hardware is somewhat different from software.

Title: Verilog Iteration error

Body:
Hi I am trying to execute this piece of code in Vivado 2017.2.1 and I keep getting this error

[Synth 8-3380] loop condition does not converge after 2000 iterations

while (side == 1)
  begin
  ball_x<=ball_x - 11'd10;
  end
while (side == 0)
  begin
  ball_x<=ball_x + 11'd10;
  end

if (ball_x <14)
begin
side=0;
end
else if (ball_x>1394)
begin
side=1;
end

this code is to get a ball to change directions when it has hit the 10px wide border. I googled it online and apparently Vivado did not support a while loop a few versions back but has added support recently and so this should work?


答:
One way to make multi-line literal strings look good is to use a backslash to escape the newline, like this:

```<code>s = '''\
*********************************************************************
                                 hello
*********************************************************************
'''
print(s)
</code>```

output

```<code>*********************************************************************
                                 hello
*********************************************************************
</code>```

However, PEP-008 discourages backslash usage like that. It's too fragile:  if there's a space between the backslash and the newline then the newline won't get escaped, and the backslash will get printed.

A more versatile approach is to use a function which calculates the amount of padding required to centre the text, and applies it via a nested formatting specifier. For example:

```<code>def banner(s, width=69):
    stars = '*' * width
    pad = (width + len(s)) // 2
    return '{0}\n{1:>{2}}\n{0}'.format(stars, s, pad)

print(banner('hello'))
print(banner('Hello, world', width=16))
</code>```

output

```<code>*********************************************************************
                                hello
*********************************************************************
****************
  Hello, world
****************
</code>```

How it works

That format string is a little dense, so I guess I should try to explain it. ;) For full information on this topic please see Format String Syntax in the docs. The explanation below borrows from & paraphrases those docs.

```<code>'{0}\n{1:>{2}}\n{0}'.format(stars, s, pad)
</code>```

The stuff enclosed in {} in a format string is called a "replacement field". The first item in a replacement field is the optional field name. This lets us identify which arg of .format goes with this replacement field. There are a couple of possible variations for field names, this format string uses numeric names, so it identifies the .format args by their position. That is, 0 corresponds to stars, 1 corresponds to s and 2 corresponds to pad.

If no field names are given they get automatically filled by the numbers 0, 1, 2, ... etc (unless you're using Python 2.6, where field names are mandatory). That's quite useful most of the time, so most format strings don't bother using field names.

After the field name we can give a "format specifier" or "format spec" which describes how the value is to be presented. A colon : separates the field name from the format spec. If you don't supply a format spec then you get a default one, and most of the time that's adequate. But here we do want a little more control, so we need to supply a format spec.

In a form spec the > sign forces the field to be right-aligned within the available space. After the alignment sign we can provide a number to specify the minimum field width; the field will automatically be made larger if necessary.

For example, '{0:>6}'.format('test') says to put argument 0 ('test') in a space that's at least 6 chars wide, aligned to the right. Which results in the string '  test'.

But a format spec can actually contain a whole new replacement field! This allows us to supply a variable to control the field width. So in my format string {1:>{2}} says to put arg 1 here (s), right aligned in a field with a width given by arg 2 (pad). Only one level of replacement field nesting is permitted, but it's hard to think of a situation where you'd actually want deeper nesting.

So putting it all together: '{0}\n{1:>{2}}\n{0}' tells .format to build a string that starts with arg 0 (stars) using the default format spec, followed by a newline, followed by arg 1 (s) right aligned in a field of width pad, followed by another newline, finally followed by arg 0 (stars) again.

I hope that made enough sense. :)

In Python 3.6+, we could use an f-string:

```<code>def banner(s, width=69):
    stars = '*' * width
    pad = (width + len(s)) // 2
    return f'{stars}\n{s:>{pad}}\n{stars}'
</code>```

Title: multi line string formatting in python

Body:
To begin with, I am working to a get a desired output like this:

*********************************************************************
                                 hello
*********************************************************************

To achieve this I have assigned the desired output to a variable with multiline string and printing the same with format.

$ cat varibale.py
decorator = """ **********************************************************************
                               {}
            ********************************************************************** """
print(decorator.format("hello"))

Output:

**********************************************************************
                               hello
            **********************************************************************

The issue with above approach is the extra spaces in the third line of output which is looking odd.

I am able to achieve this in the following way:

$ cat varibale.py
decorator = """ **********************************************************************
                             {}
*********************************************************************
"""
print(decorator.format("hello"))

Output:

 **********************************************************************
                             hello
*********************************************************************

But this way my code doesn't look good, as it is not following the indentation.

Please suggest the right way to achieve the desired output.

Body:
One way to make multi-line literal strings look good is to use a backslash to escape the newline, like this:

s = '''\
*********************************************************************
                                 hello
*********************************************************************
'''
print(s)

output

*********************************************************************
                                 hello
*********************************************************************

However, PEP-008 discourages backslash usage like that. It's too fragile:  if there's a space between the backslash and the newline then the newline won't get escaped, and the backslash will get printed.

A more versatile approach is to use a function which calculates the amount of padding required to centre the text, and applies it via a nested formatting specifier. For example:

def banner(s, width=69):
    stars = '*' * width
    pad = (width + len(s)) // 2
    return '{0}\n{1:>{2}}\n{0}'.format(stars, s, pad)

print(banner('hello'))
print(banner('Hello, world', width=16))

output

*********************************************************************
                                hello
*********************************************************************
****************
  Hello, world
****************

How it works

That format string is a little dense, so I guess I should try to explain it. ;) For full information on this topic please see Format String Syntax in the docs. The explanation below borrows from & paraphrases those docs.

'{0}\n{1:>{2}}\n{0}'.format(stars, s, pad)

The stuff enclosed in {} in a format string is called a "replacement field". The first item in a replacement field is the optional field name. This lets us identify which arg of .format goes with this replacement field. There are a couple of possible variations for field names, this format string uses numeric names, so it identifies the .format args by their position. That is, 0 corresponds to stars, 1 corresponds to s and 2 corresponds to pad.

If no field names are given they get automatically filled by the numbers 0, 1, 2, ... etc (unless you're using Python 2.6, where field names are mandatory). That's quite useful most of the time, so most format strings don't bother using field names.

After the field name we can give a "format specifier" or "format spec" which describes how the value is to be presented. A colon : separates the field name from the format spec. If you don't supply a format spec then you get a default one, and most of the time that's adequate. But here we do want a little more control, so we need to supply a format spec.

In a form spec the > sign forces the field to be right-aligned within the available space. After the alignment sign we can provide a number to specify the minimum field width; the field will automatically be made larger if necessary.

For example, '{0:>6}'.format('test') says to put argument 0 ('test') in a space that's at least 6 chars wide, aligned to the right. Which results in the string '  test'.

But a format spec can actually contain a whole new replacement field! This allows us to supply a variable to control the field width. So in my format string {1:>{2}} says to put arg 1 here (s), right aligned in a field with a width given by arg 2 (pad). Only one level of replacement field nesting is permitted, but it's hard to think of a situation where you'd actually want deeper nesting.

So putting it all together: '{0}\n{1:>{2}}\n{0}' tells .format to build a string that starts with arg 0 (stars) using the default format spec, followed by a newline, followed by arg 1 (s) right aligned in a field of width pad, followed by another newline, finally followed by arg 0 (stars) again.

I hope that made enough sense. :)

In Python 3.6+, we could use an f-string:

def banner(s, width=69):
    stars = '*' * width
    pad = (width + len(s)) // 2
    return f'{stars}\n{s:>{pad}}\n{stars}'


问:
Symfony - Doctrine - Select query with a user (but can be anonymous user)
I'm using symfony 3, and I'm storing some data to database.
For this, the user does not have to be logged in.

Now I've created a select query with $this->getUser();. But the User can be NULL. When I execute this query, it does not select any rows.

return $this->createQueryBuilder('product')
        ->where('product.user = :user')
        ->andWhere('product.product = :product')
        ->andWhere('product.cartId = :uniqueCartId')
        ->setParameters([
            'product' => $product,
            'user' => $user,
            'uniqueCartId' => $uniqueCartId
        ])
        ->getQuery()
        ->execute();

$user = $this->getUser();

I already tried this:
if(!$user instanceof User) $user = NULL;
But that does not work.

If I remove the User check, it works.

Any ideas?

答:
I guess you should bind the where clause if there is an user object like </p>

```<code>$parameters=array(
    'product' => $product,
    'uniqueCartId' => $uniqueCartId
);
$user = $this->getUser();
$query = $this->createQueryBuilder('product')
        ->where('product.product = :product')
        ->andWhere('product.cartId = :uniqueCartId');
if($user != null){  /* if($user instanceof User) */
    $parameters['user'] = $user;
    $query = $query->andWhere('product.user = :user');
}else{
    /* $query = $query->andWhere('product.user IS NULL'); Not necessary */
}
$query->setParameters($parameters)
      ->getQuery()
      ->execute();
</code>```

Body:
I guess you should bind the where clause if there is an user object like

$parameters=array(
    'product' => $product,
    'uniqueCartId' => $uniqueCartId
);
$user = $this->getUser();
$query = $this->createQueryBuilder('product')
        ->where('product.product = :product')
        ->andWhere('product.cartId = :uniqueCartId');
if($user != null){  /* if($user instanceof User) */
    $parameters['user'] = $user;
    $query = $query->andWhere('product.user = :user');
}else{
    /* $query = $query->andWhere('product.user IS NULL'); Not necessary */
}
$query->setParameters($parameters)
      ->getQuery()
      ->execute();


问:
How to connect to RabbitMQ using RabbitMQ JMS client from an existing JMS application?
I have a generic standalone JMS application which works with following JMS providers WebSphere, HornetQ and ActiveMq. I pass Context.INITIAL_CONTEXT_FACTORY and Context.PROVIDER_URL as parameters to my application and create a naming context out of them by doing something like this

```<code>Properties environmentParameters = new Properties();
environmentParameters.put(Context.INITIAL_CONTEXT_FACTORY, property.context);
environmentParameters.put(Context.PROVIDER_URL, property.provider);
namingContext = new InitialContext(environmentParameters);
</code>```

And use this context for object lookup.

I understand RabbitMQ isn't a JMS provider so it doesn't have an InitialContext class or a Provider URL but it provides a JMS Client which is an abstraction of its Java client conforming to JMS specification. RabbitMQ's JMS client documentation has an example of defining objects in JNDI as a resource configuration as part of a web application but I quite couldn't figure out how to do something similar for my standalone application which creates a naming context based on JNDI provider using JMS client's dependencies or to create an InitialContext out of the available dependencies.

So can someone throw some light on how this can be done? Hope my question is clear.

答:
We can generate the .bindings file for RabbitMQ using below java code:</p>

```<code>import java.util.Properties;
import javax.jms.ConnectionFactory;
import javax.jms.Queue;
import javax.jms.Topic;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.Reference;
import javax.naming.StringRefAddr;

Properties env = new Properties();
    env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.fscontext.RefFSContextFactory");
    env.put(Context.PROVIDER_URL, "file:bindings");
    Context ctx = new InitialContext(env);

    Reference connectionFactoryRef = new Reference(ConnectionFactory.class.getName(), RMQObjectFactory.class.getName(), null);
    connectionFactoryRef.add(new StringRefAddr("name", "jms/ConnectionFactory"));
    connectionFactoryRef.add(new StringRefAddr("type", ConnectionFactory.class.getName()));
    connectionFactoryRef.add(new StringRefAddr("factory", RMQObjectFactory.class.getName()));
    connectionFactoryRef.add(new StringRefAddr("host", "$JMS_RABBITMQ_HOST$"));
    connectionFactoryRef.add(new StringRefAddr("port", "$JMS_RABBITMQ_PORT$"));
    ctx.rebind("ConnectionFactory", connectionFactoryRef);

    String jndiAppend = "jndi";
    for (int i = 1; i <= 10; i++) {
        String name = String.format("queue%02d", i);
        Reference ref = new Reference(Queue.class.getName(), com.rabbitmq.jms.admin.RMQObjectFactory.class.getName(), null);
        ref.add(new StringRefAddr("name", "jms/Queue"));
        ref.add(new StringRefAddr("type", Queue.class.getName()));
        ref.add(new StringRefAddr("factory", RMQObjectFactory.class.getName()));
        ref.add(new StringRefAddr("destinationName", name));
        ctx.rebind(name+jndiAppend, ref);

        name = String.format("topic%02d", i);
        ref = new Reference(Topic.class.getName(), com.rabbitmq.jms.admin.RMQObjectFactory.class.getName(), null);
        ref.add(new StringRefAddr("name", "jms/Topic"));
        ref.add(new StringRefAddr("type", Topic.class.getName()));
        ref.add(new StringRefAddr("factory", RMQObjectFactory.class.getName()));
        ref.add(new StringRefAddr("destinationName", name));
        ctx.rebind(name+jndiAppend, ref);
    }
</code>```

Body:
I have a generic standalone JMS application which works with following JMS providers WebSphere, HornetQ and ActiveMq. I pass Context.INITIAL_CONTEXT_FACTORY and Context.PROVIDER_URL as parameters to my application and create a naming context out of them by doing something like this

Properties environmentParameters = new Properties();
environmentParameters.put(Context.INITIAL_CONTEXT_FACTORY, property.context);
environmentParameters.put(Context.PROVIDER_URL, property.provider);
namingContext = new InitialContext(environmentParameters);

And use this context for object lookup.

I understand RabbitMQ isn't a JMS provider so it doesn't have an InitialContext class or a Provider URL but it provides a JMS Client which is an abstraction of its Java client conforming to JMS specification. RabbitMQ's JMS client documentation has an example of defining objects in JNDI as a resource configuration as part of a web application but I quite couldn't figure out how to do something similar for my standalone application which creates a naming context based on JNDI provider using JMS client's dependencies or to create an InitialContext out of the available dependencies.

So can someone throw some light on how this can be done? Hope my question is clear.

Body:
We can generate the .bindings file for RabbitMQ using below java code:

import java.util.Properties;
import javax.jms.ConnectionFactory;
import javax.jms.Queue;
import javax.jms.Topic;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.Reference;
import javax.naming.StringRefAddr;

Properties env = new Properties();
    env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.fscontext.RefFSContextFactory");
    env.put(Context.PROVIDER_URL, "file:bindings");
    Context ctx = new InitialContext(env);

    Reference connectionFactoryRef = new Reference(ConnectionFactory.class.getName(), RMQObjectFactory.class.getName(), null);
    connectionFactoryRef.add(new StringRefAddr("name", "jms/ConnectionFactory"));
    connectionFactoryRef.add(new StringRefAddr("type", ConnectionFactory.class.getName()));
    connectionFactoryRef.add(new StringRefAddr("factory", RMQObjectFactory.class.getName()));
    connectionFactoryRef.add(new StringRefAddr("host", "$JMS_RABBITMQ_HOST$"));
    connectionFactoryRef.add(new StringRefAddr("port", "$JMS_RABBITMQ_PORT$"));
    ctx.rebind("ConnectionFactory", connectionFactoryRef);

    String jndiAppend = "jndi";
    for (int i = 1; i <= 10; i++) {
        String name = String.format("queue%02d", i);
        Reference ref = new Reference(Queue.class.getName(), com.rabbitmq.jms.admin.RMQObjectFactory.class.getName(), null);
        ref.add(new StringRefAddr("name", "jms/Queue"));
        ref.add(new StringRefAddr("type", Queue.class.getName()));
        ref.add(new StringRefAddr("factory", RMQObjectFactory.class.getName()));
        ref.add(new StringRefAddr("destinationName", name));
        ctx.rebind(name+jndiAppend, ref);

        name = String.format("topic%02d", i);
        ref = new Reference(Topic.class.getName(), com.rabbitmq.jms.admin.RMQObjectFactory.class.getName(), null);
        ref.add(new StringRefAddr("name", "jms/Topic"));
        ref.add(new StringRefAddr("type", Topic.class.getName()));
        ref.add(new StringRefAddr("factory", RMQObjectFactory.class.getName()));
        ref.add(new StringRefAddr("destinationName", name));
        ctx.rebind(name+jndiAppend, ref);
    }


答:
str.rstrip() removes characters from the end of the string that are present in the set of characters supplied to rstrip() (if passed, and not None). rstrip() stops as soon as a character in the string is found that is not in the set of stripping characters.

So, for the first example, the final character in string a is 'd' which is not in the set of stripping characters passed to rstrip(). Therefore nothing is stripped from the original string.

In the second example, any of the characters in the set 'World' can be removed from the end of the string. You will notice that the substring 'lloWorld' comprises characters that are present in the stripping characters, so all of those characters are removed, leaving 'He' as the final result.

However, consider the case that there is a character at the end of the string that is not in the set 'World', e.g. a full stop.

```<code>>>> 'HelloWorld'.rstrip('World')
'He'
>>> 'HelloWorld.'.rstrip('World')
'HelloWorld.'
</code>```

nothing has been stripped because '.' is not in 'World'.

Body:
I had started learning python recently, and I have encountered a awkward behavior with rstrip.

My understanding is that the str.rstrip() will delete all characters as soon as it encounters one of the character it took in an argument.

>>> a = 'HelloWorld'
>>> a.rstrip('l')
'HelloWorld'
>>> a = 'HelloWorld'
>>> a.rstrip('World')
'He'

I'm totally confused by the result I've got.

Shouldn't the first code supposed be producing 'He' instead?

Body:
str.rstrip() removes characters from the end of the string that are present in the set of characters supplied to rstrip() (if passed, and not None). rstrip() stops as soon as a character in the string is found that is not in the set of stripping characters.

So, for the first example, the final character in string a is 'd' which is not in the set of stripping characters passed to rstrip(). Therefore nothing is stripped from the original string.

In the second example, any of the characters in the set 'World' can be removed from the end of the string. You will notice that the substring 'lloWorld' comprises characters that are present in the stripping characters, so all of those characters are removed, leaving 'He' as the final result.

However, consider the case that there is a character at the end of the string that is not in the set 'World', e.g. a full stop.

>>> 'HelloWorld'.rstrip('World')
'He'
>>> 'HelloWorld.'.rstrip('World')
'HelloWorld.'

nothing has been stripped because '.' is not in 'World'.