text:
Q: Does $\sum^\infty_{s=1}\delta^{s-1}\frac{1}{1 + cs}$ have a closed-form expression?
I'm wondering whether
$$
\sum^\infty_{s=1}\delta^{s-1}\frac{1}{1 + c \cdot s},
$$
with $\delta \in (0,1)$ and $c\ge 0$ has a closed-form expression.

While I don't know of a general closed-form I can think if a special case:
Setting $c=0$ we obtain
$$
\sum^\infty_{s=1}\delta^{s-1}=\frac{1}{1-\delta},
$$
which is the geometric series. As for the more general case $c\neq 0$ I'm not sure.

A: For $|x^c|< 1$, consider the geometric series $\sum\limits_{n=0}^{\infty}x^{nc}$. Then we know
$$\frac{1}{1-x^c}=\sum\limits_{n=0}^{\infty}x^{nc}.$$
So
\begin{align*}
\frac{x^c}{1-x^c}& =\sum_{n=0}^{\infty}x^{nc+c}\\
\int\frac{x^c}{1-x^c} \, dx& =\sum_{n=0}^{\infty}\frac{x^{nc+c+1}}{1+c(n+1)}\\
\int\frac{x^c}{1-x^c} \, dx& =x^{c+1}\sum_{n=0}^{\infty}\frac{x^{nc}}{1+c(n+1)}.
\end{align*}
Now let $\delta=x^c$ (with $c \neq 0$), so we have
\begin{align*}
\frac{1}{c}\int\frac{\delta^{1/c}}{1-\delta} \, d\delta& =\delta^{\frac{c+1}{c}}\sum_{n=0}^{\infty}\frac{\delta^{n}}{1+c(n+1)}\\
\color{red}{\frac{1}{c\delta^{\frac{c+1}{c}}}\int\frac{\delta^{1/c}}{1-\delta} \, d\delta}& =\sum_{n=0}^{\infty}\frac{\delta^{n}}{1+c(n+1)}.
\end{align*}
So if we can solve the integral then we can get some closed form. However solving this integral may not be that straightforward.

A: Picking up where @Anurag left off we have
$$
\begin{align*}
\sum_{n=1}^{\infty}\frac{\delta^{n-1}}{1+cn}
&=\frac{1}{c\delta^{\frac{c+1}{c}}}\int\frac{\delta^{1/c}}{1-\delta} \,\mathrm d\delta\\
&=\frac{1}{c\delta^{\frac{c+1}{c}}}\int_0^\delta\frac{t^{1/c}}{1-t} \,\mathrm dt\\
&\overset{t=\delta z}{=}\frac{1}{c}\int_0^1\frac{z^{1/c}}{1-\delta z} \,\mathrm dz\\
&=\frac{1}{c}\int_0^1\frac{z^{(1+1/c)-1}(1-z)^{(2+1/c)-(1+1/c)-1}}{1-\delta z} \,\mathrm dz\\
&=\frac{1}{c(1+1/c)}(1+1/c)\int_0^1\frac{z^{(1+1/c)-1}(1-z)^{(2+1/c)-(1+1/c)-1}}{1-\delta z} \,\mathrm dz\\
&=\frac{1}{c+1}\frac{\Gamma(2+1/c)}{\Gamma(1+1/c)\Gamma(1)}\int_0^1\frac{z^{(1+1/c)-1}(1-z)^{(2+1/c)-(1+1/c)-1}}{1-\delta z} \,\mathrm dz,
\end{align*}
$$
which according to DLMF 15.6.1 equals
$$
\sum_{n=1}^{\infty}\frac{\delta^{n-1}}{1+cn}=\frac{1}{c+1}{_2F_1}\left({1,1+\frac{1}{c}\atop 2+\frac{1}{c}};\delta\right),
$$
with ${_2F_1}(\cdot)$ being the (Gauss) hypergeometric function.
Note that the series representation converges for $|\delta|<1$ and $c\in\Bbb C\setminus\{-1,-2,\dots\}$, whereas the hypergeometric representation can be extended to $\delta\in\Bbb C$ via analytic continuation and thus is a more general form.
Furthermore, using this relationship we can also express this result in terms of the Lerch Transcendent as
$$
\sum_{n=1}^{\infty}\frac{\delta^{n-1}}{1+cn}=\frac{1}{c}\Phi(\delta,1,1+\tfrac{1}{c}).
$$


text:
Q: How to unstack after aggregation using Groupby in Pandas Hello Data Scientist and Pandas Experts,
I need some help to figure out how to better organize my data after applying groupby aggregation method.  I have tried unstack to new dataframe but it does not yield the intended results.
Here is my data frame:
df = [{'Store': 's1', 'Date': Timestamp('2020-08-01 00:00:00'), 'Employee': 'a', 'Department': 'd1', 'ID': 's1ad1', 'Level': 2, 'duties': 'O'},\
 {'Store': 's1', 'Date': Timestamp('2020-08-02 00:00:00'), 'Employee': 'a', 'Department': 'd2', 'ID': 's1ad2', 'Level': 2, 'duties': 'C'},\
 {'Store': 's1', 'Date': Timestamp('2020-08-03 00:00:00'), 'Employee': 'a', 'Department': 'd1', 'ID': 's1ad1', 'Level': 2, 'duties': 'O'},\
 {'Store': 's1', 'Date': Timestamp('2020-08-04 00:00:00'), 'Employee': 'a', 'Department': 'd1', 'ID': 's1ad1', 'Level': 2, 'duties': 'O'},\
 {'Store': 's1', 'Date': Timestamp('2020-08-05 00:00:00'), 'Employee': 'a', 'Department': 'd2', 'ID': 's1ad2', 'Level': 2, 'duties': 'C'},\
 {'Store': 's2', 'Date': Timestamp('2020-08-08 00:00:00'), 'Employee': 'a', 'Department': 'd1', 'ID': 's2ad1', 'Level': 2, 'duties': 'O'},\
 {'Store': 's2', 'Date': Timestamp('2020-08-09 00:00:00'), 'Employee': 'a', 'Department': 'd3', 'ID': 's2ad3', 'Level': 2, 'duties': 'C'},\
 {'Store': 's2', 'Date': Timestamp('2020-08-10 00:00:00'), 'Employee': 'a', 'Department': 'd1', 'ID': 's2ad1', 'Level': 2, 'duties': 'O'},\
 {'Store': 's2', 'Date': Timestamp('2020-08-11 00:00:00'), 'Employee': 'a', 'Department': 'd1', 'ID': 's2ad1', 'Level': 2, 'duties': 'O'},\
 {'Store': 's2', 'Date': Timestamp('2020-08-12 00:00:00'), 'Employee': 'a', 'Department': 'd3', 'ID': 's3ad1', 'Level': 2, 'duties': 'C'},\
 {'Store': 's1', 'Date': Timestamp('2020-08-01 00:00:00'), 'Employee': 'b', 'Department': 'd1', 'ID': 's1bd1', 'Level': 1, 'duties': 'O'},\
 {'Store': 's1', 'Date': Timestamp('2020-08-02 00:00:00'), 'Employee': 'b', 'Department': 'd2', 'ID': 's1bd2', 'Level': 1, 'duties': 'C'},\
 {'Store': 's1', 'Date': Timestamp('2020-08-03 00:00:00'), 'Employee': 'b', 'Department': 'd1', 'ID': 's1bd1', 'Level': 1, 'duties': 'O'},\
 {'Store': 's1', 'Date': Timestamp('2020-08-04 00:00:00'), 'Employee': 'b', 'Department': 'd1', 'ID': 's1bd1', 'Level': 1, 'duties': 'O'},\
 {'Store': 's1', 'Date': Timestamp('2020-08-05 00:00:00'), 'Employee': 'b', 'Department': 'd2', 'ID': 's1bd2', 'Level': 1, 'duties': 'C'},\
 {'Store': 's2', 'Date': Timestamp('2020-08-08 00:00:00'), 'Employee': 'c', 'Department': 'd1', 'ID': 's2ac1', 'Level': 3, 'duties': 'O'},\
 {'Store': 's2', 'Date': Timestamp('2020-08-09 00:00:00'), 'Employee': 'c', 'Department': 'd3', 'ID': 's2cd3', 'Level': 3, 'duties': 'C'},\
 {'Store': 's2', 'Date': Timestamp('2020-08-10 00:00:00'), 'Employee': 'c', 'Department': 'd1', 'ID': 's2cd1', 'Level': 3, 'duties': 'O'},\
 {'Store': 's2', 'Date': Timestamp('2020-08-11 00:00:00'), 'Employee': 'c', 'Department': 'd1', 'ID': 's2cd1', 'Level': 3, 'duties': 'O'},\
 {'Store': 's2', 'Date': Timestamp('2020-08-12 00:00:00'), 'Employee': 'c', 'Department': 'd3', 'ID': 's3cd1', 'Level': 3, 'duties': 'C'},\
 {'Store': 's3', 'Date': Timestamp('2020-08-08 00:00:00'), 'Employee': 'd', 'Department': 'd1', 'ID': 's3cd1', 'Level': 3, 'duties': 'O'},\
 {'Store': 's3', 'Date': Timestamp('2020-08-09 00:00:00'), 'Employee': 'd', 'Department': 'd3', 'ID': 's3dd3', 'Level': 3, 'duties': 'C'},\
 {'Store': 's3', 'Date': Timestamp('2020-08-10 00:00:00'), 'Employee': 'd', 'Department': 'd1', 'ID': 's3dd1', 'Level': 3, 'duties': 'O'},\
 {'Store': 's3', 'Date': Timestamp('2020-08-11 00:00:00'), 'Employee': 'd','Department': 'd1', 'ID': 's3dd1', 'Level': 3, 'duties': 'O'},\
 {'Store': 's3', 'Date': Timestamp('2020-08-12 00:00:00'), 'Employee': 'd', 'Department': 'd3', 'ID': 's3dd1', 'Level': 3, 'duties': 'C'}]

I want to organize my output so its nicely stacked in Store --> Department --> Employee.  Something like as follow (Sorry the output is not nicely lined):
Store           s1                      s2                                     s3
Department      d1          d2          d1          d3          d1          d3
Employee    ID   Level duties   first shift   last shift #ofshift   first shift   last shift #ofshift   first shift   last shift #ofshift   first shift   last shift #ofshift   first shift   last shift #ofshift   first shift   last shift #ofshift
a   s1ad1 2 O   2020-08-01 2020-08-04 3
a   s1ad2 2 C               2020-08-02 2020-08-05 2
a   s2ad1 2 O                           2020-08-08 2020-08-11 3
a   s2ad3 2 O                                       2020-08-09 2020-08-12 2
b   s1bd1 1 O   2020-08-01 2020-08-04 3
b   s1bd2 1 C               2020-08-02 2020-08-05 2
c   s2cd1 3 O                           2020-08-08 2020-08-11 3
c   s3ad3 3 O                                       2020-08-09 2020-08-12 2
d   s3dd1 3 O                                                   2020-08-08 2020-08-11 3
d   s3dd3 3 O                                                               2020-08-09 2020-08-12 2

So I have tried following Group by expression:
df = df.groupby(['Employee', 'Store', 'Department'])\
                .agg({'Date':['first', 'last', 'size'],
                      'ID': 'first',
                      'Level': 'first',
                      'duties': 'first'})

# Join the Each Column with its operation.
df.columns = df.columns.map('_'.join)

# Reset the Index
df = df.reset_index().set_index('Employee')

# Renaming Columns of Dataframe.
df.rename(columns={'Date_first':'First Shift',
        'Date_last':'Last Shift',
        'Date_size':'# of shift',
        'ID_first':'ID',
        'Level_first':'Level',
        'duties_first':'duties'},
        inplace=True)

This prints following results:
            Store  Department  First Shift       Last Shift      # of shift    ID_first     Level    duties
Employee
a               s1         d1                    2020-08-01    2020-08-04           3          s1ad1             2      O
a               s1         d2                    2020-08-02   2020-08-05           2           s1ad2            2      C
a               s2         d1                    2020-08-08   2020-08-11            3           s2ad1            2      O
a               s2         d3                   2020-08-09    2020-08-12           2           s2ad3           2      C
b               s1         d1                    2020-08-01     2020-08-04           3          s1bd1            1      O
b               s1         d2                   2020-08-02     2020-08-05           2          s1bd2           1      C
c               s2         d1                   2020-08-08     2020-08-11            3           s2ac1           3      O
c               s2         d3                  2020-08-09     2020-08-12           2           s2cd3          3      C
d               s3         d1                   2020-08-08    2020-08-11           3           s3cd1           3      O
d               s3         d3                  2020-08-09     2020-08-12           2         s3dd3           3      C

Then I applied the unstack expression as follow:
df = df.groupby(['Employee', 'Store', 'Department', 'First Shift', 'Last Shift', '# of shift', 'ID_first',\
                     'Level', 'duties'])\
            .size()\
            .unstack(['Store', 'Department']).fillna(0)

It prints our the result as follow:
Store                                                              s1        s2        s3
Department                                                         d1   d2   d1   d3   d1   d3
Employee First Shift Last Shift # of shift ID_first Level duties
a        2020-08-01  2020-08-04 3          s1ad1    2     O       1.0  0.0  0.0  0.0  0.0  0.0
         2020-08-02  2020-08-05 2          s1ad2    2     C       0.0  1.0  0.0  0.0  0.0  0.0
         2020-08-08  2020-08-11 3          s2ad1    2     O       0.0  0.0  1.0  0.0  0.0  0.0
         2020-08-09  2020-08-12 2          s2ad3    2     C       0.0  0.0  0.0  1.0  0.0  0.0
b        2020-08-01  2020-08-04 3          s1bd1    1     O       1.0  0.0  0.0  0.0  0.0  0.0
         2020-08-02  2020-08-05 2          s1bd2    1     C       0.0  1.0  0.0  0.0  0.0  0.0
c        2020-08-08  2020-08-11 3          s2ac1    3     O       0.0  0.0  1.0  0.0  0.0  0.0
         2020-08-09  2020-08-12 2          s2cd3    3     C       0.0  0.0  0.0  1.0  0.0  0.0
d        2020-08-08  2020-08-11 3          s3cd1    3     O       0.0  0.0  0.0  0.0  1.0  0.0
         2020-08-09  2020-08-12 2          s3dd3    3     C       0.0  0.0  0.0  0.0  0.0  1.0

I think I am wrongly using Size and unstack.  However I can't seems to figure out how to reorganize the data.
I would highly appreciate the expert opinion on how to properly organize my data.
Once again really appreciate your help and consideration.
Thank You.

A: The crux of your problem is that you need to restructure the data prior to using .unstack(), because your desired format is a matrix with the values being three repeated columns. So, you need to change your dataframe from wide to long and create a new column with these three values in one column Values with another column that categorizes them Shift.
# Step 1: Named Groupby Agregation naming columns ins specific format required for `pd.wide_to_long`. Must end with integer.
df = (df.groupby(['Employee', 'Store', 'Department'])
        .agg(Shift_1=('Date','first'),
             Shift_2=('Date','last'),
             Shift_3=('Date','size'),
             ID=('ID', 'first'),
             Level=('Level', 'first'),
             duties=('duties', 'first'))
        .reset_index())

# Step 2: In preparation for a matrix The data must be transformed so that the three columns that are values in the matrix must be in long format.
df = pd.wide_to_long(df, stubnames='Shift_', i='ID', j='Shift').reset_index().rename(columns={'Shift_':'Values'})

# Step 3: 1,2,3 were required integer suffixes for wide_to_long but now let's change to what we want the columns to be called.
df['Shift'] = df['Shift'].replace([1,2,3],['First Shift','Last Shift','# of shift'])

# Step 4: Create the matrix be setting index and unstacking to columns
df = (df.sort_values(['Employee', 'Store', 'Department']) #values must be sorted in order for how we want columns to appear in matrix format
        .set_index(['Employee', 'ID', 'Level', 'duties', 'Store', 'Department', 'Shift'])
        .unstack(['Store', 'Department', 'Shift']).fillna(0))

# Step 5: Cleanup of Multi-index into desred format
df.columns = df.columns.reorder_levels([1,2,3,0]).droplevel(3)
df = df.reset_index()
df
Out[1]:
Store      Employee     ID Level duties                   s1  \
Department                                                d1
Shift                                            First Shift
0                 a  s1ad1     2      O  2020-08-01 00:00:00
1                 a  s1ad2     2      C                    0
2                 a  s2ad1     2      O                    0
3                 a  s2ad3     2      C                    0
4                 b  s1bd1     1      O  2020-08-01 00:00:00
5                 b  s1bd2     1      C                    0
6                 c  s2ac1     3      O                    0
7                 c  s2cd3     3      C                    0
8                 d  s3cd1     3      O                    0
9                 d  s3dd3     3      C                    0

Store                                                            \
Department                                                   d2
Shift                Last Shift # of shift          First Shift
0           2020-08-04 00:00:00          3                    0
1                             0          0  2020-08-02 00:00:00
2                             0          0                    0
3                             0          0                    0
4           2020-08-04 00:00:00          3                    0
5                             0          0  2020-08-02 00:00:00
6                             0          0                    0
7                             0          0                    0
8                             0          0                    0
9                             0          0                    0

Store                                       ...         s2  \
Department                                  ...         d1
Shift                Last Shift # of shift  ... # of shift
0                             0          0  ...          0
1           2020-08-05 00:00:00          2  ...          0
2                             0          0  ...          3
3                             0          0  ...          0
4                             0          0  ...          0
5           2020-08-05 00:00:00          2  ...          0
6                             0          0  ...          3
7                             0          0  ...          0
8                             0          0  ...          0
9                             0          0  ...          0

Store                                                            \
Department                   d3
Shift               First Shift           Last Shift # of shift
0                             0                    0          0
1                             0                    0          0
2                             0                    0          0
3           2020-08-09 00:00:00  2020-08-12 00:00:00          2
4                             0                    0          0
5                             0                    0          0
6                             0                    0          0
7           2020-08-09 00:00:00  2020-08-12 00:00:00          2
8                             0                    0          0
9                             0                    0          0

Store                        s3                                  \
Department                   d1
Shift               First Shift           Last Shift # of shift
0                             0                    0          0
1                             0                    0          0
2                             0                    0          0
3                             0                    0          0
4                             0                    0          0
5                             0                    0          0
6                             0                    0          0
7                             0                    0          0
8           2020-08-08 00:00:00  2020-08-11 00:00:00          3
9                             0                    0          0

Store
Department                   d3
Shift               First Shift           Last Shift # of shift
0                             0                    0          0
1                             0                    0          0
2                             0                    0          0
3                             0                    0          0
4                             0                    0          0
5                             0                    0          0
6                             0                    0          0
7                             0                    0          0
8                             0                    0          0
9           2020-08-09 00:00:00  2020-08-12 00:00:00          2

[10 rows x 22 columns]

redpajama_set_name: RedPajamaStackExchange


text:
Q: Paginación de muchos resultados Estoy creando una aplicación con Laravel que se espera que muestre resultados de una tabla con varios miles de registros. El recordset será una paginación de la tabla. Se me plantean dos alternativas:
$libros = Book::paginate(50);

o
$libros = Book::get()->paginate(50);

Según he podido ver en Internet, la primera forma de paginación consume menos memoria. Parece ser que extrae directamente el recordset necesario, mientras que la segunda extrae toda la tabla y luego saca de ahí los datos necesarios para crear un recordset. Esto es así, o realmente da lo mismo, a efectos de no saturar la memoria del servidor?


text:
Q: WPF Listview Getting row values I have XAML File as below:
<Window x:Class="ComboBoxCheck.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:check="clr-namespace:ComboBoxCheck"
Title="Window1" Height="300" Width="320">
<Window.Resources>
    <ObjectDataProvider x:Name="Designation" MethodName="GetDesignations" ObjectType="{x:Type check:Window1}" x:Key="Designation" IsAsynchronous="True"/>
</Window.Resources>
<Grid>
    <Grid.RowDefinitions>
        <RowDefinition Height="*"/>
        <RowDefinition Height="30"/>
    </Grid.RowDefinitions>
    <ListView Grid.Row="0" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" Name="lsvStaffList"  Margin="0,0,0,3"
          BorderBrush="Transparent" BorderThickness="0">
        <ListView.View>
            <GridView>
                <GridViewColumn Header="Employee Id" Width="70" DisplayMemberBinding="{Binding Path=EmployeeId}"/>
                <GridViewColumn Header="Employee Name" Width="90" DisplayMemberBinding="{Binding Path=EmployeeName}"/>
                <GridViewColumn Header="Designation" Width="120">
                    <GridViewColumn.CellTemplate>
                        <DataTemplate>
                            <ComboBox Name="cmbDesignation" Height="20" Width="90" SelectedValue="{Binding Path=EmployeeDesignation}"
                                      ItemsSource="{Binding Source={StaticResource Designation}}"
                                      DisplayMemberPath="Name" SelectedValuePath="Id"
                                      VerticalAlignment="Top" HorizontalAlignment="Stretch"/>
                        </DataTemplate>
                    </GridViewColumn.CellTemplate>
                </GridViewColumn>
            </GridView>
        </ListView.View>
    </ListView>
    <Button Name="btnProperty" Width="75" Content="Get Value" Height="25" Click="btnProperty_Click" Grid.Row="1"/>
</Grid>

The code behind file is as below:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace ComboBoxCheck
{
public partial class Window1 : Window
{
    public static Designations designations = null;
    public Employees employees = null;

    public Window1()
    {
        InitializeComponent();

        designations = new Designations();
        employees = new Employees();

        Designation d1 = new Designation();
        d1.Id = 1;
        d1.Name = "Manager";
        designations.Add(d1);

        Designation d2 = new Designation();
        d2.Id = 2;
        d2.Name = "Developer";
        designations.Add(d2);

        Designation d3 = new Designation();
        d3.Id = 3;
        d3.Name = "Lead";
        designations.Add(d3);

        Employee e1 = new Employee();
        e1.EmployeeId = 1;
        e1.EmployeeName = "Name1";
        e1.EmployeeDesignation = 2;
        employees.Add(e1);

        Employee e2 = new Employee();
        e2.EmployeeId = 2;
        e2.EmployeeName = "Name2";
        e2.EmployeeDesignation = 2;
        employees.Add(e2);

        Employee e3 = new Employee();
        e3.EmployeeId = 3;
        e3.EmployeeName = "Name3";
        e3.EmployeeDesignation = 1;
        employees.Add(e3);

        lsvStaffList.ItemsSource = employees;

    }

    public static Designations GetDesignations()
    {
        return designations;
    }

    private void btnProperty_Click(object sender, RoutedEventArgs e)
    {
        //I need something like this
        //Employees employeesCollection = new Employees();
        //employeesCollection[0].EmployeeId = 1
        //employeesCollection[0].EmployeeName = Name1
        //employeesCollection[0].EmployeeDesignation = Developer

        //employeesCollection[1].EmployeeId = 2
        //employeesCollection[1].EmployeeName = Name2
        //employeesCollection[1].EmployeeDesignation = Developer

        //employeesCollection[2].EmployeeId = 3
        //employeesCollection[2].EmployeeName = Name3
        //employeesCollection[2].EmployeeDesignation = Manager
    }

}

public class Designations : List<Designation> {}

public class Designation
{
    private int id;

    public int Id
    {
        get { return id; }
        set { id = value; }
    }
    private string name;

    public string Name
    {
        get { return name; }
        set { name = value; }
    }

}

public class Employees : List<Employee> { }

public class Employee
{
    private int employeeid;

    public int EmployeeId
    {
        get { return employeeid; }
        set { employeeid = value; }
    }
    private string employeename;

    public string EmployeeName
    {
        get { return employeename; }
        set { employeename = value; }
    }
    private int employeedesignation;

    public int EmployeeDesignation
    {
        get { return employeedesignation; }
        set { employeedesignation = value; }
    }
}

}
I would like to get the employees collection which has employee name, employee id and employee designation. I need a code in the click event of 'Get Value' button and given the format.

A: Your bindings work fine.  Just get the Items collection of your ListView like this:
private void btnProperty_Click(object sender, RoutedEventArgs e)
{
    IEnumerable items = this.lsvStaffList.Items;
    foreach (Employee employee in items)
    {
        Console.WriteLine(employee.EmployeeId.ToString()
            + "," + employee.EmployeeName.ToString()
            + "," + employee.EmployeeDesignation.ToString());
    }
}

However, the EmployeeDesignation here is an int.  If you want to get the actual EmployeeDesignation instance, you can manually "query" it like this:
private void btnProperty_Click(object sender, RoutedEventArgs e)
{
    IEnumerable items = this.lsvStaffList.Items;
    foreach (Employee employee in items)
    {
        Designation d = designations.First(p => p.Id == employee.EmployeeDesignation);

        Console.WriteLine(employee.EmployeeId.ToString()
            + "," + employee.EmployeeName.ToString()
            + "," + d.Name);
    }
}


text:
Q: Python Turtle Graphics Keyboard Commands Anybody have any insight into controlling turtle graphics in python 2.7 with keyboard commands? I have done extensive research on this website and others and feel like I am doing the right thing but it just doesn't want to work for me. Below is what I have so far, can anyone tell me where I am going wrong????
from turtle import *
turtle.setup(500, 500)
wn = turtle.Screen()
wn.title("Turtle Keys")
move = turtle.Turtle()
showturtle()

def k1():
move.forward(45)

def k2():
move.left(45)

def k3():
move.right(45)

def k4():
move.back(45)

wn.onkey(k1, "Up")
wn.onkey(k2, "Left")
wn.onkey(k3, "Right")
wn.onkey(k4, "Down")

wn.listen()

A: When you specified import * you don't have to use turtle., also you have to use mainloop() read (infinite loop) to watch over user interactions, in your example wn is also unnecessary.
Here is the working code...
from turtle import *
setup(500, 500)
Screen()
title("Turtle Keys")
move = Turtle()
showturtle()

def k1():
    move.forward(45)

def k2():
    move.left(45)

def k3():
    move.right(45)

def k4():
    move.back(45)

onkey(k1, "Up")
onkey(k2, "Left")
onkey(k3, "Right")
onkey(k4, "Down")

listen()
mainloop()

A: import turtle

image = "C:/Python27/PythonProgramming/picture.gif"
screenr = turtle.Screen()

Lewi = turtle.Turtle()

screenr.addshape(image)
Lewi.shape(image)

Lewi.penup()

def up():
    Lewi.sety(Lewi.ycor()+10)

def down():
    Lewi.sety(Lewi.ycor()-10)

def left():
    Lewi.forward(-10)

def right():
    Lewi.forward(10)

screenr.onkey(up, "Up")
screenr.onkey(down, "Down")
screenr.onkey(right, "Right")
screenr.onkey(left, "Left")
screenr.listen()

turtle.mainloop()

I just recently came up with this. Hope it helps!

A: I found that with the code above and my example code, the keypresses were not registered until I clicked on the window. In my example, the turtle would move but the left/right action would not occur until I clicked on the window.
import turtle

def rightTurn():
   bob.rt(90)

def leftTurn():
   bob.lt(90)

wn=turtle.Screen()
wn.bgcolor('lightblue')

bob=turtle.Turtle()

wn.onkeypress(rightTurn, "Right")
wn.onkeypress(leftTurn, "Left")
wn.listen()

while True:
   bob.fd(1)

A: When you issue commands like this:
move = turtle.Turtle()
showturtle()

you're actually talking to two different turtles, your turtle object in 'move' and the default turtle.  Most of the screen and default turtle methods can be called without an explicit object as they are also top level functions.  To avoid confusion, I recommend you always import turtle this way:
from turtle import Turtle, Screen

and explicitly create your own turtle(s) and screen object.  This way you won't be able to call the alternative functiions and won't get confused.  Your example rewritten with the above in mind:
from turtle import Turtle, Screen

screen = Screen()

screen.setup(500, 500)
screen.title("Turtle Keys")

move = Turtle(shape="turtle")

def k1():
    move.forward(10)

def k2():
    move.left(45)

def k3():
    move.right(45)

def k4():
    move.backward(10)

screen.onkey(k1, "Up")
screen.onkey(k2, "Left")
screen.onkey(k3, "Right")
screen.onkey(k4, "Down")

screen.listen()

screen.exitonclick()


text:
Q: Low orbit space debris affects magnetic field? Theory reduce earth temperature by removing low orbit junk and consolidating needed satellites
With all the space junk in low orbit, we effect both earth's magnetic field by moving metals into the magnetic  field that are generated to protect from gamma Ray's the I creasing metal also reflects gamma  rays bouncing off the earths surface it's like wrapping the earth with Reynolds wrap and placing us in a space oven
We need so much more research into the planet and how to save it from ourselves.
This maybe crazy I am no scientist and have little experience with magnetic but if you apply Tesla's theory the metal in space make sense it will effect the natural defense our planet has.

A: No, space junk does not affect the earth's magnetic field.
I think your confusion stems from the image with the space junk, in which the junk seems to form a thick shell. In reality, the satellites and pieces of junk are extremely tiny compared to the earth, and they are separated by great distances. If a 10 cm piece of junk gets within 100 km of a satellite, people are worried as that is too close for comfort.
In addition, most of the space junk is made of non-magnetic materials like aluminium, stainless steel and titanium. Of course, as they travel through the earth's magnetic field, that will induce currents in them, but those currents are so small as to be completely negligible.
I'm not sure I understand your comments about gamma rays. They do not "bounce off the earth's surface"; instead, they penetrate the earth. They also penetrate the material of the spacecraft so, if anything, you could say that the junk reduces the gamma ray flux ever so slightly. Gamma rays are also not affected by magnetic fields, which affect only charged particles. As for Tesla, he had some good ideas (like AC power) as well as crazy ones that have been discredited. I don't know which of his theories you are talking about.


text:
Q: javascript with firebase Push method display values two or multiple times, in the chat page. whenever I go back page and come to chat page I am creating a simple chat page using firebase Whenever I go to back page from current page(Chat page) and coming back to chat page and sending a message "Hi" it is displaying two times in chat page, if I return back to another page and again come back to chat page and send message, it is showing 3 times same vice versa it is showing multiple times.
The bellow is my coding. Please some one guide me..
$(document).on('pagebeforeshow', '#chatpage', function() {

    var ref = new Firebase("https://firechatweb-60edc.firebaseio.com/6pzzmujf");
    $("#images6").empty();
    ActivityIndicator.show();
    ref.orderByChild("messages").on("child_added", function(snapshot) {

        $("#images6").append(movielist(snapshot.val()));

        var last_li = $("ul li:last-child").offset().top;

        //alert(last_li);
        setTimeout(function() {
            $.mobile.silentScroll(last_li);
        }, 50);

        //console.log(JSON.stringify(snapshot.key()) + " was " +JSON.stringify(snapshot.val()));
        ActivityIndicator.hide();

    });

});

function movielist(item) {
    //return "
"+item.text+"

";
    return "
" + item.text + "

";
}

$("#button").click(function() {

    //alert("Hi");
    var u = $.trim($("#uname").val());
    var p = $("#pwd").val();
    localStorage.setItem("locuname", u);
    localStorage.setItem("locpwd", p);

    var v = localStorage.getItem("locuname");
    var m = localStorage.getItem("locpwd");

    if (typeof(Storage) !== "undefined") {
        $.mobile.changePage("#chatpage", {
            transition: "slideup",
            changeHash: false
        });
    } else {
        // Sorry! No Web Storage support..
        console.log("Please Login");
    }

});

$("#send").click(function() {
    var mes = $("#message").val();
    if (mes.length == 0) {
        //alert("Please Enter Text");
        navigator.notification.alert(
            'Please Enter Text', // message
            alertDismissed, // callback
            'Text Message', // title
            'Done' // buttonName
        );

    } else {
        var v = localStorage.getItem("locuname");
        var ref = new Firebase("https://firechatweb-60edc.firebaseio.com/6pzzmujf");

        ref.push({
            name: v,
            text: mes,
            photoUrl: "/images/profile_placeholder.png"
        });

        $('#message').val('');

        var last_li = $("ul li:last-child").offset().top;
        setTimeout(function() {
            $.mobile.silentScroll(last_li);
        }, 50);

    }

});

function alertDismissed() {
    // do something
}

A: You're attaching a new listener each time the page is shown:
$(document).on('pagebeforeshow', '#chatpage', function() {
    var ref = new Firebase("https://firechatweb-60edc.firebaseio.com/6pzzmujf");
    $("#images6").empty();
    ActivityIndicator.show();
    ref.orderByChild("messages").on("child_added", function(snapshot) {

In this case you should also detach the listener when the page is being hidden:
$(document).on('pagebeforehide', '#chatpage', function() {
    var ref = new Firebase("https://firechatweb-60edc.firebaseio.com/6pzzmujf");
    $("#images6").empty();
    ActivityIndicator.show();
    ref.orderByChild("messages").off("child_added");


text:
Q: macros - multiple dotted lines with answer on the lines To make my lessons, I often use the \Pointilles macro that I've found here. I've built other macros based on this who allowed me to create two documents : my book and student's book. One of them is \ProfReponseLigne who used \Pointilles to make dotted lines if it is the student version or display the answer if it is the teacher one.
To make the two versions more coherent each other (vertical space and alignment), I want to keep the dotted lines produced by \Pointilles and displayed the answer on it. As suggested by this topic for exam.cls.
Question :

*

*How can I change my \ProfReponseLigne to display answer on the dotted lines with same vertical spacing ?

*Or is there another way to achieve the same goal ? (I know about \blank command but it's not dotted and I'm not able to make it usable out of solution environment.)

Goal :

*

*Keep the same vertical spacing and number of lines between the two versions.

MWE
Here is a compilable MWE and the definition of my macros I've got so far.
\documentclass[10pt,a4paper]{article}
\usepackage[utf8]{inputenc}
\usepackage{etoolbox}
\usepackage{multido}
\usepackage{lipsum}
\usepackage{xcolor}

%% Permet de différencier une version prof et une version élève
\newbool{studentversion}
\setbool{studentversion}{true}      %true for students' version

%% Extract from : https://tex.stackexchange.com/questions/248451/how-to-create-multiple-dotted-lines
\newcommand{\Pointilles}[2][3]%
{%
    \par\nobreak
    \noindent\rule{0pt}{1.5\baselineskip}       % Provides a larger gap between the preceding paragraph and the dots
    \multido{}{#2}{\noindent\makebox[\linewidth]{\rule{0pt}{#1\baselineskip}\dotfill}\\}    % ... dotted lines ...
    %           \medskip                                    % Gap between dots and next paragraph
}

\newcommand{\ProfReponseLigne}[2][1]%
{%
    \ifbool{studentversion}%
    {%%True (donc version pour étudiant)
        \Pointilles[1.5]{#1}
    }%
    {%%False (donc version pour prof)
        \par
        \textcolor{red}{$\rightarrow$ #2}\dotfill\vspace{\baselineskip}\\
    }
}
\begin{document}
\section{My lessons}
What a wonderful document to exploit :
\begin{quote}
    \itshape
    \lipsum[1]
\end{quote}
What can we conclude :
\ProfReponseLigne[2]{My very very very very very very very very very very very very long answer.}

\end{document}

Edit : For now, I'm testing some solution relied on \dotuline{} command provided by ulem package but I encountered some trouble when I'm calling this solution with \SI{}{} provided by siunitx package inside of the solution.

A: I remember an approach provided by the user gusbrs which is about using the facilities of the TikZ-package for drawing dashed-dotted underlines by means of the internal macros of the soul-package.
The user gusbrs published this approach as an answer to the question "Underlining words with dash-dotted line without affecting the other text in LaTeX".
Extempore I can only offer deriving a quick'n-dirty-workaround from this approach in terms of an environment FillInTheBlanksText.
That environment can be used for creating fill-in-the-blanks-texts. That environment takes an optional argument where you can specify the look of the fill-in-the-blanks-text via a comma-separated keyval-list.
More details are in the section "Documentation" of the example below.
Please don't overlook the "Watch out"-hints!
Be aware that I just wrote this piece of work impromptu.
Therefore: !!! No warranties - use at your own risk !!!
%% FillInTheBlanks.tex
%%
%% Copyright by Ulrich Diez (ud.usenetcorrespondence@web.de)
%% Date: April 08, 2020
%% License: LPPL
%% Format: LaTeX 2e
%% Documentclass: article
%% Required packages: soul, tikz, inputenc
%%
%% !!! No warranties - use at your own risk !!!
%%
\makeatletter
%------------------------------------------------------------------------------
% Code that could be moved to a newly to create LaTeX2e-package but currently
% is nested into a \makeatletter..\makeatother-pair---documentation/user-manual
% is below the code, in the section"Documentation":
%------------------------------------------------------------------------------
\RequirePackage{soul, tikz}%
\usetikzlibrary{calc}%
%------------------------------------------------------------------------------
% Define pgfkeys for
% - the style of the underlining
% - the color of the underlining
% - the color of the (underlined) text
% - the font used for (underlined) text
% - writing text only
% - drawing lines only
% - writing text and drawing lines
\pgfkeys{%
  /BlankToFill/Aboveskip/.initial=\parskip,
  /BlankToFill/Belowskip/.initial=\parskip,
  /BlankToFill/Linestyle/.initial=solid,
  /BlankToFill/Linecolor/.initial=black,
  /BlankToFill/Textcolor/.initial=blue,
  /BlankToFill/Textfontcommand/.initial=\fontsize{17}{23}\itshape,
  /BlankToFill/Whitespaceonly/.code=\underlinefalse\visiblelettersfalse,
  /BlankToFill/Whitespaceonly/.value forbidden,
  /BlankToFill/Textonly/.code=\underlinefalse\visibleletterstrue,
  /BlankToFill/Textonly/.value forbidden,
  /BlankToFill/Underlinesonly/.code=\underlinetrue\visiblelettersfalse,
  /BlankToFill/Underlinesonly/.value forbidden,
  /BlankToFill/Underlinedtext/.code=\underlinetrue\visibleletterstrue,
  /BlankToFill/Underlinedtext/.value forbidden,
  /BlankToFill/UnderlinedtextDefault/.style={/BlankToFill/Underlinedtext},
  /BlankToFillDefaults/Aboveskip/.code=\pgfkeys{%
    /BlankToFill/Aboveskip/.initial=#1,
  },
  /BlankToFillDefaults/Aboveskip/.value required,
  /BlankToFillDefaults/Belowskip/.code=\pgfkeys{%
    /BlankToFill/Belowskip/.initial=#1,
  },
  /BlankToFillDefaults/Belowskip/.value required,
  /BlankToFillDefaults/Linestyle/.code=\pgfkeys{%
    /BlankToFill/Linestyle/.initial=#1,
  },
  /BlankToFillDefaults/Linestyle/.value required,
  /BlankToFillDefaults/Linecolor/.code=\pgfkeys{%
    /BlankToFill/Linecolor/.initial=#1,
  },
  /BlankToFillDefaults/Linecolor/.value required,
  /BlankToFillDefaults/Textcolor/.code=\pgfkeys{%
    /BlankToFill/Textcolor/.initial=#1,
  },
  /BlankToFillDefaults/Textcolor/.value required,
  /BlankToFillDefaults/Textfontcommand/.code=\pgfkeys{%
    /BlankToFill/Textfontcommand/.initial=#1,%
  },
  /BlankToFillDefaults/Textfontcommand/.value required,
  /BlankToFillDefaults/Whitespaceonly/.code=\pgfkeys{%
    /BlankToFill/UnderlinedtextDefault/.style={/BlankToFill/Whitespaceonly},
  },
  /BlankToFillDefaults/Whitespaceonly/.value forbidden,
  /BlankToFillDefaults/Textonly/.code=\pgfkeys{%
    /BlankToFill/UnderlinedtextDefault/.style={/BlankToFill/Textonly},
  },
  /BlankToFillDefaults/Textonly/.value forbidden,
  /BlankToFillDefaults/Underlinesonly/.code=\pgfkeys{%
    /BlankToFill/UnderlinedtextDefault/.style={/BlankToFill/Underlinesonly},
  },
  /BlankToFillDefaults/Underlinesonly/.value forbidden,
  /BlankToFillDefaults/Underlinedtext/.code=\pgfkeys{%
    /BlankToFill/UnderlinedtextDefault/.style={/BlankToFill/Underlinedtext},
  },
  /BlankToFillDefaults/Underlinedtext/.value forbidden,
}%
\newcommand\SetFillInTheBlanksTextDefaults[1]{%
  \pgfkeys{/BlankToFillDefaults/.cd,#1,}%
}%
%------------------------------------------------------------------------------
% A command for drawing dashed lines from within soul-package via tikz-package:
%  The command \dotuline is derived/copied from the command \dashdotuline
%  which was written and published by the user "gusbrs"
%    (URL: <https://tex.stackexchange.com/users/105447/gusbrs>)
%  in her/his answer to the question "Underlining words with dash-dotted line
%  without affecting the other text in LaTeX
%    (URL: <https://tex.stackexchange.com/a/376364/118714>).
%------------------------------------------------------------------------------
\newlength\LineWidth
\setlength\LineWidth{0.7pt}%
\newlength\baseliney
\setlength\baseliney{-1.5pt}%
\newcommand\highlight@DoHighlight{%
    \expandafter\expandafter\expandafter\draw
    \expandafter\expandafter\expandafter[%
      \pgfkeysvalueof{/BlankToFill/Linestyle}, HLcolor,line width=\LineWidth,opacity=.5%
    ]%
    ($(begin highlight)+(0,\baseliney)$) -- ($(end highlight)+(0,\baseliney)$) ;
}%
\newcommand{\highlight@BeginHighlight}{%
    \coordinate (begin highlight) at (0,0) ;
}%
\newcommand{\highlight@EndHighlight}{%
    \coordinate (end highlight) at (0,0) ;
}%
\newdimen\highlight@previous
\newdimen\highlight@current
\DeclareRobustCommand*\dashdotuline[1][]{%
    \tikzset{this highlighter/.style={#1}}%
    \SOUL@setup
    %
    \def\SOUL@preamble{%
        \begin{tikzpicture}[overlay, remember picture]%
        \highlight@BeginHighlight
        \highlight@EndHighlight
        \end{tikzpicture}%
    }%
    %
    \def\SOUL@postamble{%
        \begin{tikzpicture}[overlay, remember picture]%
        \highlight@EndHighlight
        \highlight@DoHighlight
        \end{tikzpicture}%
    }%
    %
    \def\SOUL@everyhyphen{%
        \discretionary{%
            \SOUL@setkern\SOUL@hyphkern
            \ifvisibleletters\SOUL@sethyphenchar\else\phantom{\SOUL@sethyphenchar}\fi
            \tikz[overlay, remember picture] \highlight@EndHighlight ;%
        }{}{\SOUL@setkern\SOUL@charkern}%
    }%
    %
    \def\SOUL@everyexhyphen##1{%
        \SOUL@setkern\SOUL@hyphkern
        \ifvisibleletters\hbox{##1}\else\phantom{\hbox{##1}}\fi
        \discretionary{%
            \tikz[overlay, remember picture] \highlight@EndHighlight ;%
        }{}{\SOUL@setkern\SOUL@charkern}%
    }%
    %
    \def\SOUL@everysyllable{%
        \begin{tikzpicture}[overlay, remember picture]
        \path let \p0 = (begin highlight), \p1 = (0,0) in \pgfextra
        \global\highlight@previous=\y0
        \global\highlight@current =\y1
        \endpgfextra (0,0) ;
        \ifdim\highlight@current < \highlight@previous
        \highlight@DoHighlight
        \highlight@BeginHighlight
        \fi
        \end{tikzpicture}%
        \ifvisibleletters\the\SOUL@syllable\else\phantom{\the\SOUL@syllable}\fi
        \tikz[overlay, remember picture] \highlight@EndHighlight ;%
    }%
    %
    \ifvisibleletters\else
      \def\SOUL@underline##1{{%
        \setbox\z@\hbox{\phantom{##1}}%
        \dimen@=\wd\z@
        \dimen@i=\SOUL@uloverlap
        \advance\dimen@2\dimen@i
        \rlap{%
          \null
          \kern-\dimen@i
          \SOUL@ulcolor{\SOUL@ulleaders\hskip\dimen@}%
        }%
        \unhcopy\z@
      }}%
    \fi
    \SOUL@
}%
%------------------------------------------------------------------------------
\newif\ifunderline\underlinefalse
\newif\ifvisibleletters\visibleletterstrue
\newcommand\UD@PassFirstToSecond[2]{#2{#1}}%
\newenvironment{FillInTheBlanksText}[1][]{%
  \newcommand\BlankToFill[1]{%
    \begingroup
    \ifunderline
      \expandafter\expandafter\expandafter\UD@PassFirstToSecond
      \expandafter\expandafter\expandafter{%
        \pgfkeysvalueof{/BlankToFill/Linecolor}%
      }{\colorlet{HLcolor}}%
    \else
      \colorlet{HLcolor}{white}%
    \fi
    \ifvisibleletters
      \expandafter\expandafter\expandafter\color
      \expandafter\expandafter\expandafter{%
        \pgfkeysvalueof{/BlankToFill/Textcolor}%
      }%
    \fi
    \pgfkeysvalueof{/BlankToFill/Textfontcommand}%
    \selectfont
    \dashdotuline{##1}%
    \endgroup
  }%
  \par
  \pgfkeys{/BlankToFill/.cd,UnderlinedtextDefault,#1}%
  {%
    \pgfkeysvalueof{/BlankToFill/Textfontcommand}%
    \selectfont
    \vspace{-\parskip}%
    \vspace{-\dp\strutbox}%
    \vspace{-\lineskip}%
    \vspace{\pgfkeysvalueof{/BlankToFill/Aboveskip}}%
    \edef\@tempa{%
      \baselineskip=\the\baselineskip
      \def\noexpand\baselinestretch{\baselinestretch}%
    }%
  \expandafter}\@tempa\selectfont
  \ignorespaces
}{%
  \par\vspace{-\parskip}%
  {%
    \pgfkeysvalueof{/BlankToFill/Textfontcommand}%
    \selectfont
    \vspace{\pgfkeysvalueof{/BlankToFill/Belowskip}}%
  }%
}%
%------------------------------------------------------------------------------
% Documentation:
%
% There is an environment whose name is FillInTheBlanksText .
%
% That environment is intended to provide a scope where you can
% write a fill-in-the-blanks-text.
%
% That environment takes an optional argument where you can
% specify the look of the fill-in-the-blanks-text via a
% comma-separated keyval-list:
%
% ---------------+-------------------------+-----------------------------------
% Key:           |Default-Value:           |Purpose:
% ----           |--------------           |--------
% ---------------+-------------------------+-----------------------------------
% Linestyle      |solid                    |The style of the underlines.
%                |                         |Possible values:
%                |                         |solid, dotted, densely dotted,
%                |                         |loosely dotted, dashed,
%                |                         |densely dashed, loosely dashed,
%                |                         |dash dot, densely dash dot,
%                |                         |loosely dash dot, dash dot dot,
%                |                         |densely dash dot dot,
%                |                         |loosely dash dot dot
% ---------------+-------------------------+-----------------------------------
% Linecolor      |black                    |The color of the underlines.
%                |                         |Possible values:
%                |                         |All definded colors.(See manual of
%                |                         |tikz-package/xxcolor)
% ---------------+-------------------------+-----------------------------------
% Textfontcommand|\fontsize{17}{23}\itshape|The font for the fill-in-the-
%                |                         |blanks-texts.
% ---------------+-------------------------+-----------------------------------
% Textcolor      |blue                     |The color of the fill-in-the-
%                |                         |blanks-texts.
%                |                         |Possible values:
%                |                         |All definded colors.(See manual of
%                |                         |tikz-package/xxcolor)
% ---------------+-------------------------+-----------------------------------
% Aboveskip      |\parskip                 |The vertical distance between the
%                |                         |bottomline (not baseline) of the
%                |                         |box which forms the last line of
%                |                         |text above the environment and the
%                |                         |topline (not baseline) of the
%                |                         |first line of the environment.
%                |                         |Possible values:
%                |                         |A length. If you use \baselineskip
%                |                         |or \parskip or the like, things
%                |                         |will be calculated with the font in
%                |                         |use for writing the fill-in-the-
%                |                         |blanks-text.
% ---------------+-------------------------+-----------------------------------
% Belowskip      |\parskip                 |The vertical distance between the
%                |                         |bottomline (not baseline) of the
%                |                         |last line of the environment and
%                |                         |the topline (not baseline) of the
%                |                         |box which forms the first line of
%                |                         |text below the environment.
%                |                         |Possible values:
%                |                         |A length. If you use \baselineskip
%                |                         |or \parskip or the like, things
%                |                         |will be calculated with the font in
%                |                         |use for writing the fill-in-the-
%                |                         |blanks-text.
% ---------------+-------------------------+-----------------------------------
% Textonly       |[none]                   |Print only the texts.
%                |                         |Possible values: None.
% ---------------+-------------------------+-----------------------------------
% Underlinesonly |[none]                   |Print only the underlines.
%                |                         |Possible values: None.
% ---------------+-------------------------+-----------------------------------
% Underlinedtext |[none]                   |Print both texts and underlines.
%                |                         |Possible values: None.
% ---------------+-------------------------+-----------------------------------
% Whitespaceonly |[none]                   |Prints neither texts nor underli-
%                |                         |nes. You just get white gaps.
%                |                         |Possible values: None.
% ---------------+-------------------------+-----------------------------------
%
% Within that environment a command \BlankToFill is defined.
%
% That command takes a mandatory argument denoting a phrase of text.
%
% \BlankToFill will process that phrase of text according to the settings
% provisionable in the optional argument of the FillInTheBlanksText-
% environment.
%
% Within the environment all lines of text will have a distance according to
% the Textfontcommand/\fontsize-command specified.
%
% There is also the command
%
%     \SetFillInTheBlanksTextDefaults{<key-value-list>}
%
% It serves the purpose of specifying global defaults for the
% FillInTheBlanksText-environment so that you only need to specify an
% optional argument for the FillInTheBlanksText-environment when deviating
% from the defaults.
%
% This way you can, e.g., toggle the defaults in the preamble of your
% document for specifying whether to create a document with underlines
% only or with text also.
%
% The command \begin{FillInTheBlanksText} ends the paragraph LaTeX is about to
% produce when encountering that command.
%
% The command \end{FillInTheBlanksText} ends the paragraph LaTeX is about to
% produce when encountering that command.
%
% !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
% Watch out 1:
% ============
%
% As things provided by the TikZ-package are used for drawing the underlines,
% you need to compile the document at least twice (without deleting auxiliary-
% files between compilations!) until everything matches out. After each
% compilation the .log-file will contain a hint in case another compilation is
% needed.
%
% Watch out 2:
% ============
%
% As the text of the blanks to fill in is produced by means of mechanisms of
% the soul package, all restrictions that apply to text that is to be processed
% by macros of the soul-package apply to the argument of \BlankToFill also.
%
% Watch out 3:
% ============
%
% Be aware that I just wrote this piece of work impromptu.
%
% Therefore: !!! No warranties - use at your own risk !!!
% !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
%------------------------------------------------------------------------------
% End of code that could be moved to a newly to create LaTeX2e-package
\makeatother
%
% Code exhibiting the usage:
%
\documentclass[a4paper]{article}
\usepackage[latin1]{inputenc}

\hyphenation{ph-r-a-se}
\setlength{\parindent}{0pt}
\parskip=\baselineskip

\SetFillInTheBlanksTextDefaults{%
  Linestyle=densely dotted,
  Linecolor=black,
  Textcolor=blue,
  Textfontcommand=\fontsize{17}{23}\itshape,
  Underlinedtext,
  Aboveskip=\dimexpr\baselineskip-\dp\strutbox,
  Belowskip=\dimexpr\baselineskip-\dp\strutbox,
}

\begin{document}

%----------- Key Underlinesonly ---------------------------------------

\vspace{-\ht\strutbox}
\noindent\null\cleaders\hrule height 1.2pt\hfill\null
\vspace{-\dp\strutbox}

Key in use with environment \verb|FillInTheBlanksText|:
\verb|Underlinesonly|

\vspace{-\ht\strutbox}
\noindent\null\cleaders\hrule height 1.2pt\hfill\null
\vspace{-\dp\strutbox}

This is not part of a FillInTheBlanksText-environment.
This is not part of a FillInTheBlanksText-environment.
This is not part of a FillInTheBlanksText-environment.
This is not part of a FillInTheBlanksText-environment.
\begin{FillInTheBlanksText}[Underlinesonly]
Text. \BlankToFill{%
  This phrase is part of the blank to fill---%
  abcdefghijklmnopqrstuvwxyzäöüß.%
}
This phrase is not part of a blank to fill.
This phrase is not part of a blank to fill.
\BlankToFill{%
  This phrase is part of the blank to fill---%
  abcdefghijklmnopqrstuvwxyzäöüß.%
}
This phrase is not part of a blank to fill.
This phrase is not part of a blank to fill.
\BlankToFill{%
  This phrase is part of the blank to fill---%
  abcdefghijklmnopqrstuvwxyzäöüß.%
}
Text.
\end{FillInTheBlanksText}
This is not part of a FillInTheBlanksText-environment.
This is not part of a FillInTheBlanksText-environment.
This is not part of a FillInTheBlanksText-environment.
This is not part of a FillInTheBlanksText-environment.

\vspace{-\ht\strutbox}
\noindent\null\cleaders\hrule height 1.2pt\hfill\null
\vspace{-\dp\strutbox}

\textbf{Provide a pattern for all primitive pythagorean triples
\(x^2+y^2=z^2\), \(2\mid x\), \(x>0\), \(y>0\), \(z>0\):}
\begin{FillInTheBlanksText}[Textfontcommand=\fontsize{17}{23}, Underlinesonly]
\BlankToFill{%
  \mbox{\makebox[\textwidth][l]{\hfill $x=2st$,\hfill}}\\
  \mbox{\makebox[\textwidth][l]{\hfill $y=s^2-t^2$,\hfill}}\\
  \mbox{\makebox[\textwidth][l]{\hfill $z=s^2+t^2$,\hfill}}\\
  \mbox{\makebox[\textwidth][l]{%
   \hfill $s>t>0, \textrm{gcd}(s,t)=1, s\not\equiv t (\textrm{mod }2)$\hfill
  }}%
}%
\end{FillInTheBlanksText}

\vspace{-\ht\strutbox}
\noindent\null\cleaders\hrule height 1.2pt\hfill\null
\vspace{-\dp\strutbox}

\newpage %----------- Key Underlinedtext (default)-------------------------------

\vspace{-\ht\strutbox}
\noindent\null\cleaders\hrule height 1.2pt\hfill\null
\vspace{-\dp\strutbox}

Key in use with environment \verb|FillInTheBlanksText|:
\verb|Underlinedtext|

\vspace{-\ht\strutbox}
\noindent\null\cleaders\hrule height 1.2pt\hfill\null
\vspace{-\dp\strutbox}

This is not part of a FillInTheBlanksText-environment.
This is not part of a FillInTheBlanksText-environment.
This is not part of a FillInTheBlanksText-environment.
This is not part of a FillInTheBlanksText-environment.
\begin{FillInTheBlanksText}
Text. \BlankToFill{%
  This phrase is part of the blank to fill---%
  abcdefghijklmnopqrstuvwxyzäöüß.%
}
This phrase is not part of a blank to fill.
This phrase is not part of a blank to fill.
\BlankToFill{%
  This phrase is part of the blank to fill---%
  abcdefghijklmnopqrstuvwxyzäöüß.%
}
This phrase is not part of a blank to fill.
This phrase is not part of a blank to fill.
\BlankToFill{%
  This phrase is part of the blank to fill---%
  abcdefghijklmnopqrstuvwxyzäöüß.%
}
Text.
\end{FillInTheBlanksText}
This is not part of a FillInTheBlanksText-environment.
This is not part of a FillInTheBlanksText-environment.
This is not part of a FillInTheBlanksText-environment.
This is not part of a FillInTheBlanksText-environment.

\vspace{-\ht\strutbox}
\noindent\null\cleaders\hrule height 1.2pt\hfill\null
\vspace{-\dp\strutbox}

\textbf{Provide a pattern for all primitive pythagorean triples
\(x^2+y^2=z^2\), \(2\mid x\), \(x>0\), \(y>0\), \(z>0\):}
\begin{FillInTheBlanksText}[Textfontcommand=\fontsize{17}{23}]
\BlankToFill{%
  \mbox{\makebox[\textwidth][l]{\hfill $x=2st$,\hfill}}\\
  \mbox{\makebox[\textwidth][l]{\hfill $y=s^2-t^2$,\hfill}}\\
  \mbox{\makebox[\textwidth][l]{\hfill $z=s^2+t^2$,\hfill}}\\
  \mbox{\makebox[\textwidth][l]{%
   \hfill $s>t>0, \textrm{gcd}(s,t)=1, s\not\equiv t (\textrm{mod }2)$\hfill
  }}%
}%
\end{FillInTheBlanksText}

\vspace{-\ht\strutbox}
\noindent\null\cleaders\hrule height 1.2pt\hfill\null
\vspace{-\dp\strutbox}

\newpage %----------- Key Textonly ---------------------------------------

\vspace{-\ht\strutbox}
\noindent\null\cleaders\hrule height 1.2pt\hfill\null
\vspace{-\dp\strutbox}

Key in use with environment \verb|FillInTheBlanksText|:
\verb|Textonly|

\vspace{-\ht\strutbox}
\noindent\null\cleaders\hrule height 1.2pt\hfill\null
\vspace{-\dp\strutbox}

This is not part of a FillInTheBlanksText-environment.
This is not part of a FillInTheBlanksText-environment.
This is not part of a FillInTheBlanksText-environment.
This is not part of a FillInTheBlanksText-environment.
\begin{FillInTheBlanksText}[Textonly]
Text. \BlankToFill{%
  This phrase is part of the blank to fill---%
  abcdefghijklmnopqrstuvwxyzäöüß.%
}
This phrase is not part of a blank to fill.
This phrase is not part of a blank to fill.
\BlankToFill{%
  This phrase is part of the blank to fill---%
  abcdefghijklmnopqrstuvwxyzäöüß.%
}
This phrase is not part of a blank to fill.
This phrase is not part of a blank to fill.
\BlankToFill{%
  This phrase is part of the blank to fill---%
  abcdefghijklmnopqrstuvwxyzäöüß.%
}
Text.
\end{FillInTheBlanksText}
This is not part of a FillInTheBlanksText-environment.
This is not part of a FillInTheBlanksText-environment.
This is not part of a FillInTheBlanksText-environment.
This is not part of a FillInTheBlanksText-environment.

\vspace{-\ht\strutbox}
\noindent\null\cleaders\hrule height 1.2pt\hfill\null
\vspace{-\dp\strutbox}

\textbf{Provide a pattern for all primitive pythagorean triples
\(x^2+y^2=z^2\), \(2\mid x\), \(x>0\), \(y>0\), \(z>0\):}
\begin{FillInTheBlanksText}[Textfontcommand=\fontsize{17}{23}, Textonly]
\BlankToFill{%
  \mbox{\makebox[\textwidth][l]{\hfill $x=2st$,\hfill}}\\
  \mbox{\makebox[\textwidth][l]{\hfill $y=s^2-t^2$,\hfill}}\\
  \mbox{\makebox[\textwidth][l]{\hfill $z=s^2+t^2$,\hfill}}\\
  \mbox{\makebox[\textwidth][l]{%
   \hfill $s>t>0, \textrm{gcd}(s,t)=1, s\not\equiv t (\textrm{mod }2)$\hfill
  }}%
}%
\end{FillInTheBlanksText}

\vspace{-\ht\strutbox}
\noindent\null\cleaders\hrule height 1.2pt\hfill\null
\vspace{-\dp\strutbox}

\newpage %----------- Key Whitespaceonly ---------------------------------

\vspace{-\ht\strutbox}
\noindent\null\cleaders\hrule height 1.2pt\hfill\null
\vspace{-\dp\strutbox}

Key in use with environment \verb|FillInTheBlanksText|:
\verb|Whitespaceonly|

\vspace{-\ht\strutbox}
\noindent\null\cleaders\hrule height 1.2pt\hfill\null
\vspace{-\dp\strutbox}

This is not part of a FillInTheBlanksText-environment.
This is not part of a FillInTheBlanksText-environment.
This is not part of a FillInTheBlanksText-environment.
This is not part of a FillInTheBlanksText-environment.
\begin{FillInTheBlanksText}[Whitespaceonly]
Text. \BlankToFill{%
  This phrase is part of the blank to fill---%
  abcdefghijklmnopqrstuvwxyzäöüß.%
}
This phrase is not part of a blank to fill.
This phrase is not part of a blank to fill.
\BlankToFill{%
  This phrase is part of the blank to fill---%
  abcdefghijklmnopqrstuvwxyzäöüß.%
}
This phrase is not part of a blank to fill.
This phrase is not part of a blank to fill.
\BlankToFill{%
  This phrase is part of the blank to fill---%
  abcdefghijklmnopqrstuvwxyzäöüß.%
}
Text.
\end{FillInTheBlanksText}
This is not part of a FillInTheBlanksText-environment.
This is not part of a FillInTheBlanksText-environment.
This is not part of a FillInTheBlanksText-environment.
This is not part of a FillInTheBlanksText-environment.

\vspace{-\ht\strutbox}
\noindent\null\cleaders\hrule height 1.2pt\hfill\null
\vspace{-\dp\strutbox}

\textbf{Provide a pattern for all primitive pythagorean triples
\(x^2+y^2=z^2\), \(2\mid x\), \(x>0\), \(y>0\), \(z>0\):}
\begin{FillInTheBlanksText}[Textfontcommand=\fontsize{17}{23}, Whitespaceonly]
\BlankToFill{%
  \mbox{\makebox[\textwidth][l]{\hfill $x=2st$,\hfill}}\\
  \mbox{\makebox[\textwidth][l]{\hfill $y=s^2-t^2$,\hfill}}\\
  \mbox{\makebox[\textwidth][l]{\hfill $z=s^2+t^2$,\hfill}}\\
  \mbox{\makebox[\textwidth][l]{%
   \hfill $s>t>0, \textrm{gcd}(s,t)=1, s\not\equiv t (\textrm{mod }2)$\hfill
  }}%
}%
\end{FillInTheBlanksText}

\vspace{-\ht\strutbox}
\noindent\null\cleaders\hrule height 1.2pt\hfill\null
\vspace{-\dp\strutbox}

\end{document}

In the .pdf-file that results from compiling the example, you can check the position of elements as follows:

*

*Zoom the height of the page to fit the height of the window where the .pdf-file is displayed.

*Set the viewing-mode to "single page" and "non-continuous".

*Now you can play "virtual flipbook" by scrolling between pages:
Some elements should vanish/pop up, but none of the elements should be shifted vertically/horizontally.


text:
Q: Numerical Integral of a "Complicated" Function I am trying to calculate the numerical integral of a 4D function, but NIntegrate keeps saying that is not able to perform a good estimate.
My function comes from an exponential of four derivatives of something else so it is a "big" chunck (around 3 lines), but it is not oscillatory, it does not have divergences and the final value cannot be zero because it is always positive. It actually looks more or less like a 4D Gaussian.
The function is:
L[a_,c_,w_,u_]=    Exp[
  -(Y[1] - f[X[1], a, c, w, u])^2/(2*0.005^2) - (Y[2] - f[X[2], a, c, w, u])^2/(2*0.005^2)
  -(Y[3] - f[X[3], a, c, w, u])^2/(2*0.005^2) - (Y[4] - f[X[4], a, c, w, u])^2/(2*0.005^2)
    ]

where:
X={0.266667, 0.5, 1, 1.16667}
Y={0.867, 0.596, 0.0689, -0.00554}

and f[q,a,c,w,u] is given by:
f[q_,a_,c_,w_,u_]=(1/(c (c^2 + a^2 π^2) q)
   3 a π Csch[a π q] (c Cos[
      c q] (-1 - c^4 u - 5 a^4 π^4 u +
       c^2 (10 a^2 π^2 u - w) + 3 a^2 π^2 w +
       2 a^2 π^2 Csch[a π q]^2 (10 (c^2 - 5 a^2 π^2) u + 3 w -
          60 a^2 π^2 u Csch[a π q]^2)) +
    a π Coth[a π q] (1 + 5 c^4 u + a^4 π^4 u - a^2 π^2 w +
       c^2 (-10 a^2 π^2 u + 3 w) +
       6 a^2 π^2 Csch[a π q]^2 (-10 (c - a π) (c + a π) u - w +
          20 a^2 π^2 u Csch[a π q]^2)) Sin[c q]))/1.653

In theory I am interested in the integral from -infinity to infinity of the four parameters a,c,w,u. But I know that most of the time the function is zero, so it will be enough to integrate {a, 0.5,0.7}, {c, 3.05, 3.25}, {w, 0.02, 0.2}, {u, -0.003,-0.0001}.
I have tried with the automatic configurations for NIntegrate and it says:

NIntegrate::eincr: The global error of the strategy GlobalAdaptive has increased more
  than 2000 times. The global error is expected to decrease
  monotonically after a number of integrand evaluations. Suspect one of
  the following: the working precision is insufficient for the
  specified precision goal; the integrand is highly oscillatory or it
  is not a (piecewise) smooth function; or the true value of the
  integral is 0. Increasing the value of the GlobalAdaptive option
  MaxErrorIncreases might lead to a convergent numerical integration.
  NIntegrate obtained 6.0484948162078716`*^-9 and
  1.3350642633041837`*^-12 for the integral and error estimates.

Do you know a better NIntegrate strategy for my problem? I was thinking of replacing my function by an approximate interpolating function, but I don't know if this is the best I can do. I have tried MonteCarlo methods but after increasing the Iterations until it finally says it converges, the results changes by 10% if you try the command again.

A: The general rule with multivariate integrals should be, to do as much integration as you can analytically.
Here the u und w integration can be done analytically and then the remaining two-dimensional numerical integration is better to do.
For analytical integration it is better to rationalize the functions
X = Rationalize[{0.266667, 0.5, 1, 1.16667}, 0]
Y = Rationalize[{0.867, 0.596, 0.0689, -0.00554}, 0]

f[q_, a_, c_, w_, u_] = (1/(c (c^2 + a^2 \[Pi]^2) q) 3 a \[Pi] Csch[
  a \[Pi] q] (c Cos[
     c q] (-1 - c^4 u - 5 a^4 \[Pi]^4 u +
      c^2 (10 a^2 \[Pi]^2 u - w) + 3 a^2 \[Pi]^2 w +
      2 a^2 \[Pi]^2 Csch[
         a \[Pi] q]^2 (10 (c^2 - 5 a^2 \[Pi]^2) u + 3 w -
         60 a^2 \[Pi]^2 u Csch[a \[Pi] q]^2)) +
   a \[Pi] Coth[
     a \[Pi] q] (1 + 5 c^4 u + a^4 \[Pi]^4 u - a^2 \[Pi]^2 w +
      c^2 (-10 a^2 \[Pi]^2 u + 3 w) +
      6 a^2 \[Pi]^2 Csch[
         a \[Pi] q]^2 (-10 (c - a \[Pi]) (c + a \[Pi]) u - w +
         20 a^2 \[Pi]^2 u Csch[a \[Pi] q]^2)) Sin[c q]))/(1653/
 1000) // Simplify

L[a_, c_, w_, u_] =
   Simplify[Rationalize[
    Exp[-(Y[[1]] - f[X[[1]], a, c, w, u])^2/(2*0.005^2) - (Y[[2]] -
     f[X[[2]], a, c, w, u])^2/(2*0.005^2) - (Y[[3]] -
     f[X[[3]], a, c, w, u])^2/(2*0.005^2) - (Y[[4]] -
     f[X[[4]], a, c, w, u])^2/(2*0.005^2)], 0],
   Assumptions -> {a, c, w, u} \[Element] Reals]

L is of the form Exp[L[a,c,w,u][[2]]] and can be writen as Exp[r + s u + t u^2]
Calculate the coefficients r,s,t
cl = CoefficientList[Collect[L[a, c, w, u][[2]], u], u]

(*  A very large output was generated ...   *)

cl // Length

(*  3   *)

rule1 = Thread[{r, s, t} ->
  Simplify[cl, Assumptions -> {a, c, w, u} \[Element] Reals]];

The integration over u can be done easily.
According to graphical tests t is assumed to be t<0, although no deep proof is done here.
 int11 = Integrate[Exp[r + s u + t u^2], {u, -\[Infinity], \[Infinity]},
    Assumptions -> t < 0]

 (*  (E^(r - s^2/(4 t)) Sqrt[\[Pi]])/Sqrt[-t]    *)

Nearly the same can be done with the w-integration
 exp2 = int11 /. rule1;

 exp2 // Length

 (*  4   *)

 exp2 == exp2[[1]]*Exp[exp2[[2, 2]]]*exp2[[3]]*exp2[[4]] // Simplify

 (*   True   *)

 fac = exp2[[1]]*exp2[[3]]*exp2[[4]];

Fortunately fac does not depend on w
 clw = Simplify[CoefficientList[exp2[[2, 2]], w],
    Assumptions -> {a, c, w} \[Element] Reals]

 (*  A very large output was generated ...   *)

 clw // Length
 (*  3  *)

 rule2 = Thread[{o, p, q} -> clw];

 int12 = Integrate[
   fact*Exp[o + p*w + q*w^2], {w, -\[Infinity], \[Infinity]},
     Assumptions -> q < 0]

 (*    (E^(o - p^2/(4 q)) fact Sqrt[\[Pi]])/Sqrt[-q]   *)

 fact = Simplify[fac, Assumptions -> {a, c} \[Element] Reals];

Finaly you get the integrand for the twodimensional numerical integration
 integrand[a_, c_] = int12 /. rule2

Since this integrand has a few thousands of terms, it takes quite a long time to calculate. And it is very sensitive to input. MachinePrecision is not enough here. Examples:
 N[integrand[4/10, 1/2], 3]

 (*   0.0000400 + 0.*10^-8 I    *)

 N[integrand[3/10, 1/2], 3] // Timing

 (*    {2.688, 7.78*10^-38 + 0.*10^-41 I}    *)

Calculate an array of the integrand in order to get a rough overview where to integrate
 (tab4 = Table[{a, c, N[integrand[a, c], 3]}, {a, 1/40, 4, 1/20}, {c,
  1/10, 20, 2/10}];) // Timing

  ListPlot3D[Flatten[Re[tab4], 1], PlotRange -> All,
    AxesLabel -> {a, c, integrand}]

But attention, this and the following integration takes several hours (I aborted therefore)
 int1 = NIntegrate[integrand[a, c], {a, 0, 1}, {c, 0, 5},
    Method -> {"MultidimensionalRule", "Generators" -> 9},
      MaxRecursion -> 100, WorkingPrecision -> 45]

A: If the only thing you need is the value of this integral, I would try to use Monte Carlo integration by using Mathematica for generation of random input, evaluation of your function and averaging results. If you are not familiar with this technique, please see simple explanation on the Internet, for example, a good review with illustrations in https://www.cs.dartmouth.edu/~wjarosz/publications/dissertation/appendixA.pdf.
You may also look at presentation in  http://www.cs.utah.edu/~edwards/research/mcIntegration.pdf.
Monte Carlo method is one of the most popular when it comes to computation of multi-dimensional integral. Nick L.


text:
Q: Liquid analog of the Black Hole (Part 2) Similar question has been asked but did no get good answers.
We know that black hole can confine light, but can we create an ocean black hole -
which can confine surface water waves or sound waves in water?
Definition:

*

*What is a static water flow which can CONFINE water waves?

*Is there a configuration confining only surface waves?

*Is there a configuration confining volume waves?

Description:
Inside a confined region any water density perturbations can not propagate outside.
PS:

*

*Overall volume of water in the "tank" can not change so the solution
when the water is removed faster then the waves travel is ruled out.

*There possibly can be additional objects presented in the water
"tank".

*It can be some unsual liquid or gas, whith additional "new"
properties.

Thanks for your answers.

A: A quick run of "black hole analog" through google produces a number of hits about creating black hole analogues on Bose-Einstein condensates manipulated with light. The analogy is of course not exact but the propagation does exhibit an event horizon, with atomic currents faster than the local speed of sound, strong enough that an analogue of Hawking radiation can hopefully be detected. These analogues have been detected experimentally; for a more accessible  resource try this article.
This might sound at odds to your question, but there is no removal of the fluid, whilst the fluid involved is certainly "new" and "unusual".


text:
Q: Sort String of Characters Using Hashed Array and Java 8 Streams I stumble upon this cool sorting algorithm with O(n) time complexity on GeeksforGeeks - Sort string of characters and I was trying to refactor the code to use Java Streams on the nested for loops instead and collect the result in a string variable but I can't seem to wrap my head around it.
Here's the original code:
// Java program to sort
// a string of characters
public class SortString{
    static final int MAX_CHAR = 26;

    // function to print string in sorted order
    static void sortString(String str) {

        // Hash array to keep count of characters.
        int letters[] = new int[MAX_CHAR];

        // Traverse string and increment
        // count of characters
        for (char x : str.toCharArray()) {

            // 'a'-'a' will be 0, 'b'-'a' will be 1,
            // so for location of character in count
            // array we will do str[i]-'a'.
            letters[x - 'a']++;
        }

        // HOW TO CONVERT THIS TO JAVA STREAM?
        // Traverse the hash array and print
        // characters
        for (int i = 0; i < MAX_CHAR; i++) {
            for (int j = 0; j < letters[i]; j++) {
                System.out.print((char) (i + 'a'));
            }
        }
    }

    // Driver program to test above function
    public static void main(String[] args) {
        sortString("geeksforgeeks");
    }
}
// This code is contributed
// by Sinuhe

A: We can sort the given string, which is expected to contain only lower case English letters, in O(n) time with streams only (without using a precalculated array) by making use of the LinkedHashMap, which would be used internally inside the collector.
We can create a custom collector which will accumulate stream elements into a LinkedHashMap by using static method Collector.of(). After processing the whole string, a LinkedHashMap will contain a frequency of every lower case English letter in the given string and finisher function of the collector will turn this map into the resulting string.
public static void main(String[] args) {
    String str = "aewwawaeaea";

    String result = str.chars()
        .boxed()
        .collect(Collector.of(
            () -> IntStream.rangeClosed('a', 'z')
                .collect(LinkedHashMap::new, (map, next) -> map.put(next, 0), LinkedHashMap::putAll),
            (LinkedHashMap<Integer, Integer> map, Integer next) -> map.merge(next, 1, Integer::sum),
            (left, right) -> {
                right.forEach((k, v) -> left.merge(k, v, Integer::sum));
                return left;
            },
            map -> map.entrySet().stream()
                .map(entry -> Character.toString(entry.getKey()).repeat(entry.getValue()))
                .collect(Collectors.joining())
        ));

    System.out.println(result);
}

Output:
aaaaaeeewww

As it has been suggested by @Holger in the comments, we can build a collector on based on the int array of 26 elements.
The collector is more concise and performant than the previous one:
public static void main(String[] args) {
    String str = "aewwawaeaea";
    String result = str.chars()
        .boxed()
        .collect(Collector.of(
            () -> new int['z' - 'a' + 1],
            (int[] arr, Integer next) -> arr[next - 'a']++,
            (left, right) -> {
                Arrays.setAll(left, i -> left[i] + right[i]);
                return left;
            },
            arr -> IntStream.range(0, arr.length)
                .mapToObj(i -> Character.toString(i + 'a').repeat(arr[i]))
                .collect(Collectors.joining())
        ));

    System.out.println(result);
}

Output:
aaaaaeeewww

A: You can use IntStream to convert the nested loop to a stream, like this:
import java.util.*;
import java.util.stream.IntStream;

public class ABC{
  static final int MAX_CHAR = 26;
  static void sortString(String str) {
    int letters[] = new int[MAX_CHAR];
    for (char x : str.toCharArray()) {
      letters[x - 'a']++;
    }
    IntStream.range(0, letters.length).forEach(i -> {
      IntStream.range(0, letters[i]).forEach(ch -> {
        System.out.print((char) (i + 'a'));
      });
    });
  }

  // Driver program to test above function
  public static void main(String[] args) {
    sortString("geeksforgeeks");
  }
}

Working link.

A: The best snippet that doesn't require precalculated array I am able to produce is this:
final String result = str.chars()
    .boxed()
    .collect(
        Collectors.collectingAndThen(
            Collectors.groupingBy(
                ch -> ch - 'a',
                TreeMap::new,
                Collectors.counting()),
            map -> map.entrySet().stream().collect(
                StringBuilder::new,
                (sb, e) -> sb.append(Character.toString(e.getKey() + 'a')
                                              .repeat(e.getValue().intValue())),
                StringBuilder::append)
        )
    ).toString();

*

*The inner groupingBy groups the characters to the position in an alphabet (key) and the count (value). The keys for the count is 0 are omitted (they don't get into the map at all). The output after this part looks like this:

{4=4, 5=1, 6=2, 10=2, 14=1, 17=1, 18=2}

Note I used TreeMap to keep the characters sorted.

*The collectingAndThen wraps the Map<Integer, Long> and using a mutable reduction in another stream to resull in StringBuilder with the correct position and amount of the characters (note I use String#repeat as of Java 11 that can be backported or easily substituted by a custom/utility method).
Conclusion:

*

*Is this solution in the declarative spirit of java-stream? Yes, it is.

*Is this solution better? Nope. It is not even more readable or nice piece of code to look at. It is ok for sake of getting more familiar with streams.

*Is this solution more efficient? Nope, it is not 0(n) anymore. Remember it is not always possible to represent iterative for loop(s) directly by a declarative approach using Stream API and achieve the same performance.

A: Try this.
static final int MAX_CHAR = 26;

static String sortString(String str) {
    int[] letters = new int[MAX_CHAR];
    str.chars().forEach(i -> letters[i - 'a']++);
    return IntStream.range(0, MAX_CHAR)
        .mapToObj(i -> Character.toString(i + 'a').repeat(letters[i]))
        .collect(Collectors.joining());
}

public static void main(String[] args) {
    System.out.println(sortString("geeksforgeeks"));
}

output:
eeeefggkkorss

A: For example (Java 11+):
String foo(String s) {
    return s.chars().boxed().collect(Collectors.collectingAndThen(
            Collectors.groupingBy(Function.identity(), Collectors.summingInt(ignore -> 1)),
            integerLongMap -> IntStream.rangeClosed('a', 'z')
                    .mapToObj(value -> Character.toString(value).repeat(integerLongMap.getOrDefault(value, 0)))
                    .collect(Collectors.joining())
    ));
}

System.out.println(foo("bbccdefbbaa"));  // aabbbbccdef
System.out.println(foo("geeksforgeeks"));  // eeeefggkkorss

But it's harder to read than iterative version, imho.


text:
Q: Mixture of UK and US Dates - Convert All to UK I have just realised that after importing 8 million records into the database (long time!) that sadly some dates are mixed (UK and US format, not good!)
i.e.
26/03/2015
22/12/2014
10/08/2012
11/17/2011
11/30/2010
Not only this, the column of the database is varchar, which isnt good for performance either.
I have made a test database and I have tried this with fail:
SELECT convert(varchar, getdate(), 103)

I'm trying to get the UK dates i.e. 25/11/1992 and not 11/25/1992
Any help would be great otherwise thats a night wasted uploading data!

A: the correct way of the select on your example is like this:
select CONVERT(VARCHAR(10),GETDATE(),103)

But i was thinking of two solution
make a function the take a varchar of US date and return varchar of UK date
but the big problem you don´t know if in table all the date is US type, if you can figure witch surly what type of the date you just resolved the problem, and you can put this rule on the function passing some params that help to figure that.
also you don´t need to import all the data again, after you make the above things just make an update statement of the current table using the function.
good luck.


text:
Q: Setting max date value to current date OR 1 year from start date What should I do to restrict the user to select the end date beyond one year from the starting date OR the current date. I have my codes like this.
$(function () {
$('#DateFrom').datepicker({
    dateFormat:'d-M-y',
    changeMonth: true,
    changeYear: true,
    minDate: new Date(2000, 7, 23),
    maxDate: 0,
    onSelect: function() {
        var date = $('#DateFrom').datepicker('getDate');
        date.setTime(date.getTime() + (1000*60*60*24*365));
        $('#DateTo').datepicker('option', 'maxDate', date);
        $('#DateTo').datepicker('option', 'minDate',$('#DateFrom').datepicker('getDate'));
        displayToUser();
    },

});

$('#DateTo').datepicker({
    dateFormat:'d-M-y',
    maxDate: 0,
    changeMonth: true,
    changeYear: true,
    onSelect: displayToUser,
});
});
function displayToUser() {}

Here although it restricts the user within one year from starting date, but it allows the user to select dates beyond the current date.
Example: if start date is 23-01-2016, it allows to select the end date upto 22-01-2017. I want it to be at most today's date.

A: Does this do it?
$(function () {
    $('#DateFrom').datepicker({
        dateFormat:'d-M-y',
        changeMonth: true,
        changeYear: true,
        minDate: new Date(2000, 7, 23),
        maxDate: 0,
        onSelect: function() {
            var date = $('#DateFrom').datepicker('getDate');
            date.setTime(date.getTime() + (1000*60*60*24*365));
            var todaysDate = new Date();
            if(date.getTime() > todaysDate.getTime()) date = todaysDate;
            $('#DateTo').datepicker('option', 'maxDate', date);
            $('#DateTo').datepicker('option', 'minDate',$('#DateFrom').datepicker('getDate'));
            displayToUser();
        },

    });

    $('#DateTo').datepicker({
        dateFormat:'d-M-y',
        maxDate: 0,
        changeMonth: true,
        changeYear: true,
        onSelect: displayToUser,
    });
});
function displayToUser() {}

I only added these two lines
            var todaysDate = new Date();
            if(date.getTime() > todaysDate.getTime()) date = todaysDate;


text:
Q: Sidekiq-Unique-jobs Lock works only for first Worker, then all pending jobs get executed at the same time? I could have 3 jobs pending in the queue, as soon as the first Job is done, all remaining workers get executed at the same time. Why is that? I want each worker to get a lock and make the other jobs wait, in a serialized-fashion.
class StuffWorker
  include Sidekiq::Worker
  sidekiq_options lock: :until_executed,
                  lock_timeout: 999,
                  lock_info: true,
                  lock_args_method: :lock_args

  def self.lock_args(args)
    [args[0], args[1]]
  end

  def perform(company_id, person_id)
    sleep 10
    logger.info "STARTING IT! at #{DateTime.now.strftime('%H:%M:%S')}"
  end
end

Produces the following:
JID-ce8c692b5341adb7a24584ab INFO: STARTING IT! at 23:29:52
JID-ce8c692b5341adb7a24584ab INFO: done: 10.728 sec
JID-ca8dac1cbd7cbaf5d87f6096 INFO: STARTING IT! at 23:30:02
JID-463bfe792775e1412d3c0af7 INFO: STARTING IT! at 23:30:02
JID-463bfe792775e1412d3c0af7 INFO: done: 17.754 sec
JID-ca8dac1cbd7cbaf5d87f6096 INFO: done: 14.024 sec

A: Possible, what you want is a runtime lock only, not queue lock. You have to use while_executing lock type https://github.com/mhenrixon/sidekiq-unique-jobs#while-executing.


text:
Q: libgdx ActorGestureListener.pan() parameters not moving actor in smooth line I override the pan method in ActorGestureListener to implement dragging actors in libgdx (scene2d).
When I move individual pieces on a board they move smoothly, but when moving the whole board, the x and y coordinates that is sent to pan is "jumping", and in an increasingly amount the longer it is dragged.
These are an example of the deltaY coordinates sent to pan when dragging smoothly downwards:
 1.1156368
-0.13125038
-1.0500145
 0.98439217
-1.0500202
 0.91877174
-0.984396
 0.9187679
-0.98439026
 0.9187641
-0.13125038

This is how I move the camera:
public void pan (InputEvent event, float x, float y, float deltaX, float deltaY) {
    cam.translate(-deltaX, -deltaY);

I have been using both the delta values sent to pan and the real position values, but similar results. And since it is the coordinates that are wrong, it doesn't matter whether I move the board itself or the camera.
What could the cause be for this and what is the solution?
EDIT
When I move camera only half the delta-values, it moves smoothly but only at half the speed of the mouse pointer:
cam.translate(-deltaX / 2, -deltaY / 2);

It seems like the moving of camera or board affects the mouse input coordinates. How can I drag at "mouse speed" and still get smooth movements?

A: I'm aware this is really late and you've probably already solved the problem but for future readers:
This forum post helped me: http://badlogicgames.com/forum/viewtopic.php?f=11&t=12343
If you move the camera while part way through a pan or ANY gesture the coordinate system being used for the x and y coordinates is changed and that's why you get the jumpy deltas alternating between +ve and -ve values.
The fix I used is to not use the pan() gesture and implement it like so:
private Vector3 prevDragPos;
addListener(new InputListener(){
        @Override
        public boolean touchDown(InputEvent event, float x, float y, int pointer, int button) {
            return true;
        }

        @Override
        public void touchDragged(InputEvent event, float x, float y, int pointer) {
            x = Gdx.input.getX(pointer);
            y = Gdx.input.getY(pointer);
            if(prevDragPos == null) prevDragPos = new Vector3(x, y, 0);

            getStage().getCamera().position.add(prevDragPos.x - x, y - prevDragPos.y, 0);
            prevDragPos.set(x, y, 0);
        }

        @Override
        public void touchUp(InputEvent event, float x, float y, int pointer, int button) {
            prevDragPos = null ;
        }
    });

Gdx.input.getX() and Gdx.input.getY() don't get converted to camera coordinates so using them fixes the problem.

A: it's because you're using translate. Try this:
public void pan (InputEvent event, float x, float y, float deltaX, float deltaY) {
    camera.position.add((-x), (y), 0);
    camera.update();
}


text:
Q: INSERT INTO COUNT(*) updating timestamp automatically in MYSQL How can i run the below query with the following table structure under test_reports
Table_Name
Date (Current TimeStamp)
Total_Count
INSERT INTO test_reports SELECT "table1", "date", COUNT(*) from `table1`;

The above works fine apart from the time stamp is not updated and remains 00:00:00

A: If the date column is set to CURRENT_TIMESTAMP by definition, you can just leave it off.
INSERT INTO test_reports (Table_Name, Total_Count)
SELECT "table1", COUNT(*) FROM table1


text:
Q: Unity - GameObject positioning at RayCast hit without clipping So, I´m developing a VR game with base building functionalities and am using the position where the player hand Raycast hit as the position a preview GameObject has to go. But obviously when I do that, the gameObject clips through the Hit mesh. I am trying to find a way to avoid that.
I´ve came up with a solution but don´t get it to work in any way. Maybe it´s my idea, maybe my programming knowledge, no idea, but well. This would be it.

So Preview GameObject Transform is set to the HitPoint transform and moved away from point of collision until not colliding anymore. I guess? I only come up with performance heavy solutions and they don´t even work anyways. Does someone know a good solution?
Thanks in advance!

A: This sounds like you are looking for Physics.ComputePenetration

Compute the minimal translation required to separate the given colliders apart at specified poses.

So you will need a Collider on your placed object (the hit one already has one anyway) and then do e.g.
// Wherever you get this from
Collider objectToPlace;

if(Physics.Raycast(yourRay, out var hit))
{
    objectToPlace.trabsform.position = hit.point;

    if(Physics.ComputePenetration(objectToPlace, objectToPlace.transform.position, objectToPlace.transform.rotation, hit.collider, hit.transform.position, hit.transform.rotation, out var direction, out var distance))
    {
        objectToPlace.position += direction * distance;
    }
}


text:
Q: Javascript - if the width of an element is 100%, do something How do I force javascript to do the following?
If the width of an element with the id myBar is 100%, change the style of an element with the ID result to be "block" (it's set to none)?
Please answer!
Code: html

<button onclick="move()">Run Malware Code Scan</button>

Fount 142 threats! Take responsibility please!

Code: CSS
#myProgress {
    width: 100%;
    background-color: #ebf442;
}
#myBar {
    width: 1%;
    height: 30px;
    background-color: #ed4949;
}

#result {display:none;}
ul li {list-style-type:square;}

Code: JS

P.S.: I'm a beginner at JS!

A: Edit
You can change display to block in your frame function when you check if width is >= 100. Wouldn't that solve your problem?

A: The problem of style properties
The element.style.property returns no value until the css is applied from the tag i.e

.
So your code is not working. You should apply the width css from the tag to make your code work.

<button onclick="move()">Run Malware Code Scan</button>

  Fount 142 threats! Take responsibility please!

As Oen44 figured out, there is a syntax error too in your if condition (== is written as =).


text:
Q: html2canvas jspdf table data word-break not working I am trying to export some tables to pdf in my application. The export functionality works. However, if table data has some long text in it, it overflows into the other rows when it is exported. I have word-break:break-word for that data, but it is being ignored when exporting to PDF. I also have letterRendering set to true. Here is my function:
var data = document.getElementById('table');
    html2canvas(data).then(canvas => {
      // Few necessary setting options
      var imgWidth = 208;
      var pageHeight = 295;
      var imgHeight = canvas.height * imgWidth / canvas.width;
      var heightLeft = imgHeight;

      const contentDataURL = canvas.toDataURL('image/png')
      let pdf = new jspdf('p', 'mm', 'a4');
      var position = 0;
      pdf.addImage(contentDataURL, 'PNG', 0, position, imgWidth, imgHeight)
      pdf.save('table.pdf');
      letterRendering: true;
    });

Here is an image of part of the exported table that is showing the problem:

It looks fine on the webpage itself:

How should I modify my function to prevent this overflow from happening?

A: OK, so, I changed work-break:break-word to word-break:break-all and it is working perfectly now. Happy Coding!