问:
Having trouble receiving data back from post using php fopen with a stream context
I've been trying to figure out where my error is in this particular function.
It's very similar to a posted function online with a few minor tweaks.  Anyway, I have a specific url in the variable $PAYMENTPAGE->ipa_url.  I'm trying to post to this and simply have the return data be a die('test') to verify the connection is going through properly.
Instead I keep getting a blank page.

I have managed to get it working using the curl extension but would prefer to simply use streams as they work out of the box with any extensions.  I know the connection is being made, because I was receiving exception errors which I fixed, but now I'm just having trouble figuring out why no information is being returned from the post.

```<code>function doPostRequest($url, $data, $optional_headers = null)
{
    $params = array('http' => array(
                'method' => 'POST',
                'content' => $data
             ));
    if ($optional_headers !== null) {
        $params['http']['header'] = $optional_headers;
    }
    $ctx = stream_context_create($params);
    $get_stream = true;
    try{
        $fp = @fopen($url, 'rb', false, $ctx);
        if (!$fp) {
             throw new Exception("Problem creating stream from $url, \n\t".implode("\n\t", error_get_last()));
        }
        $response = @stream_get_contents($fp);
        if ($response === false) {
           throw new Exception("Problem reading data from $url, \n\t".implode("\n\t", error_get_last()));
        }
        $get_stream = false;
    } catch(Exception $e){
        mcFatal("Error(".date('Y-m-d h:i:s').'):'.$e->getMessage()."\n");
    }

    if($get_stream){
        return false;
    }

    return $response;
}
</code>```

答: If you are using Ubuntu: This is a bug in the PHP version Ubuntu ships. See https://bugs.launchpad.net/ubuntu/+source/php5/+bug/650779 for more details.</p>

Body:
I've been trying to figure out where my error is in this particular function.
It's very similar to a posted function online with a few minor tweaks.  Anyway, I have a specific url in the variable $PAYMENTPAGE->ipa_url.  I'm trying to post to this and simply have the return data be a die('test') to verify the connection is going through properly.
Instead I keep getting a blank page.

I have managed to get it working using the curl extension but would prefer to simply use streams as they work out of the box with any extensions.  I know the connection is being made, because I was receiving exception errors which I fixed, but now I'm just having trouble figuring out why no information is being returned from the post.

function doPostRequest($url, $data, $optional_headers = null)
{
    $params = array('http' => array(
                'method' => 'POST',
                'content' => $data
             ));
    if ($optional_headers !== null) {
        $params['http']['header'] = $optional_headers;
    }
    $ctx = stream_context_create($params);
    $get_stream = true;
    try{
        $fp = @fopen($url, 'rb', false, $ctx);
        if (!$fp) {
             throw new Exception("Problem creating stream from $url, \n\t".implode("\n\t", error_get_last()));
        }
        $response = @stream_get_contents($fp);
        if ($response === false) {
           throw new Exception("Problem reading data from $url, \n\t".implode("\n\t", error_get_last()));
        }
        $get_stream = false;
    } catch(Exception $e){
        mcFatal("Error(".date('Y-m-d h:i:s').'):'.$e->getMessage()."\n");
    }

    if($get_stream){
        return false;
    }

    return $response;
}


来源: stackexchange

问:
How to close WPF window without shutdown .NET Application in IronPython
So I'm writing a WPF application with IronPython.  Everything works great if I run the script outside of IronPython REPL via command "ipy.exe wpf.py".  However, if the script were run inside IronPython REPL via command "execfile('wpf.py')", the first time it runs OK, the second time it errors out "SystemError: Cannot create more than one System.Windows.Application instance in the same AppDomain."

From my understanding, it's because it'll create a new AppDomain every time you run it outside REPL while it'll share the same domain when running inside REPL, and you can initialize Application twice.  The problem is I have to run it inside the same AppDomain many times as it's not a standalone IronPython application.  I've tried many things such as change shutdown mode by add app.ShutdownMode = ShutdownMode.OnExplicitShutdown after app=Application(), but that just hang the whole REPL.

Can someone please help shed some light?  Thank you very much!

```<code>import clr
clr.AddReference("PresentationFramework")
clr.AddReference("PresentationCore")
clr.AddReference("System.Xml")

from System.Xml import XmlReader
from System.IO import StringReader
from System.Windows.Markup import XamlReader
from System.Windows import Application

s = XmlReader.Create(StringReader('''
<Window
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="IronPython MVVM Demo2"
    Width="450"
    SizeToContent="Height">
    <Grid Margin="15" x:Name="grid1">
        <StackPanel Margin="5">
            <Button Margin="5">One</Button>
            <Button Margin="5">Two</Button>
            <Button Margin="5">Three</Button>
        </StackPanel>
    </Grid>
</Window>
'''))

win = XamlReader.Load(s)

app = Application()
app.Run(win)
print("The End.")
</code>```

答:
I believe you need to create a long-running STA thread to host the Applilcation, and communicate with it through the Applciations's Dispatcher.  Here's an example in C#:</p>

```<code>using System;
using System.IO;
using System.Threading;
using System.Windows;
using System.Xml;

namespace ConsoleApp1
{
    class Program
    {
        static void ShowWindow(string Xaml)
        {
            var s = XmlReader.Create(new StringReader(Xaml));
            var win = (Window)System.Windows.Markup.XamlReader.Load(s);
            win.ShowDialog();
        }
        static void Main(string[] args)
        {

           Application app = null;
           var UIThread = new Thread(() =>
           {
               app = new Application();
               app.ShutdownMode = ShutdownMode.OnExplicitShutdown;
               app.Run();
           });

            UIThread.SetApartmentState(ApartmentState.STA);
            UIThread.Start();

            while (app == null )
                Thread.Sleep(100);

            app.Dispatcher.Invoke(() => Console.WriteLine("Started"));

            var xaml = @"
        <Window
            xmlns = ""http://schemas.microsoft.com/winfx/2006/xaml/presentation""
            xmlns:x = ""http://schemas.microsoft.com/winfx/2006/xaml""
            Title = ""IronPython MVVM Demo2""
            Width = ""450""
            SizeToContent = ""Height"">
            <Grid Margin = ""15"" x:Name = ""grid1"">
                <StackPanel Margin = ""5"">
                    <Button Margin = ""5""> One </Button>
                    <Button Margin = ""5""> Two </Button>
                    <Button Margin = ""5""> Three </Button>
                </StackPanel>
            </Grid>
        </Window>";

            for (int i = 0; i < 3; i++)
            {

                Application.Current.Dispatcher.Invoke(() =>
                {
                    ShowWindow(xaml);
                });
            }

            Application.Current.Dispatcher.Invoke(() =>
            {
                Application.Current.Shutdown();
            });

        }
    }
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
So I'm writing a WPF application with IronPython.  Everything works great if I run the script outside of IronPython REPL via command "ipy.exe wpf.py".  However, if the script were run inside IronPython REPL via command "execfile('wpf.py')", the first time it runs OK, the second time it errors out "SystemError: Cannot create more than one System.Windows.Application instance in the same AppDomain."

From my understanding, it's because it'll create a new AppDomain every time you run it outside REPL while it'll share the same domain when running inside REPL, and you can initialize Application twice.  The problem is I have to run it inside the same AppDomain many times as it's not a standalone IronPython application.  I've tried many things such as change shutdown mode by add app.ShutdownMode = ShutdownMode.OnExplicitShutdown after app=Application(), but that just hang the whole REPL.

Can someone please help shed some light?  Thank you very much!

import clr
clr.AddReference("PresentationFramework")
clr.AddReference("PresentationCore")
clr.AddReference("System.Xml")

from System.Xml import XmlReader
from System.IO import StringReader
from System.Windows.Markup import XamlReader
from System.Windows import Application

s = XmlReader.Create(StringReader('''
<Window
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="IronPython MVVM Demo2"
    Width="450"
    SizeToContent="Height">
    <Grid Margin="15" x:Name="grid1">
        <StackPanel Margin="5">
            <Button Margin="5">One</Button>
            <Button Margin="5">Two</Button>
            <Button Margin="5">Three</Button>
        </StackPanel>
    </Grid>
</Window>
'''))

win = XamlReader.Load(s)

app = Application()
app.Run(win)
print("The End.")

Body:
I believe you need to create a long-running STA thread to host the Applilcation, and communicate with it through the Applciations's Dispatcher.  Here's an example in C#:

using System;
using System.IO;
using System.Threading;
using System.Windows;
using System.Xml;

namespace ConsoleApp1
{
    class Program
    {
        static void ShowWindow(string Xaml)
        {
            var s = XmlReader.Create(new StringReader(Xaml));
            var win = (Window)System.Windows.Markup.XamlReader.Load(s);
            win.ShowDialog();
        }
        static void Main(string[] args)
        {

           Application app = null;
           var UIThread = new Thread(() =>
           {
               app = new Application();
               app.ShutdownMode = ShutdownMode.OnExplicitShutdown;
               app.Run();
           });

            UIThread.SetApartmentState(ApartmentState.STA);
            UIThread.Start();

            while (app == null )
                Thread.Sleep(100);

            app.Dispatcher.Invoke(() => Console.WriteLine("Started"));

            var xaml = @"
        <Window
            xmlns = ""http://schemas.microsoft.com/winfx/2006/xaml/presentation""
            xmlns:x = ""http://schemas.microsoft.com/winfx/2006/xaml""
            Title = ""IronPython MVVM Demo2""
            Width = ""450""
            SizeToContent = ""Height"">
            <Grid Margin = ""15"" x:Name = ""grid1"">
                <StackPanel Margin = ""5"">
                    <Button Margin = ""5""> One </Button>
                    <Button Margin = ""5""> Two </Button>
                    <Button Margin = ""5""> Three </Button>
                </StackPanel>
            </Grid>
        </Window>";

            for (int i = 0; i < 3; i++)
            {

                Application.Current.Dispatcher.Invoke(() =>
                {
                    ShowWindow(xaml);
                });
            }

            Application.Current.Dispatcher.Invoke(() =>
            {
                Application.Current.Shutdown();
            });

        }
    }
}


问:
Subtract time and show difference in mins:secs format
I want to accurately display the difference between two times. The different should be displayed in a format such as mm:ss

```<code>    methods: {
        calcuateTimeDifference: function (startTime, endTime) {
            let result = 0;
            if (startTime && endTime) {
                let start = startTime.split(":");
                let end = endTime.split(':');
                let startTimeInHrs = (parseFloat(start[0]/3600) + parseFloat(start[1]/60) + parseFloat(start[2]/3600));
                let endTimeInHrs = (parseFloat(end[0]/3600) + parseFloat(end[1]/60) + parseFloat(end[2] /3600));
                result = endTimeInHrs - startTimeInHrs;
            }
            return result.toFixed(2);

        },
</code>```

Using this function - the difference between the following times: 16:03:01 - 16:04:01 - I get the result as -32.00.

答:
```<code>function calcuateTimeDifference(startTime, endTime) {
    let toSeconds = (time) => {
        let [h, m, s] = time.split(':');
        return h * 360 + m * 60 + +s;
    };

    let d = Math.abs(toSeconds(startTime) - toSeconds(endTime));

    let mm = String(Math.floor(d / 60));
    if (mm.length == 1) mm = '0' + mm;

    let ss = String(d % 60);
    if (ss.length == 1) ss = '0' + ss;

    return `${mm}:${ss}`;
}
</code>```

Body:
I want to accurately display the difference between two times. The different should be displayed in a format such as mm:ss

    methods: {
        calcuateTimeDifference: function (startTime, endTime) {
            let result = 0;
            if (startTime && endTime) {
                let start = startTime.split(":");
                let end = endTime.split(':');
                let startTimeInHrs = (parseFloat(start[0]/3600) + parseFloat(start[1]/60) + parseFloat(start[2]/3600));
                let endTimeInHrs = (parseFloat(end[0]/3600) + parseFloat(end[1]/60) + parseFloat(end[2] /3600));
                result = endTimeInHrs - startTimeInHrs;
            }
            return result.toFixed(2);

        },

Using this function - the difference between the following times: 16:03:01 - 16:04:01 - I get the result as -32.00.


问:
How to remove title and bulletins from google charts
I'm using google donut chart, but it's showing the title and bullets.

I need to know how to remove them and make the chart fit inside the card.

```<code><div class="col-xl-4 col-lg-12 col-md-4 col-sm-12 col-12">
    <div class="card">
        <h5 class="card-header">Credits History</h5>
        <div class="card-body">
            <script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
            <script type="text/javascript">
              google.charts.load("current", {packages:["corechart"]});
              google.charts.setOnLoadCallback(drawChart);
              function drawChart() {
                var data = google.visualization.arrayToDataTable([
                  ['Task', 'Hours per Day'],
                  ['Work',     11],
                  ['Eat',      2]
                ]);

                var options = {
                  title: 'My Daily Activities',
                  pieHole: 0.4,
                };

                var chart = new google.visualization.PieChart(document.getElementById('donutchart'));
                chart.draw(data, options);
              }
            </script>
            <div id="donutchart" style="width: 220px; height: 155px;"></div>
        </div>
    </div>
</div>
</code>```

答:
to remove the chart title, remove the title option from the chart options.

as for the bullets, or bulletins, that is the chart's legend,

to remove, add the following option --> legend: 'none'

and you can use the chartArea option to maximize the chart within the container.

```<code>var options = {
  chartArea: {
    height: '100%',
    width: '100%'
  },
  legend: 'none',
  pieHole: 0.4
};
</code>```

see following working snippet...

google.charts.load("current", {
  packages: ["corechart"]
});
google.charts.setOnLoadCallback(drawChart);

function drawChart() {
  var data = google.visualization.arrayToDataTable([
    ['Task', 'Hours per Day'],
    ['Work', 11],
    ['Eat', 2]
  ]);

  var options = {
    chartArea: {
      height: '100%',
      width: '100%'
    },
    legend: 'none',
    pieHole: 0.4
  };

  var chart = new google.visualization.PieChart(document.getElementById('donutchart'));
  chart.draw(data, options);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="donutchart" style="width: 220px; height: 155px;"></div></code>```

Body:
I'm using google donut chart, but it's showing the title and bullets.

I need to know how to remove them and make the chart fit inside the card.

Credits History

Body:
to remove the chart title, remove the title option from the chart options.

as for the bullets, or bulletins, that is the chart's legend,

to remove, add the following option --> legend: 'none'

and you can use the chartArea option to maximize the chart within the container.

var options = {
  chartArea: {
    height: '100%',
    width: '100%'
  },
  legend: 'none',
  pieHole: 0.4
};

see following working snippet...

google.charts.load("current", {
  packages: ["corechart"]
});
google.charts.setOnLoadCallback(drawChart);

function drawChart() {
  var data = google.visualization.arrayToDataTable([
    ['Task', 'Hours per Day'],
    ['Work', 11],
    ['Eat', 2]
  ]);

  var options = {
    chartArea: {
      height: '100%',
      width: '100%'
    },
    legend: 'none',
    pieHole: 0.4
  };

  var chart = new google.visualization.PieChart(document.getElementById('donutchart'));
  chart.draw(data, options);
}

<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="donutchart" style="width: 220px; height: 155px;"></div>


问:
Width and Height not doing effect when trying to resize an image inside a div
I'm trying to resize my image inside a form but width and height are not doing any effect.

```<code>.sectionForm {
        display: table;
        margin: 0 auto;
        background: url("https://image.flaticon.com/icons/svg/1914/1914882.svg") no-repeat center center;
        width: 100px;
        height: 100px;
    }
</code>```

.sectionForm {
  display: table;
  margin: 0 auto;
  background: url("https://image.flaticon.com/icons/svg/1914/1914882.svg") no-repeat center center;
  width: 100px;
  height: 100px;
}

.sectionForm form {
  width: 400px;
  box-shadow: 0px 4px 30px rgba(0, 0, 0, 0.2);
  border-radius: 40px;
}

.form-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 66px 0 50px 0;
}

footer {
  height: 1500px;
}

.footer-content {
  display: flex;
  flex-direction: column;
  display: table;
  margin: 0 auto;
}

.form-container input {
  border: none;
  border-bottom: 1px solid #828282;
  padding: 26px 0;
  margin-bottom: 100px;
  font-size: 20px;
  color: #4F4F4F;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="sectionForm">
  <form>
    <div class="form-container">
      <input type="text" id="fname" name="fname" value="Nome">
      <input type="text" id="lname" name="lname" value="E-mail">
      <input type="text" id="lname" name="lname" value="Assunto">

    </div>
  </form>
</div></code>```

答:
Try using {

background-size: 100% auto;

}

Body:
I'm trying to resize my image inside a form but width and height are not doing any effect.

.sectionForm {
        display: table;
        margin: 0 auto;
        background: url("https://image.flaticon.com/icons/svg/1914/1914882.svg") no-repeat center center;
        width: 100px;
        height: 100px;
    }

.sectionForm {
  display: table;
  margin: 0 auto;
  background: url("https://image.flaticon.com/icons/svg/1914/1914882.svg") no-repeat center center;
  width: 100px;
  height: 100px;
}

.sectionForm form {
  width: 400px;
  box-shadow: 0px 4px 30px rgba(0, 0, 0, 0.2);
  border-radius: 40px;
}

.form-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 66px 0 50px 0;
}

footer {
  height: 1500px;
}

.footer-content {
  display: flex;
  flex-direction: column;
  display: table;
  margin: 0 auto;
}

.form-container input {
  border: none;
  border-bottom: 1px solid #828282;
  padding: 26px 0;
  margin-bottom: 100px;
  font-size: 20px;
  color: #4F4F4F;
}

  <form>

      <input type="text" id="fname" name="fname" value="Nome">
      <input type="text" id="lname" name="lname" value="E-mail">
      <input type="text" id="lname" name="lname" value="Assunto">

  </form>


问:
Finding percentage time by hour from irregular dates
I have a table like the following, each entry a change in STATUS on the given time.
The status can be repeated because other columns have sub-status information.

How can I get a percentage time for each status by, say, hour?

```<code>NAME STATUS_CHANGE_TIME  STATUS
foo  15-MAY-11 18:52     A
foo  15-MAY-11 18:38     A
foo  15-MAY-11 18:33     B
foo  15-MAY-11 16:53     A
foo  15-MAY-11 16:47     B
foo  15-MAY-11 13:37     A
foo  15-MAY-11 13:33     C
foo  15-MAY-11 10:23     C
foo  15-MAY-11 10:17     A
foo  ...
</code>```

Desired return:

```<code>HH24  STATUS  PERCENT
10  ...
11    C       100        (No entries; last change was to C)
12    C       100        ""                       ""
13    C        62
13    A        38        (From C to A at :37 with 23 mins left; 23/60 ~ 38%)
14    A       100
15    A       100
16    A        90        (= A for first 47 minutes, then for another 7)
16    B        10        (16:53 - 16:47 = 6 minutes or 10% of an hour)
17    A       100
18 ... etc.
</code>```

答:
Great question, this was an interesting challenge!

What you need is an ancillary table to store each time division (in this case, hours), then join to it where the status updates overlap. LEAD() can grab the next status entry to check when it was, and GREATEST() and LEAST() can figure out which time is applicable for the start/end of the status for each hour.

Of course, this is much easier explained in an example. Here is the HOURS table needed:

```<code>SQL> CREATE TABLE hours (HOUR NUMBER(2), start_m date, end_m date);

Table created.

SQL> BEGIN
  2      FOR i IN 0..23 LOOP
  3          INSERT INTO hours VALUES(i, to_date(lpad(i, 2, '0')||':00:00', 'HH24:MI:SS')
  4                                    , to_date(lpad(i, 2, '0')||':59:59', 'HH24:MI:SS'));
  5      END loop;
  6      COMMIT;
  7  END;
  8  /

PL/SQL procedure successfully completed.
</code>```

The following is just population of your test data from your question.

```<code>SQL> CREATE TABLE status_updates (NAME VARCHAR2(3), status_change_time DATE, status CHAR(1));

Table created.

SQL> INSERT INTO status_updates VALUES ('foo',TO_DATE('15-MAY-11 18:52', 'DD-MON-RR HH24:MI:SS'), 'A');

1 row created.

SQL> INSERT INTO status_updates VALUES ('foo',TO_DATE('15-MAY-11 18:38', 'DD-MON-RR HH24:MI:SS'), 'A');

1 row created.

SQL> INSERT INTO status_updates VALUES ('foo',TO_DATE('15-MAY-11 18:33', 'DD-MON-RR HH24:MI:SS'), 'B');

1 row created.

SQL> INSERT INTO status_updates VALUES ('foo',TO_DATE('15-MAY-11 16:53', 'DD-MON-RR HH24:MI:SS'), 'A');

1 row created.

SQL> INSERT INTO status_updates VALUES ('foo',TO_DATE('15-MAY-11 16:47', 'DD-MON-RR HH24:MI:SS'), 'B');

1 row created.

SQL> INSERT INTO status_updates VALUES ('foo',TO_DATE('15-MAY-11 13:37', 'DD-MON-RR HH24:MI:SS'), 'A');

1 row created.

SQL> INSERT INTO status_updates VALUES ('foo',TO_DATE('15-MAY-11 13:33', 'DD-MON-RR HH24:MI:SS'), 'C');

1 row created.

SQL> INSERT INTO status_updates VALUES ('foo',TO_DATE('15-MAY-11 10:23', 'DD-MON-RR HH24:MI:SS'), 'C');

1 row created.

SQL> INSERT INTO status_updates VALUES ('foo',TO_DATE('15-MAY-11 10:17', 'DD-MON-RR HH24:MI:SS'), 'A');

1 row created.

SQL> commit;

Commit complete.
</code>```

Now here is the select statement to get the required percentages.

```<code>SELECT t.NAME, t.HOUR, t.status, sum(round((status_end_h-start_status_h)*24*100)) per_cent
FROM   (
    SELECT A.NAME
    ,      A.status
    ,      A.status_change_time
    ,      A.next_change_time
    ,      b.HOUR
    ,      greatest(status_change_time, trunc(status_change_time)+(b.start_m-trunc(b.start_m))) start_status_h
    ,      least(next_change_time, trunc(next_change_time)+(b.end_m-trunc(b.end_m))) status_end_h
    FROM   (
        SELECT NAME
        ,      status
        ,      status_change_time
        ,      lead(status_change_time) OVER (ORDER BY NAME, status_change_time) next_change_time
        FROM   status_updates
    ) A, hours b
    WHERE  TO_CHAR(b.start_m, 'HH24:MI:SS') BETWEEN TO_CHAR(A.status_change_time, 'HH24:MI:SS') AND TO_CHAR(A.next_change_time, 'HH24:MI:SS')
    OR     TO_CHAR(b.end_m, 'HH24:MI:SS') BETWEEN TO_CHAR(A.status_change_time, 'HH24:MI:SS') AND TO_CHAR(A.next_change_time, 'HH24:MI:SS')
    OR    (TO_CHAR(A.status_change_time, 'HH24:MI:SS') BETWEEN TO_CHAR(b.start_m, 'HH24:MI:SS') AND TO_CHAR(b.end_m, 'HH24:MI:SS')
    AND    TO_CHAR(A.next_change_time, 'HH24:MI:SS') BETWEEN TO_CHAR(b.start_m, 'HH24:MI:SS') AND TO_CHAR(b.end_m, 'HH24:MI:SS'))
) t
GROUP BY t.NAME, t.HOUR, t.status
ORDER BY t.HOUR;

NAM       HOUR S   PER_CENT
--- ---------- - ----------
foo         10 A         10
foo         10 C         62
foo         11 C        100
foo         12 C        100
foo         13 A         38
foo         13 C         62
foo         14 A        100
foo         15 A        100
foo         16 A         90
foo         16 B         10
foo         17 A        100

NAM       HOUR S   PER_CENT
--- ---------- - ----------
foo         18 A         78
foo         18 B          8

13 rows selected.
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have a table like the following, each entry a change in STATUS on the given time.
The status can be repeated because other columns have sub-status information.

How can I get a percentage time for each status by, say, hour?

NAME STATUS_CHANGE_TIME  STATUS
foo  15-MAY-11 18:52     A
foo  15-MAY-11 18:38     A
foo  15-MAY-11 18:33     B
foo  15-MAY-11 16:53     A
foo  15-MAY-11 16:47     B
foo  15-MAY-11 13:37     A
foo  15-MAY-11 13:33     C
foo  15-MAY-11 10:23     C
foo  15-MAY-11 10:17     A
foo  ...

Desired return:

HH24  STATUS  PERCENT
10  ...
11    C       100        (No entries; last change was to C)
12    C       100        ""                       ""
13    C        62
13    A        38        (From C to A at :37 with 23 mins left; 23/60 ~ 38%)
14    A       100
15    A       100
16    A        90        (= A for first 47 minutes, then for another 7)
16    B        10        (16:53 - 16:47 = 6 minutes or 10% of an hour)
17    A       100
18 ... etc.

Body:
Great question, this was an interesting challenge!

What you need is an ancillary table to store each time division (in this case, hours), then join to it where the status updates overlap. LEAD() can grab the next status entry to check when it was, and GREATEST() and LEAST() can figure out which time is applicable for the start/end of the status for each hour.

Of course, this is much easier explained in an example. Here is the HOURS table needed:

SQL> CREATE TABLE hours (HOUR NUMBER(2), start_m date, end_m date);

Table created.

SQL> BEGIN
  2      FOR i IN 0..23 LOOP
  3          INSERT INTO hours VALUES(i, to_date(lpad(i, 2, '0')||':00:00', 'HH24:MI:SS')
  4                                    , to_date(lpad(i, 2, '0')||':59:59', 'HH24:MI:SS'));
  5      END loop;
  6      COMMIT;
  7  END;
  8  /

PL/SQL procedure successfully completed.

The following is just population of your test data from your question.

SQL> CREATE TABLE status_updates (NAME VARCHAR2(3), status_change_time DATE, status CHAR(1));

Table created.

SQL> INSERT INTO status_updates VALUES ('foo',TO_DATE('15-MAY-11 18:52', 'DD-MON-RR HH24:MI:SS'), 'A');

1 row created.

SQL> INSERT INTO status_updates VALUES ('foo',TO_DATE('15-MAY-11 18:38', 'DD-MON-RR HH24:MI:SS'), 'A');

1 row created.

SQL> INSERT INTO status_updates VALUES ('foo',TO_DATE('15-MAY-11 18:33', 'DD-MON-RR HH24:MI:SS'), 'B');

1 row created.

SQL> INSERT INTO status_updates VALUES ('foo',TO_DATE('15-MAY-11 16:53', 'DD-MON-RR HH24:MI:SS'), 'A');

1 row created.

SQL> INSERT INTO status_updates VALUES ('foo',TO_DATE('15-MAY-11 16:47', 'DD-MON-RR HH24:MI:SS'), 'B');

1 row created.

SQL> INSERT INTO status_updates VALUES ('foo',TO_DATE('15-MAY-11 13:37', 'DD-MON-RR HH24:MI:SS'), 'A');

1 row created.

SQL> INSERT INTO status_updates VALUES ('foo',TO_DATE('15-MAY-11 13:33', 'DD-MON-RR HH24:MI:SS'), 'C');

1 row created.

SQL> INSERT INTO status_updates VALUES ('foo',TO_DATE('15-MAY-11 10:23', 'DD-MON-RR HH24:MI:SS'), 'C');

1 row created.

SQL> INSERT INTO status_updates VALUES ('foo',TO_DATE('15-MAY-11 10:17', 'DD-MON-RR HH24:MI:SS'), 'A');

1 row created.

SQL> commit;

Commit complete.

Now here is the select statement to get the required percentages.

SELECT t.NAME, t.HOUR, t.status, sum(round((status_end_h-start_status_h)*24*100)) per_cent
FROM   (
    SELECT A.NAME
    ,      A.status
    ,      A.status_change_time
    ,      A.next_change_time
    ,      b.HOUR
    ,      greatest(status_change_time, trunc(status_change_time)+(b.start_m-trunc(b.start_m))) start_status_h
    ,      least(next_change_time, trunc(next_change_time)+(b.end_m-trunc(b.end_m))) status_end_h
    FROM   (
        SELECT NAME
        ,      status
        ,      status_change_time
        ,      lead(status_change_time) OVER (ORDER BY NAME, status_change_time) next_change_time
        FROM   status_updates
    ) A, hours b
    WHERE  TO_CHAR(b.start_m, 'HH24:MI:SS') BETWEEN TO_CHAR(A.status_change_time, 'HH24:MI:SS') AND TO_CHAR(A.next_change_time, 'HH24:MI:SS')
    OR     TO_CHAR(b.end_m, 'HH24:MI:SS') BETWEEN TO_CHAR(A.status_change_time, 'HH24:MI:SS') AND TO_CHAR(A.next_change_time, 'HH24:MI:SS')
    OR    (TO_CHAR(A.status_change_time, 'HH24:MI:SS') BETWEEN TO_CHAR(b.start_m, 'HH24:MI:SS') AND TO_CHAR(b.end_m, 'HH24:MI:SS')
    AND    TO_CHAR(A.next_change_time, 'HH24:MI:SS') BETWEEN TO_CHAR(b.start_m, 'HH24:MI:SS') AND TO_CHAR(b.end_m, 'HH24:MI:SS'))
) t
GROUP BY t.NAME, t.HOUR, t.status
ORDER BY t.HOUR;

NAM       HOUR S   PER_CENT
--- ---------- - ----------
foo         10 A         10
foo         10 C         62
foo         11 C        100
foo         12 C        100
foo         13 A         38
foo         13 C         62
foo         14 A        100
foo         15 A        100
foo         16 A         90
foo         16 B         10
foo         17 A        100

NAM       HOUR S   PER_CENT
--- ---------- - ----------
foo         18 A         78
foo         18 B          8

13 rows selected.


问:
use grep or awk to split a column into multiple columns with the headers in the original file headers
I have the following output

```<code>SRR51XXXX
5
6
7
SRR51XXYY
8
9
1
2
</code>```

and so on..

SO each header file begins with SRR51 and then with unique 4 digit numbers.I want to turn this single column output into separate columns
such as

```<code>SRR513XXXX            SRR513XXXY
5                        8
6                        9
7                        1
</code>```

Fig to show the data

答:
A simple bash approach:

```<code>csplit -s -z -f columns sample.txt '/^SRR51/' '{*}'
paste columns* > pivot.txt
rm columns*
</code>```

This will use csplit to split the file into individual files based on the ^SRR51 pattern, then paste all the "columns" separated with TAB. Finally rm removes the temporary column files.

If you are stuck with a bsd style csplit use:

```<code>csplit -s -f columns sample.txt '%^SRR51%' '/^SRR51/' "{$( expr $(grep -c '^SRR51') + 1)}"
</code>```

If you want them "aligned" use column -t, but that's not POSIX.

Body:
I have the following output

SRR51XXXX
5
6
7
SRR51XXYY
8
9
1
2

and so on..

SO each header file begins with SRR51 and then with unique 4 digit numbers.I want to turn this single column output into separate columns
such as

SRR513XXXX            SRR513XXXY
5                        8
6                        9
7                        1

Fig to show the data

Body:
A simple bash approach:

csplit -s -z -f columns sample.txt '/^SRR51/' '{*}'
paste columns* > pivot.txt
rm columns*

This will use csplit to split the file into individual files based on the ^SRR51 pattern, then paste all the "columns" separated with TAB. Finally rm removes the temporary column files.

If you are stuck with a bsd style csplit use:

csplit -s -f columns sample.txt '%^SRR51%' '/^SRR51/' "{$( expr $(grep -c '^SRR51') + 1)}"

If you want them "aligned" use column -t, but that's not POSIX.


问:
Is it possible to do a dropna-like operation before creating a DataFrame?
I am trying to create a DataFrame with more than 500 rows, derived from an API query. When I check the length of my arrays, as so:

```<code>print(len(cities), len(country), len(max_temp), len(latit), len(longit), len(humid_), len(cloud_), len(wind))
</code>```

I get the following output:

```<code>577 526 526 526 526 526 526 526
</code>```

Now, I read the answers about casting these to Series, which adds NaN to the empty cells. The problem is that this mismatches the column values, i.e., all the numeric values are listed first, then all the NaN's at the end. This will cause the country, max_temp, etc., to line up with the wrong city. What I want to do is have the NaN appear in the correct row of each city with missing data. I could simply dropna if I had a DataFrame; but with the different array lengths, I cannot get a DataFrame.

Okay, editing in light of the comments: I began with a randomly generated list of coordinates, then:

```<code>for lat_lng in lat_lngs:
    city = citipy.nearest_city(lat_lng[0], lat_lng[1]).city_name

    # If the city is unique, then add it to a our cities list
    if city not in cities:
        cities.append(city)
</code>```

This generated a list of cities. Then I did:

```<code>country = []
latit = []
longit = []
max_temp = []
humid_ = []
cloud_ = []
wind = []
for city in cities:
    try:
        query_url = base_url + "q=" + city + "&appid=" + weather_api_key
        response = requests.get(query_url).json()
        country.append(response['sys']['country'])
        latit.append(response['coord']['lat'])
        longit.append(response['coord']['lon'])
        max_temp.append(response['main']['temp_max'])
        humid_.append(response['main']['humidity'])
        cloud_.append(response['clouds']['all'])
        wind.append(response['wind']['speed'])
    except:
        print(f'Data not found.')
</code>```

What I believe is occurring is that I am getting an array something like this:

```<code>City     Country     Max Temp     (etc.)
Boston     US          30           (etc.)
Honolulu
Rome        IT         27
Vladivostok RU          20
</code>```

In this example, "Honolulu" had no data, so generated a row with only the city Column filled. I can't be sure, since I can't view it as a DataFrame. What I want to do is either put NaN in the same row as Honolulu, or drop the row with Honolulu.

答:
So after consulting with an expert offline, I got this solution:

In my lists of variables, add a new one:

```<code>new_city = []
country = []
latit = []
longit = []
max_temp = []
humid_ = []
cloud_ = []
wind = []
</code>```

Then, in my Try loop:

```<code>for city in cities:
    try:
        query_url = base_url + "q=" + city + "&appid=" + weather_api_key
        response = requests.get(query_url).json()
        new_city.append(response['name])
        country.append(response['sys']['country'])
        latit.append(response['coord']['lat'])
        longit.append(response['coord']['lon'])
        max_temp.append(response['main']['temp_max'])
        humid_.append(response['main']['humidity'])
        cloud_.append(response['clouds']['all'])
        wind.append(response['wind']['speed'])
    except:
        print(f'Data not found.')
</code>```

And finally, build my dataframe with that new_city variable instead of the original city variable. This gives me all lists of the same length.

Body:
I am trying to create a DataFrame with more than 500 rows, derived from an API query. When I check the length of my arrays, as so:

print(len(cities), len(country), len(max_temp), len(latit), len(longit), len(humid_), len(cloud_), len(wind))

I get the following output:

577 526 526 526 526 526 526 526

Now, I read the answers about casting these to Series, which adds NaN to the empty cells. The problem is that this mismatches the column values, i.e., all the numeric values are listed first, then all the NaN's at the end. This will cause the country, max_temp, etc., to line up with the wrong city. What I want to do is have the NaN appear in the correct row of each city with missing data. I could simply dropna if I had a DataFrame; but with the different array lengths, I cannot get a DataFrame.

Okay, editing in light of the comments: I began with a randomly generated list of coordinates, then:

for lat_lng in lat_lngs:
    city = citipy.nearest_city(lat_lng[0], lat_lng[1]).city_name

    # If the city is unique, then add it to a our cities list
    if city not in cities:
        cities.append(city)

This generated a list of cities. Then I did:

country = []
latit = []
longit = []
max_temp = []
humid_ = []
cloud_ = []
wind = []
for city in cities:
    try:
        query_url = base_url + "q=" + city + "&appid=" + weather_api_key
        response = requests.get(query_url).json()
        country.append(response['sys']['country'])
        latit.append(response['coord']['lat'])
        longit.append(response['coord']['lon'])
        max_temp.append(response['main']['temp_max'])
        humid_.append(response['main']['humidity'])
        cloud_.append(response['clouds']['all'])
        wind.append(response['wind']['speed'])
    except:
        print(f'Data not found.')

What I believe is occurring is that I am getting an array something like this:

City     Country     Max Temp     (etc.)
Boston     US          30           (etc.)
Honolulu
Rome        IT         27
Vladivostok RU          20

In this example, "Honolulu" had no data, so generated a row with only the city Column filled. I can't be sure, since I can't view it as a DataFrame. What I want to do is either put NaN in the same row as Honolulu, or drop the row with Honolulu.

Body:
So after consulting with an expert offline, I got this solution:

In my lists of variables, add a new one:

new_city = []
country = []
latit = []
longit = []
max_temp = []
humid_ = []
cloud_ = []
wind = []

Then, in my Try loop:

for city in cities:
    try:
        query_url = base_url + "q=" + city + "&appid=" + weather_api_key
        response = requests.get(query_url).json()
        new_city.append(response['name])
        country.append(response['sys']['country'])
        latit.append(response['coord']['lat'])
        longit.append(response['coord']['lon'])
        max_temp.append(response['main']['temp_max'])
        humid_.append(response['main']['humidity'])
        cloud_.append(response['clouds']['all'])
        wind.append(response['wind']['speed'])
    except:
        print(f'Data not found.')

And finally, build my dataframe with that new_city variable instead of the original city variable. This gives me all lists of the same length.


问:
Why i have Cannot read property 'addEventListener' of null error?
HTML:

```<code> <body>
<script src="dynamic.js"></script>
<nav>
  <label id="logo">My Life</label>
  <ul id="test">
    <li>
      <a href="#" id="change">Home</a>
    </li>
    <li>
      <a href="#">Contact</a>
    </li>
    <li>
      <a href="#">News</a>
    </li>
    <li>
      <a href="#">Feedback</a>
    </li>
    <li>
      <a href="#" class="active">Log in</a>
    </li>
  </ul>
</nav>
</code>```

JavaScript:

```<code>const change = document.getElementById("change");
change.addEventListener("mouseover", () => changeFont());
change.addEventListener("mouseout", () => normalFont());

function changeFont() {
  change.style.fontSize = "25px";
}

function normalFont() {
  change.style.fontSize = "15px";
}
</code>```

I have simple navigation bar and when i decide to make it more interesting with hover effect I decide to be with JS NOT CSS and when i run the code in chrome i have a "Cannot read property 'addEventListener' of null" error and I can't figure out why?

I need some help ...

答:
You can also wrap your code in a DOMContentLoaded event listener to make sure it only fires after the DOM is ready.

```<code>window.addEventListener('DOMContentLoaded', () => {
  const change = document.getElementById("change");
  change.addEventListener("mouseover", () => changeFont());
  change.addEventListener("mouseout", () => normalFont());

  function changeFont() {
    change.style.fontSize = "25px";
  }

  function normalFont() {
    change.style.fontSize = "15px";
  }
});
</code>```

Snippet before the change (error thrown)

  My Life

      Home

      Contact

      News

      Feedback

      Log in

```
</div>
</div>
</p>

<p>snippet after change (no error)</p>

<p><div class="snippet" data-lang="js" data-hide="true" data-console="true" data-babel="false">
<div class="snippet-code snippet-currently-hidden">
<pre class="snippet-code-html lang-html prettyprint-override"><code><script>
  window.addEventListener('DOMContentLoaded', () => {
    const change = document.getElementById("change");
    change.addEventListener("mouseover", () => changeFont());
    change.addEventListener("mouseout", () => normalFont());

    function changeFont() {
      change.style.fontSize = "25px";
    }

    function normalFont() {
      change.style.fontSize = "15px";
    }
  });
</script>
<nav>
  <label id="logo">My Life</label>
  <ul id="test">
    <li>
      Home
    </li>
    <li>
      Contact
    </li>
    <li>
      News
    </li>
    <li>
      Feedback
    </li>
    <li>
      Log in
    </li>
  </ul>
</nav></code>```

But anyway, besides that, you actually don't need to use javascript if you're only changing the element font-size on hover. You can do that with CSS like so

Pure CSS snippet

#change:hover,
#change:active,
#change:focus {
  font-size: 25px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><nav>
  <label id="logo">My Life</label>
  <ul id="test">
    <li>
      Home
    </li>
    <li>
      Contact
    </li>
    <li>
      News
    </li>
    <li>
      Feedback
    </li>
    <li>
      Log in
    </li>
  </ul>
</nav></code>```

Body:
HTML:

  My Life

      Home

      Contact

      News

      Feedback

      Log in

JavaScript:

const change = document.getElementById("change");
change.addEventListener("mouseover", () => changeFont());
change.addEventListener("mouseout", () => normalFont());

function changeFont() {
  change.style.fontSize = "25px";
}

function normalFont() {
  change.style.fontSize = "15px";
}

I have simple navigation bar and when i decide to make it more interesting with hover effect I decide to be with JS NOT CSS and when i run the code in chrome i have a "Cannot read property 'addEventListener' of null" error and I can't figure out why?

I need some help ...

Body:
You can also wrap your code in a DOMContentLoaded event listener to make sure it only fires after the DOM is ready.

window.addEventListener('DOMContentLoaded', () => {
  const change = document.getElementById("change");
  change.addEventListener("mouseover", () => changeFont());
  change.addEventListener("mouseout", () => normalFont());

  function changeFont() {
    change.style.fontSize = "25px";
  }

  function normalFont() {
    change.style.fontSize = "15px";
  }
});

Snippet before the change (error thrown)

<script>
  const change = document.getElementById("change");
  change.addEventListener("mouseover", () => changeFont());
  change.addEventListener("mouseout", () => normalFont());

  function changeFont() {
    change.style.fontSize = "25px";
  }

  function normalFont() {
    change.style.fontSize = "15px";
  }
</script>
<nav>
  <label id="logo">My Life</label>
  <ul id="test">
    <li>
      <a href="#" id="change">Home</a>
    </li>
    <li>
      <a href="#">Contact</a>
    </li>
    <li>
      <a href="#">News</a>
    </li>
    <li>
      <a href="#">Feedback</a>
    </li>
    <li>
      <a href="#" class="active">Log in</a>
    </li>
  </ul>
</nav>

snippet after change (no error)

<script>
  window.addEventListener('DOMContentLoaded', () => {
    const change = document.getElementById("change");
    change.addEventListener("mouseover", () => changeFont());
    change.addEventListener("mouseout", () => normalFont());

    function changeFont() {
      change.style.fontSize = "25px";
    }

    function normalFont() {
      change.style.fontSize = "15px";
    }
  });
</script>
<nav>
  <label id="logo">My Life</label>
  <ul id="test">
    <li>
      <a href="#" id="change">Home</a>
    </li>
    <li>
      <a href="#">Contact</a>
    </li>
    <li>
      <a href="#">News</a>
    </li>
    <li>
      <a href="#">Feedback</a>
    </li>
    <li>
      <a href="#" class="active">Log in</a>
    </li>
  </ul>
</nav>

But anyway, besides that, you actually don't need to use javascript if you're only changing the element font-size on hover. You can do that with CSS like so

Pure CSS snippet

#change:hover,
#change:active,
#change:focus {
  font-size: 25px;
}

<nav>
  <label id="logo">My Life</label>
  <ul id="test">
    <li>
      <a href="#" id="change">Home</a>
    </li>
    <li>
      <a href="#">Contact</a>
    </li>
    <li>
      <a href="#">News</a>
    </li>
    <li>
      <a href="#">Feedback</a>
    </li>
    <li>
      <a href="#" class="active">Log in</a>
    </li>
  </ul>
</nav>


问:
How to sort DataGridView when bound to a binding source that is linked to an EF4 Entity
I have a DataGridView that is linked to a BindingSource.

My BindingSource is linked to an IQueryable list of entities:

```<code>    public void BindTo(IQueryable elements)
    {
        BindingSource source = new BindingSource();
        source.DataSource = elements;

        bindingNavigator1.BindingSource = source;
        dataGridView1.DataSource = source;

    }
</code>```

I am wanting my users to be able to click on the grid headers to sort the data - struggling to get this to work.  Is it possible? If so, how do I do it?

答:
maybe this will help you.</p>

```<code>internal class CustomDataGridView : DataGridView
{
    public SortOrder MySortOrder { get; set; }
    protected override void OnColumnHeaderMouseClick(DataGridViewCellMouseEventArgs e)
    {
        BindingSource MyBindingSource = (BindingSource)base.DataSource;
        DataTable MyDataTable = (DataTable)MyBindingSource.DataSource;
        switch (MySortOrder)
        {
            case SortOrder.None:
                MyDataTable.DefaultView.Sort = base.Columns[e.ColumnIndex].Name + " ASC";
                MyDataTable = MyDataTable.DefaultView.ToTable();
                MyBindingSource.DataSource = MyDataTable;
                MySortOrder = SortOrder.Ascending;
                break;

            case SortOrder.Ascending:
                MyDataTable.DefaultView.Sort = base.Columns[e.ColumnIndex].Name + " DESC";
                MyDataTable = MyDataTable.DefaultView.ToTable();
                MyBindingSource.DataSource = MyDataTable;
                MySortOrder = SortOrder.Descending;
                break;

            case SortOrder.Descending:
                MyDataTable.DefaultView.Sort = Properties.Settings.Default.OderDataGridView; //SqlOriginOrder
                MyDataTable = MyDataTable.DefaultView.ToTable();
                MyBindingSource.DataSource = MyDataTable;
                MySortOrder = SortOrder.None;
                break;
        }
        base.Columns[e.ColumnIndex].HeaderCell.SortGlyphDirection = MySortOrder; //mini arrow
    }
}
</code>```

Body:
I have a DataGridView that is linked to a BindingSource.

My BindingSource is linked to an IQueryable list of entities:

    public void BindTo(IQueryable elements)
    {
        BindingSource source = new BindingSource();
        source.DataSource = elements;

        bindingNavigator1.BindingSource = source;
        dataGridView1.DataSource = source;

    }

I am wanting my users to be able to click on the grid headers to sort the data - struggling to get this to work.  Is it possible? If so, how do I do it?

Body:
maybe this will help you.

internal class CustomDataGridView : DataGridView
{
    public SortOrder MySortOrder { get; set; }
    protected override void OnColumnHeaderMouseClick(DataGridViewCellMouseEventArgs e)
    {
        BindingSource MyBindingSource = (BindingSource)base.DataSource;
        DataTable MyDataTable = (DataTable)MyBindingSource.DataSource;
        switch (MySortOrder)
        {
            case SortOrder.None:
                MyDataTable.DefaultView.Sort = base.Columns[e.ColumnIndex].Name + " ASC";
                MyDataTable = MyDataTable.DefaultView.ToTable();
                MyBindingSource.DataSource = MyDataTable;
                MySortOrder = SortOrder.Ascending;
                break;

            case SortOrder.Ascending:
                MyDataTable.DefaultView.Sort = base.Columns[e.ColumnIndex].Name + " DESC";
                MyDataTable = MyDataTable.DefaultView.ToTable();
                MyBindingSource.DataSource = MyDataTable;
                MySortOrder = SortOrder.Descending;
                break;

            case SortOrder.Descending:
                MyDataTable.DefaultView.Sort = Properties.Settings.Default.OderDataGridView; //SqlOriginOrder
                MyDataTable = MyDataTable.DefaultView.ToTable();
                MyBindingSource.DataSource = MyDataTable;
                MySortOrder = SortOrder.None;
                break;
        }
        base.Columns[e.ColumnIndex].HeaderCell.SortGlyphDirection = MySortOrder; //mini arrow
    }
}


问:
'CityListViewSet' should either include a `serializer_class` attribute, or override the `get_serializer_class()` method
I am assuming by the error in the title, once more here for clarity

```<code>'CityListViewSet' should either include a `serializer_class` attribute,
or override the `get_serializer_class()` method.
</code>```

that my serializer isn't connected to my view, which in my code it should be. I'm not really sure where the bug is in this one. I wonder if any of you have seen something similar?

Here is the code.

Router:

```<code>router.register(r'city-list', CityListViewSet, base_name='city-list')
</code>```

view:

```<code>class CityListViewSet(viewsets.ReadOnlyModelViewSet):
    queryset = Venue.objects.values('city').distinct()
    serializer = CitySerializer(queryset, many=True)
    ordering_fields = ('city',)
    ordering = ('city',)
</code>```

serializer:

```<code>class CitySerializer(serializers.ModelSerializer):
    class Meta:
        model = City
        fields =('city',)
</code>```

what is it that would be causing such an assertion error with the code seemly wired up correctly?

答: i got this error when declared post method in view and trying to send post data without serialize, if you are doing the request from javascript i solved it using JSON.stringify()

Body:
I am assuming by the error in the title, once more here for clarity

'CityListViewSet' should either include a `serializer_class` attribute,
or override the `get_serializer_class()` method.

that my serializer isn't connected to my view, which in my code it should be. I'm not really sure where the bug is in this one. I wonder if any of you have seen something similar?

Here is the code.

Router:

router.register(r'city-list', CityListViewSet, base_name='city-list')

view:

class CityListViewSet(viewsets.ReadOnlyModelViewSet):
    queryset = Venue.objects.values('city').distinct()
    serializer = CitySerializer(queryset, many=True)
    ordering_fields = ('city',)
    ordering = ('city',)

serializer:

class CitySerializer(serializers.ModelSerializer):
    class Meta:
        model = City
        fields =('city',)

what is it that would be causing such an assertion error with the code seemly wired up correctly?


问:
Building angular library at ng serve
I am struggling with my angular library development. First of all, I am building an angular 8 library (current cli version 9) and I want to live see my library code changes while I am serving the demo app in which I am using this library.

Current behavior: When I am making changes on library source code, angular demo application reloads but I am non seeing any changes to take affect. This behavior was mainly applied with css changes and not every time on a .ts file.

Expected behavior: To being able to see every change I am making on the library source code.

Current angular.json file

```<code>    {
  "$schema": "./node_modules/@angular/cli/lib/config/schema.json",
  "version": 1,
  "newProjectRoot": "projects",
  "projects": {
    "bDataTableDemo": {
      "projectType": "application",
      "schematics": {
        "@schematics/angular:component": {
          "style": "scss"
        }
      },
      "root": "",
      "sourceRoot": "src",
      "prefix": "app",
      "architect": {
        "build": {
          "builder": "@angular-devkit/build-angular:browser",
          "options": {
            "outputPath": "dist/bDataTableDemo",
            "index": "src/index.html",
            "main": "src/main.ts",
            "polyfills": "src/polyfills.ts",
            "tsConfig": "tsconfig.app.json",
            "aot": false,
            "assets": [
              "src/favicon.ico",
              "src/assets"
            ],
            "styles": [
              "node_modules/bootstrap/dist/css/bootstrap.min.css",
              "src/styles.scss"
            ],
            "scripts": [
              "node_modules/jquery/dist/jquery.min.js"
            ]
          },
          "configurations": {
            "production": {
              "fileReplacements": [
                {
                  "replace": "src/environments/environment.ts",
                  "with": "src/environments/environment.prod.ts"
                }
              ],
              "optimization": true,
              "outputHashing": "all",
              "sourceMap": false,
              "extractCss": true,
              "namedChunks": false,
              "aot": true,
              "extractLicenses": true,
              "vendorChunk": false,
              "buildOptimizer": true,
              "budgets": [
                {
                  "type": "initial",
                  "maximumWarning": "2mb",
                  "maximumError": "5mb"
                },
                {
                  "type": "anyComponentStyle",
                  "maximumWarning": "6kb",
                  "maximumError": "10kb"
                }
              ]
            }
          }
        },
        "serve": {
          "builder": "@angular-devkit/build-angular:dev-server",
          "options": {
            "browserTarget": "bDataTableDemo:build"
          },
          "configurations": {
            "production": {
              "browserTarget": "bDataTableDemo:build:production"
            }
          }
        },
        "extract-i18n": {
          "builder": "@angular-devkit/build-angular:extract-i18n",
          "options": {
            "browserTarget": "bDataTableDemo:build"
          }
        },
        "test": {
          "builder": "@angular-devkit/build-angular:karma",
          "options": {
            "main": "src/test.ts",
            "polyfills": "src/polyfills.ts",
            "tsConfig": "tsconfig.spec.json",
            "karmaConfig": "karma.conf.js",
            "assets": [
              "src/favicon.ico",
              "src/assets"
            ],
            "styles": [
              "src/styles.scss"
            ],
            "scripts": []
          }
        },
        "lint": {
          "builder": "@angular-devkit/build-angular:tslint",
          "options": {
            "tsConfig": [
              "tsconfig.app.json",
              "tsconfig.spec.json",
              "e2e/tsconfig.json"
            ],
            "exclude": [
              "**/node_modules/**"
            ]
          }
        },
        "e2e": {
          "builder": "@angular-devkit/build-angular:protractor",
          "options": {
            "protractorConfig": "e2e/protractor.conf.js",
            "devServerTarget": "bDataTableDemo:serve"
          },
          "configurations": {
            "production": {
              "devServerTarget": "bDataTableDemo:serve:production"
            }
          }
        }
      }
    },
    "ng-bootstrap-table": {
      "projectType": "library",
      "root": "projects/ng-bootstrap-table",
      "sourceRoot": "projects/ng-bootstrap-table/src",
      "prefix": "lib",
      "architect": {
        "build": {
          "builder": "@angular-devkit/build-ng-packagr:build",
          "options": {
            "tsConfig": "projects/ng-bootstrap-table/tsconfig.lib.json",
            "project": "projects/ng-bootstrap-table/ng-package.json"
          }
        },
        "test": {
          "builder": "@angular-devkit/build-angular:karma",
          "options": {
            "main": "projects/ng-bootstrap-table/src/test.ts",
            "tsConfig": "projects/ng-bootstrap-table/tsconfig.spec.json",
            "karmaConfig": "projects/ng-bootstrap-table/karma.conf.js"
          }
        },
        "lint": {
          "builder": "@angular-devkit/build-angular:tslint",
          "options": {
            "tsConfig": [
              "projects/ng-bootstrap-table/tsconfig.lib.json",
              "projects/ng-bootstrap-table/tsconfig.spec.json"
            ],
            "exclude": [
              "**/node_modules/**"
            ]
          }
        }
      }
    }
  },
  "defaultProject": "bDataTableDemo"
}
</code>```

And my tsconfig.json file

```<code>{
  "compileOnSave": false,
  "compilerOptions": {
    "baseUrl": "./",
    "outDir": "./dist/out-tsc",
    "sourceMap": true,
    "declaration": false,
    "downlevelIteration": true,
    "experimentalDecorators": true,
    "module": "esnext",
    "moduleResolution": "node",
    "importHelpers": true,
    "target": "es2015",
    "typeRoots": [
      "node_modules/@types"
    ],
    "lib": [
      "es2018",
      "dom"
    ],
    "paths": {
      "ng-bootstrap-table": [
        "dist/ng-bootstrap-table"
      ],
      "ng-bootstrap-table/*": [
        "dist/ng-bootstrap-table/*"
      ]
    }
  },
  "angularCompilerOptions": {
    "fullTemplateTypeCheck": true,
    "strictInjectionParameters": true
  }
}
</code>```

What should I change in order to have the expected behavior?

P.S. I am new to angular libraries, so I can't find a solution yet.

Thank you in advance!!

答:
You should edit the paths in tsconfig to point to your library's index.ts instead of dist/ - which is the built artifact generated with ng build my-library:

```<code>"my-library" : [ "libs/my-library/index.ts" ]
</code>```

Title: Building angular library at ng serve

Body:
I am struggling with my angular library development. First of all, I am building an angular 8 library (current cli version 9) and I want to live see my library code changes while I am serving the demo app in which I am using this library.

Current behavior: When I am making changes on library source code, angular demo application reloads but I am non seeing any changes to take affect. This behavior was mainly applied with css changes and not every time on a .ts file.

Expected behavior: To being able to see every change I am making on the library source code.

Current angular.json file

    {
  "$schema": "./node_modules/@angular/cli/lib/config/schema.json",
  "version": 1,
  "newProjectRoot": "projects",
  "projects": {
    "bDataTableDemo": {
      "projectType": "application",
      "schematics": {
        "@schematics/angular:component": {
          "style": "scss"
        }
      },
      "root": "",
      "sourceRoot": "src",
      "prefix": "app",
      "architect": {
        "build": {
          "builder": "@angular-devkit/build-angular:browser",
          "options": {
            "outputPath": "dist/bDataTableDemo",
            "index": "src/index.html",
            "main": "src/main.ts",
            "polyfills": "src/polyfills.ts",
            "tsConfig": "tsconfig.app.json",
            "aot": false,
            "assets": [
              "src/favicon.ico",
              "src/assets"
            ],
            "styles": [
              "node_modules/bootstrap/dist/css/bootstrap.min.css",
              "src/styles.scss"
            ],
            "scripts": [
              "node_modules/jquery/dist/jquery.min.js"
            ]
          },
          "configurations": {
            "production": {
              "fileReplacements": [
                {
                  "replace": "src/environments/environment.ts",
                  "with": "src/environments/environment.prod.ts"
                }
              ],
              "optimization": true,
              "outputHashing": "all",
              "sourceMap": false,
              "extractCss": true,
              "namedChunks": false,
              "aot": true,
              "extractLicenses": true,
              "vendorChunk": false,
              "buildOptimizer": true,
              "budgets": [
                {
                  "type": "initial",
                  "maximumWarning": "2mb",
                  "maximumError": "5mb"
                },
                {
                  "type": "anyComponentStyle",
                  "maximumWarning": "6kb",
                  "maximumError": "10kb"
                }
              ]
            }
          }
        },
        "serve": {
          "builder": "@angular-devkit/build-angular:dev-server",
          "options": {
            "browserTarget": "bDataTableDemo:build"
          },
          "configurations": {
            "production": {
              "browserTarget": "bDataTableDemo:build:production"
            }
          }
        },
        "extract-i18n": {
          "builder": "@angular-devkit/build-angular:extract-i18n",
          "options": {
            "browserTarget": "bDataTableDemo:build"
          }
        },
        "test": {
          "builder": "@angular-devkit/build-angular:karma",
          "options": {
            "main": "src/test.ts",
            "polyfills": "src/polyfills.ts",
            "tsConfig": "tsconfig.spec.json",
            "karmaConfig": "karma.conf.js",
            "assets": [
              "src/favicon.ico",
              "src/assets"
            ],
            "styles": [
              "src/styles.scss"
            ],
            "scripts": []
          }
        },
        "lint": {
          "builder": "@angular-devkit/build-angular:tslint",
          "options": {
            "tsConfig": [
              "tsconfig.app.json",
              "tsconfig.spec.json",
              "e2e/tsconfig.json"
            ],
            "exclude": [
              "**/node_modules/**"
            ]
          }
        },
        "e2e": {
          "builder": "@angular-devkit/build-angular:protractor",
          "options": {
            "protractorConfig": "e2e/protractor.conf.js",
            "devServerTarget": "bDataTableDemo:serve"
          },
          "configurations": {
            "production": {
              "devServerTarget": "bDataTableDemo:serve:production"
            }
          }
        }
      }
    },
    "ng-bootstrap-table": {
      "projectType": "library",
      "root": "projects/ng-bootstrap-table",
      "sourceRoot": "projects/ng-bootstrap-table/src",
      "prefix": "lib",
      "architect": {
        "build": {
          "builder": "@angular-devkit/build-ng-packagr:build",
          "options": {
            "tsConfig": "projects/ng-bootstrap-table/tsconfig.lib.json",
            "project": "projects/ng-bootstrap-table/ng-package.json"
          }
        },
        "test": {
          "builder": "@angular-devkit/build-angular:karma",
          "options": {
            "main": "projects/ng-bootstrap-table/src/test.ts",
            "tsConfig": "projects/ng-bootstrap-table/tsconfig.spec.json",
            "karmaConfig": "projects/ng-bootstrap-table/karma.conf.js"
          }
        },
        "lint": {
          "builder": "@angular-devkit/build-angular:tslint",
          "options": {
            "tsConfig": [
              "projects/ng-bootstrap-table/tsconfig.lib.json",
              "projects/ng-bootstrap-table/tsconfig.spec.json"
            ],
            "exclude": [
              "**/node_modules/**"
            ]
          }
        }
      }
    }
  },
  "defaultProject": "bDataTableDemo"
}

And my tsconfig.json file

{
  "compileOnSave": false,
  "compilerOptions": {
    "baseUrl": "./",
    "outDir": "./dist/out-tsc",
    "sourceMap": true,
    "declaration": false,
    "downlevelIteration": true,
    "experimentalDecorators": true,
    "module": "esnext",
    "moduleResolution": "node",
    "importHelpers": true,
    "target": "es2015",
    "typeRoots": [
      "node_modules/@types"
    ],
    "lib": [
      "es2018",
      "dom"
    ],
    "paths": {
      "ng-bootstrap-table": [
        "dist/ng-bootstrap-table"
      ],
      "ng-bootstrap-table/*": [
        "dist/ng-bootstrap-table/*"
      ]
    }
  },
  "angularCompilerOptions": {
    "fullTemplateTypeCheck": true,
    "strictInjectionParameters": true
  }
}

What should I change in order to have the expected behavior?

P.S. I am new to angular libraries, so I can't find a solution yet.

Thank you in advance!!

Body:
You should edit the paths in tsconfig to point to your library's index.ts instead of dist/ - which is the built artifact generated with ng build my-library:

"my-library" : [ "libs/my-library/index.ts" ]


问:
How to pipe Howler.masterGain output to mediaRecorder
I'm trying to record composed Web-Audio-API output from Howler (a bunch of sounds and audio sprites combined programmatically).

So far I've tried connecting the Howler.masterGain context to a createMediaStreamDestination Node but the MediaRecorder.ondataavailable event only fires once and without data.

Here's an example with a wired up version here: https://jsfiddle.net/chadananda/kvzrsx5t/86/

const audioURL = 'https://cdn.glitch.com/02dcea11-9bd2-4462-ac38-eeb6a5ad9530%2F331_full_beautiful-minds_0171_preview.mp3?1522829295082'

// connect MediaStreamDestination to Howler.masterGain
Howler.mute(false) // to initialize Howler internals
let mediaDest = Howler.ctx.createMediaStreamDestination()
// first disconnect
Howler.masterGain.disconnect()
// then reconnect to our new destination?
Howler.masterGain.connect(mediaDest)

// set up media recorder to record output
let audioChunks = []
let mediaRecorder = new MediaRecorder(mediaDest.stream, {mimeType: 'audio/webm'})
mediaRecorder.onstart = (event) => { console.log('Started recording Howl output...') }
mediaRecorder.ondataavailable = (e) => { if (e.data.size) audioChunks.push(e.data) }
mediaRecorder.onstop = (event) => {
  console.log('Completed Recording', audioChunks) // why is this returning empty?
    // let buffer = new Blob(chunks)
    // let audioPlayer = document.createElement("AUDIO")
    // audioPlayer.src = window.URL.createObjectURL(buffer)
    // audioPlayer.play()
}

// example of recording one sound looping for 3 seconds
let sound = new Howl({ html5: false, src: audioURL })
// start sound and recording
sound.play(); mediaRecorder.start()
// stop in a few seconds
setTimeout( ()=>{ mediaRecorder.stop(); sound.stop() }, 5000)

```

答:
The recording seems to be blocked by the autoplay policy which prevents you from playing anything without a user interaction. If you trigger the recording from within a click handler it works. I created an updated version of your fiddle which does that.

https://jsfiddle.net/786zkLcu/

I only changed the last lines. The code now generates a dynamic button and attaches a click handler. This also means that the user has to click the button to start the recording.

```<code>const $button = document.createElement('button');

$button.innerHTML = 'click';
$button.onclick = () => {
    sound.play();
    mediaRecorder.start();

    setTimeout(() => {
        mediaRecorder.stop();
        sound.stop();
    }, 5000);
};

document.body.append($button);
</code>```

Body:
The recording seems to be blocked by the autoplay policy which prevents you from playing anything without a user interaction. If you trigger the recording from within a click handler it works. I created an updated version of your fiddle which does that.

https://jsfiddle.net/786zkLcu/

I only changed the last lines. The code now generates a dynamic button and attaches a click handler. This also means that the user has to click the button to start the recording.

const $button = document.createElement('button');

$button.innerHTML = 'click';
$button.onclick = () => {
    sound.play();
    mediaRecorder.start();

    setTimeout(() => {
        mediaRecorder.stop();
        sound.stop();
    }, 5000);
};

document.body.append($button);


问:
localhost refuses to connect - ERR_CONNECTION_REFUSED
I have a simple MVC web application where javascript code sends ajax requests to the controller and the controller sends back responses.

I built the app 2 years ago and everything used to work fine. Now I tried to run the app again locally and met with the following problem:
whenever an Ajax request is sent from the frontend to the controller (running on localhost), the localhost refuses to connect and I get an ERR_CONNECTION_REFUSED message in (chrome's) javascript-console. (In Safari's javascript-console I get the following error message: "Failed to load resource: Could not connect to the server.")

I'm running the app using NetBeans 11.2. My NetBeans IDE uses GlassFish as server:

I removed the Glassfish server from NetBeans IDE, deleted its folder in my home directory and then added the Glassfish server again in my NetBeans IDE (which also entailed downloading the the newest version of the Glassfish server).

Still, the server refuses to accept any requests from the frontend.

I also tried using Payara Server (version 5.193). That didn't make a difference either.

The frontend itself looks fine at first glance by the way. That is, going to http://localhost:8080/myapp loads the frontend of the app. However, any dynamic features of the app don't work because the server refuses to accept any Ajax requests coming from the frontend (and initiated through mouse clicks).

How can I fix this?

I think I found the reason for the problem:

In my javascript-file I have the following line of code:

```<code>var url = "http://localhost:8080/myapp/Controller";
</code>```

The variable "url" is passed to all the AJAX requests sent to localhost.
But here is the crazy thing: the AJAX requests are not sent to "http://localhost:8080/myapp/Controller" but to "http://localhost:8081/myapp/Controller" !!!!!

What the hell is going on here?!

答:
If the value of the attribute http-listener is localhost, it will refuse the connection external connection.

You can verify using its value using the command

```<code>asadmin> get server-config.network-config.network-listeners.network-listener.http-listener-1.*
</code>```

Information similar to the following should returned:

```<code>server.http-service.http-listener.http-listener-1.acceptor-threads = 1
server.http-service.http-listener.http-listener-1.address = 0.0.0.0
server.http-service.http-listener.http-listener-1.blocking-enabled = false
server.http-service.http-listener.http-listener-1.default-virtual-server = server
server.http-service.http-listener.http-listener-1.enabled = true
server.http-service.http-listener.http-listener-1.external-port =
server.http-service.http-listener.http-listener-1.family = inet
server.http-service.http-listener.http-listener-1.id = http-listener-1
server.http-service.http-listener.http-listener-1.port = 8080
server.http-service.http-listener.http-listener-1.redirect-port =
server.http-service.http-listener.http-listener-1.security-enabled = false
server.http-service.http-listener.http-listener-1.server-name =
server.http-service.http-listener.http-listener-1.xpowered-by = true
</code>```

Modify an attribute by using the set subcommand.

This example sets the address attribute of http-listener-1 to 0.0.0.0:

```<code>asadmin> set server.http-service.http-listener.http-listener-1.address = 0.0.0.0
</code>```

Reference:

https://docs.oracle.com/cd/E19798-01/821-1751/ablaq/index.html

Body:
I have a simple MVC web application where javascript code sends ajax requests to the controller and the controller sends back responses.

I built the app 2 years ago and everything used to work fine. Now I tried to run the app again locally and met with the following problem:
whenever an Ajax request is sent from the frontend to the controller (running on localhost), the localhost refuses to connect and I get an ERR_CONNECTION_REFUSED message in (chrome's) javascript-console. (In Safari's javascript-console I get the following error message: "Failed to load resource: Could not connect to the server.")

I'm running the app using NetBeans 11.2. My NetBeans IDE uses GlassFish as server:

I removed the Glassfish server from NetBeans IDE, deleted its folder in my home directory and then added the Glassfish server again in my NetBeans IDE (which also entailed downloading the the newest version of the Glassfish server).

Still, the server refuses to accept any requests from the frontend.

I also tried using Payara Server (version 5.193). That didn't make a difference either.

The frontend itself looks fine at first glance by the way. That is, going to http://localhost:8080/myapp loads the frontend of the app. However, any dynamic features of the app don't work because the server refuses to accept any Ajax requests coming from the frontend (and initiated through mouse clicks).

How can I fix this?

I think I found the reason for the problem:

In my javascript-file I have the following line of code:

var url = "http://localhost:8080/myapp/Controller";

The variable "url" is passed to all the AJAX requests sent to localhost.
But here is the crazy thing: the AJAX requests are not sent to "http://localhost:8080/myapp/Controller" but to "http://localhost:8081/myapp/Controller" !!!!!

What the hell is going on here?!

Body:
If the value of the attribute http-listener is localhost, it will refuse the connection external connection.

You can verify using its value using the command

asadmin> get server-config.network-config.network-listeners.network-listener.http-listener-1.*

Information similar to the following should returned:

server.http-service.http-listener.http-listener-1.acceptor-threads = 1
server.http-service.http-listener.http-listener-1.address = 0.0.0.0
server.http-service.http-listener.http-listener-1.blocking-enabled = false
server.http-service.http-listener.http-listener-1.default-virtual-server = server
server.http-service.http-listener.http-listener-1.enabled = true
server.http-service.http-listener.http-listener-1.external-port =
server.http-service.http-listener.http-listener-1.family = inet
server.http-service.http-listener.http-listener-1.id = http-listener-1
server.http-service.http-listener.http-listener-1.port = 8080
server.http-service.http-listener.http-listener-1.redirect-port =
server.http-service.http-listener.http-listener-1.security-enabled = false
server.http-service.http-listener.http-listener-1.server-name =
server.http-service.http-listener.http-listener-1.xpowered-by = true

Modify an attribute by using the set subcommand.

This example sets the address attribute of http-listener-1 to 0.0.0.0:

asadmin> set server.http-service.http-listener.http-listener-1.address = 0.0.0.0

Reference:

https://docs.oracle.com/cd/E19798-01/821-1751/ablaq/index.html


问:
'TypeError [ERR_INVALID_ARG_TYPE]: The "path" argument must be of type string. Received type undefined'
I'm working on a project in React and ran into a problem that has me stumped.

Whenever I run yarn start I get this error:

TypeError [ERR_INVALID_ARG_TYPE]: The "path" argument must be of type
string. Received type undefined

I have no idea why this is happening.

答:
To fix this issue simply upgrade react-scripts package (check latest version with npm info react-scripts version):

Replace in your package.json "react-scripts": "^3.x.x" with "react-scripts": "^3.4.1" (or the latest available version)

(optional for some) Delete your node_modules folder

Run npm install or yarn install

Some people reported that this issue was caused by running npm audit fix (avoid it!).


问:
ViewHolder returns the old position in RecyclerView
I have a Fragment with BottomSheet behavior that contains a horizontal RecyclerView. RecyclerView is adjusted by SnapHelper to achieve a page effect. It looks something like this:

In the onCreateView event in the Fragment, I set Adapter and LayoutManager:

```<code>recycler_view.setAdapter(new MyRecyclerAdapter(getContext(), dataList));
recycler_view.setLayoutManager(new LinearLayoutManager(getContext(), LinearLayoutManager.HORIZONTAL, false));
</code>```

After I set Adapter, the onCreateViewHolder event is triggered in the MyRecyclerAdapter class object, followed by onBindViewHolder:

```<code>@Override
public MyRecyclerAdapter.MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    View view = inflater.inflate(R.layout.fragment_recycler_item, parent, false);
    return new MyViewHolder(view, parent);
}

@Override
public void onBindViewHolder(MyRecyclerAdapter.MyViewHolder viewHolder, int position) {
    /**I do something using position**/
}
</code>```

When I create this Fragment and configure RecyclerView for the first time-everything works well, onBindViewHolder returns the correct position. But when I flip to the 1st, 2nd, etc. element RecyclerView, and then recreate the fragment, for some unknown reason onBindViewHolder return the old (last) position, although a new Adapter and LineraLayoutManager were created.

To make it clear, I'll break it down into steps:

Creating a Fragment.

Creating an object of the MyRecyclerAdapter class. Set it in RecyclerView.

Creating an object of the LinearLayoutManager class. Set it in RecyclerView.

The onBindViewHolder event in MyRecyclerAdapteris triggered. I get position = 0.

I scroll to the element with position = 2.

I do detach this fragment, and then immediately attach this fragment.

Creating an object of the MyRecyclerAdapter class. Set it in RecyclerView.

Creating an object of the LinearLayoutManager class. Set it in RecyclerView.

The onBindViewHolder event in MyRecyclerAdapteris triggered. I get position = 2.

Question: Why do I get the old position and most importantly how do I fix it?

I read that Android specifically saves the old ViewHolder to use memory more efficiently, but I don't need it.

UPD (Solution): It seems to me that this is a temporary solution (not ideal), but it works. You need to run smoothScrollToPosition(0) after you have installed Adapter and LayoutManager. It is very important to use smoothScrollToPosition(0), not scrollToPosition(0):

```<code>recycler_view.setAdapter(new MyRecyclerAdapter(getContext(), dataList));
recycler_view.setLayoutManager(new LinearLayoutManager(getContext(), LinearLayoutManager.HORIZONTAL, false));
recycler_view.smoothScrollToPosition(0);
</code>```

UPD.1 (Best Solution): Just use this:

```<code>recyclerView.setSaveEnabled(false);
</code>```

答:
If you detach and reattach the fragment then only its View hierarchy is being destroyed and recreated. Restoring scroll position is part of RecyclerViews state restoration behavior.

If you want your RecyclerView to always start at scroll 0 you can prevent it from saving its scroll state in the first place by disabling that behavior:

```<code>recyclerView.setSaveEnabled(false);
</code>```

Body:
I have a Fragment with BottomSheet behavior that contains a horizontal RecyclerView. RecyclerView is adjusted by SnapHelper to achieve a page effect. It looks something like this:

In the onCreateView event in the Fragment, I set Adapter and LayoutManager:

recycler_view.setAdapter(new MyRecyclerAdapter(getContext(), dataList));
recycler_view.setLayoutManager(new LinearLayoutManager(getContext(), LinearLayoutManager.HORIZONTAL, false));

After I set Adapter, the onCreateViewHolder event is triggered in the MyRecyclerAdapter class object, followed by onBindViewHolder:

@Override
public MyRecyclerAdapter.MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    View view = inflater.inflate(R.layout.fragment_recycler_item, parent, false);
    return new MyViewHolder(view, parent);
}

@Override
public void onBindViewHolder(MyRecyclerAdapter.MyViewHolder viewHolder, int position) {
    /**I do something using position**/
}

When I create this Fragment and configure RecyclerView for the first time-everything works well, onBindViewHolder returns the correct position. But when I flip to the 1st, 2nd, etc. element RecyclerView, and then recreate the fragment, for some unknown reason onBindViewHolder return the old (last) position, although a new Adapter and LineraLayoutManager were created.

To make it clear, I'll break it down into steps:

Creating a Fragment.

Creating an object of the MyRecyclerAdapter class. Set it in RecyclerView.

Creating an object of the LinearLayoutManager class. Set it in RecyclerView.

The onBindViewHolder event in MyRecyclerAdapteris triggered. I get position = 0.

I scroll to the element with position = 2.

I do detach this fragment, and then immediately attach this fragment.

Creating an object of the MyRecyclerAdapter class. Set it in RecyclerView.

Creating an object of the LinearLayoutManager class. Set it in RecyclerView.

The onBindViewHolder event in MyRecyclerAdapteris triggered. I get position = 2.

Question: Why do I get the old position and most importantly how do I fix it?

I read that Android specifically saves the old ViewHolder to use memory more efficiently, but I don't need it.

UPD (Solution): It seems to me that this is a temporary solution (not ideal), but it works. You need to run smoothScrollToPosition(0) after you have installed Adapter and LayoutManager. It is very important to use smoothScrollToPosition(0), not scrollToPosition(0):

recycler_view.setAdapter(new MyRecyclerAdapter(getContext(), dataList));
recycler_view.setLayoutManager(new LinearLayoutManager(getContext(), LinearLayoutManager.HORIZONTAL, false));
recycler_view.smoothScrollToPosition(0);

UPD.1 (Best Solution): Just use this:

recyclerView.setSaveEnabled(false);

Body:
If you detach and reattach the fragment then only its View hierarchy is being destroyed and recreated. Restoring scroll position is part of RecyclerViews state restoration behavior.

If you want your RecyclerView to always start at scroll 0 you can prevent it from saving its scroll state in the first place by disabling that behavior:

recyclerView.setSaveEnabled(false);


问:
Char array with cin.getline()
I'm doing an assignment where we aren't allowed to use strings, we have to use char arrays. This is my code:

```<code>cout << "Enter Album name: ";
cin >> CDdata[count].title;
fout << CDdata[count].title;
</code>```

the problem is that when I enter something with a space in it, the rest of my code gets screwed up.

How do I get it so that I can enter something with a space in it?

答: when cin.getline() is escaping some thing its bc of some previous data in buffer that we can clean by cin.ignore() it escape the first caracter while reading from buffer

Title: Char array with cin.getline()

Body:
I'm doing an assignment where we aren't allowed to use strings, we have to use char arrays. This is my code:

cout << "Enter Album name: ";
cin >> CDdata[count].title;
fout << CDdata[count].title;

the problem is that when I enter something with a space in it, the rest of my code gets screwed up.

How do I get it so that I can enter something with a space in it?


问:
c++ assert error C2120: 'void' illegal with all types
Error after compiling in visual studio (C2120: 'void' illegal with all types). New to c++, basically trying to make the program return an error if the file they enter does not exist. Any advice would help. Thanks!</p>

```<code>#include <iostream>
#include <fstream>
#include <string>
#include <cassert>
using namespace std;
int main()
{
    string input_file_name;
    cout << "Give name of input file : ";
    cin >> input_file_name;
    ifstream ins(input_file_name.c_str());
    assert(ins);

    if (assert(ins) == false)
        cout << "Error: " << input_file_name << "does not exist";
}
</code>```

答:
The definition of assert macro is void assert (int expression); as in C++ assert, thus you should not compare its return value.

Additionally, there are some ways you can accomplish some of your goals:

Fastest way to check if a file exist using standard C++/C++11/C?

Body:
Error after compiling in visual studio (C2120: 'void' illegal with all types). New to c++, basically trying to make the program return an error if the file they enter does not exist. Any advice would help. Thanks!

#include <iostream>
#include <fstream>
#include <string>
#include <cassert>
using namespace std;
int main()
{
    string input_file_name;
    cout << "Give name of input file : ";
    cin >> input_file_name;
    ifstream ins(input_file_name.c_str());
    assert(ins);

    if (assert(ins) == false)
        cout << "Error: " << input_file_name << "does not exist";
}


问:
drag and drop list of objects on a grid
I'm building a webapp (on django) where I'm asking the user to provide the following:

number of rows: x

number of columns: y

interactively let the user decide the rows and columns labels

and a list of objects to be pulled into the virtual grid

let's take the example of 3 columns, 4 rows with labels Column i (i=1..x), Row j (j=1..y), and 3 objects named "red" "black" "grey"

with these I would like to have a drag and drop object interaction on an automatically build grid.

when pulling blocks from the pool of objects, they can be placed in the boxes of the grid without removing them from the pool (the objects are infinite). So basically the user can fill everything with red, a mix of the 3 colors, some filled and some empty, and so on..

Screenshot example can be found here:
https://imgur.com/a/BJMzr9q

DO you know if there is something already created with this purpose? I took a look at the library "draggable" but none of the examples really fit my case.

Hope you can help.

If it was not clear, I'm still in the learning phase.

答:
You could use HTML5DnD
https://developer.mozilla.org/en-US/docs/Web/API/HTML_Drag_and_Drop_API
It has API's to configure the items to be dragged and items to be dropped.</p>

Title: drag and drop list of objects on a grid


问:
How is SHA unique?
I am trying to understand SHA uniqueness in simple terms.
For example let us assume there are only messages with maximum length of 4 bits (binery) in whole world. Number of possible messages with different lengths is

2 for single bit length

2^2 for double bit length

2^3 for 3 bit length

2^4 for 4 bit length

that would be 2+4+8+16 = 30 (31 if we consider empty message 2^0 = 1)

Lets us consider SHA3(for example) with output length of 3bits (binery), so maximum possible number of digest are 8.
How can a digest be unique if we need to map 30 messages to 8, or why is it hard to find digest collision for 2 unique messages

答:
I'm not sure what you mean by "SHA uniqueness". An SHA value (any version) is not unique, it cannot be, because it maps an infinite number of inputs (an input of any length) to a finite number of outputs.

A cryptographic hash function has three important properties (which make it a crypto hash, over a regular hash):

strong collision resistance: it is very difficult (computationally infeasible, ie. "not practically possible") to find two inputs that produce the same output (even if you can choose both)

weak collision resistance: for a given input, it is computationally infeasible to find another input that gives the same hash value (you can choose one input to match the output of a given input)

preimage resistance: for a hash value, it's computationally infeasible to find an input that produces that output (it's "one-way")

The only problem in your example is the size. With such small numbers it doesn't  make sense of course. But if the hash value is say 512 bits, it suddenly gets really time consuming and hence practically impossible to brute force.

Title: How is SHA unique?