text:
Q: Style DataGridTemplateColumn to Match DataGridComboBoxColumn EDIT (clarification of requirements)
I have a DataGrid as shown below.  The values in the "Field Name To Store Old EmpNo" column change based on the value selected in "New EmpNo Rule" column.  To accommodate this, each item in the DataGrid ItemsSource has its own TableNameForOldDataCollection.  I need to bind to this TableNameForOldDataCollection and not a static property that cannot change.
If there is a way to do this binding while using DataGridComboBoxTemplate I would prefer that.  If not, I would like to know if it is possible to template the DataGridTemplateColumn/ComboBox to match that of the DataGridComboBoxTemplate
OP
I have a scenario where I am using DataGridComboBoxColumn for one of the DataGrid columns.  In another column, I need to use the DataGridTemplateColumn, with a ComboBox, to properly bind to a dynamic ItemSource in the VM.
The DataGridComboBoxColumn ("New EmpNo Rule") is styled differently than the DataGridTemplateColumn, with a ComboBox ("Field Name To Store Old EmpNo") as shown here:

How can I  style the DataGridTemplateColumn/ComboBox to match the DataGridComboBoxColumn, particularly how the combobox is hidden when the actual cell is not selected (like the second row of "New EmpNo Rule").
EDIT (added DataGrid code):
   <UserControl.Resources>
        <ResourceDictionary>
             <CollectionViewSource x:Key="StaticEmpNoRuleCollection" Source="{Binding EmpNoRuleCollection}" />
        </ResourceDictionary>
    </UserControl.Resources>

....

                <DataGrid Name="DataGrid_MultiCompanyInfo"
                          ItemsSource="{Binding Model.EmpNoOptionsCollection}"
                          SelectedItem="{Binding SelectedEmpNoOptions}"
                          AutoGenerateColumns="False"
                          CanUserAddRows="False"
                          CanUserDeleteRows="False">
                    <DataGrid.Columns>

                        <!-- Company -->
                        <DataGridTextColumn Header="Company"
                                            Binding="{Binding Company}"
                                            IsReadOnly="True" />

                        <!-- New EmpNo Rule -->
                        <DataGridComboBoxColumn Header="New EmpNo Rule"
                                                Width="200"
                                                ItemsSource="{Binding Source={StaticResource StaticEmpNoRuleCollection}}"
                                                DisplayMemberPath="Description"
                                                SelectedValueBinding="{Binding SelectedEmpNoRule, UpdateSourceTrigger=PropertyChanged}"/>

                        <!-- Field Name To Store Old EmpNo -->
                        <DataGridTemplateColumn Header="Field Name To
Store Old EmpNo"
                                                Width="150" >
                            <DataGridTemplateColumn.CellTemplate>
                                <DataTemplate>
                                    <ComboBox Name="OldEmpNo_ComboBox"
                                              Margin="-5,0,0,0"
                                              ItemsSource="{Binding TableNameForOldDataCollection}"
                                              SelectedValue="{Binding TableNameForOldData, UpdateSourceTrigger=PropertyChanged}" />
                                </DataTemplate>
                            </DataGridTemplateColumn.CellTemplate>
                        </DataGridTemplateColumn>

                        ...

                    </DataGrid.Columns>
                </DataGrid>

A: Keeping in mind that DataGridComboBoxColumn is not in the same visual tree, you can use a BindingProxy:
public class BindingProxy : Freezable
{
    #region Overrides of Freezable

    protected override Freezable CreateInstanceCore()
    {
        return new BindingProxy();
    }

    #endregion

    public object Data
    {
        get { return (object)GetValue(DataProperty); }
        set { SetValue(DataProperty, value); }
    }

    // Using a DependencyProperty as the backing store for Data. This enables animation, styling, binding, etc...
    public static readonly DependencyProperty DataProperty =
        DependencyProperty.Register("Data", typeof(object), typeof(BindingProxy), new UIPropertyMetadata(null));
}

XAML resources:
<Window.Resources>
    <local:BindingProxy x:Key="proxy" Data="{Binding}" />
</Window.Resources>

XAML binding(not on the visual tree):
<DataGridComboBoxColumn ItemsSource="{Binding Data.TableNameForOldDataCollection, Source={StaticResource proxy}}"/>

UPDATE
Totally different solution...Looks a little hackish, but I've tested it an it works:
<DataGridComboBoxColumn Header="Field Name To
Store Old EmpNo" Width="150"
SelectedItemBinding="{Binding TableNameForOldData, UpdateSourceTrigger=PropertyChanged}>
    <DataGridComboBoxColumn.ElementStyle>
        <Style TargetType="ComboBox">
            <Setter Property="ItemsSource" Value="{Binding TableNameForOldDataCollection}"/>
            <Setter Property="IsReadOnly" Value="True"/>
        </Style>
    </DataGridComboBoxColumn.ElementStyle>
    <DataGridComboBoxColumn.EditingElementStyle>
        <Style TargetType="ComboBox">
            <Setter Property="ItemsSource" Value="{Binding TableNameForOldDataCollection}"/>
        </Style>
    </DataGridComboBoxColumn.EditingElementStyle>
</DataGridComboBoxColumn>

Also I think it is a duplicate, so I will flag it.


text:
Q: Python "triplet" dictionary? If we have (a1, b1) and (a2, b2) it's easy to use a dictionary to store the correspondences:
dict[a1] = b1
dict[a2] = b2

And we can get (a1, b1) and (a2, b2) back no problem.
But, if we have (a1, b1, c1) and (a2, b2, c2), is it possible to get something like:
dict[a1] = (b1, c1)
dict[b1] = (a1, c1)

Where we can use either a1 or b1 to get the triplet (a1, b1, c2) back? Does that make sense? I'm not quite sure which datatype to use for this problem. The above would work but there would be duplicate data.
Basically, if I have a triplet, which data type could I use such that I can use either the first or second value to get the triplet back?

A: An alternative if you want to subclass dict (to get all other methods associated with dict like .get and whatnot) and only get the other elements when asked (for some reason). You can make a new dictionary that is all your own
class TupleDict(dict):

    def __setitem__(self, key, value):
        assert isinstance(key, tuple)
        for i, e in enumerate(key):
            dict.__setitem__(self, e, key[:i] + key[i+1:] + (value,))
        dict.__setitem__(self, value, key)

and then assign any key that is a tuple to a single value (not sure I like this syntax, but we can make it different or use a stand-alone method)
d = TriDict()
d[(1,2)] = 4

and you will have the result of __getitem__ return the rest of the tuple not present.
>>> print(d[1])
(2, 4)
>>> print(d[2])
(1, 4)
print(d[4])
>>> (1, 2)

A: Solution
You can write your own mapping data-structure which allows to add triples, or groups of any size, and recover the group with __getitem__.
class GroupMap:
    def __init__(self):
        self.data = {}

    def add(self, group):
        for item in group:
            self.data[item] = group

    def __getitem__(self, item):
        return self.data[item]

group = (1, 2, 3)
group_map = GroupMap()

group_map.add(group)

print(group_map[1]) # (1, 2, 3)

Notice that this GroupMap can be used for groups of any size, not only triples.
The next step in the above would be to extend the class to avoid collisions according to the behaviour you want when a collision occurs.
Theory
You might wonder if there is a better way to represent groups of connected objects. The answer is not really.
Suppose you have a graph containing n vertices. Then for the graph to be connected, you must have at least n - 1 edges. In the above data-structure, I used n entry in the dict, meaning the solution is nearly optimal.
Why not use n - 1 entries if it can be done? Because you would then need to traverse all your graph to recover the whole group. Thus using one more edge allows for O(1) lookup, which is a trade-off you probably want to take.

A: Dictionaries can store key value pairs only.
You could make your own triplet dictionary however using operator overloading so that when you index with any member of the triplets you get back the other two, maybe something like this:
class trictionary:
    def __init__(self):
        self.data = []

    def add(self, group):
        self.data.append(group)

    def __getitem__(self, key):
        for group in data: #Find the set the key belongs to.
            if key in group:
                return tuple(group)

This avoids replicating the data and has the functionality you're looking for at the expense of performance. There may be a better way of doing the same.

A: Building on Olivier Melançons answer, I came up with this - in case the position of the value in the tuple matters:
class GroupMap:
    def __init__(self, data=None):
        self.data = {}
        if data:
            self.add(data)

    def add(self, data):
        for idx, key in enumerate(data):
            self.data.setdefault(idx, {})[key] = data

    def __getitem__(self, key):
        # lookup in first index
        return self.getby(0, key)

    def getby(self, idx, key):
        return self.data[idx].get(key)

data = ('a', 'b', 'c')
g = GroupMap(data)
more_data = ('b', 'a', 'z')
g.add(more_data)

assert g['a'] == data

assert g.getby(0, 'a') == data
assert g.getby(0, 'b') == more_data
assert g.getby(0, 'c') is None

assert g.getby(1, 'a') == more_data
assert g.getby(1, 'b') == data

assert g.getby(2, 'c') == data
assert g.getby(2, 'z') == more_data

assert id(data) == id(g['a']) == id(g.getby(1, 'b'))

A: Your question has examples that deviate from the main question:

Basically, if I have a triplet, which data type could I use such that I can use either the first or second value to get the triplet back?

A dict. Assign key-value pairs of element, triplet (see @Olivier Melançon's answer):
Code
d = {}
for x in triplet:
   d[x] = triplet

Demo
d["a"]
# ('a', 'b', 'c')

d["b"]
# ('a', 'b', 'c')

d["c"]
# ('a', 'b', 'c')

The OP requires clarity on preferred behavior in:

*

*adding elements, e.g. d[a1] = (b1, c1) vs. f((a1, b1, c1))

*element ordering, e.g. (a1, b1, c1) vs. (b1, a1, c1)

*duplicate data, e.g. hold (a1, b1, c1) three times or combinations of 2-tuple subsets

With these items addressed, more elaborate solutions are possible.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Any library to handle incoming email and parse it? I'm wondering if there is any php class to handle pipe incoming mail and split headers, body, and split the headers into parts too to easily gather subject and stuffs.
Any recommandations?
Thanks

A: class HTMLParserIterator
{
    var $contents;
    var $pos=0;
    var $endPos=0;
    function HTMLParserIterator( $contents )
    {
        $this->contents=$contents;
        $this->pos=0;
        $this->endPos=strlen($contents);
    }
    function setPos( $pos )
    {
        $this->pos=$pos;
    }
    function getPos()
    {
        return $this->pos;
    }
    function hasMore()
    {
        return $this->pos <$this->endPos;
    }
    function getChar()
    {
        return $this->hasMore()?$this->contents[$this->pos++]:'';
    }
    function peek()
    {
        return $this->hasMore()?$this->contents[$this->pos]:'';
    }
    function skip($num=1 )
    {
        $this->pos=min($this->pos+$num,$this->endPos);
    }
    function getChars($num)
    {
        $out='';
        $len=min($num,$this->endPos-$this->pos);
        $out=substr($this->contents,$this->pos,$len);
        $this->pos+=$len;
        return $out;
    }
    function readUntil( $until,$ignoreCase=true )
    {
        $end=$ignoreCase?stripos ( $this->contents, $until ,$this->pos ):strpos ( $this->contents, $until ,$this->pos );
        if($end===false)
        {
            $end=$this->endPos;
        }
        $out=substr($this->contents,$this->pos,$end-$this->pos);
        $this->pos=$end;
        return $out;
    }
    function skipWhiteSpace()
    {
        $out=0;
        while( $this->hasMore() && isWhiteSpace( $this->contents[$this->pos] ) )
        {
            $out++;
            $this->pos++;
        }
        return $out;
    }
    function match( $str,$ignoreCase=true )
    {
        if( sWith($this->contents,$str,$ignoreCase,$this->pos ) )
        {
            $out=substr($this->contents,$this->pos,strlen($str));
            $this->pos+=strlen($str);
            return true;
        }
        return false;
    }
}
define("HTMLParserTag_CONTENT",0);
define("HTMLParserTag_OPEN",1);
define("HTMLParserTag_CLOSE",2);
define("HTMLParserTag_STANDALONE",3);
define("HTMLParserTag_COMMENT",4);
define("HTMLParserTag_EXTENDED_COMMENT",5);
define("HTMLParserTag_SCRIPT",6);
define("HTMLParserTag_STYLE",7);
define("HTMLParserTag_TEXTAREA",8);

class HTMLParserSectionTag
{

    var $type;
    var $value;
    var $attrs=Array();
    function HTMLParserSectionTag( &$iterator )
    {
        if( ($value= $iterator->match( '<!--' ))!==false)
        {
            $this->type=HTMLParserTag_EXTENDED_COMMENT;
            $this->value=$iterator->readUntil('-->');
            $iterator->skip(3);
        }
        else if( ($value= $iterator->match( '<!' ))!==false)
        {
            $this->type=HTMLParserTag_COMMENT;
            $this->value=$iterator->readUntil('>');
            $iterator->skip(1);
        }
        else if( ($value= $iterator->match( '</' ))!==false)
        {
            $this->type=HTMLParserTag_CLOSE;
            $ch=$iterator->getChar();
            $buffer='';
            while( $ch!='' && !isWhiteSpace($ch) && $ch!='>' && $ch!='/')
            {
                $this->value.=$ch;
                $ch=$iterator->getChar();
            }
            if( $this->value=='' )
            {
                $this->value='<'.$ch;
                $this->type=HTMLParserTag_CONTENT;
            }
            else if( $ch=='/' && ($value= $iterator->match( '>' ))!==false )
            {
            }
            else if($ch!='>')
            {
                $endOfTag=$this->readAttrs($iterator);
            }
        }
        else if( ($value= $iterator->match( '<' ))!==false)
        {
            $this->type=HTMLParserTag_OPEN;
            $ch=$iterator->getChar();
            $buffer='';
            while( $ch!='' && !isWhiteSpace($ch) && $ch!='>' && $ch!='/')
            {
                $this->value.=$ch;
                $ch=$iterator->getChar();
            }
            if( $this->value=='' )
            {
                $this->value='<'.$ch;
                $this->type=HTMLParserTag_CONTENT;
            }
            else if( $ch=='/' && ($value= $iterator->match( '>' ))!==false )
            {
                $this->type=HTMLParserTag_STANDALONE;
            }
            else if($ch!='>')
            {
                $endOfTag=$this->readAttrs($iterator);
                if($endOfTag=='/>')
                {
                    $this->type=HTMLParserTag_STANDALONE;
                }
            }
        }
        else
        {
            $this->value=$iterator->readUntil('<');
            $this->type=HTMLParserTag_CONTENT;
        }
        if( $this->type==HTMLParserTag_OPEN && strtolower($this->value)=="script" )
        {
            $this->readScript($iterator);
        }
        else if( $this->type==HTMLParserTag_STANDALONE && strtolower($this->value)=="script" )
        {
            $this->type=HTMLParserTag_SCRIPT;
            $this->value='';
        }
        else if( $this->type==HTMLParserTag_OPEN && strtolower($this->value)=="textarea" )
        {
            $this->type=HTMLParserTag_TEXTAREA;
            $this->readUntilEndTag($iterator,"textarea");
        }
        else if( $this->type==HTMLParserTag_STANDALONE && strtolower($this->value)=="textarea" )
        {
            $this->type=HTMLParserTag_TEXTAREA;
            $this->value='';
        }
        else if( $this->type==HTMLParserTag_OPEN && strtolower($this->value)=="style" )
        {
            $this->type=HTMLParserTag_STYLE;
            $this->readUntilEndTag($iterator,"style");
        }
        else if( $this->type==HTMLParserTag_STANDALONE && strtolower($this->value)=="style" )
        {
            $this->type=HTMLParserTag_STYLE;
            $this->value='';
        }
    }
    function readScript(&$iterator)
    {
        $this->type=HTMLParserTag_SCRIPT;
        $this->readUntilEndTag($iterator,"script");
    }
    function readUntilEndTag(&$iterator,$tag)
    {

        $this->value='';
        while ($iterator->hasMore() )
        {
            $this->value.=$iterator->readUntil( '</'.$tag );
            if( $iterator->match("</$tag>") )
            {
                return;
            }
            else
            {
            $pos=$iterator->getPos();
                $section=new HTMLParserSectionTag($iterator);
                if( $section->type==HTMLParserTag_STANDALONE && strtolower($section->value)==$tag )
                {
                    return;
                }
                else
                {
                    $iterator->setPos($pos);
                    $this->value.=$iterator->getChar();
                }
            }
        }
    }
    function getAttribute( $name )
    {
        return array_key_exists($name,$this->attrs)?$this->attrs[$name]:null;
    }
    function readAttrs(&$iterator)
    {
        while( $iterator->hasMore() )
        {
            if( $iterator->match( '>' ) )
            {
                return '>';
            }
            else if( $iterator->match( '/>' ) )
            {
                return '/>';
            }
            $iterator->skipWhiteSpace();
            $name='';
            $value='';
            $ch=$iterator->getChar();
            while( $ch!='' && !isWhiteSpace($ch) && $ch!='>' && $ch!='=' )
            {
                if( $ch=='/' && $iterator->peek()=='>')
                {
                    $ch='/>';
                    $iterator->getChar();
                    break;
                }
                $name.=$ch;
                $ch=$iterator->getChar();
            }
            if( $ch=='>' || $ch=='/>')
            {
                $this->attrs[$name]=false;
                return $ch;
            }
            $whitespace=(isWhiteSpace($ch)?1:0)+$iterator->skipWhiteSpace();
            if( $iterator->peek()=='=' )
            {
                $ch='=';
                $iterator->skip();
                $whitespace=0;
            }
            $whitespace=$whitespace+$iterator->skipWhiteSpace();
            $value=false;
            if( $iterator->peek()=='\'' )
            {
                $iterator->skip();
                $ch=$iterator->getChar();
                while( $ch!='\'' )
                {
                    $value.=$ch;
                    $ch=$iterator->getChar();
                }
            }
            else if( $iterator->peek()=='"' )
            {
                $iterator->skip();
                $ch=$iterator->getChar();
                while( $ch!='"' )
                {
                    $value.=$ch;
                    $ch=$iterator->getChar();
                }

            }
            else
            {
                if( $whitespace==0 )
                {
                    $value='';
                    $ch=$iterator->getChar();
                    while( $ch!='' && !isWhiteSpace($ch) && $ch!='>' && $ch!='=' )
                    {
                        if( $ch=='/' && $iterator->peek()=='>')
                        {
                            $ch='/>';
                            $iterator->getChar();
                            break;
                        }
                        $value.=$ch;
                        $ch=$iterator->getChar();
                    }
                    if( $ch=='>' || $ch=='/>')
                    {
                        $this->attrs[$name]=$value;
                        return $ch;
                    }
                }
            }
            if( $name!='' )
            {
                $this->attrs[$name]=$value;
            }

        }
    }
    function isEntirelyWhiteSpace()
    {
        if( count($this->attrs)==0 )
        {
            for( $i=0;$i<strlen($this->value);$i++)
            {
                if( !isWhiteSpace($this->value[$i]) )
                {
                    return false;
                }
            }
            return true;
        }
        else
        {
            return false;
        }
    }
    /*
    define("HTMLParserTag_CONTENT",0);
define("HTMLParserTag_OPEN",1);
define("HTMLParserTag_CLOSE",2);
define("HTMLParserTag_STANDALONE",3);
define("HTMLParserTag_COMMENT",4);
define("HTMLParserTag_EXTENDED_COMMENT",5);
define("HTMLParserTag_SCRIPT",6);
define("HTMLParserTag_STYLE",7);
define("HTMLParserTag_TEXTAREA",8);
*/
    function getAttributesText()
    {
        $out='';
        foreach( $this->attrs as $name=>$value )
        {
            $out.=' '.$name;
            if( $value!==false)
            {
                $out.='="'.str_replace('"','"',$value ).'"';
            }
        }
        return $out;
    }
    function getContent()
    {
        $out='';
        switch( $this->type)
        {
            case HTMLParserTag_CONTENT:
            {
                $out=$this->value;
            }
            break;
            case HTMLParserTag_OPEN:
            case HTMLParserTag_STANDALONE:
            {
                $out='<'.$this->value;
                $attr=$this->getAttributesText();
                if( $attr!='')
                {
                    $out.=$attr.' ';
                }
                $out.=$this->type==HTMLParserTag_STANDALONE?'/>':'>';
            }
            break;
            case HTMLParserTag_CLOSE:
            {

                $out='</'.$this->value.">";
            }
            break;
            case HTMLParserTag_SCRIPT:
            {
                $out='<script';
                $attr=$this->getAttributesText();
                if( $attr!='')
                {
                    $out.=$attr.' ';
                }
                $out.='>'.$this->value."</script>";
            }
            break;
            case HTMLParserTag_TEXTAREA:
            {
                $out='<textarea';
                $attr=$this->getAttributesText();
                if( $attr!='')
                {
                    $out.=$attr.' ';
                }
                $out.='>'.$this->value."</textarea>";
            }
            break;
            case HTMLParserTag_STYLE:
            {
                $out='<style';
                $attr=$this->getAttributesText();
                if( $attr!='')
                {
                    $out.=$attr.' ';
                }
                $out.='>'.$this->value."</style>";
            }
            break;
            case HTMLParserTag_COMMENT:
            {
                $out.='<!'.$this->value.">";
            }
            break;
            case HTMLParserTag_EXTENDED_COMMENT:
            {
                $out.='<!--'.$this->value."-->";
            }
            break;
        }
        return $out;
    }
    function hasTagName( $name )
    {
        $out=false;
        switch( $this->type)
        {
            case HTMLParserTag_OPEN:
            case HTMLParserTag_STANDALONE:
            case HTMLParserTag_CLOSE:
            {
                $out=strtolower($this->value)==strtolower($name);
            }
            break;
            case HTMLParserTag_SCRIPT:
            {
                $out=strtolower($name)=='script';
            }
            break;
            case HTMLParserTag_TEXTAREA:
            {
                $out=strtolower($name)=='textarea';
            }
            break;
            case HTMLParserTag_STYLE:
            {
                $out=strtolower($name)=='style';
            }
            break;
            case HTMLParserTag_COMMENT:
            case HTMLParserTag_EXTENDED_COMMENT:
            {
                if( strtolower($name)=='~comment' )
                {
                    $out=true;
                }
                else if( sWith(strtolower($name),'~comment:' ) )
                {
                    $out=$this->value==substr($name,strlen('~comment:'));
                }
            }
            break;
            case HTMLParserTag_CONTENT:
            {
                $out=strtolower($name)=='~content';
            }
            break;
            default:
            {
                $out=false;
            }
            break;
        }
        return $out;
    }
    function removeAttributes( $name )
    {
        $newAttrs=Array();
        $name=strtolower($name);
        foreach( $this->attrs as $attrName=>$attrValue )
        {
            if( strtolower($name)!=strtolower($attrName) )
            {
                $newAttrs[$attrName]=$attrValue;
            }
        }
        $this->attrs=$newAttrs;
    }
    function removeAttributesStartingWith( $name )
    {
        $newAttrs=Array();
        $name=strtolower($name);
        foreach( $this->attrs as $attrName=>$attrValue )
        {
            if( !sWith(strtolower($attrName),strtolower($name)) )
            {
                $newAttrs[$attrName]=$attrValue;
            }
        }
        $this->attrs=$newAttrs;
    }
    function removeStyle( $name )
    {
        $name=strtolower($name);
        $styleKey='';
        foreach( $this->attrs as $attrName=>$attrValue )
        {
            if( strtolower($attrName)=='style' )
            {
                $styleKey=$attrName;
            }
        }
        if( $styleKey!='' )
        {
            $styleDef=new HTMLParserIteratorStyleDefintion( $this->attrs[$styleKey] );
            $styleDef->removeStyle($name);
            $this->attrs[$styleKey]=$styleDef->getContent();
        }
    }
    function removeStyleStartingWith( $name )
    {
        $name=strtolower($name);
        $styleKey='';
        foreach( $this->attrs as $attrName=>$attrValue )
        {
            if( strtolower($attrName)=='style' )
            {
                $styleKey=$attrName;
            }
        }
        if( $styleKey!='' )
        {
            $styleDef=new HTMLParserIteratorStyleDefintion( $this->attrs[$styleKey] );
            $styleDef->removeStyleStartingWith($name);
            $this->attrs[$styleKey]=$styleDef->getContent();
        }
    }
    function replaceSources( $srcs )
    {

        foreach($this->attrs as $name=>$val )
        {
            if(strtolower($name)=='src' && array_key_exists($val,$srcs ))
            {
                $this->attrs[$name]=$srcs[$val];
            }
        }
    }
    function getSources(&$srcs)
    {
        foreach($this->attrs as $name=>$val )
        {
            if(strtolower($name)=='src' )
            {
                $srcs[$this->attrs[$name]]=true;
            }
        }
    }
}

class HTMLParser
{
    var $sections=Array();
    function HTMLParser( $contents )
    {
        $iterator=new HTMLParserIterator($contents);
        $this->sections=Array();
        while( $iterator->hasMore() )
        {

            $startPos=$iterator->getPos();
            $section=new HTMLParserSectionTag($iterator);
            $this->sections[]=$section;
            if( $startPos==$iterator->getPos() )
            {
                break;
            }
        }
    }
    function getContent()
    {
        $out='';
        foreach( $this->sections as $section )
        {
            $out.=$section->getContent();
        }
        return $out;
    }
    function removeTags( $name )
    {
        $newSections=Array();
        foreach( $this->sections as $section )
        {
            if( !$section->hasTagName($name) )
            {
                $newSections[]=$section;
            }
        }
        $this->sections=$newSections;
    }
    function removeAttributes( $name )
    {
        for( $i=0;$i<count($this->sections);$i++)
        {
            $this->sections[$i]->removeAttributes($name);
        }
    }
    function removeAttributesStartingWith( $name )
    {
        for( $i=0;$i<count($this->sections);$i++)
        {
            $this->sections[$i]->removeAttributesStartingWith($name);
        }
    }
    function removeStyle( $name )
    {
        for( $i=0;$i<count($this->sections);$i++)
        {
            $this->sections[$i]->removeStyle($name);
        }
    }
    function removeStyleStartingWith( $name )
    {
        for( $i=0;$i<count($this->sections);$i++)
        {
            $this->sections[$i]->removeStyleStartingWith($name);
        }
    }
    function removeSections( $name )
    {
        $newSections=Array();
        $openTags=0;
        foreach( $this->sections as $section )
        {
            if( !$section->hasTagName($name) )
            {
                if( $openTags==0 )
                {
                    $newSections[]=$section;
                }
            }
            else
            {
                if( $section->type==HTMLParserTag_OPEN )
                {
                    $openTags++;
                }
                else if( $section->type==HTMLParserTag_CLOSE && $openTags>0)
                {
                    $openTags--;
                }
            }
        }
        $this->sections=$newSections;
    }
    function replaceSources( $srcs )
    {
        foreach( $this->sections as $id=>$section )
        {
            $this->sections[$id]->replaceSources( $srcs );
        }
    }
    function moveSources( $basePath,$oldFolder,$newFolder )
    {
        $srcs=$this->getSources();
        $newSrcs=Array();
        foreach($srcs as $src=>$junk )
        {
            if( substr( $src,0,strlen($oldFolder) )==$oldFolder )
            {
                if( !file_exists($basePath.$newFolder ) )
                {
                    mkdir($basePath.$newFolder );
                }
                $newSrc=$newFolder.substr( $src,strlen($oldFolder) );
                rename($basePath.$src,$basePath.$newSrc);
                $newSrcs[$src]=$newSrc;

            }
        }
        $this->replaceSources( $newSrcs );
    }
    function getSources()
    {
        $srcs=Array();
        foreach( $this->sections as $id=>$section )
        {
            $this->sections[$id]->getSources( $srcs) ;
        }
        return $srcs;
    }
    function compact( )
    {
        $newSections=Array();
        $openTags=0;
        foreach( $this->sections as $section )
        {
            if( !$section->isEntirelyWhiteSpace() )
            {
                $newSections[]=$section;
            }
        }
        $this->sections=$newSections;
    }

    function removeUpto( $name, $inclusive=false)
    {
        $newSections=Array();
        $found=false;
        foreach( $this->sections as $section )
        {
            if( !$inclusive && $section->hasTagName($name) )
            {
                $found=true;
            }
            if( $found)
            {
                $newSections[]=$section;
            }
            if( $inclusive && $section->hasTagName($name) )
            {
                $found=true;
            }
        }
        $this->sections=$newSections;
    }
    function removeAfter( $name, $inclusive=false)
    {
        $newSections=Array();
        $found=false;
        foreach( $this->sections as $section )
        {
            if( $inclusive && $section->hasTagName($name) )
            {
                $found=true;
            }
            if( !$found)
            {
                $newSections[]=$section;
            }
            if( !$inclusive && $section->hasTagName($name) )
            {
                $found=true;
            }
        }
        $this->sections=$newSections;
    }
}

?>

EDIT: This is actually the part you want, the part above parses the HTML emails.
<?php
define('ATTACHMENT_UPLOAD_SERVER_DIRECTORY',dirname(__FILE__).'/storedimages');
define('ATTACHMENT_UPLOAD_WEB_DIRECTORY','storedimages');
    if( !function_exists('randomString') )
    {
        function randomString( $len,$chrs='abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789')
        {
          $out="";
          for($i=0;$i<$len;$i++)
          {
            $out=$out.substr($chrs,rand()%strlen($chrs),1);
        }
        return $out;
      }
    }
class EmailDownloader
{
    var $imageTypesAllowed=Array('JPEG'=>'.jpg','GIF'=>'.gif','PNG'=>'.png');
    var $mbox           =   NULL;   /* mailbox resource */
    function EmailDownloader($username,$password,$mailserver='localhost',$servertype='pop',$port='default')
    {
        if($port=='default')
        {
            $imap_port='143';
            $pop_port='110';
        }
        else
        {
            $imap_port=$port;
            $pop_port=$port;
        }
        if($servertype=='pop')
        {
             $strconnect= '{'.$mailserver.':'.$pop_port. '/pop3}INBOX';
        }
        else if($servertype=='imap')
        {
            $strconnect= $strconnect='{'.$mailserver.':'.$imap_port. '}INBOX';
        }
        else
        {
            die("*** error, mailserver type should be either 'pop' or 'imap'\n");
        }
        $this->mbox=imap_open($strconnect,$username,$password);
    }
    function getEmails($deleteMessages=false,$attachmentLocationServer=ATTACHMENT_UPLOAD_SERVER_DIRECTORY,$attachmentLocationWeb=ATTACHMENT_UPLOAD_WEB_DIRECTORY)
    {
        $headers=imap_headers($this->mbox);
        //print_r($headers);
        $emails=Array();

        for($idx=0,$mid=1;$idx<count($headers);$idx++,$mid++)
        {
            $tmpFolder='';
            while ($tmpFolder=='' )
            {
                $tmpFolder='/tmp_'.randomString( 5,'abcdefghijklmnopqrstuvwxyz0123456789');
                if( file_exists($attachmentLocationServer.$tmpFolder) )
                {
                    $tmpFolder='';
                }
            }
            mkdir($attachmentLocationServer.$tmpFolder );

            $images=Array();
            $mail_header=imap_header($this->mbox,$mid);
            $fromAddress=($mail_header->from[0]->mailbox).'@'.($mail_header->from[0]->host);
            //print_r($mail_header);
            // $message=imap_body($this->mbox,$mid); # yeah, not so simple, some voodoo needed
            $mob=imap_fetchstructure($this->mbox,$mid);
            if(($mob->type)==0)
            {
                // simple text message so, no problemo!
                $message=imap_body($this->mbox,$mid);
            }else
            {
                // oops, multipart message
            //  echo  get_part($this->mbox, $mid, "MULTIPART");
                $contentParts = count($mob->parts);
                $message=get_part($this->mbox, $mid, "TEXT/HTML", $mob);
                foreach( $mob->parts as $nm=>$part )
                {
                    if( $part->type==5  ||$part->type==3 )
                    {
                        $ext='';
                        if( array_key_exists($part->subtype,$this->imageTypesAllowed) )
                        {
                            $ext=$this->imageTypesAllowed[$part->subtype];
                        }
                        if( $ext=='' && $part->subtype=='OCTET-STREAM' && isset($part->dparameters) )
                        {
                            $attFilename='';
                            foreach( $part->dparameters as $dpara )
                            {
                                if( $dpara->attribute=='FILENAME' )
                                {
                                    $attFilename=$dpara->value;
                                }
                            }
                            foreach( $this->imageTypesAllowed as $allowedExt )
                            {
                                if( substr($attFilename,-strlen($allowedExt) )== $allowedExt )
                                {
                                    $ext=$allowedExt;
                                }
                            }
                        }
                        if( $ext!=''  )
                        {
                            $filename='';
                            while(  $filename=='' )
                            {
                                $filename=randomString( 20,'abcdefghijklmnopqrstuvwxyz0123456789').$ext;
                                if( file_exists($attachmentLocationServer.$tmpFolder.'/'.$filename ) )
                                {
                                    $filename='';
                                }
                            }
                            if( $file=fopen($attachmentLocationServer.$tmpFolder.'/'.$filename,'w') )
                            {
                                fwrite($file,imap_base64(imap_fetchbody($this->mbox,$mid,$nm+1)));
                                fclose($file);
                                $images[str_replace(array('>','<'),array('','cid:'),$part->id)]=$attachmentLocationWeb.$tmpFolder.'/'.$filename;
                            }

                        }

                    }
                }

            }
            $emails[]=Array('from'=>$fromAddress,'subject'=>$mail_header->Subject,'body'=>$message,'header'=>$mail_header,'images'=>$images,'tmp_folder'=>$tmpFolder);
            if( $deleteMessages )
            {
                imap_delete($this->mbox,$mid);
            }
        }
        imap_expunge($this->mbox);
        return $emails;
    }

    function close()
    {
        imap_close($this->mbox);
    }
}
?>

<?
   function get_mime_type(&$structure) {
   $primary_mime_type = array("TEXT", "MULTIPART","MESSAGE", "APPLICATION", "AUDIO","IMAGE", "VIDEO", "OTHER");
   if($structure->subtype) {
    return $primary_mime_type[(int) $structure->type] . '/' .$structure->subtype;
   }
    return "TEXT/PLAIN";
   }
   function get_part($stream, $msg_number, $mime_type, $structure = false,$part_number    = false) {

    if(!$structure) {
        $structure = imap_fetchstructure($stream, $msg_number);
    }
    if($structure) {
        if($mime_type == get_mime_type($structure)) {
            if(!$part_number) {
                $part_number = "1";
            }
            $text = imap_fetchbody($stream, $msg_number, $part_number);
            if($structure->encoding == 3) {
                return imap_base64($text);
            } else if($structure->encoding == 4) {
                return imap_qprint($text);
            } else {
            return $text;
        }
    }

        if($structure->type == 1) /* multipart */
        {
            $prefix ='';
        while(list($index, $sub_structure) = each($structure->parts)) {
            if($part_number) {
                $prefix = $part_number . '.';
            }
            $data = get_part($stream, $msg_number, $mime_type, $sub_structure,$prefix .    ($index + 1));
            if($data) {
                return $data;
            }
        } // END OF WHILE
        } // END OF MULTIPART
    } // END OF STRUTURE
    return false;
   } // END OF FUNCTION

?>

EDIT #2:  One More Part to complete the entire process
<?php

    define('RECEIVING_EMAIL_SERVER','mail.server.com');
    define('RECEIVING_EMAIL_ACCOUNT','incoming@server.com');
    define('RECEIVING_EMAIL_PASSWORD','myPasswordIsHere');
    define('DELETE_MAIL_MESSAGES_FROM_SERVER',false);
    define('USE_MYSQL_ESCAPE',false);
    define('STORED_FOLDER_BASE',dirname(__FILE__).'/');
    define('STORED_IMAGES_LOCATION','storedimages');
    define('STORED_IMAGES_LOCATION_ABSOLUTE',STORED_FOLDER_BASE.STORED_IMAGES_LOCATION);
    include_once('class.emaildownloader.php');
    include_once('class.htmlparser.php');
    $getEmail=new EmailDownloader(RECEIVING_EMAIL_ACCOUNT,RECEIVING_EMAIL_PASSWORD,RECEIVING_EMAIL_SERVER);
    $emails=$getEmail->getEmails( DELETE_MAIL_MESSAGES_FROM_SERVER,STORED_IMAGES_LOCATION_ABSOLUTE,STORED_IMAGES_LOCATION );
    $getEmail->close();

    if( $emails )
    {
echo "EMAILS FOUND: ".count($emails)." <br />";
    }

    foreach( $emails as $email )
    {
echo "PARSING EMAIL<br />";
        $parsedDoc=new HTMLParser($email['body']);
        $parsedDoc->removeSections( "script" );
        $parsedDoc->removeSections( "style" );
        $parsedDoc->removeSections( "head" );
        $parsedDoc->removeSections( "applet");
        $parsedDoc->removeSections( "embed");
        $parsedDoc->removeSections( "object");
        $parsedDoc->removeSections( "iframe" );
        $parsedDoc->removeSections( "select" );
        $parsedDoc->removeSections( "option" );
        $parsedDoc->removeTags("noscript");
        $parsedDoc->removeTags("html");
        $parsedDoc->removeTags("body");
        $parsedDoc->removeTags("~comment");
        $parsedDoc->removeTags( "input" );
        $parsedDoc->removeTags( "link" );
        $parsedDoc->removeTags( "form");
        $parsedDoc->removeAttributes("background");
        $parsedDoc->removeAttributes("bgcolor");
        $parsedDoc->removeAttributesStartingWith("on");
        $parsedDoc->removeStyleStartingWith('background');
        $parsedDoc->compact( );
        if( count($email['images'])>0 )
        {
            $parsedDoc->replaceSources( $email['images'] );
        }
        $subject=explode(' ',$email['subject']);
        if( USE_MYSQL_ESCAPE)
        {
            $project_id=mysql_real_escape_string($subject[0]);
            $page_id=mysql_real_escape_string($subject[1]);
        }
        else
        {
            $project_id=addSlashes($subject[0]);
            $page_id=addSlashes($subject[1]);
        }

echo "PARSING COMPLETE<br />";
    }

?>

A: Zend_Mail:
http://framework.zend.com/manual/en/zend.mail.html
Specifically:
Zend_Mail_Storage
http://framework.zend.com/manual/en/zend.mail.read.html
Note: You don't need to use the whole framework. You can just use the classes you need. It's designed that way.


text:
Q: Reference book of Abstract Algebra - view with teaching and research There are continuously publishing the books of Abstract Algebra.
For the question purpose: let us say "Modern Books" to the books came in print after year 2000.
The modern books, written by new generation of mathematicians and researchers cover the topics of  Herstein,  Fraleigh, Gallian etc.
But, in many books of Abstract Algebra, nothing more than content of these old books it is said except "detailed explanation" or "different explanation".
Can one suggest some modern books on Abstract Algebra which includes (each of the) following:

*

*Cover (most of) the material in Herstein, Fraleigh, Gallian (such old texts).

*Include new topics, essential for research in new branches of algebra

*Includes the tricky challenging exercises on all topics.

*Touches some topics for very current research in algebra


text:
Q: Row_Number() over 2 billion records (Teradata) I am working with a Teradata warehouse, and I am using row_number in one of my sql scripts. The record set I am trying to use my script on is larger than the maximum of the integer value threshold. What to do in such a situation?
(casting the "row_number() over (par..)" expression to bigint did not work)
If you have found a solution for this problem in another DBMS, then I also welcome your solution as it might work in Teradata too.

A: It is possible that just casting the value would work.
If not, try this:
select sum(cast(1 as bigint)) over (order by . . . Rows Unbounded Preceding)

Or, alternatively,
select csum(cast(1 as bigint), <order by column here>)


text:
Q: How to maintain font styles in json file? I am trying to convert a spry(dreamweaver) table to a json file. The json file is working fine but I can't figure out how to read a paragraph of text(string) and maintain the paragraph's styling. I have mixed bold, italic, and underlines in each paragraph array.{description}
Does anyone know how this is done?
It seems like text styling must be possible, but I'm new to json and feeling a little overwhelmed. I am trying to change to json only because reading the data from a spry table is very slow. I'm developing a mobile app. The data resides on the client side. As it stands now, I load a separate .html page in order to grab the data. That takes too much time on the initial load.

A: JSON is a plain-text format. It is not possible to save styled text in JSON. You can, however, save marked up text (for instance, with HTML tags, Markdown, etc) in a JSON string just like you would any other piece of text.

A: A JSON File is a plain text file, so you can't use style fonts, you can use spaces, breaklines. But you can use the same format JSON to insert the kind of style that you want.


text:
Q: crossbar.io python application components, unknown attribute 'processes' in top-level configuration I'm trying/learning crossbar.io with Autobahn/Python. I could create some small components to write a file, run shell commands and now I'm following this description.
I have the config example from Router with Application Session in .crossbar/config.json.
unfortunately I get this:
[root@devtest write_file]# /opt/pypy/buildout/venv/bin/crossbar check
Checking local configuration file /opt/crossbar/write_file/.crossbar/config.json

Error: encountered unknown attribute 'processes' in top-level configuration

I don't know how to combine the example config with some working config.
I'll appreciate any help.
Thanks.

A: Studying in depth the configuration of Crossbar.io I figured out, that I cannot simply copy-paste the example config file from the mentioned description.
After some trial and error I have now a decent router component configuration:

{
   "controller": {
   },
   "workers": [
      {
         "type": "router",
         "options": {
            "pythonpath": [".."]
         },
         "realms": [
            {
               "name": "realm1",
               "roles": [
                  {
                     "name": "anonymous",
                     "permissions": [
                        {
                           "uri": "*",
                           "publish": true,
                           "subscribe": true,
                           "call": true,
                           "register": true
                        }
                     ]
                  }
               ]
            }
         ],
         "transports": [
            {
               "type": "web",
               "endpoint": {
                  "type": "tcp",
                  "port": 8080
               },
               "paths": {
                  "/": {
                     "type": "static",
                     "directory": ".."
                  },
                  "ws": {
                     "type": "websocket"
                  }
               }
            }
         ],
         "components": [
            {
                "type": "class",
                "realm": "realm1",
                "classname": "write_file.write_file.WriteFile"
            }
         ]
      }
   ]
}


text:
Q: Can not read file on NTFS volume although rights are sufficient Altough permissions should be OK, one single file on an NTFS partition can not be read, even as root. Not even the 'file' command works.
Any ideas?
# file myfile.jpg
myfile.jpg: ERROR: cannot read `myfile.jpg' (Permission denied)

# whoami
root

# ls -l myfile.jpg
-rwxr-xr-x 2 root root 84270 Jul 22  2015 myfile.jpg

# getfacl myfile.jpg
# file: myfile.jpg
# owner: root
# group: root
user::rwx
group::r-x
other::r-x

# stat myfile.jpg
  File: »myfile.jpg"
  Size: 84270       Blocks: 168        IO Block: 4096   regular file
Device: 814h/2068d  Inode: 178967      Links: 2
Access: (0755/-rwxr-xr-x)  Uid: ( 0/  root)   Gid: ( 0/  root)
Access: 2010-06-15 20:05:00.000000000 +0200
Modify: 2015-07-22 11:27:48.699794900 +0200
Change: 2015-07-22 11:27:48.699794900 +0200
 Birth: -

# pwd
/mnt/data/foo

# mount | grep data
/dev/sdb4 on /mnt/data type fuseblk (rw,noexec,nosuid,nodev,allow_other,default_permissions,blksize=4096)

# grep data /etc/fstab
UUID=44B45957B4591D2A   /mnt/data              ntfs-3g auto,permissions,user,fmask=0022,dmask=0000

A: ok, 5 years too late but the search still reveals this topic:
Issue in my setup an existing file created by Windows and file level encryption on.
> $ umount ...
> $ntfsinfo /dev/sde1 -i 3237774
> ...
> Dumping attribute $STANDARD_INFORMATION (0x10) from mft record 3237774(0x31678e)
> ...
>       File attributes: ARCHIVE NOT_CONTENT_INDEXED ENCRYPTED (0x00006020)


text:
Q: Nodejs: Unable to get query results and store in array this is my code

const mysqlssh = require('mysql-ssh');
var Promise = require('promise');

const startSSHSQLTunnel = () =>{
    return mysqlssh.connect(
        {
            host: 'xxx.xxx.xx.xxx',
            user: 'ball',
            password: 'r252_bat'
        },
        {
            host: '192.xxx.xxx.xxx',
            user: 'portal',
            password: 'r252_bat',
            database: 'mydb'
        }
    )
}

exports.getSignupSummary = async() => {
    let res = []
    let queryStrings = ['SELECT year, WorkWeek, COUNT(*) AS Count from (SELECT YEAR(signed_up) as year, WEEK(signed_up) as WorkWeek from `chatbots` where signed_up is not null) temp_table group by WorkWeek, year',
    'SELECT year, WorkMonth, COUNT(*) AS Count from (SELECT YEAR(signed_up) as year, MONTH(signed_up) as WorkMonth from `chatbots` where signed_up is not null) temp_table group by WorkMonth, year',
    'SELECT COUNT(*) as count from `chatbots`']
    //SELECT COUNT(*) as count from `chatbots`;
    getUserData = function(qs, cb) {
        startSSHSQLTunnel().then(client => {
          client.query(qs,
          function(err, results) {
            if (err)
              return cb(err);
            cb(undefined, results);
        })});
      }

      // Usage:
    queryStrings.map(x => {
        getUserData(x,
            function(err, results) {
                res.push(results);
                }
            )
        });

    console.log(res);
}

I am trying to get the query results and store in an array called "res"
however I am facing the following issues

*

*the results from the callback function can be console.logged but if I store in array and then try to print it out, I see an empty array.

*I tried to use async -> await but it was no use

*I tried to encapsulate everything in a new promise and then resolve the results but that was no point as I got an empty promise
please advise

A: You should try something like this:
exports.getSignupSummary = async() => {
  let queryStrings = ['SELECT year, WorkWeek, COUNT(*) AS Count from (SELECT YEAR(signed_up) as year, WEEK(signed_up) as WorkWeek from `chatbots` where signed_up is not null) temp_table group by WorkWeek, year',
  'SELECT year, WorkMonth, COUNT(*) AS Count from (SELECT YEAR(signed_up) as year, MONTH(signed_up) as WorkMonth from `chatbots` where signed_up is not null) temp_table group by WorkMonth, year',
  'SELECT COUNT(*) as count from `chatbots`']
  //SELECT COUNT(*) as count from `chatbots`;
  getUserData = function(qs, cb) {
    startSSHSQLTunnel().then(client => {
      client.query(qs, function(err, results) {
        if (err) return cb(err);
        cb(undefined, results);
      });
    });
  }

  // Usage:
  const promises = queryStrings.map(x => {
    return new Promise((resolve, reject) => {
      getUserData(x, function(err, results) {
        if (err) reject(err);
        resolve(results);
       });
     });
   });
   const res = await Promise.all(promises);

   console.log(res);
}

This code uses the .map function to create a promise for each of your queries and store it in an array.
Then we use await Promise.all to wait for all the promises to be resolved.


text:
Q: A relation concerning the "sum of squares" counting function $r_2(n)$ Let $r_2(n)$ denote the number of ways in which a positive integer $n$ can be expressed as the sum of squares of two integers. Here the sign as well as order of summands matters. Also by convention we set $r_2(0)=1$.
G. H. Hardy mentions the following formula in his book Ramanujan : Twelve Lectures on Subjects Suggested by His Life and Work (see page $82$) $$\sum_{0\leq n<x} \frac{r_2(n)}{\sqrt{x-n}}=2\pi\sqrt {x} +\sum_{n=1}^{\infty} \frac{r_2(n)}{\sqrt{n}}\sin 2\pi\sqrt{nx} \tag{1}$$ This is preceded by mention of another formula of Ramanujan $$\sum_{n = 0}^{\infty}\frac{r_{2}(n)}{\sqrt{n + a}}e^{-2\pi\sqrt{(n + a)b}} = \sum_{n = 0}^{\infty}\frac{r_{2}(n)}{\sqrt{n + b}}e^{-2\pi\sqrt{(n + b)a}}\tag{2}$$ which is proved here. Next Hardy says that the above formula of Ramanujan is valid when $\sqrt{a}, \sqrt{b} $ have positive real parts. Putting $a=xe^{it} $ for $x>0, x\notin\mathbb{Z} ,0<t<\pi$ in $(2)$ and letting $t\to\pi$ followed by equating imaginary parts and setting $b=0$ the relation $(1)$ is obtained.
And then comes the remark "this deduction, of course, is not a proof of $(1)$ and I do not know that there is any proof standing in the literature".

Has a proof of $(1)$ been found since? If so a reference would be greatly appreciated. Can the deduction mentioned above be fixed by making some modification? Any other approaches to prove $(1)$ are also welcome.


text:
Q: What is the best way to save ssh output into a struct in golang? I'm trying to save output of running some commands on other machine with SSH, into a struct.
I used CombinedOutput to save the output. Something like this:
...
combo, err := session.CombinedOutput("hostname;pwd")
outputResult = string(combo)
...

It gives me a 2-line output. I want to save these lines into the below struct:
type Result struct {
    Hostname string `json:"hostname"`
    PWD      string `json:"pwd"`
}

What is the best (and easy) way to do that? Thanks.

A:
It gives me a 2-line output. I want to save these lines into the below struct

Your question really has nothing to do with SSH. You have a []byte that represents the output of your commands.  You want to split it into two strings.
strings.SplitN is the perfect solution for this.  You pass it the original string (to which the []byte must be converted), the separator (\n in your case), and the maximum number of strings to return.  For us, we want at most 2 strings.  How could there be more than one \n?  pwd returns a directory, and directories can have newlines in their names, though they very rarely do in practice.
    out := []byte("myhost\n/dir")
    fmt.Println(string(out))
    strs := strings.SplitN(string(out), "\n", 2)
    res := Result{Hostname: strs[0], PWD: strs[1]}

    out := []byte("myhost\n/dir")
    fmt.Println(string(out))
    strs := strings.SplitN(string(out), "\n", 2)
    res := Result{Hostname: strs[0], PWD: strs[1]}

https://go.dev/play/p/5ENSgAPg3ER

combo, err := session.CombinedOutput("hostname;pwd")

Remember that this will also include the stderr in addition to the stdout.  I can't think of a situation where either command would generate any output to stderr, but keep in mind that you're not distinguishing between the two.  Hopefully you're checking the result of err and if not nil, not consuming the results of the command.  That should protect you from unanticipated results from the combination of stdout and stderr.  If stderr is never relevant for you, you might want to use ssh.Session.Output instead


text:
Q: Prove Magic Square Suppose that $S$ is a square such that the sum of the entries in each row is some number
$R$, and the sum of the entries in each column is some number $C$. Prove that $S$ is in fact a magic square, i.e., $R = C$.
What I thought?
The sum of a row is $(1+..+n-1)n+(1+..+n)$, and the same for any col,
hence the square in magic. Can someone verify this and help me elaborate on this.

A: $\textbf{Hint:}$ Compute the sum of all the numbers in the square in two different ways.
I don't understand your attempt. What is $n$? And why does the sum have to equal that thing?

A: Let $a_{i,j}$ be the entry in the $i$th row and $j$th column.
So, in an $n$x$n$ square, the sum of each row is: $a_{i,1} + ... + a_{i,n} =R$
And the sum of each column is: $a_{1,j} + ... + a_{n,j}=C$
As Arthur said, the sum of all the entries is
$$ (a_{1,1} + ... + a_{1,n}) + (a_{2,1} + ... + a_{2,n})+ ...+(a_{n,1} + ... + a_{n,n}) = (R)+(R)+...+(R)=nR$$
$$||\quad\quad\quad\quad\quad\quad\quad\quad\quad\quad\quad$$
$$ (a_{1,1} + ... + a_{n,1}) + (a_{1,2} + ... + a_{n,2})+ ...+(a_{1,n} + ... + a_{n,n}) = (C)+(C)+...+(C)=nC$$
Then divide both sides by $n$
$$nR=nC \quad\Rightarrow\quad R=C$$


text:
Q: FCM: iOS device registered with two different working tokens We're using Firebase Cloud Messaging for delivering push notifications.
Recently, I started seeing that the push notifications are delivered twice to the same device.
When I dug deeper, I found out that in our backend one device is registered with 2 firebase tokens. And both of them are working. Therefore, the device token provided by iOS must not have changed.
As per GCM documentation, this could happen due to a bug in the client:

Canonical IDs
If a bug in the client app triggers multiple registrations for the same device, it can be hard to reconcile state and the client app might end up with duplicate messages.
Implementing canonical IDs can help you more easily recover from these situations. A canonical registration ID is the registration token of the last registration requested by the client app . This is the ID that the server should use when sending messages to the device.
If you try to send a message using an old registration token, GCM will process the request as usual, but it will include the canonical ID in the registration_id field of the response. Make sure to replace the registration token stored in your server with this canonical ID, as eventually the old registration token will stop working.

So in case that we send a push notification to the old token, we should get a response with registration_id key value pair in it.
FCM documentation describes this case in more detail:

If message_id is set, check for registration_id:
If registration_id is set, replace the original ID with the new value (canonical ID) in your server database. Note that the original ID is not part of the result, so you need to obtain it from the list of registration_ids passed in the request (using the same index).

However, there's no registration_id in the response when using any of the two working tokens. So it seems FCM is not aware that the device is registered with multiple tokens and therefore does not include registration_id in the response.
The response looks like this:
{
    "multicast_id": 9087190295926530487,
    "success": 1,
    "failure": 0,
    "canonical_ids": 0,
    "results": [{
        "message_id": "0:1498726709849471%10726fcd10726fcd"
    }]
}

My question is: Is there any way how to get canonical ids for all devices that are registered in FCM and have multiple tokens? Or what would be the recommended way to fixing a problem like this?


text:
Q: Cannot verify lock on path When I want to delete some files, it happens to show me the error below:

Commit failed (details follow):
  Cannot verify lock on path
  'the file name...';
  no matching lock-token available
  If you want to break the lock, use the 'Check For Modifications' dialog.

Please help me to solve it.

A: At least one of the files is locked. As the error tells you, use the "Check for Modifications" dialog, click on the "check repository" button and then find the files which have a lock on them. Then either remove, break of steal that lock.

A: *

*For client-side command line approach, you can run
svn unlock --force problematic.file.name

*An administrator who has local access to the repositories could run
svnadmin unlock
Hope this helps.

A: What command were you using to delete the files? Is this a local command or a remote command in Subversion?
$ svn rm file   #Local mode

$ svn http://svnhost/svn/project/trunk/file   #Remote mode

If you were deleting files in local mode, are they read-only? If so, you'll have to determine what made them read-only. Is there a lock on them? See the Red Bean book chapter on locks.
You were using a Subversion command. Right?

A: if you are in eclipse , go to team, click lock, then there is check box for (steal lock) click it and retry with check it , then it should work for you


text:
Q: How to increase the responsiveness of 'ManagementEventWatcher' logic? I'm suscribed to Win32_ProcessStartTrace class events to notify when a process is ran on the PC:
Me.processStartWatcher =
    New ManagementEventWatcher(New WqlEventQuery("SELECT * FROM Win32_ProcessStartTrace"))

However, this seems not efficient because it takes 1 or 2 seconds to fire the event after I ran an executable file:
Private Sub ProcessStartWatcher_EventArrived(sender As Object, e As EventArrivedEventArgs) _
Handles processStartWatcher.EventArrived

    If (Me.ProcessStartedEvent IsNot Nothing) Then
        RaiseEvent ProcessStarted(Me, e)
    End If

End Sub

This means that if a process is ran and has exited quickly then I will not be notified.
Is there something I could do to increase responsiveness on a ManagementEventWatcher object?.
I tried to set the Timeout property but as the description of the member says, it seems does have nothing to do with this purpose.

A: You use the WITHIN clause in your WMI query to specify the polling interval.  The article gives plenty of warning that using small intervals is not recommended.  But forge ahead and try it anyway:
Me.processStartWatcher =
    New ManagementEventWatcher(
       New WqlEventQuery("SELECT * FROM Win32_ProcessStartTrace WITHIN 0.1"))

And you'll find out that it simply doesn't make any difference, the default is already as fast as it can be.  This is architectural in Windows, the kernel has no 'hook' to generate a notification when a process is created.  Important as it might be to, say, a virus scanner.  They are forced to patch the OS to be able to jump in.  The WMI provider that implements this query (C:\Windows\System32\wbem\KrnlProv.dll) does not do this.
Another way to see this is to just implement it yourself with the Process class.  For example:
Public Class ProcessMonitor
    Public Event Started As Action(Of Integer)
    Public Event Stopped As Action(Of Integer)

    Public Sub New(interval As Integer)
        Me.interval = interval
        running = Scan()
        timer = New Threading.Timer(AddressOf callback, Nothing, interval, 0)
    End Sub

    Private Sub callback(state As Object)
        Dim active As HashSet(Of Integer) = Scan()
        Dim started As IEnumerable(Of Integer) = active.Except(running)
        Dim stopped As IEnumerable(Of Integer) = running.Except(active)
        running = active
        For Each pid As Integer In started
            RaiseEvent started(pid)
        Next
        For Each pid As Integer In stopped
            RaiseEvent stopped(pid)
        Next
        timer.Change(interval, 0)
    End Sub

    Private Function Scan() As HashSet(Of Integer)
        Dim ret As New HashSet(Of Integer)
        For Each proc As Process In Process.GetProcesses()
            ret.Add(proc.Id)
        Next
        Return ret
    End Function

    Private running As HashSet(Of Integer)
    Private timer As System.Threading.Timer
    Private interval As Integer
End Class

With a sample program that uses it:
Module Module1
    Sub Main()
        Dim monitor As New ProcessMonitor(100)
        AddHandler monitor.Started, AddressOf Started
        AddHandler monitor.Stopped, AddressOf Stopped
        Console.ReadLine()
    End Sub
    Sub Started(pid As Integer)
        Console.WriteLine("Started: {0}", Process.GetProcessById(pid).ProcessName)
    End Sub
    Sub Stopped(pid As Integer)
        Console.WriteLine("Stopped: {0}", pid)
    End Sub
End Module

No difference.


text:
Q: Unable to center website brand in navbar? I am trying to center my website's brand in the navbar using bootstrap 3.0 and have been unsuccessful in doing so. I have tried both of these solutions:
twitter bootstrap -- center brand in nav bar
Bootstrap: center some navbar items
And neither has worked for me. Here is my current code:
<link rel="stylesheet" href="http://netdna.bootstrapcdn.com/bootstrap/3.0.3/css/bootstrap.min.css">

      My Website's Brand

I have tried text-align: center and auto margins and nothing has worked. Any ideas?
EDIT: JSFiddle: http://jsfiddle.net/3Kqn8/

A: .navbar-header {
    text-align: center;
 }

Demo http://jsfiddle.net/ujgdL/

EDIT: Bootstrap update.
.navbar-header { text-align: center;  }
.navbar-brand { display: inline-block; float: none; }

working example http://jsfiddle.net/3Kqn8/1/

A: You have to do a couple of overwrites for the bootstrap classes, namely the following:
.navbar-header {
    padding-top:15px;
    text-align:center;
    float:none;
}
.navbar-brand {
    float:none;
}

.navbar-brand is floated left, most importantly.  So you need to set float to none.  navbar-header needs text-align:center to center, and padding-top:15px to adjust for the padding styling that is removed when you remove the float.  Probably some better ways to do this, but this is the most basic solution.
See the demo: http://jsfiddle.net/bozdoz/KDsJ8/
Update
You also need to set .navbar-header to float:none since on different screen sizes it will float left. :P
Fiddle updated.

A: I also have another solution below:
.navbar-header {
    text-align:center; // Align center will work after we clear the "Float" in ".navbar-brand"
    line-height: 50px; // To make our text to vertical align to middle;
}
.navbar-brand {
    float: none; // Clear the float for align the text
    display: block; // To Make it click on the hold box
}


text:
Q: Angular table edit inline pagination ayudenme porfavor tengo un error al querer poner paginarion (dirpagination) a mi tabla con edit inline angular js, no se porque me sale este error ya que en mis otras tablas de solo mostrar data esta todo bien, pero en esta tabla estoy con un metodo editable llamando a un ng-include.
esta es mi tabla en html:

            First Name ^v

    Last Name
    Hire Date
    Address
    City
    Postal Code
    Country
    Opciones

<dir-pagination-controls max-size="5"
                         direction-links="true"
                         boundary-links="true">
</dir-pagination-controls>

aqui mi controller :
angular.module("MyApp", ['angularUtils.directives.dirPagination','720kb.datepicker', 'chieffancypants.loadingBar', 'ngAnimate'])
.config(function (cfpLoadingBarProvider) {
      cfpLoadingBarProvider.includeSpinner = true;
  })
.controller('PartGrider', function ($scope, EmployeeService, $timeout, cfpLoadingBar) {

    $scope.orderByField = 'FirstName';
    $scope.reverseSort = false;

    $scope.Employees = [];
    $scope.employeeData = {};
    $scope.selected = {};

    $scope.CountryList = null;

    $scope.open = function ($event, employee) {
        $event.preventDefault();
        $event.stopPropagation();

        employee.isOpen = true;
    };

    $scope.showCountry = function (data) {

        var obj = null;

        angular.forEach($scope.CountryList, function (val) {

            if (val.CountryID == data) {
                obj = val.CountryName;
            }
        });

        return obj;
    }

    EmployeeService.GetCountry().then(function (d) {

        $scope.CountryList = d.data;

    }, function (error) {

        alert("Error");

    });

    EmployeeService.GetEmployeesList().then(function (d) {

        $scope.Employees = d.data;

    }, function (error) {

        alert("Error!!!!");

    });

    $scope.actualizaMatriz = function () {

        EmployeeService.GetEmployeesList().then(function (d) {

            $scope.Employees = d.data;
        }, function (error) {

            alert("Error!!!!");

        });

    }

    $scope.addEmployeetoDB = function () {

        $scope.employeeData = {
            FirstName: $scope.FirstName,
            Address: $scope.Address,
            City: $scope.City,

        };

        EmployeeService.AddEmployee(employeeData).then(function (d) {

            alert(d);

        })

        EmployeeService.GetEmployeesList().then(function (d) {

            $scope.Employees = d.data;
        }, function (error) {

            alert("Error!!!!");

        });

    };

    $scope.deleteEmployee = function (employee) {

        $scope.employeeData = {
            FirstName: $scope.FirstName,
            Address: $scope.Address,
            City: $scope.City,

        };

        EmployeeService.DeleteEmployee(employee).then(function (d) {

            alert(d);
            $scope.actualizaMatriz();

        });

        EmployeeService.GetEmployeesList().then(function (d) {

            $scope.Employees = d.data;
        }, function (error) {

            alert("Error!!!!");

        });

    };

    $scope.updateEmployee = function (employee) {

        $scope.employeeData = {
            FirstName: $scope.FirstName,
            Address: $scope.Address,
            City: $scope.City,

        };

        EmployeeService.UpdateEmployee(employee).then(function (d) {
            alert(d);
            $scope.reset();
            $scope.actualizaMatriz();
        });
    };

    $scope.getTemplate = function (employee) {
        if (employee.EmployeeID === $scope.selected.EmployeeID) {
            return 'edit';
        }
        else return 'display';
    };

    $scope.reset = function (index) {
        $scope.Employees[index] = $scope.selected;
        $scope.selected = {};
    }

    $scope.editEmployee = function (employee) {
        $scope.selected = angular.copy(employee);
    };

    $scope.start = function () {
        cfpLoadingBar.start();
    };

    $scope.complete = function () {
        cfpLoadingBar.complete();
    }

    // fake the initial load so first time users can see it right away:
    //$scope.start();
    //$scope.fakeIntro = true;
    //$timeout(function () {
    //    $scope.complete();
    //    $scope.fakeIntro = false;
    //}, 750);

})

.factory('EmployeeService', function ($http, $q) {

    var fac = {};

    fac.GetCountry = function () {

        return $http.get('/Data/GetCountries')

    }

    fac.GetEmployeesList = function () {

        return $http.get('/Data/GetEmployeeList')
    }

    fac.AddEmployee = function (data) {

        var defer = $q.defer();
        $http({

            url: '/Data/AddEmployee',
            method: 'POST',
            data: JSON.stringify(data),
            headers: { 'content-type': 'application/json' }

        }).success(function (d) {

            defer.resolve(d);

        }).error(function (e) {

            alert("Error!!!!");
            defer.reject(e);
        });

        return defer.promise;

    }

    fac.DeleteEmployee = function (data) {

        var defer = $q.defer();

        $http({

            url: '/Data/DeleteEmployee',
            method: 'POST',
            data: JSON.stringify(data),
            headers: { 'content-type': 'application/json' }

        }).success(function (d) {

            defer.resolve(d);

        }).error(function (e) {

            alert("Error!!!!");
            defer.reject(e);
        });

        return defer.promise;

    }

    fac.UpdateEmployee = function (data) {

        var defer = $q.defer();
        $http({

            url: '/Data/UpdateEmployee',
            method: 'POST',
            data: JSON.stringify(data),
            headers: { 'content-type': 'application/json' }

        }).success(function (d) {

            defer.resolve(d);

        }).error(function (e) {

            alert("Error!!!!");
            defer.reject(e);
        });

        return defer.promise;

    }

    return fac;

})

 .filter('active', function () {

     return function (input) {
         if (input == '1')
             return 'Yes';
         else
             return 'No';
     };
 })

.filter('dateFilter', function () {

    return function (item) {

        if (item != null) {
            return new Date(parseInt(item.substr(6)));
        }
        return "";
    }

});

el error es q no me muestra nada en la tabla y en la consola de chrome me sale esto:
angular.js:11655 TypeError: Cannot read property 'EmployeeID' of undefined
    at ChildScope.$scope.getTemplate (PartGrid.js:157)
    at $parseFunctionCall (angular.js:12404)
    at Object.expressionInputWatch (angular.js:12813)
    at Scope.$digest (angular.js:14300)
    at Scope.$apply (angular.js:14571)
    at bootstrapApply (angular.js:1455)
    at Object.invoke (angular.js:4203)
    at doBootstrap (angular.js:1453)
    at bootstrap (angular.js:1473)

segun entiendo es el error en el metodo getTemplate de mi controller, no se q hacer en este caso.


text:
Q: Robolectric getResources() throws RuntimeException (Android) I'm trying to use the Robolectric framework to create unit tests for my android projects.
I've started with an empty Android project created by the eclipse android project wizard.
In a different java project I use this code to try running a basic test:
@RunWith(RobolectricTestRunner.class)
public class ApiTest {

    @Before
    public void setUp() throws Exception {
    }

    @After
    public void tearDown() throws Exception {
    }

    @Test
    public void shouldHaveApplicationName() throws Exception {
        String appName = new RobolectricActivity().getResources().getString(R.string.app_name);
        assertEquals(appName, "TestDemo");
    }

    @Test
    public void testSomethingMeaningfulToMyApp() {
        fail("not implemented");
    }

}

I've configured everything like explained in the Robolectric Quick Start Guide.
However, when I'm trying to run this test class I get the following exception in the line where I'm accessing the getResources() function:
java.lang.RuntimeException: Did your shadow implementation of a method throw an exception? Refer to the bottom of this stack trace.
at com.xtremelabs.robolectric.ShadowWrangler.methodInvoked(ShadowWrangler.java:86)
at com.xtremelabs.robolectric.RobolectricInternals.methodInvoked(RobolectricInternals.java:50)
at android.content.ContextWrapper.getResources(ContextWrapper.java)
at com.xtremelabs.robolectric.shadows.ShadowContextWrapper.getResources(ShadowContextWrapper.java:40)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:616)
at com.xtremelabs.robolectric.ShadowWrangler.methodInvoked(ShadowWrangler.java:78)
at com.xtremelabs.robolectric.RobolectricInternals.methodInvoked(RobolectricInternals.java:50)
at android.content.ContextWrapper.getResources(ContextWrapper.java)
at ApiTest.shouldHaveApplicationName(ApiTest.java:28)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:616)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:44)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:15)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:41)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:20)
at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:28)
at org.junit.internal.runners.statements.RunAfters.evaluate(RunAfters.java:31)
at com.xtremelabs.robolectric.RobolectricTestRunner$1.evaluate(RobolectricTestRunner.java:164)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:76)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:50)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:193)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:52)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:191)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:42)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:184)
at org.junit.runners.ParentRunner.run(ParentRunner.java:236)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:49)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:467)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:683)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:390)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:197)
Caused by: java.lang.reflect.InvocationTargetException
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at  sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:616)
at com.xtremelabs.robolectric.ShadowWrangler.methodInvoked(ShadowWrangler.java:78)
... 36 more
Caused by: java.lang.ExceptionInInitializerError
at android.os.Build$VERSION.<clinit>(Build.java:95)
at android.content.res.Resources.<clinit>(Resources.java:57)
at com.xtremelabs.robolectric.shadows.ShadowApplication.getResources(ShadowApplication.java:74)
... 41 more
Caused by: java.lang.NullPointerException
at android.os.SystemProperties.<clinit>(SystemProperties.java:35)
... 44 more

It seems like the shadow classes are not set up properly and I didn't find a solution for this problem on google or stackoverflow.
Do you have any suggestions for me? Thank you very much!

A: Have you tried creating a constructor for the test class that calls the Activity you're trying to test?
e.g.:
public class ApiTest {

    public ApiTest() {
        super(MainActivity.class);
    }

    //...the rest of your test class
}

I'm still learning how to do unit testing and mocking in Android myself, so I apologize in advance if this doesn't work for you.


text:
Q: Draw heatmap using python I am trying to draw heatmap using Jupyter notebook. My table consists of 10 colomns and a lot of rows. The first row is the names of the colomns. I am using plotly lib.
import plotly.offline as py
import plotly.graph_objs as go
import pandas as pd
import numpy as np
import pickle
import matplotlib
import matplotlib.pyplot as plt
from pandas import ExcelWriter
from pandas import ExcelFile

heatmap = go.Heatmap(
            z=dfs.corr(method='pearson').as_matrix(),
            x=dfs.columns,
            y=dfs.columns,
            colorbar=dict(title='Pearson Coefficient'),
        )

    layoutheat = go.Layout(title="title")

    figheat = go.Figure(data=[heatmap], layout=layoutheat)
    py.iplot(figheat)

dfs is dataframe.
Instead of graphic I get a lot of line like this:
'\ntrace = dict(\n        x = x, y = y, z = z,\n        type = "scatter3d",    \n        mode = \'markers\',\n        marker = dict( size=5, color=\'black\', line=dict(width=0) ) )\ndata = [trace]\n  \nlayout = dict(\n etc
What is the problem?

A: If you are running a jupyter notebook you need to add py.init_notebook_mode() after the import. If it still does not work I suggest to reinstall plotly


text:
Q: Drawing a background grid based on \linespread value I'm trying to help a friend set an Arabic book in LaTeX and I'm facing this very same uneven line spacing issue (except that the book is completely in Arabic).
Now I'm trying to find the \linespread setting that is just big enough to ensure even line spacing but not any bigger, so I thought drawing a grid and visually examining the lines with different setting to find the desired ones.
But, I do not even understand what, say, 1.5 in \linespread{1.5} actually mean (I read many discussions and answers but I still don't get it), so I need help in:

*

*Setting a background grid (horizontal lines are enough).

*Make the spacing between grid lines follow \linespread setting i.e. they should represent the ideal line spacing if TeX didn't do its vertical glue magic.

(I tried grid option of eso-pic but couldn't wrap my head around the meaning of its options to get what I described above).

A: With package bidi-atbegshi, this even becomes much easier (you only have to change \AtBeginShipoutUpperLeft in @egreg's code to \AtBeginShipoutUpperRight:
\documentclass{article}
\usepackage{bidi-atbegshi,picture,xcolor}
\usepackage[RTLdocument]{bidi}
\AtBeginShipout{%
  \AtBeginShipoutUpperRight{%
    {\color{red}%
    \put(\dimexpr 1in+\oddsidemargin,
         -\dimexpr 1in+\topmargin+\headheight+\headsep+\topskip)%
      {%
       \vtop to\dimexpr\vsize+\baselineskip{
         \hrule
         \leaders\vbox to\baselineskip{\hrule width\hsize\vfill}\vfill
       }%
      }%
  }%
 }%
}

\linespread{1.5}

\usepackage{kantlipsum}

\begin{document}
\kant
\end{document}

A: This should do what you want. A box consisting of the requested number of lines, drawn at the baselines, is added with \AtBeginShipout.
\documentclass{article}
\usepackage{atbegshi,picture,xcolor}
\AtBeginShipout{%
  \AtBeginShipoutUpperLeft{%
    \color{red}%
    \put(\dimexpr 1in+\oddsidemargin,
         -\dimexpr 1in+\topmargin+\headheight+\headsep+\topskip)%
      {%
       \vtop to\dimexpr\vsize+\baselineskip{
         \hrule
         \leaders\vbox to\baselineskip{\hrule width\hsize\vfill}\vfill
       }%
      }%
  }%
}

\linespread{1.5}

\usepackage{kantlipsum}

\begin{document}
\kant
\end{document}

What does \linespread{1.5} do? Every time LaTeX does a setting of \baselineskip, it will multiply the normal value by that factor. For instance, if the normal baselineskip is 12pt, it will become 18pt; for \small, when the normal value is 11pt, it will become 16.5pt. However, \topskip is not modified.

A: With a little change to @egreg's code, this works fine in RTL too:
\documentclass{article}
\usepackage{atbegshi,picture,xcolor}
\usepackage[RTLdocument]{bidi}
\AtBeginShipout{%
  \AtBeginShipoutUpperLeft{%
    {\color{red}%
    \put(\dimexpr -1in-\oddsidemargin,
         -\dimexpr 1in+\topmargin+\headheight+\headsep+\topskip)%
      {%
       \vtop to\dimexpr\vsize+\baselineskip{
         \hrule
         \leaders\vbox to\baselineskip{\hrule width\hsize\vfill}\vfill
       }%
      }%
  }}%
}

\linespread{1.5}

\usepackage{kantlipsum}

\begin{document}
\kant
\end{document}

and here is what you get:


text:
Q: The whole ArrayList contains the same data I have created the following method, to add a name and number for every contact within the user's phone book:
PlayerDetails contactPlayer = new PlayerDetails();

public PlayerList getContacts(){
    ContentResolver cr = calledActivity.getContentResolver();
    Cursor contactList = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,null,null,null,null);
    while (contactList.moveToNext()){
        contactPlayer.name = contactList.getString(contactList.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
        contactPlayer.number = contactList.getString(contactList.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
        playerNameNumber.myPlayers.add(pos,contactPlayer);

        //playerNameNumber.add(pos,name + " " + phoneNumber);
        pos++;
    }
    return playerNameNumber;
}

But each position contains the same data.
When I debug, I can see that during the while loop that it is going through each contact, at contactPlayer.name and number it has a different contact each time but at the :
playerNameNumber.myPlayers.add  it will add the data but to each position.
So playerNameNumber[0] and playerNameNumber[1] have the same contact information?!
playerNameNumber is an object with the following:

ArrayList<PlayerDetails> myPlayers = new ArrayList<>();

    void addPlayer(PlayerDetails player){
        myPlayers.add(player);

        }

myPlayers:
   int id;
    String name;
    String number;

Is it the while loop that is causing this issue?
also, I know I have 'pos' but I am sure I don't need this?
Why is it the 'add' is replacing every item in the arraylist with the same data?

A: For same contactPlayer you are assigning new name and number.
Can't see where its instantiated in the loop. So everytime they are added to the list all are pointing to the same Object and will contain the name and number added last in the loop.

A: You will have to instantiate  the PlayerDetails every time you run through while loop otherwise it will point to same location (The Last Contact).
public PlayerList getContacts(){
    ContentResolver cr = calledActivity.getContentResolver();
    Cursor contactList = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,null,null,null,null);
    while (contactList.moveToNext()){
        contactPlayer = new PlayerDetails();
        contactPlayer.name = contactList.getString(contactList.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
        contactPlayer.number = contactList.getString(contactList.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
        playerNameNumber.myPlayers.add(pos,contactPlayer);

        //playerNameNumber.add(pos,name + " " + phoneNumber);
        pos++;
    }
    return playerNameNumber;
}


text:
Q: Extract value from html tag by Regular Expression Extractor of JMeter I have a html select like below
<select id="alias" name="alias">
  <option value="">-Select-</option>
  <option
          value='100'
          data-accountnumber='2251106207001'
          data-accountholder='Ashraful'
          data-mobilenumber='01811449003'
          data-email='shadiq2@yahoo.com'>
      testBeneficiary-1
  </option>
</select>

I need a regular expression for JMeter to extract the value which is 100 of above snippet. Can anyone help me with this? Thanks in advancet

A: As per https://stackoverflow.com/a/1732454/2897748

You can't parse [X]HTML with regex. Because HTML can't be parsed by
  regex. Regex is not a tool that can be used to correctly parse HTML.

I would suggest using XPath Extractor instead.
In your case XPath Extractor should be configured as follows:

*

*Check Use Tidy if data isn't XML/XHTML compliant, elsewise you'll get SAX Exception

*Reference Name: anything meaningful, it will be the name of JMeter Variable storing XPath Expression Result. Let it be value

*XPath Query:
//select[@id='alias']/option[@data-email='shadiq2@yahoo.com']/@value

The XPath query above returns "value" attribute of option which "data-email" attribute is "shadiq2@yahoo.com" of select with "alias" id.
Once extracted you will be able to refer that variable as ${value} or ${__V(value)}
See Using the XPath Extractor in JMeter guide for more details, XPath language reference and short cookbook.

A: The given html text
<select id="alias" name="alias">
  <option value="">-Select-</option>
  <option
          value='100'
          data-accountnumber='2251106207001'
          data-accountholder='Ashraful'
          data-mobilenumber='01811449003'
          data-email='shadiq2@yahoo.com'>
      testBeneficiary-1
  </option>
</select>

We can get the option value 100 using the following regex formats
Regex formats to get the value 100
<option value="">-Select-</option>\s\s\s<option\s\s\s\s\s\s\s\s\s\s\svalue='(.+)'

Note :
\s - means single space
\s\s\s - means three spaces
\s\s\s\s\s\s\s\s\s\s\s - means eleven spaces


text:
Q: How to create an Object with multiple properties of the same name I'm using the Twitter api (and twitter node module https://www.npmjs.com/package/twitter) to retrieve a list of numeric user ids of users belonging to a specific list. What i'd like to do is leverage this data to use in the streaming api to stream tweets from the list.
All the code:
// Call Twitter, Senti, and jQuery Node Modules
    var Twitter = require('twitter');

// Verify App with Twitter via oAuth
    var client = new Twitter({
      consumer_key: 'KEY',
      consumer_secret: 'SECRET',
      access_token_key: 'TOKEN',
      access_token_secret: 'TOKEN SECRET'
    });

// Calls list Membership data (RESTful -- Will need to be timed)

   client.get('lists/members', {slug:'LIST SLUG', owner_screen_name: 'SOMETHING', count: 500}, function(error, tweets, response){
        if (!error) {
            console.log("Connected");
        }

// Pulls user[].id values and pushes them to idArray

        var idArray = [];

        for(var i in tweets.users) {
            idArray.push(tweets.users[i].id);
        }

// create object to be used as follow paramater and push idArray values to it as individual properties (All are named follow).

        var idObj = new Object();

        for(var i in idArray) {

            var follow = "follow";
            idObj.follow = Number(idArray[i]);
        }

       console.log(idObj);

// Call Streaming api to begin stream
     client.stream('statuses/filter', idObj, function(stream) {
            stream.on('data', function(tweet) {
             console.log(tweet);
            });

            stream.on('error', function(error) {
             console.log(error);
            });
        });
});

Step1 (Works)
I called the api, retrieve the user ids list and store them in an array.
  client.get('lists/members', {slug:'LIST SLUG', owner_screen_name: 'SOMETHING', count: 500}, function(error, tweets, response){
        if (!error) {
            console.log("Connected");
        }

// Pulls user[].id values and pushes them to idArray

        var idArray = [];

        for(var i in tweets.users) {
            idArray.push(tweets.users[i].id);
        }

The Problem
In order to utilize the user ids as an argument when calling the streaming api them must all be contained in a single object where each property is called follow.
I'm trying to accomplish this by creating a new object and creating a single follow property in a for in loop to cycle through the array I'm storing the user ids in, but it will only return one of the array values in the object.
    var idObj = new Object();

    for(var i in idArray) {

        var follow = "follow";
        idObj.follow = Number(idArray[i]);
    }

I've done a bunch of googling but haven't been able to find a solution. If anyone has any thoughts I'd really love to hear them.


text:
Q: Feedparser SAXParseException, bozo:1 I'm using feedparser in a script that's generally working for RSS URLs, but there's one URL that's giving me a headache: tabbforum.com/feed.atom
I get a SAXParseException('not well-formed (invalid token)',).
import feedparser

def read_from_feed(self, rss_url):
    feed = feedparser.parse(rss_url)
    for entry in feed.entries:
        print('do stuff')

>>>>feed
{'feed': {}, 'entries': [], 'bozo': 1, 'encoding': 'utf-8', 'version': '', 'bozo_exception': SAXParseException('not well-formed (invalid token)',), 'namespaces': {}}

I'm thinking that there's something wrong with the xml(?). Has anybody had previous experiences and have been able to find a work-around? Or have an idea what the problem is?

A: Had a similar problem. In my case I forgot to put http:// in front of URL and feedparser was treating it not as a url, but as an RSS XML.


text:
Q: Tomcat6 moving libraries onto external disk array The catalina.properties entry for Tomcat6 is as follows:
common.loader=${catalina.base}/lib,${catalina.base}/lib/*.jar,${catalina.home}/lib,${catalina.home}/lib/*.jar,/raid/java/lib/*.jar,/raid/java/lib/spring/spring-security-3.1.0.RE
LEASE/dist/*.jar,/raid/java/lib/spring/spring-framework-3.1.0.RELEASE/dist/*.jar,/raid/java/lib/hibernate/*.jar,/raid/java/lib/jstl/*.jar

server.loader=
shared.loader=

where /raid/.. is a disk array mount point attached to another server. Now, am wondering if i can move the ${catalina.base}/lib and ${catalina.home}/lib libs over to /raid/java/..somewhere as well?


text:
Q: Как передать данные из одного представления в другое, не используя при этом контроллер? Добрый день! У меня есть два представления. 1 отображает таблицу, при нажатии на строку таблицы открывается второе представление, необходимо из 1 представления получить данные и отобразить во втором представлении без использования контроллера. ViewBag не помогает. Как это можно сделать? и как потом сделать так чтобы при клике на текст во втором представлении открывалось 3 представление?
A: *

*Session

*ViewState

*HttpCookie
касательно второго вопроса - повесьте на клик @Url.Action("Index", "Controller3" ...)


text:
Q: how to make an object snap to another ojbect then follow its path with pure actionscript I am currently trying to create an app using flash AIR.
I would like to find some more information on how to make an object snap to another ojbect then follow its path, eg. a person object is already on the stage, then drag an arrow to the object which snaps to it, then on play button it follows the arrow path. all in pure actionscript, no guide layers.
Any help is really appreciated. Or examples if there are any around.
Regards
Mark T

A: There's a difference in their positions, so make the follower object change its X property to ((frames_to_go-frames_passed)*starting_x_difference)+target_x between the objects. Same goes for the Y property.


text:
Q: ¿Cual es el uso del operador % en printf de variables en lenguaje C? Estoy comenzando un curso en youtube de C.
Y muestran que para imprimir los valores de las variables es necesario utilizar este operador %.
ejemplo:
int suma, a, b;
a=2;
b=3;
suma=a+b;
printf("El valor de la suma es %i", suma);

En caso de entero %i, float %fy char %c
Quisiera saber que otros usos tiene este operador y que atributos tiene dependiendo el valor, pues vi que podía delimitar los decimales mostrados usando %.1f o %.2f

A: En el contexto que defines el % no es un operador sino un especificador de formato.
En C los especificadores de formatos son los que le dicen a las funciones variadicas el tipo de argumento con el que irá a trabajar.
En el caso más simple:
printf("%s\n", "hola mundo");

Le dice al compilador que optimice la llamada a la función printf para un argumento de tipo char *.
Los especificadores de formato más comunes pueden ser:
- %d o %i: Especifican un entero con signo.
- %u     : Especifican un entero sin signo.
- %p     : Direccion de un puntero u dato.
- %lld   : Especifica un entero largo (long long). [*]
- %llu   : Entero largo sin signo (unsigned long long) [*]
- %s     : Especifica que el parametro es un puntero a un arreglo de caracteres.
- %c     : Un caracter.
- %x     : Especifica un valor hexadecimal.
- %%     : Muestra un literal de porcentaje.
- %f     : Imprime un float o double.

*: Estos especificadores pueden estar fuera de estándar.
Fuera de este contexto, es un operador de módulo y sirve para obtener el residuo de una division.

EDIT:
Adicionalmente, como he mencionado en el principio, es un especificador de formato, tambien pueden utilizarse para rellenar espacios con ceros o como desees:
printf("%X es lo mismo que %02X", 0x0a, 0x0a);

Esto dara como resultado:
A es lo mismo que 0A

O tambien:
printf("%.03f es un float!\n", 0.250554);

Este ultimo limita a imprimir los 3 primeros lugares despues del punto decimal en un float.

EDIT 2:
Sentí que faltaba algo de información en esta respuesta, la cual está ahora presente en esta edición y es que los especificadores de formato tienen cierta magia por dentro.
Organicemos esto por tipos:

*

*char * o "C-String": Su especificador es %s, pero que pasa si hacemos: %.2s?

Supongamos que tenemos el siguiente string: "Hola Mundo" y hacemos:
printf("%.2s\n", "Hola Mundo"); // Resultado: Ho

La respuesta es: Se limita a imprimir solo 3 caracteres del parametro actual; de igual forma se puede utilizar para espaciar las cadenas:
printf("'%*s'\n", 20, "Hola Mundo"); // Resultado: '         Hola Mundo'

¿Y si los mezclamos?
printf("'%*.2s'\n", 20, "Hola Mundo"); // Resultado: '         Ho'

Como se puede apreciar, todo el formato de una cadena es posible en C.
El caracter * dentro de un especificador de formato, debe incluir un parámetro adicional en la llamada a la función para especificar su valor, como en los ejemplos mencionados anteriormente.
Aquí debajo una tabla con los posibles tipos de formato que se les puede dar a un parámetro, ver última referencia (Wikipedia):
Especificador   Lo que hace:
--------------------------------------------------------------------------------------------------
%07i            justificado a la derecha, 7 dígitos de largo, sin relleno
%.7i            largo mínimo de 7 dígitos, justificado a la derecha, rellena con ceros
%8.2f           tamaño total de 8 dígitos, con dos decimales
%.*f"',x,d)     tamaño predeterminado,x numeros decimales
%*.*f",x,y,d)   tamaño igual a x, y numeros decimales
%s              cadena terminada en null
%5s             primeros cinco caracteres o delimitador
%.5s            primeros cinco caracteres, sin tener en cuenta el delimitador
%20.5s          primeros cinco caracteres, justificados a la derecha, con 20 caracteres de largo
%-20.5s         primeros cinco caracteres, justificados a la izquierda, con 20 caracteres de largo

El formato se aplica prácticamente igual para todos los tipos, pero aun así hay que ser cuidadosos.

Algunas referencias (En inglés):

*

*The GNU C Programming Tutorial

*Familia printf(C++Reference)

*printf(const char fmt, ...)

*Wikipedia, printf

A: También se usa para el operador Módulo, que no es más que el resto de una división. Por ejemplo, aquí un pequeño trozo de código en C que dice si un número es par o impar:
int numero = 4;

if(numero % 2 == 0)
    printf("El número es par");

else
    printf("El número no es par");

Este debería sacar por pantalla "El número es par", ya que si divides un número par entre 2, el resto siempre va a ser 0. Espero que te haya servido de ayuda.


text:
Q: Typescript how to do nested generic types I am trying to achieve something like the following:
type GenericPerson = {
  name: string;
};

type GenericCompany<X extends GenericPerson> = {
  companyName: string;
  employees: X[];
};

const getEmployeeDetails = <T extends GenericPerson, Company extends GenericCompany<T>>(company: Company): T[] => {
  return company.employees;
};

given there is no compiler warning, I assumed getEmployeeDetails will indeed return an array of T. However, when I tried the following:
const companyA = {
  companyName: 'XYZ',
  employees: [
    {
      name: 'John',
      address: 'London',
    },
    {
      name: 'David',
      address: 'New York',
    },
  ],
};

getEmployeeDetails(companyA).map((x) => {
  console.log(x.address);
});

It doesn't work at all, surprisingly getEmployeeDetails has a return type of GenericPerson[] instead.
Can someone help me on what I did wrong please? How can I achieve the desired result instead
Thanks