问:
Two dynamically assigned ContentControls in single view in Caliburn.Micro
I have a UserControl that contains two ContentControls that need to have different UserControl Views bound to them at runtime.  The attached-Property solution noted here does not seem to work in Silverlight.  Or, I am doing something wrong.  I also, found this, but it did not bring any joy either.

I had a single ContentControl working by naming it 'ActiveItem'.  But, of course, I cannot have two ContentControls with the same name.

Thanks in advance for any help,

Jim

答:
This is an old question, but in case anyone is having the same issue, I post here my way of handling it from the beginning and in a more thorough manner:

Your main window that contain both (or even more than two) of your User Controls must be inherited from Caliburn.Micro.Conductor<Screen>.Collection.AllActive;

Your User Controls must be inherited from Caliburn.Micro.Screen;

You must also keep naming conventions in mind. If you use MenuUC as the name of a ContentControl in your View, also create a property named MenuUC in your ViewModel;

Initialize your UserControl as I do in Constructor;

Now you can use ActivateItem(MenuUC) and DeactivateItem(MenuUC) everywhere in your code. Caliburn.Micro automatically detects which one you want to work with.

Example XAML View code:

<Window x:Class="YourProject.Views.YourView"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        mc:Ignorable="d"
        Title="YourViewTitle" Width="900" Height="480">

    <Grid>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="*"/>
            <ColumnDefinition Width="4*"/>
        </Grid.ColumnDefinitions>
        <Grid.RowDefinitions>
            <RowDefinition Height="auto"/>
            <RowDefinition Height="*"/>
        </Grid.RowDefinitions>

        <ContentControl Grid.Row="0" Grid.Column="0" x:Name="MenuUC" />

        <Border Grid.Column="1" Grid.RowSpan="2" BorderThickness="1,0,0,0" BorderBrush="#FF707070" >
            <ContentControl x:Name="PanelUC" />
        </Border>
    </Grid>
</Window>
```

<blockquote>
  <p>Example C# ViewModel code:</p>
</blockquote>

<pre class="lang-cs prettyprint-override"><code>class YourViewModel : Conductor<Screen>.Collection.AllActive
{
    // Menu Side Bar
    private MenuUCViewModel _menuUC;
    public MenuUCViewModel MenuUC
    {
        get { return _menuUC; }
        set { _menuUC = value; NotifyOfPropertyChange(() => MenuUC); }
    }

    // Panel
    private Screen _panelUC;
    public Screen PanelUC
    {
        get { return _panelUC; }
        set { _panelUC = value; NotifyOfPropertyChange(() => PanelUC); }
    }

    // Constructor
    public YourViewModel()
    {
        MenuUC = new MenuUCViewModel();
        ActivateItem(MenuUC);

        PanelUC = new FirstPanelUCViewModel();
        ActivateItem(PanelUC);
    }

    // Some method that changes PanelUC (previously FirstPanelUCViewModel) to SecondPanelUCViewModel
    public void ChangePanels()
    {
        DeactivateItem(PanelUC);
        PanelUC = new SecondPanelUCViewModel();
        ActivateItem(PanelUC);
    }
}
</code>```

In the above example, ChangePanels() acts as a method to load new User Control into your ContentControl.

Also read this question, it might be help you further.

Body:
This is an old question, but in case anyone is having the same issue, I post here my way of handling it from the beginning and in a more thorough manner:

Your main window that contain both (or even more than two) of your User Controls must be inherited from Caliburn.Micro.Conductor<Screen>.Collection.AllActive;

Your User Controls must be inherited from Caliburn.Micro.Screen;

You must also keep naming conventions in mind. If you use MenuUC as the name of a ContentControl in your View, also create a property named MenuUC in your ViewModel;

Initialize your UserControl as I do in Constructor;

Now you can use ActivateItem(MenuUC) and DeactivateItem(MenuUC) everywhere in your code. Caliburn.Micro automatically detects which one you want to work with.

Example XAML View code:

<Window x:Class="YourProject.Views.YourView"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        mc:Ignorable="d"
        Title="YourViewTitle" Width="900" Height="480">

    <Grid>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="*"/>
            <ColumnDefinition Width="4*"/>
        </Grid.ColumnDefinitions>
        <Grid.RowDefinitions>
            <RowDefinition Height="auto"/>
            <RowDefinition Height="*"/>
        </Grid.RowDefinitions>

        <!-- Menu Side Bar -->
        <ContentControl Grid.Row="0" Grid.Column="0" x:Name="MenuUC" />

        <!-- Panel -->
        <Border Grid.Column="1" Grid.RowSpan="2" BorderThickness="1,0,0,0" BorderBrush="#FF707070" >
            <ContentControl x:Name="PanelUC" />
        </Border>
    </Grid>
</Window>

Example C# ViewModel code:

class YourViewModel : Conductor<Screen>.Collection.AllActive
{
    // Menu Side Bar
    private MenuUCViewModel _menuUC;
    public MenuUCViewModel MenuUC
    {
        get { return _menuUC; }
        set { _menuUC = value; NotifyOfPropertyChange(() => MenuUC); }
    }

    // Panel
    private Screen _panelUC;
    public Screen PanelUC
    {
        get { return _panelUC; }
        set { _panelUC = value; NotifyOfPropertyChange(() => PanelUC); }
    }

    // Constructor
    public YourViewModel()
    {
        MenuUC = new MenuUCViewModel();
        ActivateItem(MenuUC);

        PanelUC = new FirstPanelUCViewModel();
        ActivateItem(PanelUC);
    }

    // Some method that changes PanelUC (previously FirstPanelUCViewModel) to SecondPanelUCViewModel
    public void ChangePanels()
    {
        DeactivateItem(PanelUC);
        PanelUC = new SecondPanelUCViewModel();
        ActivateItem(PanelUC);
    }
}

In the above example, ChangePanels() acts as a method to load new User Control into your ContentControl.

Also read this question, it might be help you further.


来源: stackexchange

问:
Tornado websocket client: how to async on_message? (coroutine was never awaited)
How can I make the on_message function work asynchronously in my Tornado WebSocketClient?

I guess I need to await the on_message function, but I don't know how.

Or is there even a fundamental misconception in the way how I try to implement an asynchronous WebSocketClient?

```<code>import tornado.websocket
from tornado.queues import Queue
from tornado import gen
import json

q = Queue()

class WebsocketClient():

    def __init__(self, url, connections):
        self.url = url
        self.connections = connections
        print("CLIENT started")
        print("CLIENT initial connections: ", len(self.connections))

    async def send_message(self):
        async for message in q:
            try:
                msg = json.loads(message)
                print(message)
                await gen.sleep(0.001)
            finally:
                q.task_done()

    async def update_connections(self, connections):
        self.connections = connections
        print("CLIENT updated connections: ", len(self.connections))

    async def on_message(self, message):
        await q.put(message)
        await gen.sleep(0.001)

    async def connect(self):
        client = await tornado.websocket.websocket_connect(url=self.url, on_message_callback=self.on_message)
</code>```

```<code>RuntimeWarning: coroutine 'WebsocketClient.on_message' was never awaited
  self._on_message_callback(message)
RuntimeWarning: Enable tracemalloc to get the object allocation traceback
</code>```

答:
on_message_callback is supposed to be a regular function, not a coroutine. And it is meant to be used in old-style code when people used callbacks instead of coroutines.

For the newer async-style code, you don't need this callback. You can just do this:

```<code>async def connect(self):
    client = await tornado.websocket.websocket_connect(url=self.url)

    while True:
        message = await client.read_message()

        if message is None:
            # None message means the connection was closed
            break

        print("Message received:", message)
        await q.put(message)
        await gen.sleep(0.001)
</code>```

ContentLicense: CC BY-SA 4.0

Body:
How can I make the on_message function work asynchronously in my Tornado WebSocketClient?

I guess I need to await the on_message function, but I don't know how.

Or is there even a fundamental misconception in the way how I try to implement an asynchronous WebSocketClient?

import tornado.websocket
from tornado.queues import Queue
from tornado import gen
import json

q = Queue()

class WebsocketClient():

    def __init__(self, url, connections):
        self.url = url
        self.connections = connections
        print("CLIENT started")
        print("CLIENT initial connections: ", len(self.connections))

    async def send_message(self):
        async for message in q:
            try:
                msg = json.loads(message)
                print(message)
                await gen.sleep(0.001)
            finally:
                q.task_done()

    async def update_connections(self, connections):
        self.connections = connections
        print("CLIENT updated connections: ", len(self.connections))

    async def on_message(self, message):
        await q.put(message)
        await gen.sleep(0.001)

    async def connect(self):
        client = await tornado.websocket.websocket_connect(url=self.url, on_message_callback=self.on_message)

RuntimeWarning: coroutine 'WebsocketClient.on_message' was never awaited
  self._on_message_callback(message)
RuntimeWarning: Enable tracemalloc to get the object allocation traceback

Body:
on_message_callback is supposed to be a regular function, not a coroutine. And it is meant to be used in old-style code when people used callbacks instead of coroutines.

For the newer async-style code, you don't need this callback. You can just do this:

async def connect(self):
    client = await tornado.websocket.websocket_connect(url=self.url)

    while True:
        message = await client.read_message()

        if message is None:
            # None message means the connection was closed
            break

        print("Message received:", message)
        await q.put(message)
        await gen.sleep(0.001)


问:
Run Command Instructions to open and save excel file
I am using the run command.  It starts with
Start Excel.exe "Filepath\FileName.xls"
This opens the file.  A popup appears, and asks if you would like to update the links.
I need to know what commands in the run commands to use that would:

Tab and select "Don't Update", then save and close the file.
(this will be refreshing data that was just input into the file from Alteryx)
Thanks for any help you can provide.

答: It may be possible to do this altering the Excel settings, this is outside of the command line. </p>


问:
How do i pass php variable to .js file to create function Chart
i done create my chart but i dont know how to pass it, i already try use ?php  but its not working.. and i already define in head like below, but when i try to pass it. the php file returning "''" like function tooltips title

```<code><script src="includes/templates/chart.js"></script>
</code>```

chart.js

```<code>
window.onload = function() {
    var ctx = document.getElementById('myChart').getContext('2d');
        var myChart = new Chart(ctx, {
            type: 'line',
            data: {
                labels: ['08:00'] , //Jamnya
                datasets: [{
                    backgroundColor: 'rgba(85, 212, 226, 0.2)',
                    borderColor: '#55d4e2',
                    label: '<?php echo $dtDateChart1; ?>' ,
                    data: [600],
                    fill: true,
                    pointRadius: 5,
                    pointHoverRadius: 10,
                    showLine: true
                }]
            }, options: {
                responsive: true,
                maintainAspectRatio: false,
                title: {
                    display: true,
                    text: 'Total Online Today',
                    position: 'top',
                    fontSize: 15,
                    fontStyle: 'bold'
                },
                legend: {
                    display: false
                },
                elements: {
                    point: {
                        pointStyle: 'circle'
                    }
                },
                scales: {
                    xAxes: [{
                        display: true,
                        scaleLabel: {
                            display: true,
                            labelString: 'TIME'
                        },
                        ticks: {
                            major: {
                                fontStyle: 'bold',
                                fontColor: '#FF0000'
                            }
                        }
                    }],
                    yAxes: [{
                        display: true,
                        scaleLabel: {
                            display: true,
                            labelString: 'TOTAL ONLINE'
                        }
                    }]
                },
                tooltips:{
                    callbacks: {
                        title: function(tooltipItem, data) {
                          return '<?php echo $dtDateChart1; ?>' +data['labels'][tooltipItem[0]['index']];
                        },
                        label: function(tooltipItem, data) {
                          return 'TOTAL : '+data['datasets'][0]['data'][tooltipItem['index']]+'';
                        },
                    },
                    titleFontSize: 15,
                    bodyFontSize: 15,
                    displayColors: false
                }
            }
        }
     );

     return myChart;

}
</code>```

in my php file

```<code>$out .=  '         <canvas id="myChart2" class="canpas chartjs-render-monitor" style="display: block; width: 454px; height: 300px;" width="454" height="300"></canvas>';
</code>```

and this is my variable that i want to pass to my .js

```<code>         //result chart1
            @mssql_free_result($graph_query2);
            $dtDateChart1 = $dateTittleChart1;
            $convertChart1 = json_encode($datesChart1);
            $totalChart1 = json_encode($nMaxChart1);
            $labelChart1 =  $convertChart1;
</code>```

i dont know how to pass it when i already succes getelementbyid thanks you if you know something about it that i should know. i dont have a lot knowledge about javascript passing variable.

答:
Try to make hidden input and put your php variable on its value then collect element value by js in your function
I almost do this and it is working well

First in your code php or html
Add input like

```<code><input type='hidden' value='<?php echo $dtDateChart1;  ?>'  id='dtDateChart1' >

</code>```

chart.js

```<code>
window.onload = function() {
    var ctx = document.getElementById('myChart').getContext('2d');
        var myChart = new Chart(ctx, {
            type: 'line',
            data: {
                labels: ['08:00'] , //Jamnya
                datasets: [{
                    backgroundColor: 'rgba(85, 212, 226, 0.2)',
                    borderColor: '#55d4e2',
                    label: document.getElementById("dtDateChart1").value,
                    data: [600],
                    fill: true,
                    pointRadius: 5,
                    pointHoverRadius: 10,
                    showLine: true
                }]
            }, options: {
                responsive: true,
                maintainAspectRatio: false,
                title: {
                    display: true,
                    text: 'Total Online Today',
                    position: 'top',
                    fontSize: 15,
                    fontStyle: 'bold'
                },
                legend: {
                    display: false
                },
                elements: {
                    point: {
                        pointStyle: 'circle'
                    }
                },
                scales: {
                    xAxes: [{
                        display: true,
                        scaleLabel: {
                            display: true,
                            labelString: 'TIME'
                        },
                        ticks: {
                            major: {
                                fontStyle: 'bold',
                                fontColor: '#FF0000'
                            }
                        }
                    }],
                    yAxes: [{
                        display: true,
                        scaleLabel: {
                            display: true,
                            labelString: 'TOTAL ONLINE'
                        }
                    }]
                },
                tooltips:{
                    callbacks: {
                        title: function(tooltipItem, data) {
                          return '<?php echo $dtDateChart1; ?>' +data['labels'][tooltipItem[0]['index']];
                        },
                        label: function(tooltipItem, data) {
                          return 'TOTAL : '+data['datasets'][0]['data'][tooltipItem['index']]+'';
                        },
                    },
                    titleFontSize: 15,
                    bodyFontSize: 15,
                    displayColors: false
                }
            }
        }
     );

     return myChart;

}
</code>```

Body:
i done create my chart but i dont know how to pass it, i already try use ?php  but its not working.. and i already define in head like below, but when i try to pass it. the php file returning "''" like function tooltips title

chart.js

window.onload = function() {
    var ctx = document.getElementById('myChart').getContext('2d');
        var myChart = new Chart(ctx, {
            type: 'line',
            data: {
                labels: ['08:00'] , //Jamnya
                datasets: [{
                    backgroundColor: 'rgba(85, 212, 226, 0.2)',
                    borderColor: '#55d4e2',
                    label: '<?php echo $dtDateChart1; ?>' ,
                    data: [600],
                    fill: true,
                    pointRadius: 5,
                    pointHoverRadius: 10,
                    showLine: true
                }]
            }, options: {
                responsive: true,
                maintainAspectRatio: false,
                title: {
                    display: true,
                    text: 'Total Online Today',
                    position: 'top',
                    fontSize: 15,
                    fontStyle: 'bold'
                },
                legend: {
                    display: false
                },
                elements: {
                    point: {
                        pointStyle: 'circle'
                    }
                },
                scales: {
                    xAxes: [{
                        display: true,
                        scaleLabel: {
                            display: true,
                            labelString: 'TIME'
                        },
                        ticks: {
                            major: {
                                fontStyle: 'bold',
                                fontColor: '#FF0000'
                            }
                        }
                    }],
                    yAxes: [{
                        display: true,
                        scaleLabel: {
                            display: true,
                            labelString: 'TOTAL ONLINE'
                        }
                    }]
                },
                tooltips:{
                    callbacks: {
                        title: function(tooltipItem, data) {
                          return '<?php echo $dtDateChart1; ?>' +data['labels'][tooltipItem[0]['index']];
                        },
                        label: function(tooltipItem, data) {
                          return 'TOTAL : '+data['datasets'][0]['data'][tooltipItem['index']]+'';
                        },
                    },
                    titleFontSize: 15,
                    bodyFontSize: 15,
                    displayColors: false
                }
            }
        }
     );

     return myChart;

}

in my php file

$out .=  '         <canvas id="myChart2" class="canpas chartjs-render-monitor" style="display: block; width: 454px; height: 300px;" width="454" height="300"></canvas>';

and this is my variable that i want to pass to my .js

         //result chart1
            @mssql_free_result($graph_query2);
            $dtDateChart1 = $dateTittleChart1;
            $convertChart1 = json_encode($datesChart1);
            $totalChart1 = json_encode($nMaxChart1);
            $labelChart1 =  $convertChart1;

i dont know how to pass it when i already succes getelementbyid thanks you if you know something about it that i should know. i dont have a lot knowledge about javascript passing variable.

Body:
Try to make hidden input and put your php variable on its value then collect element value by js in your function
I almost do this and it is working well

First in your code php or html
Add input like

<input type='hidden' value='<?php echo $dtDateChart1;  ?>'  id='dtDateChart1' >

chart.js

window.onload = function() {
    var ctx = document.getElementById('myChart').getContext('2d');
        var myChart = new Chart(ctx, {
            type: 'line',
            data: {
                labels: ['08:00'] , //Jamnya
                datasets: [{
                    backgroundColor: 'rgba(85, 212, 226, 0.2)',
                    borderColor: '#55d4e2',
                    label: document.getElementById("dtDateChart1").value,
                    data: [600],
                    fill: true,
                    pointRadius: 5,
                    pointHoverRadius: 10,
                    showLine: true
                }]
            }, options: {
                responsive: true,
                maintainAspectRatio: false,
                title: {
                    display: true,
                    text: 'Total Online Today',
                    position: 'top',
                    fontSize: 15,
                    fontStyle: 'bold'
                },
                legend: {
                    display: false
                },
                elements: {
                    point: {
                        pointStyle: 'circle'
                    }
                },
                scales: {
                    xAxes: [{
                        display: true,
                        scaleLabel: {
                            display: true,
                            labelString: 'TIME'
                        },
                        ticks: {
                            major: {
                                fontStyle: 'bold',
                                fontColor: '#FF0000'
                            }
                        }
                    }],
                    yAxes: [{
                        display: true,
                        scaleLabel: {
                            display: true,
                            labelString: 'TOTAL ONLINE'
                        }
                    }]
                },
                tooltips:{
                    callbacks: {
                        title: function(tooltipItem, data) {
                          return '<?php echo $dtDateChart1; ?>' +data['labels'][tooltipItem[0]['index']];
                        },
                        label: function(tooltipItem, data) {
                          return 'TOTAL : '+data['datasets'][0]['data'][tooltipItem['index']]+'';
                        },
                    },
                    titleFontSize: 15,
                    bodyFontSize: 15,
                    displayColors: false
                }
            }
        }
     );

     return myChart;

}


问:
R BootStrap With Strata
I learned how to do bootstrap regression. Here is my example and Code.

```<code>   library(boot)
    sampledata = data.frame(y = sample(0:20, r = T, size = 5000),
                            x1 = runif(5000),
                            x2 = runif(5000),
                            group1 = sample(1:3, r = T, size = 5000),
                            group2 = sample(0:1, r = T, size = 5000))

# function to obtain R-Squared from the data
rsq <- function(formula, data, indices) {
  d <- data[indices,]
  fit <- lm(formula, data=d)
  return(coef(fit))
}

# bootstrapping with 250 replications
results <- boot(data=sampledata, statistic=rsq,
   R=250, formula=y~x1+x2)
df <- data.frame(results$t)
names(df) <- names(results$t0)
</code>```

However if you want to do this process for subgroups of your data how can you make it more automated? This is what I hope to do but this is very tiresome and I have many more group categories but this is basically the hopeful result, basically I subset the sampledata into 6 groups and then use all those data sets separate in 6 different bootstrap models and then combine the results in DATA. I see boot has strata feature but am not getting it to function. Also are you supposed to subset your data to group and then do the bootstrap sample? Or get a bootstrap sample and then subset your data? Any way, I am wondering how can it be possible to make this more automatic where I can code the program to do the bootstrap estimate for all groups separately, where the models are stratified.

```<code>sampledata1 = subset(sampledata, group1 == 1 & group2 == 0)
sampledata2 = subset(sampledata, group1 == 2 & group2 == 0)
sampledata3 = subset(sampledata, group1 == 3 & group2 == 0)
sampledata4 = subset(sampledata, group1 == 1 & group2 == 1)
sampledata5 = subset(sampledata, group1 == 2 & group2 == 1)
sampledata6 = subset(sampledata, group1 == 3 & group2 == 1)

# bootstrapping with 250 replications
results <- boot(data=sampledata1, statistic=rsq,
   R=250, formula=y~x1+x2)
df1 <- data.frame(results$t)
names(df1) <- names(results$t0)
df1$group1 = 1
df1$group2 = 0

# bootstrapping with 250 replications
results <- boot(data=sampledata2, statistic=rsq,
   R=250, formula=y~x1+x2)
df2 <- data.frame(results$t)
names(df2) <- names(results$t0)
df2$group1 = 2
df2$group2 = 0

# bootstrapping with 250 replications
results <- boot(data=sampledata3, statistic=rsq,
   R=250, formula=y~x1+x2)
df3 <- data.frame(results$t)
names(df3) <- names(results$t0)
df3$group1 = 3
df3$group2 = 0

# bootstrapping with 250 replications
results <- boot(data=sampledata4, statistic=rsq,
   R=250, formula=y~x1+x2)
df4 <- data.frame(results$t)
names(df4) <- names(results$t0)
df4$group1 = 1
df4$group2 = 1

# bootstrapping with 250 replications
results <- boot(data=sampledata5, statistic=rsq,
   R=250, formula=y~x1+x2)
df5 <- data.frame(results$t)
names(df5) <- names(results$t0)
df5$group1 = 2
df5$group2 = 1

# bootstrapping with 250 replications
results <- boot(data=sampledata6, statistic=rsq,
   R=250, formula=y~x1+x2)
df6 <- data.frame(results$t)
names(df6) <- names(results$t0)
df6$group1 = 3
df6$group2 = 1

DATA = rbind(df1, df2, df3, df4, df5, df6)
</code>```

```<code>rsq <- function(formula, data, indices) {
  dataSUB <- data %>% filter(GROUP1 == group1, GROUP2 == group2)
  d <- dataSUB[indices,]
  fit <- lm(formula, data=d)
  return(coef(fit))
}
</code>```

答:
Using data.table may not enhance the time this would take to run. However here is a similar alternative with data.table and an assisting function to generalize the process:</p>

```<code>library(data.table)

setDT(sampledata)

boot_group <- function(sel_group1, sel_group2){
  sampledata1  <- sampledata[group1 == sel_group1 & group2 == sel_group2]
  results <- boot(data=sampledata1, statistic=rsq,
                  R=250, formula=y~x1+x2)
  df1 <- data.table(results$t)
  names(df1) <- names(results$t0)
  df1[, group1 := sel_group1]
  df1[, group2 := sel_group2]
  return(df1)
}

DATA <- data.table()
groups1 <- sampledata[, unique(group1)]
groups1 <- sort(groups1)
groups2 <- sampledata[, unique(group2)]
groups2 <- sort(groups2)

for (g2 in groups2) {
  for (g1 in groups1) {
    subdf <- boot_group(g1, g2)
    DATA <- rbind(DATA, subdf)
  }
}
</code>```

Title: R BootStrap With Strata

Body:
I learned how to do bootstrap regression. Here is my example and Code.

   library(boot)
    sampledata = data.frame(y = sample(0:20, r = T, size = 5000),
                            x1 = runif(5000),
                            x2 = runif(5000),
                            group1 = sample(1:3, r = T, size = 5000),
                            group2 = sample(0:1, r = T, size = 5000))

# function to obtain R-Squared from the data
rsq <- function(formula, data, indices) {
  d <- data[indices,]
  fit <- lm(formula, data=d)
  return(coef(fit))
}

# bootstrapping with 250 replications
results <- boot(data=sampledata, statistic=rsq,
   R=250, formula=y~x1+x2)
df <- data.frame(results$t)
names(df) <- names(results$t0)

However if you want to do this process for subgroups of your data how can you make it more automated? This is what I hope to do but this is very tiresome and I have many more group categories but this is basically the hopeful result, basically I subset the sampledata into 6 groups and then use all those data sets separate in 6 different bootstrap models and then combine the results in DATA. I see boot has strata feature but am not getting it to function. Also are you supposed to subset your data to group and then do the bootstrap sample? Or get a bootstrap sample and then subset your data? Any way, I am wondering how can it be possible to make this more automatic where I can code the program to do the bootstrap estimate for all groups separately, where the models are stratified.

sampledata1 = subset(sampledata, group1 == 1 & group2 == 0)
sampledata2 = subset(sampledata, group1 == 2 & group2 == 0)
sampledata3 = subset(sampledata, group1 == 3 & group2 == 0)
sampledata4 = subset(sampledata, group1 == 1 & group2 == 1)
sampledata5 = subset(sampledata, group1 == 2 & group2 == 1)
sampledata6 = subset(sampledata, group1 == 3 & group2 == 1)

# bootstrapping with 250 replications
results <- boot(data=sampledata1, statistic=rsq,
   R=250, formula=y~x1+x2)
df1 <- data.frame(results$t)
names(df1) <- names(results$t0)
df1$group1 = 1
df1$group2 = 0

# bootstrapping with 250 replications
results <- boot(data=sampledata2, statistic=rsq,
   R=250, formula=y~x1+x2)
df2 <- data.frame(results$t)
names(df2) <- names(results$t0)
df2$group1 = 2
df2$group2 = 0

# bootstrapping with 250 replications
results <- boot(data=sampledata3, statistic=rsq,
   R=250, formula=y~x1+x2)
df3 <- data.frame(results$t)
names(df3) <- names(results$t0)
df3$group1 = 3
df3$group2 = 0

# bootstrapping with 250 replications
results <- boot(data=sampledata4, statistic=rsq,
   R=250, formula=y~x1+x2)
df4 <- data.frame(results$t)
names(df4) <- names(results$t0)
df4$group1 = 1
df4$group2 = 1

# bootstrapping with 250 replications
results <- boot(data=sampledata5, statistic=rsq,
   R=250, formula=y~x1+x2)
df5 <- data.frame(results$t)
names(df5) <- names(results$t0)
df5$group1 = 2
df5$group2 = 1

# bootstrapping with 250 replications
results <- boot(data=sampledata6, statistic=rsq,
   R=250, formula=y~x1+x2)
df6 <- data.frame(results$t)
names(df6) <- names(results$t0)
df6$group1 = 3
df6$group2 = 1

DATA = rbind(df1, df2, df3, df4, df5, df6)

rsq <- function(formula, data, indices) {
  dataSUB <- data %>% filter(GROUP1 == group1, GROUP2 == group2)
  d <- dataSUB[indices,]
  fit <- lm(formula, data=d)
  return(coef(fit))
}

Body:
Using data.table may not enhance the time this would take to run. However here is a similar alternative with data.table and an assisting function to generalize the process:

library(data.table)

setDT(sampledata)

boot_group <- function(sel_group1, sel_group2){
  sampledata1  <- sampledata[group1 == sel_group1 & group2 == sel_group2]
  results <- boot(data=sampledata1, statistic=rsq,
                  R=250, formula=y~x1+x2)
  df1 <- data.table(results$t)
  names(df1) <- names(results$t0)
  df1[, group1 := sel_group1]
  df1[, group2 := sel_group2]
  return(df1)
}

DATA <- data.table()
groups1 <- sampledata[, unique(group1)]
groups1 <- sort(groups1)
groups2 <- sampledata[, unique(group2)]
groups2 <- sort(groups2)

for (g2 in groups2) {
  for (g1 in groups1) {
    subdf <- boot_group(g1, g2)
    DATA <- rbind(DATA, subdf)
  }
}


问:
I am setting up PayPal on a website and am using liquid to pull the cart value into JS
I am setting up Paypal on a website and am using liquid to pull the cart value into the Paypal JS.

I have achieved this with the following code:

```<code>{% capture paypal_price %}
  {%- include 'ecommerce/price_total', format_type: 'formatted' -%}
{% endcapture %}
</code>```

and

```<code>value: "{{ paypal_price | remove:'£' }}"
</code>```

Functionally it pull through the correct price but as you can see from the image below and error occurs as it pushes it down onto a new line.

Liquid Issue in Console

Is this a known issue and does anyone have a fix for this?

答:
The following amendment to the Liquid fixed it :)</p>

```<code>{{ paypal_price | remove:'£' | strip_newlines }}
</code>```

Body:
I am setting up Paypal on a website and am using liquid to pull the cart value into the Paypal JS.

I have achieved this with the following code:

{% capture paypal_price %}
  {%- include 'ecommerce/price_total', format_type: 'formatted' -%}
{% endcapture %}

and

value: "{{ paypal_price | remove:'£' }}"

Functionally it pull through the correct price but as you can see from the image below and error occurs as it pushes it down onto a new line.

Liquid Issue in Console

Is this a known issue and does anyone have a fix for this?

Body:
The following amendment to the Liquid fixed it :)

{{ paypal_price | remove:'£' | strip_newlines }}


问:
Trying to figure out how to change background image depending on the genre of that particular book REACT
*I am currently trying to figure out how to change the background image of my book--container--fiction. I have three different images and depending on the genre of the book I would like to change these images but I am unsure on how to do that. Any help would be great :) I presume it would be similar to doing an if statement. Im just not sure how to go about it </p>

```<code>  if(book.genre === "fiction") {
           return <div className="book--container--fiction"></div>
   } else if (book.genre === "non-fiction"){
           return <div className="book--container--non-fiction"></div>
    } else{
           return <div className="book--container--children"></div>
      }
</code>```

<p>*</p>

```<code>import React from "react";
import "../stylesheets/Book.scss";
import { FiHeart } from "react-icons/fi";
import { Link } from "react-router-dom";
import isBookInWishlist from "../helper/isBookInWishList";

function Book({ book, handleSelectBook, handleSelectWishList, wishlist }) {
  return (
    <React.Fragment>
      <div className="book--container--fiction">
        <div className="book--wrapper">
          <div className="book--image">
            <img
              src={book.url}
              alt={book.title}
              className="book--image-style"
            />
          </div>
          <div className="book--content--wrapper">
            <div className="book--text--information">
              <h3>
                {book.title}
                <button
                  onClick={() => handleSelectWishList(book)}
                  className={
                    isBookInWishlist(book, wishlist)
                      ? "wishlist--icon orange"
                      : "wishlist--icon"
                  }
                >
                  <FiHeart />
                </button>
              </h3>

              <p>{book.author}</p>
              <p>{book.genre}</p>
              {/* <p>{book.desc}</p> */}
              <p className="book--price--style"> € {book.price}</p>
            </div>
            <Link
              to="/productdetails"
              className="view--book--button"
              onClick={() => handleSelectBook(book)}
            >
              View Book
            </Link>
          </div>
        </div>
      </div>
    </React.Fragment>
  );
}
export default Book;

</code>```

答:
You can make use of template literals in JS like so:-</p>

```<code>import React from "react";
import "../stylesheets/Book.scss";
import { FiHeart } from "react-icons/fi";
import { Link } from "react-router-dom";
import isBookInWishlist from "../helper/isBookInWishList";

function Book({ book, handleSelectBook, handleSelectWishList, wishlist }) {
  return (
    <React.Fragment>
      <div className={`book--container--${book.genre}`}>
        <div className="book--wrapper">
          <div className="book--image">
            <img
              src={book.url}
              alt={book.title}
              className="book--image-style"
            />
          </div>
          <div className="book--content--wrapper">
            <div className="book--text--information">
              <h3>
                {book.title}
                <button
                  onClick={() => handleSelectWishList(book)}
                  className={
                    isBookInWishlist(book, wishlist)
                      ? "wishlist--icon orange"
                      : "wishlist--icon"
                  }
                >
                  <FiHeart />
                </button>
              </h3>

              <p>{book.author}</p>
              <p>{book.genre}</p>
              {/* <p>{book.desc}</p> */}
              <p className="book--price--style"> € {book.price}</p>
            </div>
            <Link
              to="/productdetails"
              className="view--book--button"
              onClick={() => handleSelectBook(book)}
            >
              View Book
            </Link>
          </div>
        </div>
      </div>
    </React.Fragment>
  );
}
export default Book;
</code>```

Body:
*I am currently trying to figure out how to change the background image of my book--container--fiction. I have three different images and depending on the genre of the book I would like to change these images but I am unsure on how to do that. Any help would be great :) I presume it would be similar to doing an if statement. Im just not sure how to go about it

  if(book.genre === "fiction") {
           return

   } else if (book.genre === "non-fiction"){
           return

    } else{
           return

      }

*

import React from "react";
import "../stylesheets/Book.scss";
import { FiHeart } from "react-icons/fi";
import { Link } from "react-router-dom";
import isBookInWishlist from "../helper/isBookInWishList";

function Book({ book, handleSelectBook, handleSelectWishList, wishlist }) {
  return (
    <React.Fragment>

                {book.title}
                <button
                  onClick={() => handleSelectWishList(book)}
                  className={
                    isBookInWishlist(book, wishlist)
                      ? "wishlist--icon orange"
                      : "wishlist--icon"
                  }
                >
                  <FiHeart />
                </button>

{book.author}

{book.genre}

              {/*
{book.desc}
 */}

 € {book.price}

            <Link
              to="/productdetails"
              className="view--book--button"
              onClick={() => handleSelectBook(book)}
            >
              View Book
            </Link>

    </React.Fragment>
  );
}
export default Book;

Body:
You can make use of template literals in JS like so:-

import React from "react";
import "../stylesheets/Book.scss";
import { FiHeart } from "react-icons/fi";
import { Link } from "react-router-dom";
import isBookInWishlist from "../helper/isBookInWishList";

function Book({ book, handleSelectBook, handleSelectWishList, wishlist }) {
  return (
    <React.Fragment>
      <div className={`book--container--${book.genre}`}>
        <div className="book--wrapper">
          <div className="book--image">
            <img
              src={book.url}
              alt={book.title}
              className="book--image-style"
            />
          </div>
          <div className="book--content--wrapper">
            <div className="book--text--information">
              <h3>
                {book.title}
                <button
                  onClick={() => handleSelectWishList(book)}
                  className={
                    isBookInWishlist(book, wishlist)
                      ? "wishlist--icon orange"
                      : "wishlist--icon"
                  }
                >
                  <FiHeart />
                </button>
              </h3>

              <p>{book.author}</p>
              <p>{book.genre}</p>
              {/* <p>{book.desc}</p> */}
              <p className="book--price--style"> &euro; {book.price}</p>
            </div>
            <Link
              to="/productdetails"
              className="view--book--button"
              onClick={() => handleSelectBook(book)}
            >
              View Book
            </Link>
          </div>
        </div>
      </div>
    </React.Fragment>
  );
}
export default Book;


问:
Troubles when trying to "remove by index" on a Purely functional Linked List
As the title states, I have been trying to code singly linked lists and its operations on a purely functional implementation. Things where pretty breezy up until now, lots of recursion, no modification... the works.

I then tried to implement a function to remove an element from a list, given a certain index. I can't for the life of me find a way to implement this without using a counter. It's almost like asking myself, "how to I know how many steps I have walked without myself or an spectator counting them?".

Since then I've been on a slump.

Here's the code I have so far:

```<code>    fun <T> removeFromIndex(list:ListNode<T>?, index: Int):ListNode<T>?{
        if(list?.data == null){
            return list
        }
            else{
            when(index){
                0 -> remove(list)
                else -> {
                    when(listSize(list) - index){
                        0 -> {
                            return list
                        }
                        1 -> {
                            removeFromTail(list)
                        }
                        else -> {
                            TODO()//HOW?
                        }

                    }
                }
            }
        }
    }

fun <T> remove(list: ListNode<T>?):ListNode<T>?{
       return if(list?.data == null){
            list
        }
        else{
            list.next
        }
    }

fun <T> removeFromTail(list:ListNode<T>?):ListNode<T>?{
        return if(list?.data == null){
            list
        } else{
            when(list.next){
                null -> null
                else -> {
                    ListNode(list.data, removeFromTail(list.next))
                }
            }
        }
    }

</code>```

Thanks a lot in advance for your help and input.

答:
Easy peasy:</p>

```<code>fun <T> removeFromIndex(list:ListNode<T>?, index: Int):ListNode<T>? = when {
    list == null || index < 0 -> list
    index == 0 -> list.next
    else -> ListNode<T> (
        list.data,
        removeFromIndex(list.next, index-1)
    )
}
</code>```

Body:
As the title states, I have been trying to code singly linked lists and its operations on a purely functional implementation. Things where pretty breezy up until now, lots of recursion, no modification... the works.

I then tried to implement a function to remove an element from a list, given a certain index. I can't for the life of me find a way to implement this without using a counter. It's almost like asking myself, "how to I know how many steps I have walked without myself or an spectator counting them?".

Since then I've been on a slump.

Here's the code I have so far:

    fun <T> removeFromIndex(list:ListNode<T>?, index: Int):ListNode<T>?{
        if(list?.data == null){
            return list
        }
            else{
            when(index){
                0 -> remove(list)
                else -> {
                    when(listSize(list) - index){
                        0 -> {
                            return list
                        }
                        1 -> {
                            removeFromTail(list)
                        }
                        else -> {
                            TODO()//HOW?
                        }

                    }
                }
            }
        }
    }

fun <T> remove(list: ListNode<T>?):ListNode<T>?{
       return if(list?.data == null){
            list
        }
        else{
            list.next
        }
    }

fun <T> removeFromTail(list:ListNode<T>?):ListNode<T>?{
        return if(list?.data == null){
            list
        } else{
            when(list.next){
                null -> null
                else -> {
                    ListNode(list.data, removeFromTail(list.next))
                }
            }
        }
    }

Thanks a lot in advance for your help and input.

Body:
Easy peasy:

fun <T> removeFromIndex(list:ListNode<T>?, index: Int):ListNode<T>? = when {
    list == null || index < 0 -> list
    index == 0 -> list.next
    else -> ListNode<T> (
        list.data,
        removeFromIndex(list.next, index-1)
    )
}


问:
queryTxt ETIMEOUT merncluster-0jdze.mongodb.net
I'm using nodejs with MongoDB server using mongoose, whenever I try to run my server, it won't connect to my database. After sometime above log is seen on CMD. My cluster name is merncluster here!!

Is there any solution to this, I've searched a lot, still can't find proper solution to this, this keeps happening all the time.

答: You may need to whitelist your IP address in MongoDB Atlas.</p>


问:
Parameter index out of range (1 > number of parameters, which is 0) When trying to read SQL Table
So I am trying to get some data out of my SQL Table with this servlet and output it in a JSP file.
I found some articles with similar problems to mine but none of them helped in my case. I Hoped someone here can help me.

I have to do this Project for one of my classes. I am basically programming an online shop for Clothing. If I click on for example t-shirts, I want this code to put out all data it can find under the sql table "t-shirts" into a JSP file.

From what i learned from other peoples mistakes is that my SQL Query is wrong. But i dont understand why it marks me line 39 as false When I call the Method display().

So Here is my Code:

```<code>    @WebServlet("/DisplayClothes")
    public class DisplayClothes extends HttpServlet {
        private static final long serialVersionUID = 1L;

    public DisplayClothes() {
        super();

    }
    @Resource(lookup = "java:jboss/datasources/MySqlThidbDS")
    private DataSource ds;

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        List<Clothes> Clothes= display();

        HttpSession session = request.getSession();
        session.setAttribute("Clothes", Clothes);

        final RequestDispatcher dispatcher = request.getRequestDispatcher("./JSP/ViewColthing.jsp");
        dispatcher.forward(request, response);
    }

    public List<Clothes> display() throws ServletException{

        List<Clothes> cl = new ArrayList<Clothes>();

        try (Connection con = ds.getConnection();
                 PreparedStatement pstmt = con.prepareStatement("SELECT * FROM clothes")) {

            pstmt.setInt(1, 1);

            try (ResultSet rs = pstmt.executeQuery()) {

                while (rs.next()) {

                    Clothes clothes= new Clothes();
                    clothes.setId(Long.valueOf(rs.getInt("id")));
                    clothes.setName(rs.getString("name"));
                    clothes.setDes(rs.getString("description"));
                    clothes.price(rs.getFloat("preis"));
                    clothes.setSize(rs.getString("sizes"));
                    clothes.setQuantity(rs.getInt("quantity"));

                    cl.add(Clothes);
                }
            }
        } catch (Exception ex) {
            throw new ServletException(ex.getMessage());
        }

        return cl;
        }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        doGet(request, response);
    }

}
</code>```

And I get This Error message.

```<code>javax.servlet.ServletException: Parameter index out of range (1 > number of parameters, which is 0).
    at Servlets.DisplayClothes.display(DisplayClothes.java:76)
    at Servlets.DisplayClothes.doGet(DisplayClothes.java:39)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:503)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:590)
    at io.undertow.servlet.handlers.ServletHandler.handleRequest(ServletHandler.java:74)
    at io.undertow.servlet.handlers.security.ServletSecurityRoleHandler.handleRequest(ServletSecurityRoleHandler.java:62)
    at io.undertow.servlet.handlers.ServletChain$1.handleRequest(ServletChain.java:68)
    at io.undertow.servlet.handlers.ServletDispatchingHandler.handleRequest(ServletDispatchingHandler.java:36)
    at org.wildfly.extension.undertow.security.SecurityContextAssociationHandler.handleRequest(SecurityContextAssociationHandler.java:78)
    at io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43)
    at io.undertow.servlet.handlers.RedirectDirHandler.handleRequest(RedirectDirHandler.java:68)
    at io.undertow.servlet.handlers.security.SSLInformationAssociationHandler.handleRequest(SSLInformationAssociationHandler.java:132)
    at io.undertow.servlet.handlers.security.ServletAuthenticationCallHandler.handleRequest(ServletAuthenticationCallHandler.java:57)
    at io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43)
    at io.undertow.security.handlers.AbstractConfidentialityHandler.handleRequest(AbstractConfidentialityHandler.java:46)
    at io.undertow.servlet.handlers.security.ServletConfidentialityConstraintHandler.handleRequest(ServletConfidentialityConstraintHandler.java:64)
    at io.undertow.security.handlers.AuthenticationMechanismsHandler.handleRequest(AuthenticationMechanismsHandler.java:60)
    at io.undertow.servlet.handlers.security.CachedAuthenticatedSessionHandler.handleRequest(CachedAuthenticatedSessionHandler.java:77)
    at io.undertow.security.handlers.NotificationReceiverHandler.handleRequest(NotificationReceiverHandler.java:50)
    at io.undertow.security.handlers.AbstractSecurityContextAssociationHandler.handleRequest(AbstractSecurityContextAssociationHandler.java:43)
    at io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43)
    at org.wildfly.extension.undertow.security.jacc.JACCContextIdHandler.handleRequest(JACCContextIdHandler.java:61)
    at io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43)
    at org.wildfly.extension.undertow.deployment.GlobalRequestControllerHandler.handleRequest(GlobalRequestControllerHandler.java:68)
    at io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43)
    at io.undertow.servlet.handlers.ServletInitialHandler.handleFirstRequest(ServletInitialHandler.java:269)
    at io.undertow.servlet.handlers.ServletInitialHandler.access$100(ServletInitialHandler.java:78)
    at io.undertow.servlet.handlers.ServletInitialHandler$2.call(ServletInitialHandler.java:133)
    at io.undertow.servlet.handlers.ServletInitialHandler$2.call(ServletInitialHandler.java:130)
    at io.undertow.servlet.core.ServletRequestContextThreadSetupAction$1.call(ServletRequestContextThreadSetupAction.java:48)
    at io.undertow.servlet.core.ContextClassLoaderSetupAction$1.call(ContextClassLoaderSetupAction.java:43)
    at org.wildfly.extension.undertow.security.SecurityContextThreadSetupAction.lambda$create$0(SecurityContextThreadSetupAction.java:105)
    at org.wildfly.extension.undertow.deployment.UndertowDeploymentInfoService$UndertowThreadSetupAction.lambda$create$0(UndertowDeploymentInfoService.java:1504)
    at org.wildfly.extension.undertow.deployment.UndertowDeploymentInfoService$UndertowThreadSetupAction.lambda$create$0(UndertowDeploymentInfoService.java:1504)
    at org.wildfly.extension.undertow.deployment.UndertowDeploymentInfoService$UndertowThreadSetupAction.lambda$create$0(UndertowDeploymentInfoService.java:1504)
    at org.wildfly.extension.undertow.deployment.UndertowDeploymentInfoService$UndertowThreadSetupAction.lambda$create$0(UndertowDeploymentInfoService.java:1504)
    at io.undertow.servlet.handlers.ServletInitialHandler.dispatchRequest(ServletInitialHandler.java:249)
    at io.undertow.servlet.handlers.ServletInitialHandler.access$000(ServletInitialHandler.java:78)
    at io.undertow.servlet.handlers.ServletInitialHandler$1.handleRequest(ServletInitialHandler.java:99)
    at io.undertow.server.Connectors.executeRootHandler(Connectors.java:376)
    at io.undertow.server.HttpServerExchange$1.run(HttpServerExchange.java:830)
    at org.jboss.threads.ContextClassLoaderSavingRunnable.run(ContextClassLoaderSavingRunnable.java:35)
    at org.jboss.threads.EnhancedQueueExecutor.safeRun(EnhancedQueueExecutor.java:1982)
    at org.jboss.threads.EnhancedQueueExecutor$ThreadBody.doRunTask(EnhancedQueueExecutor.java:1486)
    at org.jboss.threads.EnhancedQueueExecutor$ThreadBody.run(EnhancedQueueExecutor.java:1377)
    at java.lang.Thread.run(Thread.java:748)
</code>```

答:
There are no bind parameters in your query. Remove

```<code>pstmt.setInt(1, 1);
</code>```

There is nothing to set. Also,

```<code>cl.add(Clothes);
</code>```

should be

```<code>cl.add(clothes);
</code>```

Body:
So I am trying to get some data out of my SQL Table with this servlet and output it in a JSP file.
I found some articles with similar problems to mine but none of them helped in my case. I Hoped someone here can help me.

I have to do this Project for one of my classes. I am basically programming an online shop for Clothing. If I click on for example t-shirts, I want this code to put out all data it can find under the sql table "t-shirts" into a JSP file.

From what i learned from other peoples mistakes is that my SQL Query is wrong. But i dont understand why it marks me line 39 as false When I call the Method display().

So Here is my Code:

    @WebServlet("/DisplayClothes")
    public class DisplayClothes extends HttpServlet {
        private static final long serialVersionUID = 1L;

    public DisplayClothes() {
        super();

    }
    @Resource(lookup = "java:jboss/datasources/MySqlThidbDS")
    private DataSource ds;

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        List<Clothes> Clothes= display();

        HttpSession session = request.getSession();
        session.setAttribute("Clothes", Clothes);

        final RequestDispatcher dispatcher = request.getRequestDispatcher("./JSP/ViewColthing.jsp");
        dispatcher.forward(request, response);
    }

    public List<Clothes> display() throws ServletException{

        List<Clothes> cl = new ArrayList<Clothes>();

        try (Connection con = ds.getConnection();
                 PreparedStatement pstmt = con.prepareStatement("SELECT * FROM clothes")) {

            pstmt.setInt(1, 1);

            try (ResultSet rs = pstmt.executeQuery()) {

                while (rs.next()) {

                    Clothes clothes= new Clothes();
                    clothes.setId(Long.valueOf(rs.getInt("id")));
                    clothes.setName(rs.getString("name"));
                    clothes.setDes(rs.getString("description"));
                    clothes.price(rs.getFloat("preis"));
                    clothes.setSize(rs.getString("sizes"));
                    clothes.setQuantity(rs.getInt("quantity"));

                    cl.add(Clothes);
                }
            }
        } catch (Exception ex) {
            throw new ServletException(ex.getMessage());
        }

        return cl;
        }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        doGet(request, response);
    }

}

And I get This Error message.

javax.servlet.ServletException: Parameter index out of range (1 > number of parameters, which is 0).
    at Servlets.DisplayClothes.display(DisplayClothes.java:76)
    at Servlets.DisplayClothes.doGet(DisplayClothes.java:39)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:503)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:590)
    at io.undertow.servlet.handlers.ServletHandler.handleRequest(ServletHandler.java:74)
    at io.undertow.servlet.handlers.security.ServletSecurityRoleHandler.handleRequest(ServletSecurityRoleHandler.java:62)
    at io.undertow.servlet.handlers.ServletChain$1.handleRequest(ServletChain.java:68)
    at io.undertow.servlet.handlers.ServletDispatchingHandler.handleRequest(ServletDispatchingHandler.java:36)
    at org.wildfly.extension.undertow.security.SecurityContextAssociationHandler.handleRequest(SecurityContextAssociationHandler.java:78)
    at io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43)
    at io.undertow.servlet.handlers.RedirectDirHandler.handleRequest(RedirectDirHandler.java:68)
    at io.undertow.servlet.handlers.security.SSLInformationAssociationHandler.handleRequest(SSLInformationAssociationHandler.java:132)
    at io.undertow.servlet.handlers.security.ServletAuthenticationCallHandler.handleRequest(ServletAuthenticationCallHandler.java:57)
    at io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43)
    at io.undertow.security.handlers.AbstractConfidentialityHandler.handleRequest(AbstractConfidentialityHandler.java:46)
    at io.undertow.servlet.handlers.security.ServletConfidentialityConstraintHandler.handleRequest(ServletConfidentialityConstraintHandler.java:64)
    at io.undertow.security.handlers.AuthenticationMechanismsHandler.handleRequest(AuthenticationMechanismsHandler.java:60)
    at io.undertow.servlet.handlers.security.CachedAuthenticatedSessionHandler.handleRequest(CachedAuthenticatedSessionHandler.java:77)
    at io.undertow.security.handlers.NotificationReceiverHandler.handleRequest(NotificationReceiverHandler.java:50)
    at io.undertow.security.handlers.AbstractSecurityContextAssociationHandler.handleRequest(AbstractSecurityContextAssociationHandler.java:43)
    at io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43)
    at org.wildfly.extension.undertow.security.jacc.JACCContextIdHandler.handleRequest(JACCContextIdHandler.java:61)
    at io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43)
    at org.wildfly.extension.undertow.deployment.GlobalRequestControllerHandler.handleRequest(GlobalRequestControllerHandler.java:68)
    at io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43)
    at io.undertow.servlet.handlers.ServletInitialHandler.handleFirstRequest(ServletInitialHandler.java:269)
    at io.undertow.servlet.handlers.ServletInitialHandler.access$100(ServletInitialHandler.java:78)
    at io.undertow.servlet.handlers.ServletInitialHandler$2.call(ServletInitialHandler.java:133)
    at io.undertow.servlet.handlers.ServletInitialHandler$2.call(ServletInitialHandler.java:130)
    at io.undertow.servlet.core.ServletRequestContextThreadSetupAction$1.call(ServletRequestContextThreadSetupAction.java:48)
    at io.undertow.servlet.core.ContextClassLoaderSetupAction$1.call(ContextClassLoaderSetupAction.java:43)
    at org.wildfly.extension.undertow.security.SecurityContextThreadSetupAction.lambda$create$0(SecurityContextThreadSetupAction.java:105)
    at org.wildfly.extension.undertow.deployment.UndertowDeploymentInfoService$UndertowThreadSetupAction.lambda$create$0(UndertowDeploymentInfoService.java:1504)
    at org.wildfly.extension.undertow.deployment.UndertowDeploymentInfoService$UndertowThreadSetupAction.lambda$create$0(UndertowDeploymentInfoService.java:1504)
    at org.wildfly.extension.undertow.deployment.UndertowDeploymentInfoService$UndertowThreadSetupAction.lambda$create$0(UndertowDeploymentInfoService.java:1504)
    at org.wildfly.extension.undertow.deployment.UndertowDeploymentInfoService$UndertowThreadSetupAction.lambda$create$0(UndertowDeploymentInfoService.java:1504)
    at io.undertow.servlet.handlers.ServletInitialHandler.dispatchRequest(ServletInitialHandler.java:249)
    at io.undertow.servlet.handlers.ServletInitialHandler.access$000(ServletInitialHandler.java:78)
    at io.undertow.servlet.handlers.ServletInitialHandler$1.handleRequest(ServletInitialHandler.java:99)
    at io.undertow.server.Connectors.executeRootHandler(Connectors.java:376)
    at io.undertow.server.HttpServerExchange$1.run(HttpServerExchange.java:830)
    at org.jboss.threads.ContextClassLoaderSavingRunnable.run(ContextClassLoaderSavingRunnable.java:35)
    at org.jboss.threads.EnhancedQueueExecutor.safeRun(EnhancedQueueExecutor.java:1982)
    at org.jboss.threads.EnhancedQueueExecutor$ThreadBody.doRunTask(EnhancedQueueExecutor.java:1486)
    at org.jboss.threads.EnhancedQueueExecutor$ThreadBody.run(EnhancedQueueExecutor.java:1377)
    at java.lang.Thread.run(Thread.java:748)

Body:
There are no bind parameters in your query. Remove

pstmt.setInt(1, 1);

There is nothing to set. Also,

cl.add(Clothes);

should be

cl.add(clothes);


问:
Is it possible for a SQL query to crash a database
So for one of my computing assignments, I need to state, some changes that could not be made since they were out of scope.

One of the changes I intend to talk about is to "Reconsider if acquiring all the reports in a Enterprise Resource Planning software is needed"

My main argument is this, say we have  a ERP software which is hooked to database, the multinational corporation which is utilizing a database, stores approximately 25 million reports.

Can running a SQL query, which retrieves all the reports crash/really slow down the software system/crash the database.

答:
Can running a SQL query, which retrieves all the reports crash/really slow down the software system/crash the database.

Our databases run saved searches(TSQL generated by ORM  from frontend),one day we observed SQLSERVER  is very slow and not responsive enough.

We found the cause to be a  sql query generated by ORM and that sql query doesn't have any suitable index and this same query is ran by multiple people as part of their work.

so answer to your question is YES


问:
Insert client input into MySQL database with C
How do I write a C program which gets the client input for MySQL server? I'm using Fedora as my OS.

Here is my code:

```<code>#include<my_global.h>
#include<mysql.h>

main()
{
    char name[25];
    MYSQL *conn;
    conn=mysql_init(NULL);
    mysql_real_connect(conn,"localhost","root","","testdb",0,NULL,0);
    printf("Enter your name:");
    scanf("%s",name);
    mysql_query(conn,"CREATE TABLE Users(name VARCHAR(25))");

    mysql_query(conn,"INSERT INTO Users VALUES(name)");
    //mysql_query(conn,"INSERT INTO Users VALUES('Farhan')");
    //mysql_query(conn,"INSERT INTO Users VALUES('Dileep')");
    //mysql_query(conn,"INSERT INTO Users VALUES('RAJIV')");

    mysql_close(conn);
}
</code>```

I want the client input to be stored in MySQL database and not the constant values.

答:
Try sprintf'ing the name into your query, something like this:

```<code>int len = query_len + name_len + 1;
char * insert_query = (char *) malloc(len);
snprintf(insert_query, len, "INSERT INTO Users VALUES('%s')", name);
</code>```

However, you'll need to take some care when checking the buffer lengths and especially escaping the name string.

ContentLicense: CC BY-SA 3.0

Body:
How do I write a C program which gets the client input for MySQL server? I'm using Fedora as my OS.

Here is my code:

#include<my_global.h>
#include<mysql.h>

main()
{
    char name[25];
    MYSQL *conn;
    conn=mysql_init(NULL);
    mysql_real_connect(conn,"localhost","root","","testdb",0,NULL,0);
    printf("Enter your name:");
    scanf("%s",name);
    mysql_query(conn,"CREATE TABLE Users(name VARCHAR(25))");

    mysql_query(conn,"INSERT INTO Users VALUES(name)");
    //mysql_query(conn,"INSERT INTO Users VALUES('Farhan')");
    //mysql_query(conn,"INSERT INTO Users VALUES('Dileep')");
    //mysql_query(conn,"INSERT INTO Users VALUES('RAJIV')");

    mysql_close(conn);
}

I want the client input to be stored in MySQL database and not the constant values.

Body:
Try sprintf'ing the name into your query, something like this:

int len = query_len + name_len + 1;
char * insert_query = (char *) malloc(len);
snprintf(insert_query, len, "INSERT INTO Users VALUES('%s')", name);

However, you'll need to take some care when checking the buffer lengths and especially escaping the name string.


问:
Extracting and merging dataframes from an S4 class list in R
I have an S4 class list (called vi2). This is the first segment of it:

@variables: chr [1:7]

@vImplist: list of 400

$1: Formal class '.vImp' with 2 slots

@Variables: chr [1:7]

@vImp: 'data.frame': 7 bs. of 3 variables:

$variables:Factor w/ 7 levels

$Ctest: num [1:7]

$Atest: num [1:7]

$2: Formal class '.vImp' with 2 slots

@Variables: chr [1:7]

@vImp: 'data.frame': 7 bs. of 3 variables:

$variables:Factor w/ 7 levels

$Ctest: num [1:7]

$Atest: num [1:7]

In total there are 400 classes of '.vImp' which are all in the same format. What I am attempting to do is extract the '@vImp: data. frame' for each class and merge them into a new dataframe. I able am to do this individually with the following line:

```<code>vic = as.data.frame(vi2@vImplist$'1'@vImp)
</code>```

This produces the data.frame with the correct information for that class. However when I try performing this for all 400 classes at once, it fails.

```<code>vic = as.data.frame(vi2@vImplist$'1:400'@vImp)
</code>```

Error in as.data.frame(vi2@vImplist$'1:400'@vImp) :
  trying to get slot "vImp" from an object of a basic class ("NULL") with no slots.

I also tried using a loop to complete the task. However, this also failed with the same error:

```<code>for (i in seq(from = 1, to = 1, by = 1)) {
vic = as.data.frame(vi2@vImplist$'[i]'@vImp)
output <- rbind(newdf,vic)
}
</code>```

Does anyone have any suggestions for what the problem might be?

答:
According to the given information, vImplist is a list with 400 entries, so you want to access every of this entry. The entries have the names '1', ..., '400'. Therefore, your code vic = as.data.frame(vi2@vImplist$'1'@vImp) works. You references the list entry by its name ('1' is a character). When you use '1:400' or '[i]', this is also interpreted as a name due to ''. Because these data.frames don't exist, NULL is returned, from which it is tried to retrieve the slot "vImp". This explains your error message.

You need to iterate over all entries of the list. The easiest way is to do this with lapply which operates on every entry of the list and you can retrieve the correct slot:

```<code>vic <- lapply(vi2@vImplist, function(x) {
  as.data.frame(x@vImp)
})
</code>```

vic is now a list of data.frames. If you use rbind with do.call, you can directly use the list of data.frames as the input arguments, as do.call accepts a list of arguments:

```<code>output <- do.call("rbind", vic)
</code>```

Edit

As @Rui Barradas pointed out, vImp is already a data.frame, so you don't need as.data.frame. Also, you can directly access the slots with slot and use the name of the accessed slot as a further argument to the function:

```<code>vic <- lapply(vi2@vImplist, slot, 'vImp')
</code>```

Body:
I have an S4 class list (called vi2). This is the first segment of it:

@variables: chr [1:7]

@vImplist: list of 400

$1: Formal class '.vImp' with 2 slots

@Variables: chr [1:7]

@vImp: 'data.frame': 7 bs. of 3 variables:

$variables:Factor w/ 7 levels

$Ctest: num [1:7]

$Atest: num [1:7]

$2: Formal class '.vImp' with 2 slots

@Variables: chr [1:7]

@vImp: 'data.frame': 7 bs. of 3 variables:

$variables:Factor w/ 7 levels

$Ctest: num [1:7]

$Atest: num [1:7]

In total there are 400 classes of '.vImp' which are all in the same format. What I am attempting to do is extract the '@vImp: data. frame' for each class and merge them into a new dataframe. I able am to do this individually with the following line:

vic = as.data.frame(vi2@vImplist$'1'@vImp)

This produces the data.frame with the correct information for that class. However when I try performing this for all 400 classes at once, it fails.

vic = as.data.frame(vi2@vImplist$'1:400'@vImp)

Error in as.data.frame(vi2@vImplist$'1:400'@vImp) :
  trying to get slot "vImp" from an object of a basic class ("NULL") with no slots.

I also tried using a loop to complete the task. However, this also failed with the same error:

for (i in seq(from = 1, to = 1, by = 1)) {
vic = as.data.frame(vi2@vImplist$'[i]'@vImp)
output <- rbind(newdf,vic)
}

Does anyone have any suggestions for what the problem might be?

Body:
According to the given information, vImplist is a list with 400 entries, so you want to access every of this entry. The entries have the names '1', ..., '400'. Therefore, your code vic = as.data.frame(vi2@vImplist$'1'@vImp) works. You references the list entry by its name ('1' is a character). When you use '1:400' or '[i]', this is also interpreted as a name due to ''. Because these data.frames don't exist, NULL is returned, from which it is tried to retrieve the slot "vImp". This explains your error message.

You need to iterate over all entries of the list. The easiest way is to do this with lapply which operates on every entry of the list and you can retrieve the correct slot:

vic <- lapply(vi2@vImplist, function(x) {
  as.data.frame(x@vImp)
})

vic is now a list of data.frames. If you use rbind with do.call, you can directly use the list of data.frames as the input arguments, as do.call accepts a list of arguments:

output <- do.call("rbind", vic)

Edit

As @Rui Barradas pointed out, vImp is already a data.frame, so you don't need as.data.frame. Also, you can directly access the slots with slot and use the name of the accessed slot as a further argument to the function:

vic <- lapply(vi2@vImplist, slot, 'vImp')


问:
Reason and suggestion for: TypeError: not all arguments converted during string formatting
Why this error is occurring and how can I fix it?
I am trying to write this code as a practice in codewars.

```<code>def iq_test(numbers):
    splitted_num=numbers.split()
    list_numbers= list(splitted_num)#splitted string was already a list
    odds = [x for x in list_numbers if x%2!=0]
    evens= [x for x in list_numbers if x%2==0]
    return (odds.index[0, 1] if len(odds)<len(evens) else evens[0, 1])

numbers= ("2 4 7 8 10")
print(iq_test(numbers))
</code>```

ERROR:

```<code>Traceback (most recent call last):
  File "C:\Users\Masoud\Desktop\Python Exercises\codewars\9_IQ Test.py", line 13, in <module>
    print(iq_test(numbers))
  File "C:\Users\Masoud\Desktop\Python Exercises\codewars\9_IQ Test.py", line 8, in iq_test
    odds = [x for x in list_numbers if x%2!=0]
  File "C:\Users\Masoud\Desktop\Python Exercises\codewars\9_IQ Test.py", line 8, in <listcomp>
    odds = [x for x in list_numbers if x%2!=0]
TypeError: not all arguments converted during string formatting
</code>```

This is the question:

Bob is preparing to pass IQ test. The most frequent task in this test is to find out which one of the given numbers differs from the others. Bob observed that one number usually differs from the others in evenness. Help Bob — to check his answers, he needs a program that among the given numbers finds one that is different in evenness, and return a position of this number. Question: ! Keep in mind that your task is to help Bob solve a real IQ test, which means indexes of the elements start from 1 (not 0)

答:
Your list_numbers is a list of strings, ['2', '4', '7', '8', '10']

When operating on a string, the % operator has a different meaning than what it means for integers.  It is probably not worth describing that operation in detail, because its use is no longer recommended, although it relates to string formatting.  It also so happens that the values used in that operation were such as to cause a TypeError, but even if it had succeeded, the operation involving strings would still not have given the intended result.

The important thing for the current purpose is that the values in your list_numbers need to be converted into int and then the % operator will do what you intend it to, namely arithmetic modulo.  I would suggest replacing:

```<code>    list_numbers= list(splitted_num)
</code>```

with:

```<code>    list_numbers = [int(s) for s in splitted_num]
</code>```

You also have errors in your return statement, because odds.index[0, 1] and evens[0, 1] are not valid expressions here.  Given the problem which you are trying to solve, you could use something like this:

```<code>    return 1 + list_numbers.index(
        odds[0] if len(odds) < len(evens) else evens[0])
</code>```

Body:
Why this error is occurring and how can I fix it?
I am trying to write this code as a practice in codewars.

def iq_test(numbers):
    splitted_num=numbers.split()
    list_numbers= list(splitted_num)#splitted string was already a list
    odds = [x for x in list_numbers if x%2!=0]
    evens= [x for x in list_numbers if x%2==0]
    return (odds.index[0, 1] if len(odds)<len(evens) else evens[0, 1])

numbers= ("2 4 7 8 10")
print(iq_test(numbers))

ERROR:

Traceback (most recent call last):
  File "C:\Users\Masoud\Desktop\Python Exercises\codewars\9_IQ Test.py", line 13, in <module>
    print(iq_test(numbers))
  File "C:\Users\Masoud\Desktop\Python Exercises\codewars\9_IQ Test.py", line 8, in iq_test
    odds = [x for x in list_numbers if x%2!=0]
  File "C:\Users\Masoud\Desktop\Python Exercises\codewars\9_IQ Test.py", line 8, in <listcomp>
    odds = [x for x in list_numbers if x%2!=0]
TypeError: not all arguments converted during string formatting

This is the question:

Bob is preparing to pass IQ test. The most frequent task in this test is to find out which one of the given numbers differs from the others. Bob observed that one number usually differs from the others in evenness. Help Bob — to check his answers, he needs a program that among the given numbers finds one that is different in evenness, and return a position of this number. Question: ! Keep in mind that your task is to help Bob solve a real IQ test, which means indexes of the elements start from 1 (not 0)

Body:
Your list_numbers is a list of strings, ['2', '4', '7', '8', '10']

When operating on a string, the % operator has a different meaning than what it means for integers.  It is probably not worth describing that operation in detail, because its use is no longer recommended, although it relates to string formatting.  It also so happens that the values used in that operation were such as to cause a TypeError, but even if it had succeeded, the operation involving strings would still not have given the intended result.

The important thing for the current purpose is that the values in your list_numbers need to be converted into int and then the % operator will do what you intend it to, namely arithmetic modulo.  I would suggest replacing:

    list_numbers= list(splitted_num)

with:

    list_numbers = [int(s) for s in splitted_num]

You also have errors in your return statement, because odds.index[0, 1] and evens[0, 1] are not valid expressions here.  Given the problem which you are trying to solve, you could use something like this:

    return 1 + list_numbers.index(
        odds[0] if len(odds) < len(evens) else evens[0])


问:
Moving roles switches them
I want my bot to create five roles and to order them in a specific way at a specific position.

Therefore, I am looping through a list of names and creating the roles accordingly. (This is not my actual code, but the idea behind it is the same.)

```<code>for (String name : roleNames) {
    event.getGuild().createRole().setColor(color).setName(name).queue(role -> {
    role.getGuild().modifyRolePositions().selectPosition(role.getPosition()).moveTo(role.getGuild().getRoles().size()-8).queue()});
}
</code>```

To clear things up, I try to move the role by selecting its initial position role.getPosition() and moving it to a specific position role.getGuild().getRoles().size()-8.

Since the position of the highest role in the list equals the number of roles, every role created should be moved to the exact same spot, thus moving every role beneath it one position lower.

But that is not what is happening.

When executing these lines of code and slowing the process down (by using Thread.sleep and/or .queueAfter()) I witnessed the following:

The first role is created at the bottom. Everything is fine.

The first role is moved to the destined position. Works.

The second role is created at the bottom as usual.

When the second role moves up to the position, it moves the first role down to where it was created (at the bottom).

This behavior can be seen until every role is created.
The last role stays where it belongs (since no other role switches its position).

Is there a logical issue in my code, is my way of doing this the wrong solution or is this just a discord issue? How can I possibly work around this behavior?

If you suspect this to be deeper rooted in my code please let me know, for that I can provide you with more details.

答:
ModifyRolePosition uses a cached version of the roles.

Changing only one position at a time results in the same cached version being modified everytime, which leads to the changes not being carried over.

That is why it is possible to make multiple manipulations on one call, by simply queuing multiple .selectPosition(initialPosition).moveTo(newPosition) together and committing them by calling .queue() once at the end.

Title: Moving roles switches them

Body:
I want my bot to create five roles and to order them in a specific way at a specific position.

Therefore, I am looping through a list of names and creating the roles accordingly. (This is not my actual code, but the idea behind it is the same.)

for (String name : roleNames) {
    event.getGuild().createRole().setColor(color).setName(name).queue(role -> {
    role.getGuild().modifyRolePositions().selectPosition(role.getPosition()).moveTo(role.getGuild().getRoles().size()-8).queue()});
}

To clear things up, I try to move the role by selecting its initial position role.getPosition() and moving it to a specific position role.getGuild().getRoles().size()-8.

Since the position of the highest role in the list equals the number of roles, every role created should be moved to the exact same spot, thus moving every role beneath it one position lower.

But that is not what is happening.

When executing these lines of code and slowing the process down (by using Thread.sleep and/or .queueAfter()) I witnessed the following:

The first role is created at the bottom. Everything is fine.

The first role is moved to the destined position. Works.

The second role is created at the bottom as usual.

When the second role moves up to the position, it moves the first role down to where it was created (at the bottom).

This behavior can be seen until every role is created.
The last role stays where it belongs (since no other role switches its position).

Is there a logical issue in my code, is my way of doing this the wrong solution or is this just a discord issue? How can I possibly work around this behavior?

If you suspect this to be deeper rooted in my code please let me know, for that I can provide you with more details.


问:
Play store error: can't install app try again, and it still doesn't work, see common ways to fix the problem
Ive released a new app on the play store yesterday and it was published. However when I try to download and install it shows this error: can't install app X try again, and it still doesn't work, see common ways to fix the problem.

I've tried to clear play store cache, data, reset the phone several times.
Tried on my Xiami Redmi note 5, also tried on another redmi not 7. Same error happens.

PS: I know that the app is working because installing it through Android Studio works perfectly fine. However when uploading to Play Store and trying to download it does not work. Also I've saw that after I've generated the APK file, it does not work. Ive tried to install using the APK file and it showed: "App was not installed"

答:
After a lot of failed attempts from last 3 days. Today, I figured out that the problem affecting my Android App Version Update – Can't Install Error Message was to change:

```<code>compileSdkVersion 'android-R'
buildToolsVersion '30.0.0 rc4'
targetSdkVersion 30
</code>```

to

```<code>compileSdkVersion 29
buildToolsVersion '29.0.3'
targetSdkVersion 29
</code>```

Now it is working on GooglePlay. Hope it helps. Thanks!

Body:
After a lot of failed attempts from last 3 days. Today, I figured out that the problem affecting my Android App Version Update – Can't Install Error Message was to change:

compileSdkVersion 'android-R'
buildToolsVersion '30.0.0 rc4'
targetSdkVersion 30

to

compileSdkVersion 29
buildToolsVersion '29.0.3'
targetSdkVersion 29

Now it is working on GooglePlay. Hope it helps. Thanks!


问:
TADOQuery - Edit mode inserts new record rather than editing
I'm puzzled at the behavior of the TADOQuery, let's just call Q. When I use Q.Edit, populate some fields, then Post, it ends up actually inserting a new record.

The code is simple, and reading the ID from an object:

```<code>Q.SQL.Text := 'select * from SomeTable where ID = :id';
Q.Parameters.ParamValues['id'] := MyObject.ID;
Q.Open;
try
  Q.Edit;
  try
    Q['SomeField']:= MyObject.SomeField;
  finally
    Q.Post;
  end;
finally
  Q.Close;
end;
</code>```

To my surprise, rather than updating the intended record, it decided to insert a new record. Stepping through the code, immediately after Q.Edit, the query is actually in Insert mode.

What could I be doing wrong here?

答:
I'm posting both a question and an answer, because the cause of the problem was totally unexpected behavior, and surely someone else had the same bewildering thing happen.

This happens in the event that the dataset you're trying to edit doesn't have any records. Personally, I would think it should produce an exception that you can't edit when there's no records. But the TADOQuery decides to append a new record instead.

The very root cause of this issue was that the object where I supplied the ID actually had a value of 0, and therefore since there's no record in the database with ID 0, it returned nothing.

Body:
I'm puzzled at the behavior of the TADOQuery, let's just call Q. When I use Q.Edit, populate some fields, then Post, it ends up actually inserting a new record.

The code is simple, and reading the ID from an object:

Q.SQL.Text := 'select * from SomeTable where ID = :id';
Q.Parameters.ParamValues['id'] := MyObject.ID;
Q.Open;
try
  Q.Edit;
  try
    Q['SomeField']:= MyObject.SomeField;
  finally
    Q.Post;
  end;
finally
  Q.Close;
end;

To my surprise, rather than updating the intended record, it decided to insert a new record. Stepping through the code, immediately after Q.Edit, the query is actually in Insert mode.

What could I be doing wrong here?


问:
how can i align my floating button to the bottom of the page in android studio
//Parent View

```<code>    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="@drawable/back4">
</code>```

//Relative Layout Child of ScrollView

```<code><RelativeLayout

        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_marginTop="40dp">
</code>```

//Grid View with Parent Relative Layout. Grid View not allowing floating button to align bottom

```<code>    <GridView
            android:id="@+id/gridview"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:verticalSpacing="50dp">

    </GridView>
</code>```

//Floating Button adding to Bottom of screen

```<code>    <com.google.android.material.floatingactionbutton.FloatingActionButton

            android:id="@+id/addNew"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_below="@+id/gridview"
            android:layout_alignParentEnd="true"
            android:src="@drawable/addbutton"/>
</code>```

//End of Relative Layout

```<code></RelativeLayout>
</code>```

//End of Scroll View

答:
Make some changes to your FloatingActionButton XML. Hope this works for you!

```<code><com.google.android.material.floatingactionbutton.FloatingActionButton
    android:id="@+id/addNew"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentEnd="true"
    android:layout_alignParentRight="true"
    android:layout_alignParentBottom="true"
    android:layout_margin="16dp"
    android:src="@drawable/addbutton" />
</code>```

Also, there is no need of vertically scrolling ScrollView as GridView is also a vertically scrolling widget(GridView).

Body:
//Parent View

    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="@drawable/back4">

//Relative Layout Child of ScrollView

<RelativeLayout

        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_marginTop="40dp">

//Grid View with Parent Relative Layout. Grid View not allowing floating button to align bottom

    <GridView
            android:id="@+id/gridview"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:verticalSpacing="50dp">

    </GridView>

//Floating Button adding to Bottom of screen

    <com.google.android.material.floatingactionbutton.FloatingActionButton

            android:id="@+id/addNew"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_below="@+id/gridview"
            android:layout_alignParentEnd="true"
            android:src="@drawable/addbutton"/>

//End of Relative Layout

</RelativeLayout>

//End of Scroll View

Body:
Make some changes to your FloatingActionButton XML. Hope this works for you!

<com.google.android.material.floatingactionbutton.FloatingActionButton
    android:id="@+id/addNew"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentEnd="true"
    android:layout_alignParentRight="true"
    android:layout_alignParentBottom="true"
    android:layout_margin="16dp"
    android:src="@drawable/addbutton" />

Also, there is no need of vertically scrolling ScrollView as GridView is also a vertically scrolling widget(GridView).


问:
How to flatten a nested dict and use inner values on collision
Question

For the following dictionary:

```<code>{'id': 1, 'label': 'hello', 'remove_me': {'world': {'keep_me': 52}}}
</code>```

I want to create a new dictionary without the remove_me or world keys.

Edit update:

To summarise, I wanted to do the following:

If the values of an item are a nested dictionary. Update the new dictionary with the inner result while removing the current key value from the main dict.

If the values of an item are not a nested dictionary, update the new dictionary with the key, value.

The accepted answer covers this.

What have I tried?

```<code>{k:v for (k,v) in d.items() if not k == 'remove_me'}
</code>```

yields:

```<code>{'id': 1, 'label': 'hello'}
</code>```

not exactly what I need as I'm dropping the nested dict.

Desired output:

```<code>{'id': 1, 'label': 'hello','keep_me': 52}
</code>```

答:
You might need to be a bit more specific about the structure of your dictionary, and how to handle multiple keys. Regardless, here's one recursive method that fits your description and attempts to preserve as many keys as possible.

```<code>def clean_kvp(k, v, invalid_keys=["remove_me", "world"]):
    if k not in invalid_keys:
        return [(k, v)]
    if not isinstance(v, dict):
        return []
    return [
        (kkk, vvv)
        for kk, vv in v.items()
        for kkk, vvv in clean_kvp(kk, vv)
    ]

def clean_dict(d):
    return {
        kk: vv
        for k, v in d.items()
        for kk, vv in clean_kvp(k, v)
    }
</code>```

A couple of tests:

```<code>>>> d = {'id': 1, 'label': 'hello', 'remove_me': {'world': {'keep_me': 52}}}
>>> clean_dict(d)
{'id': 1, 'label': 'hello', 'keep_me': 52}

>>> d = {
...     'id': 1,
...     'label': 'hello',
...     'remove_me': {'world': {'keep_me': 52, 'test': 2}}
... }
>>> clean_dict(d)
{'id': 1, 'label': 'hello', 'keep_me': 52, 'test': 2}

>>> d = {'id': 1, 'label': {'test': 'hello'}}
>>> clean_dict(d)
{'id': 1, 'label': {'test': 'hello'}}
</code>```

Body:
Question

For the following dictionary:

{'id': 1, 'label': 'hello', 'remove_me': {'world': {'keep_me': 52}}}

I want to create a new dictionary without the remove_me or world keys.

Edit update:

To summarise, I wanted to do the following:

If the values of an item are a nested dictionary. Update the new dictionary with the inner result while removing the current key value from the main dict.

If the values of an item are not a nested dictionary, update the new dictionary with the key, value.

The accepted answer covers this.

What have I tried?

{k:v for (k,v) in d.items() if not k == 'remove_me'}

yields:

{'id': 1, 'label': 'hello'}

not exactly what I need as I'm dropping the nested dict.

Desired output:

{'id': 1, 'label': 'hello','keep_me': 52}

Body:
You might need to be a bit more specific about the structure of your dictionary, and how to handle multiple keys. Regardless, here's one recursive method that fits your description and attempts to preserve as many keys as possible.

def clean_kvp(k, v, invalid_keys=["remove_me", "world"]):
    if k not in invalid_keys:
        return [(k, v)]
    if not isinstance(v, dict):
        return []
    return [
        (kkk, vvv)
        for kk, vv in v.items()
        for kkk, vvv in clean_kvp(kk, vv)
    ]

def clean_dict(d):
    return {
        kk: vv
        for k, v in d.items()
        for kk, vv in clean_kvp(k, v)
    }

A couple of tests:

>>> d = {'id': 1, 'label': 'hello', 'remove_me': {'world': {'keep_me': 52}}}
>>> clean_dict(d)
{'id': 1, 'label': 'hello', 'keep_me': 52}

>>> d = {
...     'id': 1,
...     'label': 'hello',
...     'remove_me': {'world': {'keep_me': 52, 'test': 2}}
... }
>>> clean_dict(d)
{'id': 1, 'label': 'hello', 'keep_me': 52, 'test': 2}

>>> d = {'id': 1, 'label': {'test': 'hello'}}
>>> clean_dict(d)
{'id': 1, 'label': {'test': 'hello'}}


问:
Make sure the same array items are not next to each other in php
I am struggling with this case. I have a random array that similar items can be in the next to each other and I don't want it to happen.

Example :

```<code>array("red","red","blue","green","green","blue");

Expected Output : array("red","blue","red","green","blue","green")
</code>```

So I was thinking about shuffle the items until there are no similar items in the next to each other. But it will take a lot of time if the array has a lot of values.

Is there any effective way to make it happen?

Any help would be appreciated. Thanks

答:
I ended up re-arrange to a new array. For those who have the same problem with me here is how I do it :

```<code><?php

$colors = ["red","red","red","red","red","red","blue","blue","green","green","green","green","green","green","red","red","red"];
$newColors = array();

$uniqColors = array_values(array_unique($colors));

$countUniqColors = count($uniqColors);

$y = 0;

for ($i = 0; $i <= count($colors) - 1; $i++) {
    $newColors[$i] = $uniqColors[$y];
    $y += 1;
    if ($y >= $countUniqColors) $y = 0;
}

print_r($newColors);

?>
</code>```

I think this is the most effective way I can think of. Let me know if you have any thought about this solution

Body:
I am struggling with this case. I have a random array that similar items can be in the next to each other and I don't want it to happen.

Example :

array("red","red","blue","green","green","blue");

Expected Output : array("red","blue","red","green","blue","green")

So I was thinking about shuffle the items until there are no similar items in the next to each other. But it will take a lot of time if the array has a lot of values.

Is there any effective way to make it happen?

Any help would be appreciated. Thanks

Body:
I ended up re-arrange to a new array. For those who have the same problem with me here is how I do it :

<?php

$colors = ["red","red","red","red","red","red","blue","blue","green","green","green","green","green","green","red","red","red"];
$newColors = array();

$uniqColors = array_values(array_unique($colors));

$countUniqColors = count($uniqColors);

$y = 0;

for ($i = 0; $i <= count($colors) - 1; $i++) {
    $newColors[$i] = $uniqColors[$y];
    $y += 1;
    if ($y >= $countUniqColors) $y = 0;
}

print_r($newColors);

?>

I think this is the most effective way I can think of. Let me know if you have any thought about this solution


问:
Telegram Bot API sendPhoto url contains characters like right single quotation mark (’)
I am using standard Telegram Bot API for sending messages. When a photo url contains a special character like a right single quotation mark (’) and left single quote (‘), the message is not sent, as it is a Bad Request.
When php rawurlencode is run, ’ shows as %E2%80%99 and ‘ as %E2%80%98

```<code>$photourl='https://example.com/some/path/name-of-image-with‘quotes’.jpg';
$array =[
'chat_id' => $uid,
'photo' => $photourl,
'caption' => $caption
];
file_get_contents("https://api.telegram.org/bot$api/sendPhoto?".http_build_query($array) );
</code>```

it gives a

PHP WARNING --
  failed to open stream: HTTP request failed! HTTP/1.1 400 Bad Request

答:
Try this:

```<code>$photourl = 'https://example.com/some/path/name-of-image-with‘quotes’.jpg';
$filename = basename($photourl);
$photourl = str_replace($filename, urlencode($filename), $photourl); //Replace file name wirth url encoded filename

$array = [
    'chat_id' => $uid,
    'photo' => $photourl,
    'caption' => $caption
];
file_get_contents("https://api.telegram.org/bot$api/sendPhoto?" . http_build_query($array));
</code>```

Using characters like ’,‘ or * in photo parameter seem to cause a problem.

I don't have any explanation why this error occurs or how this fixes it. But you can url encode the URL's file name part before passing your query to http_build_query(), (which will  encode it even a second time).

Body:
I am using standard Telegram Bot API for sending messages. When a photo url contains a special character like a right single quotation mark (’) and left single quote (‘), the message is not sent, as it is a Bad Request.
When php rawurlencode is run, ’ shows as %E2%80%99 and ‘ as %E2%80%98

$photourl='https://example.com/some/path/name-of-image-with‘quotes’.jpg';
$array =[
'chat_id' => $uid,
'photo' => $photourl,
'caption' => $caption
];
file_get_contents("https://api.telegram.org/bot$api/sendPhoto?".http_build_query($array) );

it gives a

PHP WARNING --
  failed to open stream: HTTP request failed! HTTP/1.1 400 Bad Request

Body:
Try this:

$photourl = 'https://example.com/some/path/name-of-image-with‘quotes’.jpg';
$filename = basename($photourl);
$photourl = str_replace($filename, urlencode($filename), $photourl); //Replace file name wirth url encoded filename

$array = [
    'chat_id' => $uid,
    'photo' => $photourl,
    'caption' => $caption
];
file_get_contents("https://api.telegram.org/bot$api/sendPhoto?" . http_build_query($array));

Using characters like ’,‘ or * in photo parameter seem to cause a problem.

I don't have any explanation why this error occurs or how this fixes it. But you can url encode the URL's file name part before passing your query to http_build_query(), (which will  encode it even a second time).