text:
Q: First print works but second time blank page prints I have a windows app i built that has 5 tabs. On 2 of the tabs i give the option to print only if the datagridview.rowcount is greater than 0. This will allow the print button to appear. I can print the first report just fine, but if i select different parameters and repopulate the datagridview again or move to the other tab and populate its datagridview and try to print i only get blank pages for every time after the first print job. Any thought on why?
Here is All Code
    Dim strFormat As New StringFormat()
    Dim arrColumnLefts, arrColumnWidths As New ArrayList()
    Dim iCellHeight, iTotalWidth, iCount, iLeftMargin, iTopMargin, iTmpWidth, iHeaderHeight, iRow As Integer
    Dim bFirstPage, bNewPage, bMorePagesToPrint As Boolean
    Dim dgvGridCol, GridCol As DataGridViewColumn
    Dim GridRow As DataGridViewRow

    Public Sub btn_print_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btn_print.Click

        If PrintDialog1.ShowDialog() = Windows.Forms.DialogResult.OK Then
            PrintDocument1.DocumentName = "Report Printing"
            PrintDocument1.Print()
        End If
    End Sub

    'Handles the begin print event of print document
    Public Sub printDocument1_BeginPrint(ByVal sender As System.Object, ByVal e As System.Drawing.Printing.PrintEventArgs) Handles PrintDocument1.BeginPrint
        Try
            strFormat = New StringFormat()
            strFormat.Alignment = StringAlignment.Near
            strFormat.LineAlignment = StringAlignment.Center
            strFormat.Trimming = StringTrimming.EllipsisCharacter
            arrColumnLefts.Clear()
            arrColumnWidths.Clear()
            iCellHeight = 0
            iCount = 0
            bFirstPage = True
            bNewPage = True
            iTotalWidth = 0
            If TabControl1.SelectedTab.Text = "Reports" Then
                For Each dgvGridCol As DataGridViewColumn In DataGridView4.Columns
                    iTotalWidth += dgvGridCol.Width
                Next
            ElseIf TabControl1.SelectedTab.Text = "Stats" Then
                For Each dgvGridCol As DataGridViewColumn In DataGridView1.Columns
                    iTotalWidth += dgvGridCol.Width
                Next
            End If
        Catch ex As Exception
            MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.[Error])
        End Try
    End Sub

    'Handles the print page event of print document
    Public Sub printDocument1_PrintPage(ByVal sender As System.Object, ByVal e As System.Drawing.Printing.PrintPageEventArgs) Handles PrintDocument1.PrintPage
        If TabControl1.SelectedTab.Text = "Reports" Then
            Try
                'Set the left margin
                Dim iLeftMargin As Integer = e.MarginBounds.Left
                'Set the top margin
                Dim iTopMargin As Integer = e.MarginBounds.Top
                'Whether more pages have to print
                Dim bMorePagesToPrint As Boolean = False
                Dim iTmpWidth As Integer = 0
                'For the first page to print, set the cell width and header height
                If bFirstPage Then
                    For Each GridCol As DataGridViewColumn In DataGridView4.Columns
                        iTmpWidth = CInt((Math.Floor(CDbl((CDbl(GridCol.Width) / CDbl(iTotalWidth) * CDbl(iTotalWidth) * (CDbl(e.MarginBounds.Width) / CDbl(iTotalWidth)))))))
                        iHeaderHeight = CInt((e.Graphics.MeasureString(GridCol.HeaderText, GridCol.InheritedStyle.Font, iTmpWidth).Height)) + 11
                        arrColumnLefts.Add(iLeftMargin)
                        arrColumnWidths.Add(iTmpWidth)
                        iLeftMargin += iTmpWidth
                    Next
                End If
                'Loop until all the grid rows get printed
                While iRow <= DataGridView4.Rows.Count - 1
                    Dim GridRow As DataGridViewRow = DataGridView4.Rows(iRow)
                    'Set the cell height
                    iCellHeight = GridRow.Height + 5
                    Dim iCount As Integer = 0
                    'Check whether the current page settings allows more rows to print
                    If iTopMargin + iCellHeight >= e.MarginBounds.Height + e.MarginBounds.Top Then
                        bNewPage = True
                        bFirstPage = False
                        bMorePagesToPrint = True
                        Exit While
                    Else
                        If bNewPage Then
                            'Draw header
                            e.Graphics.DrawString(UCase(txt_DeptCode.Text).ToString() & "  -  " + UCase(txt_OpCode.Text).ToString(), New Font(DataGridView4.Font, FontStyle.Bold), Brushes.Black, e.MarginBounds.Left, e.MarginBounds.Top - e.Graphics.MeasureString(UCase(txt_DeptCode.Text).ToString() & "  -  " + UCase(txt_OpCode.Text).ToString(), New Font(DataGridView4.Font, FontStyle.Bold), e.MarginBounds.Width).Height - 13)
                            If CheckedListBox5.SelectedItem = "Multi" Then
                                Dim strDateMulti As String = report_start.Value.ToLongDateString() & "  -  " + report_end.Value.Date.ToLongDateString()
                                'Draw Date For Multi-Day Report
                                e.Graphics.DrawString(strDateMulti, New Font(DataGridView4.Font, FontStyle.Bold), Brushes.Black, e.MarginBounds.Left + (e.MarginBounds.Width - e.Graphics.MeasureString(strDateMulti, New Font(DataGridView4.Font, FontStyle.Bold), e.MarginBounds.Width).Width), e.MarginBounds.Top - e.Graphics.MeasureString(UCase(txt_DeptCode.Text).ToString() & "  -  " + UCase(txt_OpCode.Text).ToString(), New Font(New Font(DataGridView4.Font, FontStyle.Bold), FontStyle.Bold), e.MarginBounds.Width).Height - 13)
                            ElseIf CheckedListBox5.SelectedItem = "Daily" Then
                                Dim strDateDaily As String = report_start.Value.ToLongDateString()
                                'Draw Date For Daily Report
                                e.Graphics.DrawString(strDateDaily, New Font(DataGridView4.Font, FontStyle.Bold), Brushes.Black, e.MarginBounds.Left + (e.MarginBounds.Width - e.Graphics.MeasureString(strDateDaily, New Font(DataGridView4.Font, FontStyle.Bold), e.MarginBounds.Width).Width), e.MarginBounds.Top - e.Graphics.MeasureString(UCase(txt_DeptCode.Text).ToString() & "  -  " + UCase(txt_OpCode.Text).ToString(), New Font(New Font(DataGridView4.Font, FontStyle.Bold), FontStyle.Bold), e.MarginBounds.Width).Height - 13)
                            End If
                            'Draw Columns
                            iTopMargin = e.MarginBounds.Top
                            For Each GridCol As DataGridViewColumn In DataGridView4.Columns
                                e.Graphics.FillRectangle(New SolidBrush(Color.LightGray), New Rectangle(CInt(arrColumnLefts(iCount)), iTopMargin, CInt(arrColumnWidths(iCount)), iHeaderHeight))
                                e.Graphics.DrawRectangle(Pens.Black, New Rectangle(CInt(arrColumnLefts(iCount)), iTopMargin, CInt(arrColumnWidths(iCount)), iHeaderHeight))
                                e.Graphics.DrawString(GridCol.HeaderText, GridCol.InheritedStyle.Font, New SolidBrush(GridCol.InheritedStyle.ForeColor), New RectangleF(CInt(arrColumnLefts(iCount)), iTopMargin, CInt(arrColumnWidths(iCount)), iHeaderHeight), strFormat)
                                iCount += 1
                            Next
                            bNewPage = False
                            iTopMargin += iHeaderHeight
                        End If
                        iCount = 0
                        'Draw Column contents
                        For Each Cel As DataGridViewCell In GridRow.Cells
                            If Cel.Value IsNot Nothing Then
                                e.Graphics.DrawString(Cel.Value.ToString(), Cel.InheritedStyle.Font, New SolidBrush(Cel.InheritedStyle.ForeColor), New RectangleF(CInt(arrColumnLefts(iCount)), CSng(iTopMargin), CInt(arrColumnWidths(iCount)), CSng(iCellHeight)), strFormat)
                            End If
                            'Drawing Cell Borders
                            e.Graphics.DrawRectangle(Pens.Black, New Rectangle(CInt(arrColumnLefts(iCount)), iTopMargin, CInt(arrColumnWidths(iCount)), iCellHeight))
                            iCount += 1
                        Next
                    End If
                    iRow += 1
                    iTopMargin += iCellHeight
                End While
                'If more lines exist, print another page
                If bMorePagesToPrint Then
                    e.HasMorePages = True
                Else
                    e.HasMorePages = False
                End If
            Catch exc As Exception
                MessageBox.Show(exc.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.[Error])
            End Try
            'PRINT STATS TAB
        ElseIf TabControl1.SelectedTab.Text = "Stats" Then
            Try
                'Set the left margin
                Dim iLeftMargin As Integer = e.MarginBounds.Left
                'Set the top margin
                Dim iTopMargin As Integer = e.MarginBounds.Top
                'Whether more pages have to print
                Dim bMorePagesToPrint As Boolean = False
                Dim iTmpWidth As Integer = 0
                'For the first page to print, set the cell width and header height
                If bFirstPage Then
                    For Each GridCol As DataGridViewColumn In DataGridView1.Columns
                        iTmpWidth = CInt((Math.Floor(CDbl((CDbl(GridCol.Width) / CDbl(iTotalWidth) * CDbl(iTotalWidth) * (CDbl(e.MarginBounds.Width) / CDbl(iTotalWidth)))))))
                        iHeaderHeight = CInt((e.Graphics.MeasureString(GridCol.HeaderText, GridCol.InheritedStyle.Font, iTmpWidth).Height)) + 11
                        arrColumnLefts.Add(iLeftMargin)
                        arrColumnWidths.Add(iTmpWidth)
                        iLeftMargin += iTmpWidth
                    Next
                End If
                'Loop until all the grid rows get printed
                While iRow <= DataGridView1.Rows.Count - 1
                    Dim GridRow As DataGridViewRow = DataGridView1.Rows(iRow)
                    'Set the cell height
                    iCellHeight = GridRow.Height + 5
                    Dim iCount As Integer = 0
                    'Check whether the current page settings allows more rows to print
                    If iTopMargin + iCellHeight >= e.MarginBounds.Height + e.MarginBounds.Top Then
                        bNewPage = True
                        bFirstPage = False
                        bMorePagesToPrint = True
                        Exit While
                    Else
                        If bNewPage Then
                            If CheckedListBox3.SelectedItem = "All" And CheckedListBox2.SelectedItem = "Department" Then
                                'Draw header for ALL-Department
                                e.Graphics.DrawString(UCase(txt_DeptCode.Text).ToString() & "  -  " + UCase(txt_OpCode.Text).ToString(), New Font(DataGridView1.Font, FontStyle.Bold), Brushes.Black, e.MarginBounds.Left, e.MarginBounds.Top - e.Graphics.MeasureString("(" + UCase(txt_ID.Text).ToString() & ") " + UCase(txt_DeptCode.Text).ToString() & "  -  " + UCase(txt_OpCode.Text).ToString(), New Font(DataGridView1.Font, FontStyle.Bold), e.MarginBounds.Width).Height - 13)
                            ElseIf CheckedListBox3.SelectedItem = "All" And CheckedListBox2.SelectedItem = "AssociateID" Then
                                'Draw header for ALL -ID
                                e.Graphics.DrawString("(" + UCase(txt_ID.Text).ToString() & ") " + UCase(txt_DeptCode.Text).ToString() & "  -  " + UCase(txt_OpCode.Text).ToString(), New Font(DataGridView1.Font, FontStyle.Bold), Brushes.Black, e.MarginBounds.Left, e.MarginBounds.Top - e.Graphics.MeasureString("(" + UCase(txt_ID.Text).ToString() & ") " + UCase(txt_DeptCode.Text).ToString() & "  -  " + UCase(txt_OpCode.Text).ToString(), New Font(DataGridView1.Font, FontStyle.Bold), e.MarginBounds.Width).Height - 13)
                            ElseIf CheckedListBox3.SelectedItem = "Sum" And CheckedListBox2.SelectedItem = "AssociateID" Then
                                'Draw header SUM -ID
                                e.Graphics.DrawString("(" + UCase(txt_ID.Text).ToString() & ") " + UCase(txt_DeptCode.Text).ToString() & "  -  " + UCase(txt_OpCode.Text).ToString(), New Font(DataGridView1.Font, FontStyle.Bold), Brushes.Black, e.MarginBounds.Left, e.MarginBounds.Top - e.Graphics.MeasureString("(" + UCase(txt_ID.Text).ToString() & ") " + UCase(txt_DeptCode.Text).ToString() & "  -  " + UCase(txt_OpCode.Text).ToString(), New Font(DataGridView1.Font, FontStyle.Bold), e.MarginBounds.Width).Height - 13)
                            ElseIf CheckedListBox3.SelectedItem = "Sum" And CheckedListBox2.SelectedItem = "Department" Then
                                'Draw header SUM -Dept
                                e.Graphics.DrawString(UCase(txt_DeptCode.Text).ToString() & "  -  " + UCase(txt_OpCode.Text).ToString(), New Font(DataGridView1.Font, FontStyle.Bold), Brushes.Black, e.MarginBounds.Left, e.MarginBounds.Top - e.Graphics.MeasureString("(" + UCase(txt_ID.Text).ToString() & ") " + UCase(txt_DeptCode.Text).ToString() & "  -  " + UCase(txt_OpCode.Text).ToString(), New Font(DataGridView1.Font, FontStyle.Bold), e.MarginBounds.Width).Height - 13)

                            End If
                            'Draw Date
                            Dim strDate As String = start_stat.Value.ToLongDateString() & "  -  " + end_stat.Value.Date.ToLongDateString()
                            e.Graphics.DrawString(strDate, New Font(DataGridView1.Font, FontStyle.Bold), Brushes.Black, e.MarginBounds.Left + (e.MarginBounds.Width - e.Graphics.MeasureString(strDate, New Font(DataGridView1.Font, FontStyle.Bold), e.MarginBounds.Width).Width), e.MarginBounds.Top - e.Graphics.MeasureString("(" + UCase(txt_ID.Text).ToString() & ") " + UCase(txt_DeptCode.Text).ToString() & "  -  " + UCase(txt_OpCode.Text).ToString(), New Font(New Font(DataGridView1.Font, FontStyle.Bold), FontStyle.Bold), e.MarginBounds.Width).Height - 13)

                            'Draw Columns
                            iTopMargin = e.MarginBounds.Top
                            For Each GridCol As DataGridViewColumn In DataGridView1.Columns
                                e.Graphics.FillRectangle(New SolidBrush(Color.LightGray), New Rectangle(CInt(arrColumnLefts(iCount)), iTopMargin, CInt(arrColumnWidths(iCount)), iHeaderHeight))
                                e.Graphics.DrawRectangle(Pens.Black, New Rectangle(CInt(arrColumnLefts(iCount)), iTopMargin, CInt(arrColumnWidths(iCount)), iHeaderHeight))
                                e.Graphics.DrawString(GridCol.HeaderText, GridCol.InheritedStyle.Font, New SolidBrush(GridCol.InheritedStyle.ForeColor), New RectangleF(CInt(arrColumnLefts(iCount)), iTopMargin, CInt(arrColumnWidths(iCount)), iHeaderHeight), strFormat)
                                iCount += 1
                            Next
                            bNewPage = False
                            iTopMargin += iHeaderHeight
                        End If
                        iCount = 0
                        'Draw Column contents
                        For Each Cel As DataGridViewCell In GridRow.Cells
                            If Cel.Value IsNot Nothing Then
                                e.Graphics.DrawString(Cel.Value.ToString(), Cel.InheritedStyle.Font, New SolidBrush(Cel.InheritedStyle.ForeColor), New RectangleF(CInt(arrColumnLefts(iCount)), CSng(iTopMargin), CInt(arrColumnWidths(iCount)), CSng(iCellHeight)), strFormat)
                            End If
                            'Drawing Cell Borders
                            e.Graphics.DrawRectangle(Pens.Black, New Rectangle(CInt(arrColumnLefts(iCount)), iTopMargin, CInt(arrColumnWidths(iCount)), iCellHeight))
                            iCount += 1
                        Next
                    End If
                    iRow += 1
                    iTopMargin += iCellHeight
                End While
                'If more lines exist, print another page
                If bMorePagesToPrint Then
                    e.HasMorePages = True
                Else
                    e.HasMorePages = False
                End If
            Catch exc As Exception
                MessageBox.Show(exc.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.[Error])
            End Try

        End If

    End Sub


text:
Q: Zend_Db_Expr NOW() doesn't work? I am trying the simple insert:
$data = array
(
'whatever' => 'nevermind',
'etc' => 'more data',
'updated_on' => new Zend_Db_Expr('NOW()')
);

$this->getDbTable()->insert( $data );

Everything gets inserted correctly, but updated_on is null. Am I doing something wrong? I understand it may be not easy to determine the problem from what I said, but maybe you could suggest at least how could I debug this? Thanks in advance
p.s. database is mySQL and column is DATETIME, and if I connect to mySQL and manually try the insert or update NOW(), it does work.
Update
Using Profiler, I get the following output:
INSERT INTO `db_table` (`column1`, `column2`, `column3`, `column4`, `column5`, `column6`, `column_datetime`, `column7`) VALUES (?, ?, ?, ?, ?, ?, NOW(), ?)

Array
(
    [1] => column1 data
    [2] => column2 data
    [3] => column3 data
    [4] => column4 data
    [5] => column5 data
    [6] => column6 data
    [7] => column7 data
)

To my knowledge, everything is fine here :\
Update2: Nevermind, I got it working. Problem was entirely different.

A: Based solely on the code you are posting, this should work.
Since it does not, you should use the profiler to debug the query:
$db = $this->getDbTable();
$adapter = $db->getAdapter();
$adapter->getProfiler()->setEnabled(true);
$data = array
(
    'whatever' => 'nevermind',
    'etc' => 'more data',
    'updated_on' => new Zend_Db_Expr('NOW()')
);
$db->insert( $data );
print $adapter->getProfiler()->getLastQueryProfile()->getQuery();
print_r($adapter->getProfiler()->getLastQueryProfile()->getQueryParams());
$adapter->getProfiler()->setEnabled(false);

redpajama_set_name: RedPajamaStackExchange


text:
Q: Lockbits: The array sequence is mutating somewhere I'm using the lockbit method to manipulate an image, but I have noticed that after I save the image using the save method of the Bitmap type, the data that I manipulate in the byte array I get out of the lockbit, is manipulated.
For example assuming the following approach:
 Bitmap bmp = new Bitmap(fs);
 BitmapData bits = bmp.LockBits(new Rectangle(0, 0, bmp.Width, bmp.Height), System.Drawing.Imaging.ImageLockMode.ReadOnly, bmp.PixelFormat);
 IntPtr ptr = bits.Scan0;
 int arraySize = Math.Abs(bits.Stride) * bmp.Height;
 Byte[] rgbValues = new Byte[arraySize];
 System.Runtime.InteropServices.Marshal.Copy(ptr, rgbValues, 0, arraySize);

When I try to test this by setting all the values in the array to 0 using for example:
 for(int x = 0; x < arraySize; x++){
     rgbValues[x] = (Byte) (rgbValues[x] % 2 == 0 ? 0 : 1);
  }
 System.Runtime.InteropServices.Marshal.Copy(rgbValues, 0, ptr, arraySize);
 bmp.UnlockBits(bits);
 bmp.Save("somewhere");

Now when I read back the saved image using the same techniques, I see values like 10, 20, or other strange values in the obtained byte array out of the lockbit.
I don't think this can be a normal behavior, as when using the slower GetPixel method, I do not notice such mutation.


text:
Q: Reading bigrams in a proper way I'm developing a program that should read bigrams from a text file and classify them in a 2D matrix. It reads them in this way for example, if the word in the file is "Hello", it'd read it as: "He", "el", "ll", "lo" and then classify them in the matrix according how much times those bigrams are found all over the text file.
The function I'm writing for that purpose uses a stream (as it receives a file as argument) and I wanted to use the read() function to read 2 characters (to get the bigram), store them in an array and then classify them. The problem is, with that function, I won't be able to read bigrams the way I exposed above, it'll just read them as "He" "ll" "o " (the last one is not going to be valid).
This is the code for the actual function. Any suggestions to achieve what I'm asking?
bool BigramCounter::calculateBigramsFrecuency(const char* nfile){
ifstream finput;
bool result = true;
char bigram[3];

finput.open(nfile);

if(finput){
    while(!finput.eof()){
        finput.read(bigram, 2);

        for(int i=0; i<this->getSize(); i++){
            for(int j=0; j<this->getSize(); j++){
                if(_validCharacters[i] == bigram[0] && _validCharacters[j] == bigram[1]){
                    _bigrams[i][j]++;
                }
            }
        }
    }

    if(!finput){
        cerr << "Reading error\n";
        result = false;
    }

    finput.close();
}

else{
    cerr << "Opening error\n";
    result = false;
}

return result;

}


text:
Q: ionic 3 grid view with two col per row I have one screen , which will have the data to display from database. I already tried grid view in ionic 1 its fine. But ionic 3 i don't know how to do the grid view.From database i will get like 10 or 11 or 13 category names , that names i need to display in grid view with background some image.
I know how to display background image.But i need to display 2 col per row.here my code that i will use to fetch data from database.....
  another(loading:any) {

        this.subcatdata = { CatID: this.categoryid };

        this.authService.subcatte(this.subcatdata).then((result) => {

            this.data = result;

            console.log(this.data);

            if (this.data.status == 1) {
                this.Catdata = this.data.SubCatgeoryList;

                for (let i = 0; i < this.Catdata.length; i++) {
                    console.log(this.Catdata[i].SubCategoryName);
                }
            }

            else if (this.data.status == 0) {

                let alert = this.alertCtrl.create({
                    title: 'Error',
                    subTitle: 'Please Enter Valid Username & Password',
                    buttons: ['OK']
                });
                alert.present();
            }
            loading.dismiss();

        }, (err) => {
            loading.dismiss();
        });
    }

In my above code i will get the subcatgory name by using below code :
for (let i = 0; i < this.Catdata.length; i++) {
                        console.log(this.Catdata[i].SubCategoryName);
                    }

In my html :

{{Catdata[i].SubCategoryName}}

My scss :
.gallery {
    -webkit-flex-wrap: wrap;
    flex-wrap: wrap;
}
  div.no-padding, ion-item.no-padding {
  padding: 0 !important;
}
div.custom-design2 {
  height: 153px;
    padding: 1px;
}

.swiper-pagination-bullet-active {
  opacity: 1;
  background: #FFF !important;
}
.no-scroll .scroll-content{
     overflow: hidden;
}

div.custom-design1 {
  text-align: center;
    padding: 1px;
    height: 153px;
    vertical-align: middle;
    position: relative;
    background-color: rgba(0,0,0,0.5);
    color: #fff;
    width: 100%;
}

div.custom-design1.extended {
    height: 153px;
}

span.grid-title {
    font-weight: 700;
    position: absolute;
    top: 50%;
    left: 0;
    right: 0;
}

.transparent {
    background: transparent !important;
}

.full_height {
    height: 100% !important;
    border: none;
}

Now in my screen its coming like one data per row, with full row background.
But what i need is two col ( 2 data/sub cat name per row).I know we need to use index + 1, but in ionic 3 i dont know how to do.
If any help, that will be helpfull
Thanks.


text:
Q: Unnest data frame column with list when some lists are empty I have the following data (coming from Twitter):
structure(list(entities.urls = list(structure(list(), .Names = character(0)),
    NULL, structure(list(), .Names = character(0)), structure(list(), .Names = character(0)),
    structure(list(start = 245L, end = 268L, url = "https://something.com",
        expanded_url = "https://www.rtlnieuws.nl/nieuws/nederland/artikel/5330834/spaartaks-spaarders-compensatie-hoge-raad",
        display_url = "rtlnieuws.nl/nieuws/nederla…", images = list(
            structure(list(url = c("https://pbs.twimg.com/news_img/1569417166549663745/p12uVzUj?format=jpg&name=orig",
            "https://pbs.twimg.com/news_img/1569417166549663745/p12uVzUj?format=jpg&name=150x150"
            ), width = c(1024L, 150L), height = c(576L, 150L)), class = "data.frame", row.names = 1:2)),
        status = 200L, title = "Geen compensatie voor spaarders die te laat bezwaar maakten",
        description = "Het kabinet gaat spaarders die te laat of geen bezwaar hebben gemaakt tegen de spaartaks niet compenseren. Dat bevestigen Haagse bronnen aan RTL Nieuws. Voor de zomer oordeelde de Hoge Raad al dat deze mensen geen recht hebben op compensatie.",
        unwound_url = "https://www.rtlnieuws.nl/nieuws/nederland/artikel/5330834/spaartaks-spaarders-compensatie-hoge-raad"), class = "data.frame", row.names = 1L),
    structure(list(start = 197L, end = 220L, url = "https://something.com",
        expanded_url = "https://fd.nl/financiele-markten/1432905/oorlog-in-oekraine-is-ultieme-stresstest-voor-grondstoffenhandelaren?utm_medium=social&utm_source=app&utm_campaign=earned&utm_content=20220312&utm_term=app-ios",
        display_url = "fd.nl/financiele-mar…", status = 200L,
        unwound_url = "https://fd.nl/financiele-markten/1432905/oorlog-in-oekraine-is-ultieme-stresstest-voor-grondstoffenhandelaren?utm_medium=social&utm_source=app&utm_campaign=earned&utm_content=20220312&utm_term=app-ios"), class = "data.frame", row.names = 1L),
    structure(list(), .Names = character(0)), structure(list(), .Names = character(0)),
    structure(list(), .Names = character(0)), structure(list(), .Names = character(0)))), class = "data.frame", row.names = c(NA,
10L))

Each row of column entities.urls is either NULL, or contains a list, which is sometimes empty and sometimes holds a dataframe. I wanted to unnest that column so that so that every column of the nested data frame becomes a column in the top-level dataframe. Also, data should be in long format so that every row is repeated for the number of rows of the nested data frame.
I have tried with dplyr's unnest:
tweets_02 %>% unnest(entities.urls, keep_empty = TRUE)

which throws an error. I guess the problem are the empty lists, but I have found no way filter them out efficiently.

A: Are you looking for something like this?
library(tidyverse)

test |>
  filter( map_chr(entities.urls, class)=="data.frame") |>
  unnest(entities.urls)
#> # A tibble: 2 x 10
#>   start   end url            expan~1 displ~2 images status title descr~3 unwou~4
#>   <int> <int> <chr>          <chr>   <chr>   <list>  <int> <chr> <chr>   <chr>
#> 1   245   268 https://somet~ https:~ rtlnie~ <df>      200 Geen~ Het ka~ https:~
#> 2   197   220 https://somet~ https:~ fd.nl/~ <NULL>    200 <NA>  <NA>    https:~
#> # ... with abbreviated variable names 1: expanded_url, 2: display_url,
#> #   3: description, 4: unwound_url

A: Here is another approach using rrapply() in package rrapply with option how = "bind" to bind repeated observations in a nested list into a wide data.frame:
library(rrapply)

rrapply(tweets_02, how = "bind", options = list(coldepth = 3))

#>   start end                   url                                                                                expanded_url                  display_url                                                                                images.1.url images.1.width images.1.height status                                                       title                                                                                description                                                                                unwound_url
#> 1   245 268 https://something.com                                                                                https://www.rtlnieuws.nl/nieuws/nederland/artikel/5330834/spaartaks-spaarders-compensatie-hoge-raad rtlnieuws.nl/nieuws/nederla… https://pbs.twimg.com/news_img/1569417166549663745/p12uVzUj?format=jpg&name=orig, https://pbs.twimg.com/news_img/1569417166549663745/p12uVzUj?format=jpg&name=150x150      1024, 150        576, 150    200 Geen compensatie voor spaarders die te laat bezwaar maakten Het kabinet gaat spaarders die te laat of geen bezwaar hebben gemaakt tegen de spaartaks niet compenseren. Dat bevestigen Haagse bronnen aan RTL Nieuws. Voor de zomer oordeelde de Hoge Raad al dat deze mensen geen recht hebben op compensatie.                                                                                https://www.rtlnieuws.nl/nieuws/nederland/artikel/5330834/spaartaks-spaarders-compensatie-hoge-raad
#> 2   197 220 https://something.com https://fd.nl/financiele-markten/1432905/oorlog-in-oekraine-is-ultieme-stresstest-voor-grondstoffenhandelaren?utm_medium=social&utm_source=app&utm_campaign=earned&utm_content=20220312&utm_term=app-ios        fd.nl/financiele-mar…                                                                                NA             NA              NA    200                                                        <NA>                                                                                <NA> https://fd.nl/financiele-markten/1432905/oorlog-in-oekraine-is-ultieme-stresstest-voor-grondstoffenhandelaren?utm_medium=social&utm_source=app&utm_campaign=earned&utm_content=20220312&utm_term=app-ios


text:
Q: plotting diffrent curves in one plot in matlab I want to make a plot in Matlab like this.
How could I do something like this in Matlab?
Thank you all!

A: Make some data:
x = 1:0.1:100;
y = 1:5;
for i = y
    z(i,:) = sin(i*x);
end

Plot it:
figure
hold on
for i = y
    plot3(x,i*ones(size(x)),z(i,:))
end

Modify the plot aspect and view:
daspect([100,2,2])
view(45,60)

Does that do roughly what you need?

A: You can use the command plot3(X,Y,Z).
You have to build three matrices each one containing a number of column equal to the number of series you need. (6 in the figure you sent)
For example
X = repmat([-200:200]',1,6);
Z = rand(401,6)*10;
Y = ones(401,1)*[1:20:120];
plot3(X,Y,Z)
axis image


text:
Q: What't the relationship between SonarQube plugin and SonarQube rules? I am new to SonarQube. I know there are a few plugins like sonar-findbugs-plugin-2.1.jar located in the directory \extensions\plugins. I am not very clear about the concept for the plugins and rules. What's the difference of them? I found an article saying ' Writing custom rules in Java via a SonarQube plugin;'. It seems that the rules are stored in the plugin, am I right?
Thanks in advance!

A: A SonarQube plugin is a extension of SonarQube that contributes new features to the platform. Those features can be of many kinds:

*

*Web widgets

*Computation of new metrics

*Authentication and authorization implementations

*SCM providers

*... and for most plugins: Rules!
So to sum up, rules are brought to the platform thanks to plugins.


text:
Q: Is there a way to clear blank values from a listbox at runtime? I pull data from a table in a database and assign it as a datasource to a listbox.  If there is a blank item in the listbox, it shows up as something like this:

*

*All

*

*Red

*Green

*Blue

What is the best way to remove the blank in the listbox.  If there is a blank, it is always in the second position.  I was going to try to test to see if the second position contained blank text, but I am not sure how to do that.
Thanks,
XaiSoft

A: I'd say the best thing to do is to remove the blank item from your datasource before you bind it to the listbox.
How you do this depends on where your data's coming from and how much control you have over it.
You could add a view to the database that only returns non-blank items; if you're using LINQ to SQL you could modify your query so that it only returns non-blank items; you could copy the items into a List and remove the blank ones yourself (I guess there aren't too many items if you're putting them in a listbox).

A: Hook up an event to the data bind of the list box.  If the data item is empty or has an invalid string, then do not add it, else go ahead an add it.
Or loop through the data source yourself, and add only what is needed.

A: I used
physicalChannelComboBox.Items.Remove("");

the problem is that will only clean one item, you need to do it the as many times as empty items you have...maybe not the best solution...but it works.


text:
Q: Why don't all System.Web.UI.WebControl classes with Text properties implement ITextControl? I'm curious why only some System.Web.UI.WebControl controls implement certain interfaces when they have the same properties of an interface.
For instance, there are plenty of controls that have a Text property but only the following  implement ITextControl:

*

*Label

*Literal

*DataBoundLiteral

*TextBox

*ListControl

(TextBox and ListControl actually implement IEditableTextControl which implements ITextControl)
TableCell, Button, HyperLink and others don't so I have to write code like this
ITextControl textControl = control as ITextControl;
TableCell tableCell = control as TableCell;

if (textControl != null)
{
    textControl.Text = value;
}
else if (tableCell != null)
{
    tableCell.Text = value;
}

instead of this
control.Text = value;

Was this a design decision or an oversight?

A: I think it was designed ok, I don't think it was an oversight; those are the controls where text is the primary focus of the purpose of the control.  I do see your point because that would be very convenient to have controls utilize more of these types of interfaces.


text:
Q: MATLAB: How to find number that meet certain condition and mark it as "0"? For example,
A = [1 0 1 1 0 -1 0 1 -1]

for i = 1: length(A)

how to mark the number as "0" when sum(A(1:i)) ~= 1 && sum(A(1:i)) ~= 0?
and how to write the code?

A: A = [1 0 1 1 0 -1 0 1 -1]

%# create all sums from 1 through i
sa = cumsum(A);

%# in output: ith element is true if sum from
%# 1 through the ith element in A is 0 or 1
output = ismember(sa,[0 1])

output =
   1     1     0     0     0     0     0     0     0


text:
Q: SharePoint 2010 Getting ArgugmentException: The value is not a valid guid when calling Update on SPPersistedObject I have several classes that are derived from SPPersistedObject. One of them is my top level class that then contains a collection of other derived SPPersistedObjects. Here is a rough outline of my code:
[System.Runtime.InteropServices.GuidAttribute("9BEDC353-F0AC-40FA-A28B-E18FB22EA9CA")
internal class FolderSettings : SPPersistedObject
{
     [Persisted]
     Guid _folderId;

     [Persisted]
     string _folderName;

     public FolderSettings() : base() {}

     protected FolderSettings(Guid folderId, string folderName) : base()
     {
         _folderId = folderId;
         _folderName = folderName;
     }
}

[System.Runtime.InteropServices.GuidAttribute("329DE509-76E6-4FA5-A9C1-2543F0A6B5D3")]
internal class EnhancedFolderSettings : FolderSettings
{
    [Persisted]
    string _outputLocation;

    public EnhancedFolderSettings() : base() {}

    public EnhancedFolderSettings(Guid folderId, string folderName,
        string outputLocation) : base(folderId, folderName)
    {
         _outputLocation = outputLocation;
    }
}

[System.Runtime.InteropServices.GuidAttribute("62FA87FB-2BB4-4AC6-A82A-737E8BEC0219")]
internal class EnhancedFolderSettingsCollection : SPPersistedObject,
    IDictionary<Guid, EnhancedFolderSetrtings>
{
     [Persisted]
     Dictionary<Guid, EnhancedFolderSettings> _collection =
         Dictionary<Guid, EnhancedFolderSettings>();

     public EnhancedFolderSettingsCollection() : base() {}

     // Implementation of IDictionary Interface here

     // Implementation of ICollection Interface here

     // Implementation of IEnumerable Interface here
}

[System.Runtime.InteropServices.GuidAttribute("F080ED50-85DF-4821-884B-97B05995F8F1")]
internal class FeatureSettings : SPPersistedObject
{
     [Persisted]
     string _workingFolder;

     [Persisted]
     string _serviceIpAddress;

     public FeatureSettings() : base() {}

     public FeatureSettings(string name, SPPersistedObject parent)
         : base(name, parent)
     {
     }

     protected override bool HasAdditionalUpdateAccess()
     {
         return true;
     }
}

[System.Runtime.InteropServices.GuidAttribute("C54B006A-69D4-4315-A9FF-F7998A985935")]
internal class EnhancedFeatureSettings : FeatureSettings
{
     const string _SETTINGS_NAME = "EnhancedSettingsName";

     [Persisted]
     Dictionary<Guid, EnhancedFolderSettingsCollection> _siteFeatureSettings;

     public EnhancedFeatureSettings() : base() {}

     public EnhancedFeatureSettings(SPPersistedObject parent)
         : base(_SETTINGS_NAME, parent)
     {
     }

     public static EnhancedFeatureSettings GetSettings(bool createNew)
     {
          EnhancedFeatureSettings settings =
              SPFarm.Local.GetChild<EnhancedFeatureSettings>(_SETTINGS_NAME);
          if (settings == null && createNew)
          {
               settings = new EnhancedFeatureSettings(SPFarm.Local);
          }
          return settings;
     }

     internal EnhancedFolderSettingsCollection GetSiteSettings(Guid siteId)
     {
          EnhancedFolderSettingsCollection collection = null;
          _siteFeatureSettings.TryGetValue(siteId, out collection);
          return collection;
     }

     internal Dictionar<Guid, EnhancedFolderSettingsCollection> FolderSettings
     {
          get
          {
                return _siteFeatureSettings;
          }
     }
}

That is all of the settings classes, now here is some sample code trying to update the settings and causing the error. It should be noted that this is running in an administrative context (from a CentralAdmin configuration window) so I don't think this is permissions related:
public void UpdateSettings(Guid siteId, Guid folderId,
     EnhancedFolderSettings currentSettings)
{
      var settings = EnhancedFeatureSettings.GetSettings(true);
      var siteSettings = settings.GetSiteSettings(siteId);
      if (siteSettings == null)
      {
           siteSettings = new EnhancedFolderSettingsCollection();
      }

      siteSettings[folderId] = currentSettings;
      settings.FolderSettings[siteId] = siteSettings;

      settings.Update() // This is the line that is causing the exception
}

Any help would be appreciated. The exception is:

System.ArgumentException: The value is not a valid guid.

The stack trace points to the settings.Update() line.

A: The accepteble solution in current situation is to make change in field implementation. You can create your own class with array, derived from SPAutoSerializingObject, IEnumerable and so on, where you implement all functionality of your Dictionary (or List) field and use this class insteed of Dictionary<> or Lists<>
Hope it's help.

A: I am answering my own question since I have had no answers yet and have now received new information. You can see a related question that I posted on SharePoint.SE. I found that there were some missing pieces in this code, but even after getting some of those things handled I was still having issues. After trying to hire a consultant to help with this issue, I received back a response that basically said "Don't do that". The SPPersistedObject framework can be flaky (several posts about this on the Internet) and is not really designed to do what I am trying to do. It was recommended to redesign the settings framework to use hidden lists.

A: I have the same issue and I try to find solution goes deeper in SPPersistedObject. During my research I'm delete guid in class attributes and after that application throw a new exception.
"The INSERT statement conflicted with the FOREIGN KEY constraint "FK_Dependencies1_Objects". The conflict occurred in database "SharePoint_Config", table "dbo.Objects", column 'Id'.
The statement has been terminated." So, this exception comes from SharePoint Config database.


text:
Q: How do I add a CSS stylesheet to a WCF generated RSS feed? I have a WCF service that uses a System.ServiceModel.Syndication.SyndicationFeed to create an RSS feed.
But I'm having trouble figuring out how to add a Processing Instruction to output that points to my CSS stylesheet.
What I need is a processing instruction that looks a bit like this:
<?xml-stylesheet type="text/css" href="http://you.com/rss.css" ?>

Anyone have a hint how you add that using SyndicationFeed ?

A: I am not familiar with WCF, but I found this. I think this might help you out.
http://www.developmentnow.com/g/8_2008_2_0_0_1041398/xslt-and-System-ServiceModel-Syndication.htm

A: Since your contract is going to return an instance of SyndicationFeedFormatter, which implements IXmlSerializable, I would have your method on the service contract get that instance, then call the methods on IXmlSerializable to serialize the output to XML.  You can then add the processing instruction to the XML (XDocument, or XmlDocument) and then pass those contents back.


text:
Q: How do I put editor templates in an Eclipse plug-in? I know how to put plain text and code in the editor. Is it possible to put an editor template programmatically in an Eclipse plug-in?

A: If you are asking for an editor for plugin development then you can go for new -> plug-in project and then opt plugin with editor which creates a sample class and entry in plugin.xml which can be a start for you.


text:
Q: Iterating through a list of lists and replacing one specific character So the current problem is that I have a list of lists, for example:
info = [['X','X','X','34,0976','1,34542'],['X','X','X','23,9878','32,65354'], ['X','X','X','1,745645','5,76454']]

The 'X' are values that I am NOT interested in. However, I am trying to replace the commas in the numbers to a decimal point as they are latitude and longitude numbers that I will need to convert into a floating point later on.
My current solution is... well, crap to say the least, but here is my beginners attempt:
for lst in defib_info:
    for item in lst:
        for char in item:
            if char == ",":
                char.replace(",",".")

I have inserted print() statements in each loop to check if it is entering the necessary amount of times, which it is, but the commas are not being replaced.
I am sure python has a WWWAAAAAYYYYY easier way of doing this so that would be my first question and my second question is why doesn't my code work albeit lacks in performance and aesthetic? Is it because I am trying to modify a list which is immutable?
Any info would be awesome! Thank you!

A: A simple list comprehension will work here:
info = [['X','X','X','34,0976','1,34542'],['X','X','X','23,9878','36,65354'],['X','X','X','1,745645','5,76454']]

info = [[x.replace(',', '.') for x in i] for i in info]
print(info)

Output:
[['X', 'X', 'X', '34.0976', '1.34542'], ['X', 'X', 'X', '23.9878', '36.65354'], ['X', 'X', 'X', '1.745645', '5.76454']]

A: Since others had already answered your first question excellently, here is why your solution didn't work (second question):
for lst in info:
    for i, item in enumerate(lst):
        if item != 'X':                            # 1
            lst[i] = item.replace(',', '.')        # 2

*

*You didn't anticipate the case to ignore 'X'

*You didn't use string.replace and reassign it to lst[i] (i being the index)

A: Those are good answers , I just tried with lambda for fun :
info = [['X','X','X','34,0976','1,34542'],['X','X','X','23,9878','32,65354'], ['X','X','X','1,745645','5,76454']]

print(list(map(lambda x:list(map(lambda y:y.replace(',','.'),x)),info)))

output:
[['X', 'X', 'X', '34.0976', '1.34542'], ['X', 'X', 'X', '23.9878', '32.65354'], ['X', 'X', 'X', '1.745645', '5.76454']]


text:
Q: pgfplots bar graph: Bars are floating above the x-axis I'm trying to visualize some data with bar graphs. Some of those bar graphs work fine and some (with the same code, just different data points) have the bars "floating above the x-axis". This bar graph works fine:
\begin{tikzpicture}
        \begin{axis}[
            ybar,
            bar width=40,
            enlarge x limits=0.3,
            legend style={at={(0.5,-0.2)},
            anchor=north,legend columns=-1},
            ylabel={\# Participants},
            symbolic x coords={no limit,unclear},
            xtick=data,
            nodes near coords,
            ]
            \addplot coordinates {(no limit,17) (unclear,5)};
        \end{axis}
    \end{tikzpicture}

And this one has a distance between the onset of the bars and the x-axis that I would like to eliminate:
\begin{tikzpicture}
        \begin{axis}[
            ybar,
            bar width=40,
            enlarge x limits=0.3,
            legend style={at={(0.5,-0.2)},
            anchor=north,legend columns=-1},
            ylabel={\# Participants},
            symbolic x coords={x-10,other},
            xtick=data,
            nodes near coords,
            ]
            \addplot coordinates {(x-10,22) (other,0)};
        \end{axis}
    \end{tikzpicture}

I found different similar questions on tex-exchange, but the solutions don't seem to apply: I don't have an "enlarge y limits"-factor, and one solution mentioned setting ymin=0 as an argument in axis, which didn't change anything.

A: While @percusse has given you a working solution for graph 2, ymin=0 also works, but I note you said it didn't work for you. There must be a difference between what I have posted below and what you tested. You can also use ymin=0 in the second graph, if I have interpreted the problem correctly.

This is the code, only very slightly modified from your version by adding ymin=0,. By the way, it is always best to post full, compilable minimum working examples, inclusive of document class, the minimum packages and libraries that you are using.
\documentclass[border=10pt,crop=true]{standalone}
\usepackage{pgfplots}
\begin{document}
    \begin{tikzpicture}
    \begin{axis}[
    ybar,
    bar width=40,
    ymin=0, %<--- Set the y-axis minimum value
    enlarge x limits=0.3,
    legend style={at={(0.5,-0.2)},
        anchor=north,legend columns=-1},
    ylabel={\# Participants},
    symbolic x coords={x-10,other},
%    enlarge y limits={upper=0}, % another option to reset the x-axis intersection with the y-axis for this graph
    xtick=data,
    nodes near coords,
    ]
    \addplot coordinates {(x-10,22) (other,0)};
    \end{axis}
    \end{tikzpicture}%
    \qquad
    \begin{tikzpicture}
    \begin{axis}[
    ybar,
    bar width=40,
    ymin=0, %<--- Set the y-axis minimum value
    enlarge x limits=0.3,
    legend style={at={(0.5,-0.2)},
        anchor=north,legend columns=-1},
    ylabel={\# Participants},
    symbolic x coords={x-10,other},
    xtick=data,
    nodes near coords,
    ]
    \addplot coordinates {(x-10,22) (other,1)};
    \end{axis}
    \end{tikzpicture}
\end{document}


text:
Q: stackoverflow exception in form class When I try to create an object of the form class within the form class, it gives an exception as stackoverflow occured.However, when I declare the object of form class within a method,it works fine.the code is as follows:
namespace WindowsFormsApplication6
{
    public partial class Form1 : Form
    {

        **Form1 f1 = new Form1();**//gives stackoverflow exception.......

         char[] ar = new char[15];
        int flag = 0, end;
        double val1, val2, res;
        string oprt;
        public Form1()
        {
            InitializeComponent();
        }

        private void masters(object sender, EventArgs e)
        {
            ar[i] = char.Parse(((Button)sender).Text);
            if (char.IsDigit(ar[i]))
            {
                if (flag != 0)
                {
                    if (textBox1.Text == oprt)
                    {
                        textBox1.Clear();
                    }

                }
                else
                {
                    if (end == 1)
                    {
                        textBox1.Clear();
                        end = 0;
                    }
                }
                Button ansbox = sender as Button;
                textBox1.Text += ansbox.Text;

            }
            else if (char.IsSymbol(ar[i]))
            {
                if (textBox1.TextLength != 0)
                {
                    val1 = double.Parse(textBox1.Text);
                    textBox1.Clear();
                    Button bt = sender as Button;
                    if (bt != null)
                        textBox1.Text = bt.Text;
                    oprt = bt.Text;
                    // dot.Enabled = true;
                    flag = 1;
                }
            }
        }

        private void button14_Click(object sender, EventArgs e)
        {
            if (textBox1.TextLength != 0)
            {
                val2 = double.Parse(textBox1.Text);
                switch (oprt)
                {
                    case "+": res = val1 + val2;
                        break;
                    case "-": res = val1 - val2;
                        break;
                    case "*": res = val1 * val2;
                        break;
                    case "/": res = val1 / val2;
                        break;
                }

                textBox1.Text = res.ToString();
                flag = 0;
                end = 1;
            }
        }
    }
}

}

A: Creating an instance of Form1 would cause the f1 property to be initialised with an instance of Form1 which would cause the f1 property to be initialised with an instance of Form1 which would cause the f1 property to be initialised with an instance of Form1 which would cause the f1 property to be initialised with an instance of Form1 which would cause the f1 property to be initialised with an instance of Form1 which would cause the f1 property to be initialised with an instance of Form1 which would cause the f1 property to be initialised with an instance of Form1 which would cause the f1 property to be initialised with an instance of Form1 which would cause the f1 property to be initialised with an instance of Form1 which would cause the f1 property to be initialised with an instance of Form1 which would cause the f1 property to be initialised with an instance of Form1 which would cause the f1 property to be initialised with an instance of Form1 which would cause the f1 property to be initialised with an instance of Form1 which would ... Stack Overflow!
Within a method in the class, the 'f1' would be local and only exist for the life of the call. Unless you called the same method on the instantiated Form1 then there wouldn't be subsequent Form1s created.

A: You're creating an private instance of Form1 when Form1 is created so this is sort of an endless loop:
Somewhere in your code you create your first Form1 instance.
When this instance is creating it creates a new instance of Form1.
This instance also creates an instance of Form1 and again, and again etc.
So when an instance is created all variables are initialized and when you declare them like this:
Form1 f1 = new Form1() this automaticly instatiates a new instance of the form.
I suggest you don't have a new instance of your Form1 inside your Form1 but if you really need this create a method to make the instance:
Change the Form1 f1 = new Form1(); into Form1 f1;.
And create a method:
public void InstantiateNewForm1Instance()
{
    f1 = new Form1();
}

But: DON'T CALL THIS METHOD IN THE CONSTRUCTOR! Or else you will have the same problem :-)

A: That's because every time you create an instance of your class, it creates another instance of your class and so on...and so on...and so on...
In other words, you have a infinite recursion when you try to create an instance of your class.
You need to add some kind of control around whether or not a new instance of Form1 gets created at construction time. A simple (and not complete) solution would be something like:
public partial class Form1 : Form
{
    Form1 f1;

    public Form1() : this(false)

    public Form1(bool createNewInstance)
    {
        if(createNewInstance)
            f1 = new Form1();
        else
            f1 = null;
    }
}

A: The form is instantiated, then it processes the private fields, which instantiates the form1, which then instantiates the private fields (finding form1), which then instantiates that object and processes the private fields, continuing on.
So that is why that happens, whereas, in a method, a method only executes when called, no internal initialization.
Why, when in form1, do you need another instance of the same form?

A: Could it be because Form1 is trying to instantiate another Form1 which in turn is trying to instantiate another Form1 etc?

A: If you're in the new constructor of Form1, an instance of Form1 is already being created. So, before it's finished being created, you're creating another, then that one does the same. Before your program loads, too many form1s are going on the stack...overflowing the stack.

A: If each Form1 class contains one new instance of a Form1 class, you are bound to have a stack overflow exception when trying to create one.
You can see it more clearly by trying to draw the objects on a sheet of paper, simulating the space they occupy in memory and the space occupied by their children - but remember, each Form 1 must be of the same size!


text:
Q: javascript synchronous functions I have three functions in javascript code, one that connects to my mongo database, the other creates a child process and passes the value of database into the phantamjs child process, the third one gets the data from phantomjs and processes it.
I want to make these functions synchronous. is there any specific way of doing so?
This is what i want to do
function connectdb() {
                  //connects to mongodb and pushes the
                  //value of emails from database to an array
                  //also writes the emails into external .txt file
}
function create_child() {
                 //creates a child phantom process using external .js
                 //phantom file
                 //gets data from the child process
}
function process_data() {
                //process the data received from create_child()
}

I want these functions to be called synchronously .. connectdb() then create_child() then process_data()

A: you can use javascript generators to execute your functions synchronously.

A: You can use Promise to do this.


text:
Q: Sending data to ES index using Logstash? ES 2.4.1
Logstash 2.4.0
I am sending data to elasticsearch from local to create a index "pica".I used the below conf file.
input {
      file {
        path => "C:\Output\Receive.txt"
        start_position => "beginning"
        codec => json_lines

      }
    }
    output {
      elasticsearch {
        hosts => "http://localhost:9200/"
        index => "pica"
    }
    stdout{
    codec => rubydebug
    }
    }

I couldn't see any output in either logstash prompt or in elasticsearch cluster.
When i seen the .sincedb file it has the following code:
612384816-350504-4325376 0 0 3804
May i know what's the problem here?
Thanks

A: I guess you're missing out the square brackets [] for the hosts value, since it's a type of array as per the doc. Hence it should look like:
elasticsearch {
     hosts => ["localhost:9200"]
     index => "pica"
}

OR :
hosts => ["127.0.0.1"] OR hosts => ["localhost"]


text:
Q: Apex - i need Json format output I need apex class get the JSON output for this string:
<text>
<firstname>Text</firstname><lastname>One</lastname>
</text>
I tried the following code:
public class Country1
{
   public string jsonlist {get; set;}

   public void getExportjson()
   {

      http h=new http();
      HttpRequest req=new HttpRequest();
      string soapMsg ='<text>
<firstname>Text</firstname><lastname>One</lastname>
</text>';
      req.setEndpoint(soapMsg);
      req.setMethod('GET');
      req.setHeader('Content-Type', 'Application/JSON; charset=utf-8');
      system.debug('Request&&&&:'+req);
      req.setCompressed(true);

      httpresponse res=h.send(Req);
      system.debug('Json data&&&&:'+res.getbody());
   }
}

A: From What I have understood, You want Json for the inputted XML.
The JSON would look something like.
    {

   "Table": [{

      "firstname": "Text",

      "lastname": "One"

   }]

}

Assuming this is the Required JSOn, you can get the Wrapper class as
    public class TableWrapper{
    public TableClass[] Table;
    class TableClass {
        public String firstname;    //Text
        public String lastname; //One
    }
    public static TableWrapper parse(String json){
        return (TableWrapper) System.JSON.deserialize(json, TableWrapper.class);
    }

}


text:
Q: How can I install Ubuntu onto a flash drive and boot from any PC using EFI? I have been looking at Live disks with persistence and the fact that you can install Ubuntu to a Flash Drive, but there seems to be no stated way to install Ubuntu on a USB drive with persistence and a way to boot it from any EFI based computer.
I have a spare 124GB Flash Drive that I would like to run as a "portable" Personal OS boot device. In short I want to be able to plug this device into any computer (specifically using EFI but BIOS support is also nice) and run a full Ubuntu distro with all of my personal files and applications on it. I recently have used the mkusb code from another post to try to accomplish this and while it was the closest to what I wanted it was only a persistent version of a Live disk (in other words it was a demo set up to run like a full os.) It was interesting, though, because it made me wonder that if there was a full iso file for the code to use instead of the Live USB iso will it create a persistent, full, boot-able, drive, or (with my current luck) end up being a disaster.
I have currently looked at nearly every main break off post similar to my question but I have not found an answer. If this question has been answered in some other forum then please send me that way so I can stop obsessing over this dumb idea that I have been trying to accomplish non-stop for 4 days. Seriously, I'm loosing sleep over this.

A: I have yet to test this but I think it should work:

*

*Create a LiveUSB installation media for Ubuntu (NOT on your target device ie. the 124GB flash drive you are talking about)

*Reboot and select Try Ubuntu. Verify that it has booted with EFI support by [ -d /sys/firmware/efi ] && echo UEFI || echo BIOS.

*Insert and mount your 124GB flash drive.

*Delete all partitions and volumes on the flash drive using GParted.

*Start the Ubiquity installer and when asked for target device choose your flash drive.

*IMPORTANT: In the option labelled location to install bootloader don't forget to set it to your flash drive.

*Enjoy.

PS: This has a known side-effect (may be good or maybe bad depending on your requirements) that the grub will also detect all OS kernels on all attached devices (like your HDD) and add them to grub.


text:
Q: Connecting an Access database with password? (OledbConnection) Look, I'm working and doing tests with Access databases in Visual Basic.
I created an access database, and place it in the bin / debug folder of the project. Without assigning a password , it connects sucesfully with the database ... but when I encrypt the database (or put a password to the database with exclusively mode), my connection fails:
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    Dim tabla As DataTable = New DataTable
    Dim ds As DataSet = New DataSet
    Dim conexion As New OleDb.OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=soq.accdb;Persist Security Info=False;Jet OLEDB:Database Password=mypassword;")
    Try
        conexion.Open()
        MsgBox("Estoy operando.")
    Catch ex As Exception
        MsgBox("No ando haciendo eso")
    End Try
    conexion.Close()
End Sub

Whats the problem here?? I wrote something wrong??? (I got Microsoft Access 2013)

A: Okay guys, i found the solution!
The encryption method of Microsoft Access 2013 dont works properly. So my solution was simple: Use the encryption method of the 2007 version, and done!
Thanks all!


text:
Q: Why are these two ways of counting the same combinatorial object not yielding the same result?
In how many ways can we distribute 20 black balls and 2 white balls (indistinguishable modulo color) in
  5 numbered glasses such that the fifth one doesn't have more
  black balls than white balls?

My strategy was to break this problem into 6 incompatible scenarios according to how many balls we decide to put in the fifth glass: (i) no balls, (ii) 1W, (iii) 1W1B, (iv) 2W, (v) 2W1B, (vi) 2W2B.
Therefore, the are
$${23\choose20}{5\choose2} + {23\choose20}{4\choose1} + {22\choose19}{4\choose1} + {23\choose20} + {22\choose19} + {21\choose18} = 15 {23\choose20} + 5{22\choose19} + {21\choose18}$$
total distributions.
However, I was told each of these scenarios is equivalent to counting anagrams of $m,n,k$ copies of B, W, G respectively. But when we count anagrams of BBBBBBBBBBBBBBBBBBBBBBBBBWWGGG isn't the answer $\frac{25!}{20!2!3!}$? That's not the same as ${23\choose20}{5\choose2}$.
I'm seriously confused.

A: It's not the same as counting anagrams, because in anagrams the order of different letters matter, whereas there is no difference in what order you put white and black balls in the glass.
Consider a simpler problem: how many ways are there to put 1 white and 2 black balls in the glass. Of course it's only one! However, you have three anagrams of BBW: BBW, BWB, WBB.

A: The partition into the six possible distinguished cases is correct.
We have that the number of ways to put $b$ black balls into $g$ labelled (numbered) glasses
is equivalent to the number of weak compositions of $b$ into $g$ parts, which is
$$
\binom{b+g-1}{b}
$$
Similarly for the white balls.
Therefore
$$
\eqalign{
  & N = \sum\limits_{cases} {\left( \matrix{
  b + g - 1 \cr
  b \cr}  \right)\left( \matrix{
  w + g - 1 \cr
  w \cr}  \right)}  =   \cr
  &  = \sum\limits_{0\, \le \,k\, \le \,\,j\, \le \,2} {\left( \matrix{
  20 - k + 3 \cr
  20 - k \cr}  \right)\left( \matrix{
  2 - j + 3 \cr
  2 - j \cr}  \right)}  =   \cr
  &  = \sum\limits_{0\, \le \,k\, \le \,\,j\, \le \,2} {\left( \matrix{
  23 - k \cr
  20 - k \cr}  \right)\left( \matrix{
  5 - j \cr
  2 - j \cr}  \right)}  =   \cr
  &  = \sum\limits_{0\, \le \,j\,,\,\,k\, \le \,2} {\left( \matrix{
  23 - k \cr
  20 - k \cr}  \right)\left( \matrix{
  j - k \hfill \cr
  j - k \hfill \cr}  \right)\left( \matrix{
  5 - j \cr
  2 - j \cr}  \right)}  =   \cr
  &  = \sum\limits_{0\, \le \,k\, \le \,2} {\left( \matrix{
  23 - k \cr
  20 - k \cr}  \right)\left( \matrix{
  6 - k \cr
  2 - k \cr}  \right)}  =   \cr
  &  = \sum\limits_{0\, \le \,k\, \le \,2} {\left( \matrix{
  23 - k \cr
  3 \cr}  \right)\left( \matrix{
  6 - k \cr
  4 \cr}  \right)}  =   \cr
  &  = \left( \matrix{
  23 \cr
  3 \cr}  \right)\left( \matrix{
  6 \cr
  4 \cr}  \right) + \left( \matrix{
  22 \cr
  3 \cr}  \right)\left( \matrix{
  5 \cr
  4 \cr}  \right) + \left( \matrix{
  21 \cr
  3 \cr}  \right) =   \cr
  &  = 15\left( \matrix{
  23 \cr
  3 \cr}  \right) + 5\left( \matrix{
  22 \cr
  3 \cr}  \right) + \left( \matrix{
  21 \cr
  3 \cr}  \right) =   \cr
  &  = 15\left( \matrix{
  23 \cr
  20 \cr}  \right) + 5\left( \matrix{
  22 \cr
  19 \cr}  \right) + \left( \matrix{
  21 \cr
  18 \cr}  \right) =   \cr
  &  = 35595 \cr}
$$
which fits with your computation.
Concerning the Anagrams analogy, it is correct that the case in which, e.g., the 5th glass is empty corresponds to the anagrams of
$$[20 \times B, 5 \times W, 3 \times G]$$
since the $G$ stands for the separation between two consecutive of the four glasses.
And that is in fact equal to the weak compositions of $20$ into four parts, times the compositions of $5$ into four parts.
Now, instead, the multinomial
$$
N_{0,0}  = \left( \matrix{
  28 \cr
  20,5,3 \cr}  \right) = {{28!} \over {20!5!3!}}
$$
which appears in the expansion of the trinomial
$$
\eqalign{
  & \left( {B + W + G} \right)^{\,28}  =   \cr
  &  =  \ldots  + B^{\,20} W^{\,5} G^{\,3}  + B^{\,19} WBW^{\,4} G^{\,3}  +  \ldots  +  \ldots   \cr
  &  \cdots  + GB^{\,12} W^{\,2} B^{\,6} GW^{\,2} B^{\,2} WG +  \cdots   \cr
  &  =  \ldots  + \left( \matrix{
  28 \cr
  20,5,3 \cr}  \right)B^{\,20} W^{\,5} G^{\,3}  +  \ldots  \cr}
$$
is going to count also how a certain number of white and black balls inside a single glass alternate
in color, that is the situation in which the glass has a one-ball diameter and we distinguish
not only by the content in black/white of each glass but also by the color layering.


text:
Q: How to make image load smooth in safari and Chrome I need to change background image on hover, I am preloading images through Javascript on document ready,
Now the thig is its working fine in Firefox but in Chrome and Safari it takes time to load. So is there any way so I can make it smooth like Firefox ? Moreover, Images are heavy in size approximate in Mbs.
This is what I did to preload and change image on hover
$( document ).ready(function() {
    // Set Default home page background
    if(defaultBGimage != "" && defaultBGimage != null && typeof(defaultBGimage) != "undefined"){
        $.backstretch(defaultBGimage, {centeredY: false});
    }
    // Pre-load images
    function preloadImages(srcs) {
        if (!preloadImages.cache) {
            preloadImages.cache = [];
        }
        var img;
        for (var i = 0; i < srcs.length; i++) {
            img = new Image();
            img.src = srcs[i];
            preloadImages.cache.push(img);
        }
    }

    preloadImages(catBGimages); // Pass array of images to preload it

    jQuery(".level1-cat").hover(function(){ // on hover change home page background image
        if(catBGimages[jQuery(this).data('id')] != null && catBGimages[jQuery(this).data('id')] != "null" && catBGimages[jQuery(this).data('id')] != "" && typeof(catBGimages[jQuery(this).data('id')]) != "undefined"){
            $.backstretch(catBGimages[jQuery(this).data('id')], {centeredY: false});
        }
    });
});

Thanks in advance.

A: Below is the code which makes preload images quickly try this may help u ..
function preload(arrayOfImages) {
    $(arrayOfImages).each(function(){
        $('<img/>')[0].src = this;
        // Alternatively you could use:
        // (new Image()).src = this;
    });
}

// Usage:

preload([
    'img/imageName.jpg',
    'img/anotherOne.jpg',
    'img/blahblahblah.jpg'
]);


text:
Q: Servlet.service() throws ClassCastException I have a java web application. I have set up this new project and getting the following exception when I run a jsp,
Oct 10, 2012 3:01:49 AM org.apache.catalina.core.StandardWrapperValve invoke
SEVERE: Servlet.service() for servlet jsp threw exception
java.lang.ClassCastException: org.apache.catalina.util.DefaultAnnotationProcessor cannot be cast to org.apache.AnnotationProcessor
    at org.apache.jasper.servlet.JspServletWrapper.getServlet(JspServletWrapper.java:151)
    at org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:340)
    at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:313)
    at org.apache.jasper.servlet.JspServlet.service(JspServlet.java:260)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:233)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:127)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:298)
    at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:857)
    at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:588)
    at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:489)
    at java.lang.Thread.run(Thread.java:619)
Oct 10, 2012 3:01:57 AM org.apache.catalina.loader.WebappClassLoader modified
INFO:     Additional JARs have been added : 'activation-1.1.jar'
Oct 10, 2012 3:01:57 AM org.apache.catalina.core.StandardContext reload
INFO: Reloading this Context has started
Oct 10, 2012 3:01:57 AM org.apache.catalina.loader.WebappClassLoader clearReferencesJdbc
SEVERE: The web application [/AutoUpgrade] registered the JBDC driver [com.mysql.jdbc.Driver] but failed to unregister it when the web application was stopped. To prevent a memory leak, the JDBC Driver has been forcibly unregistered.
Oct 10, 2012 3:01:57 AM org.apache.catalina.loader.WebappClassLoader clearReferencesThreads
SEVERE: The web application [/AutoUpgrade] appears to have started a thread named [Timer-0] but has failed to stop it. This is very likely to create a memory leak.

I have tried clean and building the project many times, getting the latest service-api.jar, my lib is very extensive and I cannot figure out whether there is any inconsistencies between any jar that is causing this error. I am running the project on Apache Tomcat 6 on jdk 1.6 (my project needs to run on 1.6). I have tried googling this exception, but didnt get any post relevant to my problem. The relevant questions on stackoverflow talk about NullPointerException.
I think the problem must be with my library, but I can not point to root cause.
Thanks

A: This can happen when you have Tomcat-specific JAR files in your webapp's /WEB-INF/lib. This is not right. You should  remove all servletcontainer-specific JAR files from there. They do not belong there at all. They are supposed to be already provided by the servletcontainer itself. The /WEB-INF/lib should only contain libraries specific to the webapp itself which are not provided by the servletcontainer.
If you have placed them there as a result of an unthoughtful attempt to fix compilation errors, then please carefully read this answer how to solve it the right way: How do I import the javax.servlet API in my Eclipse project?

A: If cleaning your project didn't help, perhaps you need to clear your cache.
The Netbeans cache is located somewhere...
C:\Documents and Settings\myself.netbeans\7.0\var\cache

A: Remove the following from lib.

*

*Check for same jar with different versions

*All catalina related jars

*el-api.jar

*jsp-api.jar

This will definitely work.


text:
Q: Javascript: My  Content is Not Appearing When I Append Them With Javascript I've been working on the following problem for a while now.

*

*Make a web service request every 1 second to http://courses.acs.uwinnipeg.ca/2909-001/assignments/A2Q2.php
for 20 seconds. A JSON object will be returned. Count up the amount of circle and rectangle types and display
the counts. The web service will occasionally return a status of 500 and these should also be counted and
displayed.

The above is an example of how my output should look like.
Here's what I got coded:

<!DOCTYPE html>

So far I've fulfilled every criteria specified in the question, but I've run into an issue at the part where I have to display the counts. For some reason my page is blank even though I've appended all the content to my div. Any ideas?

A: I have updated the code slightly and it works for me:

<!DOCTYPE html>

Your problem was the execution order of code,
In your code version - this line:
if (setIntervalCounter === 20){

Was running before the interval count, and it never run again when the counter gets to 20, what I have done that after clearing the interval I call the results() function just after the clearInterval.
If you put break points and debug through the code you will realize the issue.


text:
Q: Why is it only my first picture that will resize?

 #nyanCat {
    content: url("billeder/nyan_cat.gif");
    display: table;
    margin: 0 auto;
    padding-top: 90px;
    height: 0 auto;
    max-width: 100%;
}
#gnome {
    content: url("billeder/gnome.gif");
    float: left;
    left: 10px;
    margin: 0 auto;
    display: inline;
    position: absolute;
    bottom: 0px;
    height: 0 auto;
    max-width: 100%;
}
#bernie {
    content: url("billeder/bernie.png");
    float: right;
    right: 10px;
    display: inline;
    position: absolute;
    bottom: 0px;
    height: 0 auto;
    max-width: 100%;
}
#doge {
    content: url("billeder/doge.png");
    float: right;
    position: absolute;
    top: 0px;
    transform: scaleY(-1);
    filter: FlipV;
    height: 0 auto;
    max-width: 100%;
}
#bodySnap {
    background-color: rgb(255, 0, 216);
}

@media screen and (max-width: 1700px), screen and (max-height:760px) {
#nyanCat {
    max-width: 50%;
}
#gnome {
    max-width: 70%;
}
#bernie {
    max-width: 70%;
}
#doge {
    max-width: 70%;
}
}

    <link href="../snapStyle.css"   type="text/css" rel="stylesheet">
    <meta charset="utf-8">
    <title>Zacho's Snap</title>

        <map name="map_nyan_cat" id="map_nyan_cat">
            <area href="http://www.nyan.cat/" target="_blank" shape="rect" coords="377,432,766,276" />
        </map>

        <map name="map_gnome" id="map_gnome">
            <area href="https://youtu.be/Gmf-TW5rWiY" target="_blank" shape="rect" coords="0,39,490,483" />
        </map>

        <map name="map_bernie" id="map_bernie">
            <area href="https://youtu.be/sjHSUPwHmjg" target="_blank" shape="rect" coords="51,6,391,479" />
        </map>

        <map name="map_doge" id="map_doge">
            <area href="http://knowyourmeme.com/memes/doge" target="_blank" shape="rect" coords="11,14,398,419" />
        </map>

They are all at the perfect spot but I simply just can't resize them!
I'm trying to make it perfect for all screen resolutions
This is what my page looks like at them moment https://gyazo.com/bf59e0a9c2e64bbf09dfb77a133a4537


text:
Q: New/different page for different organization IDs in Jaspersoft report I'm looking for any suggestions on how to print a new/different page for different organization IDs. I created a jaspersoft grouping and was thinking of adding a print when expression to the organization ID group header. Would that be the way to go? Can anyone help me with the expression that I would need for that?

A: "Start New Page" (isStartNewPage="true") in the Appearance tab of the Properties for the Group Header is all that is necessary to start on a new page for every new group. Group Expression for your situation would simply be something like $F{organizationID}.
Here's an example that groups on $F{city}, lists $F{CustomerID} and starts a new page for every new $F{city}:
<?xml version="1.0" encoding="UTF-8"?>
<!-- Created with Jaspersoft Studio version 6.20.0.final using JasperReports Library version 6.1.1  -->
<jasperReport xmlns="http://jasperreports.sourceforge.net/jasperreports" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://jasperreports.sourceforge.net/jasperreports http://jasperreports.sourceforge.net/xsd/jasperreport.xsd" name="Blank_A4_" pageWidth="595" pageHeight="842" columnWidth="555" leftMargin="20" rightMargin="20" topMargin="20" bottomMargin="20" uuid="62ac07f5-f11e-4179-aedb-a42e850c1ea8">
    <property name="com.jaspersoft.studio.data.defaultdataadapter" value="northwind"/>
    <queryString language="jsonql">
        <![CDATA[Northwind.Customers]]>
    </queryString>
    <field name="City" class="java.lang.String">
        <property name="net.sf.jasperreports.jsonql.field.expression" value="City"/>
        <fieldDescription><![CDATA[City]]></fieldDescription>
    </field>
    <field name="CustomerID" class="java.lang.String">
        <property name="net.sf.jasperreports.json.field.expression" value="CustomerID"/>
        <fieldDescription><![CDATA[CustomerID]]></fieldDescription>
    </field>
    <group name="City" isStartNewPage="true">
        <groupExpression><![CDATA[$F{City}]]></groupExpression>
    </group>
    <columnHeader>
        <band height="12" splitType="Stretch">
            <staticText>
                <reportElement x="0" y="0" width="100" height="12" uuid="bdf3f7ab-bf1d-451e-a2ad-831a551ce388"/>
                <textElement>
                    <font isBold="true"/>
                </textElement>
                <text><![CDATA[Company Name]]></text>
            </staticText>
        </band>
    </columnHeader>
    <detail>
        <band height="12" splitType="Stretch">
            <textField>
                <reportElement x="0" y="0" width="100" height="12" uuid="c7bcc5aa-8051-48ad-a0d6-fe27c68da204"/>
                <textFieldExpression><![CDATA[$F{CustomerID}]]></textFieldExpression>
            </textField>
        </band>
    </detail>
</jasperReport>


text:
Q: Javascript - how to take array of abbreviated days and output full name of days I am trying to take a report of class meeting days in abbreviated form. Each row has an array of days (M,T,W,TH,F,S,SU). How could I loop through the array and change each value of:
M to Monday
T to Tuesday
W to Wednesday
TH to Thursday
F to Friday
S to Saturday
SU to Sunday
I would like to keep the array intact. To switch from {M,W,F} to {Monday,Wednesday,Friday}.
I have tried to for loop through and use a switch in the loop with no luck.
Can you help?

A: I would use a constant map to help me translate from short to long.
Like this:

const DAYS_SHORT_TO_LONG = {
  SU: 'Sunday',
  M: 'Monday',
  T: 'Tuesday',
  W: 'Wednesday',
  TH: 'Thursday',
  F: 'Friday',
  S: 'Saturday',
}

const daysToConvert = ['M', 'SU', 'F', 'TH'];

const result = daysToConvert.map((shortDay) => DAYS_SHORT_TO_LONG[shortDay]);

console.log(result);


text:
Q: How to correctly trigger the change of a value in a UserControl using WinForms Data Binding? I created two UserControls in my WinForms application. One contains a TextBox (let's call this TextEntryControl for now) and the other one should use the value I entered into this TextBox to do internal stuff (enable a button and use the value when this button is clicked) - let's call this TextUsingControl.
However, I don't get this right via DataBinding.
First (naive) approach
I added a string property to TextEntryControl like this:
public string MyStringProperty { get; set; }

Then I used the UI designer to bind the TextBox's Text property to this MyStringProperty, resulting in a textEntryControlBindingSource. I added to the constructor right behind the InitializeComponents():
textEntryControlBindingSource.Add(this);

I added the same property to the TextUsingControl, and in my outer UI where I use the two controls, I bound the TextUsingControl's string property to the one of the TextEntryControl, and updated the binding source appropriately:
textEntryControlBindingSource.Add(textEntryControl1);

I use both controls on different tabs of a TabControl, and the mechanism only works once, when I first enter text into the text box and then switch to the other control.
Next try
I created a simple wrapper class for strings:
public sealed class StringWrapper {

    public string Content { get; set; }
}

In my text entry control, I bound the text box to this string wrapper, and changed the property to look like this:
public string MyStringProperty {
    get {
        return _stringWrapper.Content;
    }
    set {
        _stringWrapper.Content = value;
    }
}

I did a similar thing in the outer control with the TabControl - use a StringWrapper to bind both MyStringProperty of both user controls to.
Result: Same. But this is logical since the outer property that delegates to the wrapper doesn't get notified.
Third try
This one works, sort of, but I think this is an ugly workaround.
I ditched the MyStringProperty altogether and pass in the wrapper object itself via a property that, again, passes it down to the binding source:
public StringWrapper MyStringWrapper {
    get {
        return stringWrapperBindingSource.Cast<StringWrapper>().FirstOrDefault();
    }
    set {
        stringWrapperBindingSource.Clear();
        if(value != null) stringWrapperBindingSource.Add(value);
    }
}

Now I only create one single StringWrapper object and set it to both user controls right after InitializeComponent().
INotifyPropertyChanged
As a follow up: I tried INotifyPropertyChanged as well as described on MSDN. This did not help either.
What I want to achieve
I want both user controls to have a MyStringProperty, and when the text I enter into TextEntryControl's text box changes, the property should update and correctly notify any binding sources it is attached to.
The TextUsingControl should update itself when its property changes.
The second half is easy, I just add the appropriate logic into the set part of the property, but I am having trouble with the first one.
I am used to Eclipse's JFace Data Binding, where this functionality can be achieved with PropertyChangeSupport and PropertyChangeListener - here, I just add the appropriate event firing code to the setter and I can use BeanProperties.value() when setting up the data binding.

A: It's a combination of a proper property implementation and proper data binding.
(1) Property implementation:
The property does not need to be complex. It could be simple type as in your naïve approach, but the essential part is that it should provide property change notification. You can use the general INotifyPropertyChanged mechanism or Windows Forms specific PropertyNameChanged named event pattern. In both cases, you cannot use C# auto property feature and have to implement it manually (with an explicit backing field). Here is a sample implementation:
string myStringProperty;
public string MyStringProperty
{
    get { return myStringProperty; }
    set
    {
        if (myStringProperty == value) return;
        myStringProperty = value;
        var handler = MyStringPropertyChanged;
        if (handler != null) handler(this, EventArgs.Empty);
    }
}

public event EventHandler MyStringPropertyChanged;

(2) Data binding:
Binding single control property to a single object property is called simple data binding and is achieved via Control.DataBindings. You can take a look at ControlBindingsCollection.Add method / Binding Constructor overloads and Binding  class properties/methods/events for more info.
What the Binding does is basically creating a link (one or two way) between source object property and target object property. Note the word property - that's exactly what is supported out of the box. But with the following simple helper method (presented in my answer to How to set Textbox.Enabled from false to true on TextChange?) you can easily create one way expression like binding:
public static void Bind(this Control target, string targetProperty, object source, string sourceProperty, Func<object, object> expression)
{
    var binding = new Binding(targetProperty, source, sourceProperty, true, DataSourceUpdateMode.Never);
    binding.Format += (sender, e) => e.Value = expression(e.Value);
    target.DataBindings.Add(binding);
}

Here is a full working demo:
using System;
using System.Windows.Forms;

namespace Samples
{
    static class Program
    {
        [STAThread]
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            var form = new Form();
            var splitView = new SplitContainer { Dock = DockStyle.Fill, Parent = form };
            var textEntry = new TextEntryControl { Dock = DockStyle.Fill, Parent = splitView.Panel1 };
            var textConsumer = new TextConsumingControl { Dock = DockStyle.Fill, Parent = splitView.Panel2 };
            textConsumer.DataBindings.Add("MyStringProperty", textEntry, "MyStringProperty", true, DataSourceUpdateMode.Never);
            Application.Run(form);
        }
    }

    class TextEntryControl : UserControl
    {
        TextBox textBox;
        public TextEntryControl()
        {
            textBox = new TextBox { Parent = this, Left = 16, Top = 16 };
            textBox.DataBindings.Add("Text", this, "MyStringProperty", true, DataSourceUpdateMode.OnPropertyChanged);
        }

        string myStringProperty;
        public string MyStringProperty
        {
            get { return myStringProperty; }
            set
            {
                if (myStringProperty == value) return;
                myStringProperty = value;
                var handler = MyStringPropertyChanged;
                if (handler != null) handler(this, EventArgs.Empty);
            }
        }

        public event EventHandler MyStringPropertyChanged;
    }

    class TextConsumingControl : UserControl
    {
        Button button;
        public TextConsumingControl()
        {
            button = new Button { Parent = this, Left = 16, Top = 16, Text = "Click Me" };
            button.Bind("Enabled", this, "MyStringProperty", value => !string.IsNullOrEmpty(value as string));
        }

        string myStringProperty;
        public string MyStringProperty
        {
            get { return myStringProperty; }
            set
            {
                if (myStringProperty == value) return;
                myStringProperty = value;
                var handler = MyStringPropertyChanged;
                if (handler != null) handler(this, EventArgs.Empty);
            }
        }

        public event EventHandler MyStringPropertyChanged;
    }

    public static class BindingUtils
    {
        public static void Bind(this Control target, string targetProperty, object source, string sourceProperty, Func<object, object> expression)
        {
            var binding = new Binding(targetProperty, source, sourceProperty, true, DataSourceUpdateMode.Never);
            binding.Format += (sender, e) => e.Value = expression(e.Value);
            target.DataBindings.Add(binding);
        }
    }
}

As you can see, the requested (one way) binding between textEntry and textConsumer is established with this single line:
textConsumer.DataBindings.Add("MyStringProperty", textEntry, "MyStringProperty", true, DataSourceUpdateMode.Never);

Another interesting point you can see in the demo is that if you wish, you can actually data bind internal control properties too. The whole synchronization between the TextEntryControl internal text box and the property is achieved with this single line:
textBox.DataBindings.Add("Text", this, "MyStringProperty", true, DataSourceUpdateMode.OnPropertyChanged);

and the TextConsumingControl internal button enabling:
button.Bind("Enabled", this, "MyStringProperty", value => !string.IsNullOrEmpty(value as string));

Of course the last two things are optional, you can do that in the property setter, but it's kind of cool to know that such option exists.


text:
Q: React web app spread across multiple browser windows / dual screen app A client has tasked me with refactoring their React app to support multiple screens. I have some ideas on how to approach this, and would like to get some feedback to see if I am on the right track.
The problem:

*

*We have a relatively complex React app, and the client feels that splitting the app across multiple windows will make for a better UX.

*As example of this split-screen set up, imagine that window 1 shows some data, and window 2 contains UI elements that allow you to filter that data. In this manner, the app is split across 2 windows.

*(The 2 browser windows is a hard constraint imposed by the product owner. Other options like grid layout managers are not considered.)

The solution (so far):
We need to share state across two browser windows. To do so, we can use:

*

*Local storage to keep track of state and use StorageEvent listeners to coordinate state changes between the two windows.

*We can also use some of the web APIs designed to pass data between windows including: shared web worker, broadcast channels, and window.postmessage(). I learned about these in Blake Zimmerman's presentation here, PDF ~2mb.

*This framework - neo.mjs, which uses web workers. I would rather not abstract the low-level details to a framework, because I am not familiar with web workers myself yet.

The question:

*

*Is there something I am missing? Are there other tools I can use to share state between windows? Any good articles I can read?

*I am also having trouble visualizing how to structure the React app to account for multiple displays. The best I could come up with is something like this:

<Main>
  {isComponentAShown && <ComponentA/>}
  {isComponentBShown && <ComponentB/>}
</Main>

where isComponent_X_Shown dictate which components the browser window should be displaying at any one time. These boolean flags will be part of the state shared by the two browser windows. Is there a better way to organize the App layouts to account for dual screen?
Thank you!


text:
Q: Django trans template tag only displaying placeholder constant string I have the following tag in templates/home.html:
{% trans "test" %}

Which always prints "test" no matter the language I choose. I know for a fact that the language changes because I print it like this (and the admin's language changes, etc...):
{% get_current_language as LANGUAGE_CODE %}
{{ LANGUAGE_CODE }}

In the project's settings.py I have:
LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_L10N = True

USE_TZ = True

# modeltranslation settings

LANGUAGES = (
    ('en', _('English')),
    ('zh-hans', _('Simplified Chinese')),
    ('zh-hant', _('Traditional Chinese')),
)

LOCALE_PATHS = [
    os.path.join(BASE_DIR, 'locale')
]

I wanted to try out the translation to Simplified Chinese so I created the translation thing with python3 manage.py makemessages -l zh-hans and in locale/zh-hans/LC_MESSAGES/django.po I filled the value of test like this:
#: templates/home.html:8
msgid "test"
msgstr "你好"

Then I run python3 manage.py compilemessages.
In the templates/_base.html that templates/home.html inherits from, I have
{% load static %}
{% load static i18n %}
{% load i18n %}

and in templates/home.html, I have
{% extends '_base.html' %}
{% load i18n %}

Despite this, when I change the language to zh-hans, it always displays test. What could be wrong?
I am using django 3.0.1.
EDIT: In settings.py, I have switched from using gettext to gettext_lazy as _ as suggested by a comment.

A: The name of the locale folder has to be zh_Hans instead of zh-hans. That's what I get for not looking at the source code! https://github.com/django/django/tree/master/django/contrib/auth/locale