问:
UNRESOLVED_REFERENCE in widget (TextView) resolved to error element in android-kotlin
How to update the text of Textview in kotlin. Set Text on-create function works but when I tried outside main fun it says unresolved ref.

How can I declare widget for reuse TextView for update the Text Value?
I don't have exp with kotlin. Can somebody help me?

```<code>class MediaPickedActivity : AppCompatActivity() {

    val fullName = "Test User"
    var score = 0

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_media_picked)

        val Tv_test = findViewById(R.id.tv_text) as TextView

        Tv_test.setText("$fullName :: $score ")

        if (score in 0..300) {
            score = 5
            setText()
        }

    }

    private fun setText() {
        // Error is here. I can't set text.
        Tv_test.setText("$fullName :: $score ")
    }

}
</code>```

答:
you can also using a lazy property which will initializing the property once in needed and separate initialization from your logic, for example:

```<code>class MediaPickedActivity : AppCompatActivity() {
    val Tv_test by lazy { findViewById(R.id.tv_text) as TextView }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_media_picked)

        Tv_test.setText("$fullName :: $score ")
        // ...
    }

    private fun setText() {
        Tv_test.setText("$fullName :: $score ")
    }

}
</code>```

OR write an inline function with a reified type parameter T to makes the code more readable.

```<code>class MediaPickedActivity : AppCompatActivity() {
    val nonNull by find<TextView>(R.id.tv_text)
    val nullable by find<TextView?>(R.id.tv_text)
    // ...
}

inline fun <reified T : View?> Activity.find(id: Int): Lazy<T> {
   return lazy { findViewById(id) as T }
}
</code>```

Body:
How to update the text of Textview in kotlin. Set Text on-create function works but when I tried outside main fun it says unresolved ref.

How can I declare widget for reuse TextView for update the Text Value?
I don't have exp with kotlin. Can somebody help me?

class MediaPickedActivity : AppCompatActivity() {

    val fullName = "Test User"
    var score = 0

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_media_picked)

        val Tv_test = findViewById(R.id.tv_text) as TextView

        Tv_test.setText("$fullName :: $score ")

        if (score in 0..300) {
            score = 5
            setText()
        }

    }

    private fun setText() {
        // Error is here. I can't set text.
        Tv_test.setText("$fullName :: $score ")
    }

}

Body:
you can also using a lazy property which will initializing the property once in needed and separate initialization from your logic, for example:

class MediaPickedActivity : AppCompatActivity() {
    val Tv_test by lazy { findViewById(R.id.tv_text) as TextView }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_media_picked)

        Tv_test.setText("$fullName :: $score ")
        // ...
    }

    private fun setText() {
        Tv_test.setText("$fullName :: $score ")
    }

}

OR write an inline function with a reified type parameter T to makes the code more readable.

class MediaPickedActivity : AppCompatActivity() {
    val nonNull by find<TextView>(R.id.tv_text)
    val nullable by find<TextView?>(R.id.tv_text)
    // ...
}

inline fun <reified T : View?> Activity.find(id: Int): Lazy<T> {
   return lazy { findViewById(id) as T }
}


来源: stackexchange

问:
Long difference between server response and browser result with includes
I have an action with this kind of code :

```<code>  Timesheet::WorkPeriod.includes(:ship).limit(2000).to_a
  render nothing: true
</code>```

The server answer gives :

```<code>method=GET path=/timesheet_reports/rest_hours format=html controller=Company::Timesheet::ReportsController action=rest_hours status=200 duration=2106.43 view=3.68 db=23.75
</code>```

But, in the browser, the rendering take 6 sec (for a blank) page. There is a difference of 4 seconds and it increase if I change 2000 for an higher value.

It's correct if I remove the includes or the to_a. It's the same if I do :

```<code>Timesheet::WorkPeriod.includes(:ship).limit(2000).each(&:id)
</code>```

Removing the includes is fastest even if there is a n+1 query problem.

I'm using ruby 2.3 and Rails 4.2.

I suppose there is a problem with memory allocation but I don't know how to to solve it. What can I do?

答:
Why are you using includes? What the SQL looks like?
Maybe if you read the sql you will see :

```<code>Timesheet::WorkPeriod.includes(:ship)
# SELECT "work_period".* FROM "work_period"
# SELECT "ship".* FROM "ship" WHERE "ship"."work_period_id" IN (....)
</code>```

The cost for the query can be huge if you have lot's of rows!

Also because your result can be big. It costs to manipulate huge array in ruby.

Try to use as much as possible active record methods on your data before using ruby, also for example:

```<code>Timesheet::WorkPeriod.includes(:ship).limit(2000).each(&:id)
# use select if you need AR object
Timesheet::WorkPeriod.includes(:ship).limit(2000).select(:id)
# or pluck if you need the list of value in column
Timesheet::WorkPeriod.includes(:ship).limit(2000).pluck(:id)
</code>```

Also check the log when you page is accessed to see if you don't have N+1. The gem bullet can also help you.
If it's doesn't help you. Use rack-mini-profiler.

Further reading:

http://blog.bigbinary.com/2013/07/01/preload-vs-eager-load-vs-joins-vs-includes.html

http://blog.arkency.com/2013/12/rails4-preloading/

ContentLicense: CC BY-SA 3.0

Body:
I have an action with this kind of code :

  Timesheet::WorkPeriod.includes(:ship).limit(2000).to_a
  render nothing: true

The server answer gives :

method=GET path=/timesheet_reports/rest_hours format=html controller=Company::Timesheet::ReportsController action=rest_hours status=200 duration=2106.43 view=3.68 db=23.75

But, in the browser, the rendering take 6 sec (for a blank) page. There is a difference of 4 seconds and it increase if I change 2000 for an higher value.

It's correct if I remove the includes or the to_a. It's the same if I do :

Timesheet::WorkPeriod.includes(:ship).limit(2000).each(&:id)

Removing the includes is fastest even if there is a n+1 query problem.

I'm using ruby 2.3 and Rails 4.2.

I suppose there is a problem with memory allocation but I don't know how to to solve it. What can I do?

Body:
Why are you using includes? What the SQL looks like?
Maybe if you read the sql you will see :

Timesheet::WorkPeriod.includes(:ship)
# SELECT "work_period".* FROM "work_period"
# SELECT "ship".* FROM "ship" WHERE "ship"."work_period_id" IN (....)

The cost for the query can be huge if you have lot's of rows!

Also because your result can be big. It costs to manipulate huge array in ruby.

Try to use as much as possible active record methods on your data before using ruby, also for example:

Timesheet::WorkPeriod.includes(:ship).limit(2000).each(&:id)
# use select if you need AR object
Timesheet::WorkPeriod.includes(:ship).limit(2000).select(:id)
# or pluck if you need the list of value in column
Timesheet::WorkPeriod.includes(:ship).limit(2000).pluck(:id)

Also check the log when you page is accessed to see if you don't have N+1. The gem bullet can also help you.
If it's doesn't help you. Use rack-mini-profiler.

Further reading:

http://blog.bigbinary.com/2013/07/01/preload-vs-eager-load-vs-joins-vs-includes.html

http://blog.arkency.com/2013/12/rails4-preloading/


问:
Reset class member
```<code>#include <iostream>
#include <map>

using namespace std;

class A
{
public:
    void SetData(std::string key, int value)
    {
        if(m_data.find(key) != m_data.end()) m_data.at(key) = value;
        else m_data.insert(std::make_pair(key,value));
    }
    int GetData(std::string key)
    {
        if(m_data.find(key) != m_data.end()) return m_data.at(key);
        return 0;
    }
    void ResetData()
    {
        for(auto item : m_data)
            item.second = 0;
    }
    void ResetData2()
    {
        for(auto it=m_data.begin(); it!=m_data.end(); it++)
            (*it).second = 0;
    }

private:
    std::map<std::string, int> m_data;
};

int main()
{
    A a;
    a.SetData("KEY1", 10);
    std::cout << "Key1: " << a.GetData("KEY1") << std::endl;
    a.ResetData();
    std::cout << "Key1: " << a.GetData("KEY1") << std::endl;
    a.ResetData2();
    std::cout << "Key1: " << a.GetData("KEY1") << std::endl;

    return 0;
}
</code>```

Output:

```<code>Key1: 10
Key1: 10
Key1: 0
</code>```

Live demo: https://ideone.com/GH3Ft8

What's the difference between the two reset methods here?
Resetting the class member std::map<std::string, int> m_data with iterator approach (ResetData2()) works like expected but not range based loop (ResetData())!

答:
Your problem is here:

```<code>for(auto item : m_data)
</code>```

It creates a copy of your key-value For what you want, use:

```<code>for(auto &item: m_data)
</code>```

Title: Reset class member

Body:
#include <iostream>
#include <map>

using namespace std;

class A
{
public:
    void SetData(std::string key, int value)
    {
        if(m_data.find(key) != m_data.end()) m_data.at(key) = value;
        else m_data.insert(std::make_pair(key,value));
    }
    int GetData(std::string key)
    {
        if(m_data.find(key) != m_data.end()) return m_data.at(key);
        return 0;
    }
    void ResetData()
    {
        for(auto item : m_data)
            item.second = 0;
    }
    void ResetData2()
    {
        for(auto it=m_data.begin(); it!=m_data.end(); it++)
            (*it).second = 0;
    }

private:
    std::map<std::string, int> m_data;
};

int main()
{
    A a;
    a.SetData("KEY1", 10);
    std::cout << "Key1: " << a.GetData("KEY1") << std::endl;
    a.ResetData();
    std::cout << "Key1: " << a.GetData("KEY1") << std::endl;
    a.ResetData2();
    std::cout << "Key1: " << a.GetData("KEY1") << std::endl;

    return 0;
}

Output:

Key1: 10
Key1: 10
Key1: 0

Live demo: https://ideone.com/GH3Ft8

What's the difference between the two reset methods here?
Resetting the class member std::map<std::string, int> m_data with iterator approach (ResetData2()) works like expected but not range based loop (ResetData())!

Body:
Your problem is here:

for(auto item : m_data)

It creates a copy of your key-value For what you want, use:

for(auto &item: m_data)


问:
Detect overlapping date ranges from the same table
I have a table with the following data

```<code>PKey  Start       End         Type
====  =====       ===         ====
01    01/01/2010  14/01/2010  S
02    15/01/2010  31/01/2010  S
03    05/01/2010  06/01/2010  A
</code>```

And want to get the following results

```<code>PKey  Start       End         Type
====  =====       ===         ====
01    01/01/2010  14/01/2010  S
03    05/01/2010  06/01/2010  A
</code>```

Any ideas on where to start? A lot of the reading I've done suggests I need to create entries and for each day and join on matching days, is this the only way?

答:
If you already have entries for each day that should work, but if you don't the overhead is significant, and if that query is used often, if will affect performance.

If the data is in this format, you can detect overlaps using simple date arithmetic, because an overlap is simply one interval starting after a given interval, but before the given is finished, something like

```<code>select dr1.* from date_ranges dr1
inner join date_ranges dr2
on dr2.start > dr1.start -- start after dr1 is started
  and dr2.start < dr1.end -- start before dr1 is finished
</code>```

If you need special handling for interval that are wholly within another interval, or you need to merge intervals, i.e.

```<code>PKey  Start       End         Type
====  =====       ===         ====
01    01/01/2010  20/01/2010  S
02    15/01/2010  31/01/2010  S
</code>```

yielding

```<code>Start       End         Type
=====       ===         ====
01/01/2010  31/01/2010  S
</code>```

you will need more complex calculation.

In my experience with this kind of problems, once you get how to do the calculation by hand, it's easy to transfer it into SQL :)

ContentLicense: CC BY-SA 2.5

Body:
I have a table with the following data

PKey  Start       End         Type
====  =====       ===         ====
01    01/01/2010  14/01/2010  S
02    15/01/2010  31/01/2010  S
03    05/01/2010  06/01/2010  A

And want to get the following results

PKey  Start       End         Type
====  =====       ===         ====
01    01/01/2010  14/01/2010  S
03    05/01/2010  06/01/2010  A

Any ideas on where to start? A lot of the reading I've done suggests I need to create entries and for each day and join on matching days, is this the only way?

Body:
If you already have entries for each day that should work, but if you don't the overhead is significant, and if that query is used often, if will affect performance.

If the data is in this format, you can detect overlaps using simple date arithmetic, because an overlap is simply one interval starting after a given interval, but before the given is finished, something like

select dr1.* from date_ranges dr1
inner join date_ranges dr2
on dr2.start > dr1.start -- start after dr1 is started
  and dr2.start < dr1.end -- start before dr1 is finished

If you need special handling for interval that are wholly within another interval, or you need to merge intervals, i.e.

PKey  Start       End         Type
====  =====       ===         ====
01    01/01/2010  20/01/2010  S
02    15/01/2010  31/01/2010  S

yielding

Start       End         Type
=====       ===         ====
01/01/2010  31/01/2010  S

you will need more complex calculation.

In my experience with this kind of problems, once you get how to do the calculation by hand, it's easy to transfer it into SQL :)


问:
How to loop through each and every row, column and cells in a GridView and get its value
I have a GridView which is databound, on button_click I want to read the GridView row by row each column and read the value of each cell in a row and update a table in database? I also know how to check if that cell contains null.

I am trying something like this and got stuck:

```<code>protected void SAVE_GRID_Click(object sender, EventArgs e)
{
    int rowscount = GridView2.Rows.Count;
    int columnscount = GridView2.Columns.Count;
    for (int i = 0; i < rowscount; i++)
    {
        for (int j = 1; j < columnscount; j++)
        {
            // I want to get data of each cell in a row
            // I want to read the corresponding header and store
        }
    }
}
</code>```

答:
```<code>foreach (DataGridViewRow row in GridView2.Rows)
            {
                if ( ! row.IsNewRow)
                {
                    for (int i = 0; i < GridView2.Columns.Count; i++)
                    {
                        String header = GridView2.Columns[i].HeaderText;
                        String cellText = Convert.ToString(row.Cells[i].Value);
                    }
                }
            }
</code>```

Here Before Iterating for cell Values need to check for NewRow.

Body:
I have a GridView which is databound, on button_click I want to read the GridView row by row each column and read the value of each cell in a row and update a table in database? I also know how to check if that cell contains null.

I am trying something like this and got stuck:

protected void SAVE_GRID_Click(object sender, EventArgs e)
{
    int rowscount = GridView2.Rows.Count;
    int columnscount = GridView2.Columns.Count;
    for (int i = 0; i < rowscount; i++)
    {
        for (int j = 1; j < columnscount; j++)
        {
            // I want to get data of each cell in a row
            // I want to read the corresponding header and store
        }
    }
}

Body:
foreach (DataGridViewRow row in GridView2.Rows)
            {
                if ( ! row.IsNewRow)
                {
                    for (int i = 0; i < GridView2.Columns.Count; i++)
                    {
                        String header = GridView2.Columns[i].HeaderText;
                        String cellText = Convert.ToString(row.Cells[i].Value);
                    }
                }
            }

Here Before Iterating for cell Values need to check for NewRow.


问:
Accumulative bar chart via VBA
I have code that generates a simple graph. Now, I want to change this to:

1) The X values must be A, B, C, D.

2) For each of the X values, i need an accumulated bar, accumulating three values - displayed in red, blue, amber. (It Means, I will have four bars, each bar containing a red, blue and amber partaccumulated bar graph)

Please propose code? In example pic I still need to change X axis tags plus green colour should be amber.

BW Peter Bunde Hansen

```<code>Sub Example()
With Sheets("Sheet1").ChartObjects.Add(0, 0, 300, 300).Chart.SeriesCollection.NewSeries
  .Name = "A B C D type errors"
  .XValues = Array(1, 2, 3, 4)
  .Values = Array(1, 4, 9, 16)
End With
</code>```

End Sub

答:
What I want is a type xl3DColumnStacked graph , but it only accepts this: </p>

```<code>Sub Example()
    With Sheets("Sheet1").ChartObjects.Add(0, 0, 300, 300).Chart.SeriesCollection.NewSeries
      .Name = "A B C D type errors"
      .XValues = Array(1, 2, 3, 4, 5)
      .Values = Array(1, 4, 9, 16, 25)
      .Type = xl3DColumn
    End With
End Sub
</code>```

Title: Accumulative bar chart via VBA

Body:
I have code that generates a simple graph. Now, I want to change this to:

1) The X values must be A, B, C, D.

2) For each of the X values, i need an accumulated bar, accumulating three values - displayed in red, blue, amber. (It Means, I will have four bars, each bar containing a red, blue and amber partaccumulated bar graph)

Please propose code? In example pic I still need to change X axis tags plus green colour should be amber.

BW Peter Bunde Hansen

Sub Example()
With Sheets("Sheet1").ChartObjects.Add(0, 0, 300, 300).Chart.SeriesCollection.NewSeries
  .Name = "A B C D type errors"
  .XValues = Array(1, 2, 3, 4)
  .Values = Array(1, 4, 9, 16)
End With

End Sub

Body:
What I want is a type xl3DColumnStacked graph , but it only accepts this:

Sub Example()
    With Sheets("Sheet1").ChartObjects.Add(0, 0, 300, 300).Chart.SeriesCollection.NewSeries
      .Name = "A B C D type errors"
      .XValues = Array(1, 2, 3, 4, 5)
      .Values = Array(1, 4, 9, 16, 25)
      .Type = xl3DColumn
    End With
End Sub


问:
Google Chart not displaying correctly in Chart Area
Actually, I am facing related to the Google charts while implementing with Dynamic data. Here the issue When ever I am clicking a tab that particular data has to be displayed in Chart.Suppose Say like Clicking the current Day is displaying the below result in chart

After pressing on the tab say after pressing Last week it is not displaying chart correctly in chart area

Suppose if u press again Current Day the char is displayed like this

Here the chart area is not working properly after having first click and second click

```<code>`google.charts.load('current', { 'packages': ['bar'] });

$('#t1').click(function () {
    google.charts.setOnLoadCallback(BarC);
    function BarC() {

        var jsonData = $.ajax({
            type: 'GET',
            url: xxxx.xxxx.xxxx,

            dataType: 'json',

        }).done(function (results) {

            var data = new google.visualization.DataTable();
            data.addColumn('string', 'data1');
            data.addColumn('number', 'data2');
            data.addColumn('number', 'data3');
            data.addColumn('number', 'data4');

            data.addRows(results.length);
            for (i = 0; i < results.length; i++) {
                data.setValue(i, 0, results[i]["data1"]);
                data.setValue(i, 1, parseInt(results[i]["data2"]));
                data.setValue(i, 2, parseInt(results[i]["data3"]));
                data.setValue(i, 3, parseInt(results[i]["data4]));
            }

            var options = {

                backgroundColor: 'transparent',

                bars: 'vertical',
                chartArea: { left: 0, top: 0, width: '100%', height: '100%' }// Required for Material Bar Charts.
            };

            var chart = new google.charts.Bar(document.getElementById('chart'));
           chart.draw(data, google.charts.Bar.convertOptions(options));
        }
        );
    }

});`
</code>```

答:
Try

```<code>google.charts.setOnLoadCallback(function() {

  $('#t1').click(function () {
    // ...
  });

  $('#t2').click(function () {
    // ...
  });

  // ...

});
</code>```

https://embed.plnkr.co/19CellQvdGZTjzf9hikU/

Body:
Actually, I am facing related to the Google charts while implementing with Dynamic data. Here the issue When ever I am clicking a tab that particular data has to be displayed in Chart.Suppose Say like Clicking the current Day is displaying the below result in chart

After pressing on the tab say after pressing Last week it is not displaying chart correctly in chart area

Suppose if u press again Current Day the char is displayed like this

Here the chart area is not working properly after having first click and second click

`google.charts.load('current', { 'packages': ['bar'] });

$('#t1').click(function () {
    google.charts.setOnLoadCallback(BarC);
    function BarC() {

        var jsonData = $.ajax({
            type: 'GET',
            url: xxxx.xxxx.xxxx,

            dataType: 'json',

        }).done(function (results) {

            var data = new google.visualization.DataTable();
            data.addColumn('string', 'data1');
            data.addColumn('number', 'data2');
            data.addColumn('number', 'data3');
            data.addColumn('number', 'data4');

            data.addRows(results.length);
            for (i = 0; i < results.length; i++) {
                data.setValue(i, 0, results[i]["data1"]);
                data.setValue(i, 1, parseInt(results[i]["data2"]));
                data.setValue(i, 2, parseInt(results[i]["data3"]));
                data.setValue(i, 3, parseInt(results[i]["data4]));
            }

            var options = {

                backgroundColor: 'transparent',

                bars: 'vertical',
                chartArea: { left: 0, top: 0, width: '100%', height: '100%' }// Required for Material Bar Charts.
            };

            var chart = new google.charts.Bar(document.getElementById('chart'));
           chart.draw(data, google.charts.Bar.convertOptions(options));
        }
        );
    }

});`

Body:
Try

google.charts.setOnLoadCallback(function() {

  $('#t1').click(function () {
    // ...
  });

  $('#t2').click(function () {
    // ...
  });

  // ...

});

https://embed.plnkr.co/19CellQvdGZTjzf9hikU/


问:
Which compiler(compiler location) does weblogic 11g use to compile JSP files?
Hi can anyone please tell me which compiler(compiler location) does weblogic 11g use to compile JSP files? </p>

答: The compiler is called weblogic.rmic. You should be able to find the exact location with a simple search. You can find more information on the compiler on this page.


问:
obtain value from unknown string key property, using jq
I have data structured like this:

```<code>{
  "data": {
    "2017-06-20": {
      "shifts": [
        {
          "id": 24,
          "shift_request_id": 24,
          "created_at": "2017-06-27 15:10:50",
          "updated_at": "2017-06-27 15:10:50"
        },
        {
          "id": 38,
          "shift_request_id": 38,
          "created_at": "2017-06-27 15:10:50",
          "updated_at": "2017-06-27 15:10:50"
        },
        {
          "id": 85,
          "shift_request_id": 85,
          "created_at": "2017-06-27 15:10:51",
          "updated_at": "2017-06-27 15:10:51"
        }
      ]
    },
    ...
    ...
    ...
    ...
    "2017-06-21": {
      "shifts": [
        {
          "id": 26,
          "shift_request_id": 26,
          "created_at": "2017-06-27 15:10:50",
          "updated_at": "2017-06-27 15:10:50"
        },
        {
          "id": 28,
          "shift_request_id": 28,
          "created_at": "2017-06-27 15:10:50",
          "updated_at": "2017-06-27 15:10:50"
        },
        {
          "id": 88,
          "shift_request_id": 88,
          "created_at": "2017-06-27 15:10:51",
          "updated_at": "2017-06-27 15:10:51"
        }
      ]
    }
  }
}
</code>```

So, with those date-like formatted keys, let's say I want to extract shifts from say, first such a key. I am not interested in extracting by particular date as that would be easy as specifying that date as a key, but rather selecting from the whole set, one of them or range, by numeric index, once obtained those keys.

I tried:

```<code>jq '.[] | keys'
</code>```

which gives me an array of all keys, but then I don't know how would I extract array of shifts for a particular key indexed by number.

```<code>jq '.[] | keys[3]'
</code>```

will give me the 4th key in a row, but then .shifts won't work on that, saying that it Cannot index string with string "shifts"

答:
By looking at this https://stackoverflow.com/a/34227629/2434479, I was able to find my way around this problem, so I will keep it here as a reference for someone who might find him self in a similar situation.

So one way of doing it would be:

```<code>❯ http ... | jq '.[] | to_entries[] | [.key, (.value.shifts | length)] | @csv'
</code>```

And when specific key by index needed, say 4th in row:

```<code>❯ http|curl ... | jq '.[] | keys_unsorted[3] as $k | "\($k), \(.[$k].shifts | length)"'
</code>```

Body:
I have data structured like this:

{
  "data": {
    "2017-06-20": {
      "shifts": [
        {
          "id": 24,
          "shift_request_id": 24,
          "created_at": "2017-06-27 15:10:50",
          "updated_at": "2017-06-27 15:10:50"
        },
        {
          "id": 38,
          "shift_request_id": 38,
          "created_at": "2017-06-27 15:10:50",
          "updated_at": "2017-06-27 15:10:50"
        },
        {
          "id": 85,
          "shift_request_id": 85,
          "created_at": "2017-06-27 15:10:51",
          "updated_at": "2017-06-27 15:10:51"
        }
      ]
    },
    ...
    ...
    ...
    ...
    "2017-06-21": {
      "shifts": [
        {
          "id": 26,
          "shift_request_id": 26,
          "created_at": "2017-06-27 15:10:50",
          "updated_at": "2017-06-27 15:10:50"
        },
        {
          "id": 28,
          "shift_request_id": 28,
          "created_at": "2017-06-27 15:10:50",
          "updated_at": "2017-06-27 15:10:50"
        },
        {
          "id": 88,
          "shift_request_id": 88,
          "created_at": "2017-06-27 15:10:51",
          "updated_at": "2017-06-27 15:10:51"
        }
      ]
    }
  }
}

So, with those date-like formatted keys, let's say I want to extract shifts from say, first such a key. I am not interested in extracting by particular date as that would be easy as specifying that date as a key, but rather selecting from the whole set, one of them or range, by numeric index, once obtained those keys.

I tried:

jq '.[] | keys'

which gives me an array of all keys, but then I don't know how would I extract array of shifts for a particular key indexed by number.

jq '.[] | keys[3]'

will give me the 4th key in a row, but then .shifts won't work on that, saying that it Cannot index string with string "shifts"

Body:
By looking at this https://stackoverflow.com/a/34227629/2434479, I was able to find my way around this problem, so I will keep it here as a reference for someone who might find him self in a similar situation.

So one way of doing it would be:

❯ http ... | jq '.[] | to_entries[] | [.key, (.value.shifts | length)] | @csv'

And when specific key by index needed, say 4th in row:

❯ http|curl ... | jq '.[] | keys_unsorted[3] as $k | "\($k), \(.[$k].shifts | length)"'


问:
aspnet table - specify TableCell width?
I've a asp.net table and I'm trying to format my columns to be all equal widths, or say 4 columns of 20%, 30%, 20% and 30%.  However the following code is not working:

```<code><asp:TableCell Width="30%">
</code>```

The 'height' attribute works but this isn't the one I'm after.  Any help much appreciated. Thanks

答:
It's not working because the Width property is expecting a value of a Unit type, which defaults to Pixels..  I couldn't find an example that shows how to create an instance of Unit with a Type of Percentage

Which leaves me to suggest how you could do it with CSS..

Give the TableCell a CssClass, and set the Width in a stylesheet

<asp:TableCell CssClass="tableCellWidth30">

.tableCellWidth30 { width:30%; }

Use the Style property and set the Width inline

<asp:TableCell Style="width:30%;">

Title: aspnet table - specify TableCell width?

Body:
I've a asp.net table and I'm trying to format my columns to be all equal widths, or say 4 columns of 20%, 30%, 20% and 30%.  However the following code is not working:

<asp:TableCell Width="30%">

The 'height' attribute works but this isn't the one I'm after.  Any help much appreciated. Thanks


问:
Load a json template with an object from database
I need to fill a JSON where their properties have the same name with the attributes of the object.

MyObject:

```<code>{ idCliente: 4,
  idAplicacionEmpresa: 1,
  email: 'Jaa@jo.com',
  nombre: 'Joaquin',
  apellido: 'Diaz',
}
</code>```

MyJSON:

```<code>{ sexo: '',
  nombre: '',
  apellido: '',
  telefono: '',
  documento: '',
  provincia: '',
  fechaNacimiento: '',
  localidadResidencia: ''
}
</code>```

Only fill properties who match.

Im using a promise to generate a pdf from a template where the fields of the form match with de json properties, here is my code

```<code>TramitePdf.generatePdf = function (idTipoTramite, idCliente, callback) {
var cliente = TramitePdf.app.models.Cliente;
var modeloTipoTramite = TramitePdf.app.models.TipoTramite;
var pathModelo, pathCliente, tipoT, clienteActual;
modeloTipoTramite.findById(idTipoTramite)
  .then(tipoTramite => {
    this.pathModelo = `${__dirname}/../pdf/${tipoTramite.nombre}.pdf`;
    this.pathCliente = `${__dirname}/../pdf/clientes/${idCliente}_${idTipoTramite}_${tipoTramite.nombre}.pdf`;
    this.tipoT = tipoTramite;
    this.clienteActual = cliente.findById(idCliente);
    return this.clienteActual;
  })
  .then(cliente => {
    pdfFiller.fillForm(this.pathModelo, this.pathCliente, JSON.parse(this.tipoT.template), function (err) {
      callback(err, cliente);
    });
  })
  .catch(err => {
    callback(err);
  });
</code>```

};

Any ideas?

答:
you can try this

let a = { idCliente: 4,
  idAplicacionEmpresa: 1,
  email: 'Jaa@jo.com',
  nombre: 'Joaquin',
  apellido: 'Diaz',
}

let b = { sexo: '',
  nombre: '',
  apellido: '',
  telefono: '',
  documento: '',
  provincia: '',
  fechaNacimiento: '',
  localidadResidencia: ''
}
console.log(b,a)
let KeysOf_a = Object.keys(a);

for(let i = 0;i < KeysOf_a.length;i++){
  if(b.hasOwnProperty(KeysOf_a[i])){
    b[KeysOf_a[i]] = a[KeysOf_a[i]]
  }
}

console.log(b,a)```

Body:
I need to fill a JSON where their properties have the same name with the attributes of the object.

MyObject:

{ idCliente: 4,
  idAplicacionEmpresa: 1,
  email: 'Jaa@jo.com',
  nombre: 'Joaquin',
  apellido: 'Diaz',
}

MyJSON:

{ sexo: '',
  nombre: '',
  apellido: '',
  telefono: '',
  documento: '',
  provincia: '',
  fechaNacimiento: '',
  localidadResidencia: ''
}

Only fill properties who match.

Im using a promise to generate a pdf from a template where the fields of the form match with de json properties, here is my code

TramitePdf.generatePdf = function (idTipoTramite, idCliente, callback) {
var cliente = TramitePdf.app.models.Cliente;
var modeloTipoTramite = TramitePdf.app.models.TipoTramite;
var pathModelo, pathCliente, tipoT, clienteActual;
modeloTipoTramite.findById(idTipoTramite)
  .then(tipoTramite => {
    this.pathModelo = `${__dirname}/../pdf/${tipoTramite.nombre}.pdf`;
    this.pathCliente = `${__dirname}/../pdf/clientes/${idCliente}_${idTipoTramite}_${tipoTramite.nombre}.pdf`;
    this.tipoT = tipoTramite;
    this.clienteActual = cliente.findById(idCliente);
    return this.clienteActual;
  })
  .then(cliente => {
    pdfFiller.fillForm(this.pathModelo, this.pathCliente, JSON.parse(this.tipoT.template), function (err) {
      callback(err, cliente);
    });
  })
  .catch(err => {
    callback(err);
  });

};

Any ideas?


问:
Calculate the average of the n-th number of elements in the column in pandas
I have the following dataframe:

```<code>             df1
index   year   week   a     b     c
 -10    2017    10   45    26    19
  -9    2017    11   37    23    14
  -8    2017    12   21    66    19
  -7    2017    13   47    36    92
  -6    2017    14   82    65    18
  -5    2017    15   68    68    19
  -4    2017    16   30    95    24
  -3    2017    17   21    15    94
  -2    2017    18   67    30    16
  -1    2017    19   10    13    13
   0    2017    20   26    22    18
   1    2017    21   NaN   NaN   NaN
   2    2017    22   NaN   NaN   NaN
   3    2017    23   NaN   NaN   NaN
   4    2017    24   NaN   NaN   NaN
   ...
   53   2018    20   NaN   NaN   NaN
</code>```

I need for each empty cell to calculate the average of the previous nth values in a column and write this value into a cell. n is equal to the number of indexes from zero and up. For example, for the first empty cell in the column a I must calculate the average between the indexes 0 and -10. Then for the next cell between 1 and -9 and so on. And so do for columns a, b and c. And calculations always begin where the index = 1.

And the problem is that the number of columns such as a, b, c can be different. But I know that these columns will always be after the column week. Is it possible to apply these calculations to an indefinite number of columns, but if it is known that these columns will be located after the column week?

I tried hard to find anything, but I could not find anything suitable.

UPD: If this helps, the maximum number of rows from index = 0 and down will be 53.

Body:
I have the following dataframe:

             df1
index   year   week   a     b     c
 -10    2017    10   45    26    19
  -9    2017    11   37    23    14
  -8    2017    12   21    66    19
  -7    2017    13   47    36    92
  -6    2017    14   82    65    18
  -5    2017    15   68    68    19
  -4    2017    16   30    95    24
  -3    2017    17   21    15    94
  -2    2017    18   67    30    16
  -1    2017    19   10    13    13
   0    2017    20   26    22    18
   1    2017    21   NaN   NaN   NaN
   2    2017    22   NaN   NaN   NaN
   3    2017    23   NaN   NaN   NaN
   4    2017    24   NaN   NaN   NaN
   ...
   53   2018    20   NaN   NaN   NaN

I need for each empty cell to calculate the average of the previous nth values in a column and write this value into a cell. n is equal to the number of indexes from zero and up. For example, for the first empty cell in the column a I must calculate the average between the indexes 0 and -10. Then for the next cell between 1 and -9 and so on. And so do for columns a, b and c. And calculations always begin where the index = 1.

And the problem is that the number of columns such as a, b, c can be different. But I know that these columns will always be after the column week. Is it possible to apply these calculations to an indefinite number of columns, but if it is known that these columns will be located after the column week?

I tried hard to find anything, but I could not find anything suitable.

UPD: If this helps, the maximum number of rows from index = 0 and down will be 53.

Body:
This can be done like follows:

n = 11 # in the example of your explanation
df = df1.loc[range(1,df1.index[-1]+1)] # select rows from index 1 above

df should look like:

       year  week   a   b   c
index
1      2017    21 NaN NaN NaN
2      2017    22 NaN NaN NaN
3      2017    23 NaN NaN NaN
4      2017    24 NaN NaN NaN

then you:

for s in list(df.index): # iterate through rows with nan values
    for i in range(2,df.columns.size): # iterate through different cols ('a','b','c' or more)
        df1.loc[s,df.columns[i]] = df1.loc[range(s-n,s),df.columns[i]].sum()/n
print(df1)

please notice that in this case i followed your example and supposed that year will be always first column and week always second in order to select all columns after week and index is.. well the index

output:

       year  week          a          b          c
index
-10    2017    10  45.000000  26.000000  19.000000
-9     2017    11  37.000000  23.000000  14.000000
-8     2017    12  21.000000  66.000000  19.000000
-7     2017    13  47.000000  36.000000  92.000000
-6     2017    14  82.000000  65.000000  18.000000
-5     2017    15  68.000000  68.000000  19.000000
-4     2017    16  30.000000  95.000000  24.000000
-3     2017    17  21.000000  15.000000  94.000000
-2     2017    18  67.000000  30.000000  16.000000
-1     2017    19  10.000000  13.000000  13.000000
 0     2017    20  26.000000  22.000000  18.000000
 1     2017    21  41.272727  41.727273  31.454545
 2     2017    22  40.933884  43.157025  32.586777
 3     2017    23  41.291510  44.989482  34.276484
 4     2017    24  43.136193  43.079434  35.665255


问:
How to Design reports in progress App Builder?
I just want to design new report in progress app builder.

Example:
I just want to pass employee number as a input parameter and get the respective  employee details in excel sheet. for that how to write code in progress. please see the image.

Thanks,

答:
A simple way to get data to excel is to use EXPORT.

Ie

```<code>OUTPUT TO file.csv.
FOR EACH Customer NO-LOCK:
    EXPORT DELIMITER ";" Customer.
END.
OUTPUT CLOSE.
</code>```

That will export without any formatting though.

Body:
A simple way to get data to excel is to use EXPORT.

Ie

OUTPUT TO file.csv.
FOR EACH Customer NO-LOCK:
    EXPORT DELIMITER ";" Customer.
END.
OUTPUT CLOSE.

That will export without any formatting though.


问:
Image out of the container
```<code> <div class="container p0">
    <div class="col-md-12 p0">
        <div class="col-md-6 p0">
           <div class="imagen"></div>
        </div>
        <div class="col-md-6 p0">
           <div class="text-content"></div>
        </div>
    </div>
    </div>
</code>```

I do not have a definite css yet, I still think how I can do this

How can I make the image full width inside a container, just like in the example using bootstrap, The black border is the bootstrap container

What I try to do is the content in a container and the image outside of that container,

答:
Just set these properties--</p>

```<code>.imagen img{
  width: 100%;
  max-width: 100%;
}
</code>```

Title: Image out of the container

Body:
Just set these properties--

.imagen img{
  width: 100%;
  max-width: 100%;
}


问:
Is there any way to achieve move elision
When running the following code:

```<code>struct Copy
{
    Copy() {std::cerr << __PRETTY_FUNCTION__ << std::endl;}
    Copy(const Copy & other) {std::cerr << __PRETTY_FUNCTION__ << std::endl;}
    Copy & operator=(const Copy & other) {std::cerr << __PRETTY_FUNCTION__ << std::endl; return *this;}
    Copy(Copy && other) {std::cerr << __PRETTY_FUNCTION__ << std::endl;}
    Copy & operator=(Copy && other) {std::cerr << __PRETTY_FUNCTION__ << std::endl; return *this;}
    ~Copy() {std::cerr << __PRETTY_FUNCTION__ << std::endl;}
};

char buffer[1024];

template <typename Type>
Type * push(Type value)
{
    return new(buffer) Type(std::move(value));
};

int main()
{
    push(Copy());

    return 0;
}
</code>```

I get the following output:

```<code>Copy::Copy()
Copy::Copy(Copy &&)
Copy::~Copy()
</code>```

Is there anyway to elide the move constructor?

I was hoping that with -O3, it would be constructed in place, but by my testing, that doesn't seem to be the case.

答:
Is there anyway to elide the move constructor? [...] I was hoping that with -O3, it would be constructed in place,

Well, you're explicitly calling the move constructor... and the object is being constructed in-place in buffer. Why do you expect the move constructor call to be elided?

```<code>template <typename Type>
Type * push(Type value)
{
    //                 invokes `Type::Type(Type&&)`
    //                 vvvvvvvvvvvvvvvvvvvvvv
    return new(buffer) Type(std::move(value));
    //                      ^^^^^^^^^^^^^^^^
    //                      casts `value` to `Type&&`
};
</code>```

Your question would make more sense if you were trying to construct Copy with a value of some other type. E.g.:

```<code>struct Copy
{
    Copy(int) { std::cout << "INT\n"; }
    // ... other ctors ...
};

template <typename Type, typename Arg>
Type * push(Arg x)
{
    return new(buffer) Type(std::move(x));
};

int main()
{
    push<Copy>(1);
}
</code>```

The code above prints:

INT

No move/copy constructor is invoked.

live example on wandbox

Body:
When running the following code:

struct Copy
{
    Copy() {std::cerr << __PRETTY_FUNCTION__ << std::endl;}
    Copy(const Copy & other) {std::cerr << __PRETTY_FUNCTION__ << std::endl;}
    Copy & operator=(const Copy & other) {std::cerr << __PRETTY_FUNCTION__ << std::endl; return *this;}
    Copy(Copy && other) {std::cerr << __PRETTY_FUNCTION__ << std::endl;}
    Copy & operator=(Copy && other) {std::cerr << __PRETTY_FUNCTION__ << std::endl; return *this;}
    ~Copy() {std::cerr << __PRETTY_FUNCTION__ << std::endl;}
};

char buffer[1024];

template <typename Type>
Type * push(Type value)
{
    return new(buffer) Type(std::move(value));
};

int main()
{
    push(Copy());

    return 0;
}

I get the following output:

Copy::Copy()
Copy::Copy(Copy &&)
Copy::~Copy()

Is there anyway to elide the move constructor?

I was hoping that with -O3, it would be constructed in place, but by my testing, that doesn't seem to be the case.

Body:
Is there anyway to elide the move constructor? [...] I was hoping that with -O3, it would be constructed in place,

Well, you're explicitly calling the move constructor... and the object is being constructed in-place in buffer. Why do you expect the move constructor call to be elided?

template <typename Type>
Type * push(Type value)
{
    //                 invokes `Type::Type(Type&&)`
    //                 vvvvvvvvvvvvvvvvvvvvvv
    return new(buffer) Type(std::move(value));
    //                      ^^^^^^^^^^^^^^^^
    //                      casts `value` to `Type&&`
};

Your question would make more sense if you were trying to construct Copy with a value of some other type. E.g.:

struct Copy
{
    Copy(int) { std::cout << "INT\n"; }
    // ... other ctors ...
};

template <typename Type, typename Arg>
Type * push(Arg x)
{
    return new(buffer) Type(std::move(x));
};

int main()
{
    push<Copy>(1);
}

The code above prints:

INT

No move/copy constructor is invoked.

live example on wandbox


问:
regex to match all 3 words in a paragraph or a multiline command output
Need a regex to match 3 words in this output (syslogd, Mutex and devc-conaux )

Thu Dec 22 09:24:55.359 UTC

  Jid       Pid Tid            Name State   TimeInState    Blocked-on

  433    163845   3         syslogd Mutex 9522:45:38:0462  163845-07 #1

  433    163845   7         syslogd Reply 10618:23:23:0504   12298  devc-conaux
  433    163845   8         syslogd Mutex 10618:23:21:0802  163845-07 #1

65548     12300   1             ksh Reply 15269:15:10:0850   12298  devc-conaux

I am a beginner, pls help.

答:
This looks like homework to me, but I'll bite:</p>

```<code>/(syslogd|Mutex|devc-conaux)/g
</code>```

Body:
This looks like homework to me, but I'll bite:

/(syslogd|Mutex|devc-conaux)/g


问:
Java Server socket stuck on accept call (Android Client, Java Server)
Below I have put a fragment of code to help understand my problem. I have a server code, works fine for the first time the client loads and sends a packet. After the first packet is received, the server is stuck on "accept".

I have wireshark configured for this port, and the server is getting those packets. I just wonder why accept wont return more than once. Its driving me nuts.

Server Code

```<code> public class DAPool implements Runnable {
 private ServerSocket serverSocket;
 private ArrayList<DA> pool;
 private LinkedList<Socket> clientConnQ;
 public DAPool(int newPoolSize, int serverPort) {
  try {
     serverSocket = new ServerSocket(serverPort, 500, InetAddress.getByName("127.0.0.1"));
  } catch (IOException e) {
     e.printStackTrace();
     return;
  }
  poolSize = newPoolSize;
  clientConnQ = new LinkedList<Socket>();
  pool = new ArrayList<DA>(poolSize);
                DA deviceThread;
  for (int threads = 0; threads < poolSize; threads++) {
     deviceThread = new DA();
     connPool.add(deviceThread);
     deviceThread.start();
  }
 }
 public void run() {
    while (true) {
       Socket incomingSocket;
       try {
           incomingSocket = serverSocket.accept();
       } catch (IOException e) {
           e.printStackTrace();
       return;
     }
     insertNewConnToQ(incomingSocket);
  }
 }

 private class DA extends Thread {
  private Socket clientSocket;
  private ObjectInputStream inputObjectStream;
  public DA() {
  }
  public void run() {
   while (true) {

    while (clientConnQ.isEmpty()) {
     synchronized (clientConnQ) {
      try {
       clientConnQ.wait();
      } catch (InterruptedException ignored) {
       ignored.printStackTrace();
      }
     }
    }
    synchronized (clientConnQ) {
     clientSocket = (Socket) clientConnQ.removeFirst();
     try {
      inputObjectStream = new ObjectInputStream(clientSocket.getInputStream());
     } catch (IOException e) {
      e.printStackTrace();
      return;
     }
        // Do something useful here
                                    }
    }
   }
  }
 }
</code>```

Client Code

```<code>public class SendQueue extends Thread {
 LinkedList<Message> requestQ;
 Message sendRequest, requestMessage;

 Socket clientSocket;
 OutputStream outputStream;
 ObjectOutputStream objectOutputStream;

 public SendQueue(Socket newClientSocket) {
  requestQ = new LinkedList<Message>();
  clientSocket = newClientSocket;
 }

 public void run() {
  while (true) {
   synchronized (requestQ) {
    while (requestQ.isEmpty()) {
     try {
      requestQ.wait();
     } catch (InterruptedException ignored) {
      ignored.printStackTrace();
     }
    }
    sendRequest = requestQ.removeFirst();
   }
   try {
    outputStream = clientSocket.getOutputStream();
    objectOutputStream = new ObjectOutputStream(outputStream);
    objectOutputStream.writeObject(sendRequest);
    objectOutputStream.flush();
    outputStream.flush();
   } catch (IOException e) {
    e.printStackTrace();
   } catch (RuntimeException e) {
    e.printStackTrace();
   }
  }
 }

 public int sendRequest(Message message) {
  synchronized (requestQ) {
   requestQ.addLast(message);
   requestQ.notify();
  }
  return 0;
 }
}
</code>```

答:
Are you sure that it is sticking on the accept call? Did you get a stacktrace that shows it waiting on accept?

Assuming it is getting stuck elsewhere I'm wondering if it isn't because clientConnQ is being held in one of your DA instances. The synchronized block covers the // Do something useful here section.

I wonder if it might work if you changed the code to be

```<code>synchronized (clientConnQ) {
    clientSocket = (Socket) clientConnQ.removeFirst();
}
try {
    ...
</code>```

Once you have your clientSocket from clientConnQ then no other instance can process that socket.

Body:
Below I have put a fragment of code to help understand my problem. I have a server code, works fine for the first time the client loads and sends a packet. After the first packet is received, the server is stuck on "accept".

I have wireshark configured for this port, and the server is getting those packets. I just wonder why accept wont return more than once. Its driving me nuts.

Server Code

 public class DAPool implements Runnable {
 private ServerSocket serverSocket;
 private ArrayList<DA> pool;
 private LinkedList<Socket> clientConnQ;
 public DAPool(int newPoolSize, int serverPort) {
  try {
     serverSocket = new ServerSocket(serverPort, 500, InetAddress.getByName("127.0.0.1"));
  } catch (IOException e) {
     e.printStackTrace();
     return;
  }
  poolSize = newPoolSize;
  clientConnQ = new LinkedList<Socket>();
  pool = new ArrayList<DA>(poolSize);
                DA deviceThread;
  for (int threads = 0; threads < poolSize; threads++) {
     deviceThread = new DA();
     connPool.add(deviceThread);
     deviceThread.start();
  }
 }
 public void run() {
    while (true) {
       Socket incomingSocket;
       try {
           incomingSocket = serverSocket.accept();
       } catch (IOException e) {
           e.printStackTrace();
       return;
     }
     insertNewConnToQ(incomingSocket);
  }
 }

 private class DA extends Thread {
  private Socket clientSocket;
  private ObjectInputStream inputObjectStream;
  public DA() {
  }
  public void run() {
   while (true) {

    while (clientConnQ.isEmpty()) {
     synchronized (clientConnQ) {
      try {
       clientConnQ.wait();
      } catch (InterruptedException ignored) {
       ignored.printStackTrace();
      }
     }
    }
    synchronized (clientConnQ) {
     clientSocket = (Socket) clientConnQ.removeFirst();
     try {
      inputObjectStream = new ObjectInputStream(clientSocket.getInputStream());
     } catch (IOException e) {
      e.printStackTrace();
      return;
     }
        // Do something useful here
                                    }
    }
   }
  }
 }

Client Code

public class SendQueue extends Thread {
 LinkedList<Message> requestQ;
 Message sendRequest, requestMessage;

 Socket clientSocket;
 OutputStream outputStream;
 ObjectOutputStream objectOutputStream;

 public SendQueue(Socket newClientSocket) {
  requestQ = new LinkedList<Message>();
  clientSocket = newClientSocket;
 }

 public void run() {
  while (true) {
   synchronized (requestQ) {
    while (requestQ.isEmpty()) {
     try {
      requestQ.wait();
     } catch (InterruptedException ignored) {
      ignored.printStackTrace();
     }
    }
    sendRequest = requestQ.removeFirst();
   }
   try {
    outputStream = clientSocket.getOutputStream();
    objectOutputStream = new ObjectOutputStream(outputStream);
    objectOutputStream.writeObject(sendRequest);
    objectOutputStream.flush();
    outputStream.flush();
   } catch (IOException e) {
    e.printStackTrace();
   } catch (RuntimeException e) {
    e.printStackTrace();
   }
  }
 }

 public int sendRequest(Message message) {
  synchronized (requestQ) {
   requestQ.addLast(message);
   requestQ.notify();
  }
  return 0;
 }
}

Body:
Are you sure that it is sticking on the accept call? Did you get a stacktrace that shows it waiting on accept?

Assuming it is getting stuck elsewhere I'm wondering if it isn't because clientConnQ is being held in one of your DA instances. The synchronized block covers the // Do something useful here section.

I wonder if it might work if you changed the code to be

synchronized (clientConnQ) {
    clientSocket = (Socket) clientConnQ.removeFirst();
}
try {
    ...

Once you have your clientSocket from clientConnQ then no other instance can process that socket.


问:
Is it possible to add ID3 tags to m4a files using mutagen?
I run into a problem while writing a script to tag my music library with mutagen.
The following code works fine when dealing with mp3 files but corrupts the m4a files.

```<code>def set_video_tags(video, filepath):
    try:
        tags = ID3(filepath, v2_version=3)
    except ID3NoHeaderError:
        tags = ID3()

    tags.add(TXXX(3, desc='desc:custom_tag',text= video.custom_text))
    tags.save(filepath, v2_version=3)
</code>```

After processing the m4a files, tags can be read back using mutagen but aren't detected by any other players and the audio doesn't playback.

I tried to delete MP4 tags from the files before calling this function but it didn't help.

What am I doing wrong?

答:
As I was saying in my comment, MP4 and MP3 are different containers and they use a completely different structures to store the metadata. While, technically, you can encode ID3 fields within MP4 metadata, usage of such would heavily depend on your tagger/player because there are a lot of ways to do it and everybody think they have the best way consequently pushing their own structures.

What is ID3 for MP3 containers, XMP is for MP4/M4A containers (and for a lot of other containers like JPEG, PDF and even MP3 if you want to) - except that XMP is an actual standard while ID3 was an afterthought (it literally was just an added trailing structure at the end of MP3 files) that everybody went along with and its features were mainly dictated by massively popular players of the time like WinAmp, foobar2000 and the likes. In contrast, XMP is essentially an atom-feed like structure (which is why you'll hear mp4 tags being referred as 'atoms' even tho they are not referring to the same thing) which along with its metadata carries also the information of what that metadata presents so even players that first encounter it could, in theory, discern relevant from irrelevant metadata.

Of course, in practice this has also turned into a player/tagger war so a lot of them use their own custom 'extensions' for tagging - currently iTunes holds a massive sway over which fields should be used and how, and other players kind-of play ball - so is mutagen. Instead of a single XMP structure, iTunes spreads the tags as non-video/audio frames (the actual 'atoms') in the MP4 structure itself and some 'tags' have to be weirdly named (binary names and such) so they don't interfere with the format itself. While there is some advantage to this approach (changing the metadata with streaming, very useful for live events) it makes the tagging needlessly complicated and, again, non-standard.

Anyway, your problem occurs because you're trying to write an ID3 structure to an MP4 container - when writing ID3 tags mutagen doesn't parse the whole file to discern if the underlying file supports ID3 and where/how to write it, instead it assumes its been fed a regular MP3 file and writes down the at a wrong place, in a wrong format, at best just adding some garbage at the end of your file (earlier, non-streamable ID3 versions) or, at worst, corrupting your M4A container as a consequence. Same goes when you read the file back - it can read the ID3 structure it wrote previously at a predictable place, it doesn't care what the rest of the data is.

So, as I was saying, and as it is shown in the documentation, use mutagen.mp4.MP4 (or rather the underlying mutagen.mp4.MP4Tags) when dealing with MP4/M4A containers as those are created to work with MP4 containers. For example, to change the desc tag as you're attempting:

```<code>from mutagen.mp4 import MP4

def get_description(filename):
    return MP4(filename).tags.get("desc", [None])[-1]

def set_description(filename, description):
    tags = MP4(filename).tags
    tags["desc"] = description
    tags.save(filename)
</code>```

NOTE: I'm using only the last desc entry in the get_description() function as multiple entries per 'tag' are supported so existing tags return as lists. You obviously wouldn't be using the above in a production setting.

You can test it with:

```<code>print("Current description: {}".format(get_description("test.m4a")))
# Current description: None

set_description("test.m4a", "Test description")  # let's add some description
print("Current description: {}".format(get_description("test.m4a")))
# Current description: Test description

# You can also modify the description once set:
set_description("test.m4a", get_description("test.m4a") + " update")
print("Current description: {}".format(get_description("test.m4a")))
# Current description: Test description update

# etc.
</code>```

For a full set of 'supported' (or rather iTunes, hmmm, encouraged) keys you can check the mutagen.mp4.MP4Tag docs. Of course, you can invent your own keys using a free form structure (i.e. ----:foo:bar) but don't expect any other player to recognize them.

Body:
I run into a problem while writing a script to tag my music library with mutagen.
The following code works fine when dealing with mp3 files but corrupts the m4a files.

def set_video_tags(video, filepath):
    try:
        tags = ID3(filepath, v2_version=3)
    except ID3NoHeaderError:
        tags = ID3()

    tags.add(TXXX(3, desc='desc:custom_tag',text= video.custom_text))
    tags.save(filepath, v2_version=3)

After processing the m4a files, tags can be read back using mutagen but aren't detected by any other players and the audio doesn't playback.

I tried to delete MP4 tags from the files before calling this function but it didn't help.

What am I doing wrong?

Body:
As I was saying in my comment, MP4 and MP3 are different containers and they use a completely different structures to store the metadata. While, technically, you can encode ID3 fields within MP4 metadata, usage of such would heavily depend on your tagger/player because there are a lot of ways to do it and everybody think they have the best way consequently pushing their own structures.

What is ID3 for MP3 containers, XMP is for MP4/M4A containers (and for a lot of other containers like JPEG, PDF and even MP3 if you want to) - except that XMP is an actual standard while ID3 was an afterthought (it literally was just an added trailing structure at the end of MP3 files) that everybody went along with and its features were mainly dictated by massively popular players of the time like WinAmp, foobar2000 and the likes. In contrast, XMP is essentially an atom-feed like structure (which is why you'll hear mp4 tags being referred as 'atoms' even tho they are not referring to the same thing) which along with its metadata carries also the information of what that metadata presents so even players that first encounter it could, in theory, discern relevant from irrelevant metadata.

Of course, in practice this has also turned into a player/tagger war so a lot of them use their own custom 'extensions' for tagging - currently iTunes holds a massive sway over which fields should be used and how, and other players kind-of play ball - so is mutagen. Instead of a single XMP structure, iTunes spreads the tags as non-video/audio frames (the actual 'atoms') in the MP4 structure itself and some 'tags' have to be weirdly named (binary names and such) so they don't interfere with the format itself. While there is some advantage to this approach (changing the metadata with streaming, very useful for live events) it makes the tagging needlessly complicated and, again, non-standard.

Anyway, your problem occurs because you're trying to write an ID3 structure to an MP4 container - when writing ID3 tags mutagen doesn't parse the whole file to discern if the underlying file supports ID3 and where/how to write it, instead it assumes its been fed a regular MP3 file and writes down the at a wrong place, in a wrong format, at best just adding some garbage at the end of your file (earlier, non-streamable ID3 versions) or, at worst, corrupting your M4A container as a consequence. Same goes when you read the file back - it can read the ID3 structure it wrote previously at a predictable place, it doesn't care what the rest of the data is.

So, as I was saying, and as it is shown in the documentation, use mutagen.mp4.MP4 (or rather the underlying mutagen.mp4.MP4Tags) when dealing with MP4/M4A containers as those are created to work with MP4 containers. For example, to change the desc tag as you're attempting:

from mutagen.mp4 import MP4

def get_description(filename):
    return MP4(filename).tags.get("desc", [None])[-1]

def set_description(filename, description):
    tags = MP4(filename).tags
    tags["desc"] = description
    tags.save(filename)

NOTE: I'm using only the last desc entry in the get_description() function as multiple entries per 'tag' are supported so existing tags return as lists. You obviously wouldn't be using the above in a production setting.

You can test it with:

print("Current description: {}".format(get_description("test.m4a")))
# Current description: None

set_description("test.m4a", "Test description")  # let's add some description
print("Current description: {}".format(get_description("test.m4a")))
# Current description: Test description

# You can also modify the description once set:
set_description("test.m4a", get_description("test.m4a") + " update")
print("Current description: {}".format(get_description("test.m4a")))
# Current description: Test description update

# etc.

For a full set of 'supported' (or rather iTunes, hmmm, encouraged) keys you can check the mutagen.mp4.MP4Tag docs. Of course, you can invent your own keys using a free form structure (i.e. ----:foo:bar) but don't expect any other player to recognize them.


问:
Set progress bar on top of RecyclerView and remove after data is loaded
I want to have a loading icon that is displayed on top of where a RecyclerView would be, and disappear once the data is finished loading

It would look like:

Can anyone help me out?

I have the code which shows a TextView above the RecyclerView that says "Loading..." and disappears after the data is loaded, but the RecyclerView is still visible.

My XML:

```<code><TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/loaderTV"
    android:text="Loading..."
    android:layout_above="@+id/eventListRV"/>

<android.support.v7.widget.RecyclerView
    android:scrollbars="vertical"
    android:id="@+id/eventListRV"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_below="@+id/spinner">

    </android.support.v7.widget.RecyclerView>
</code>```

And then in my code

```<code>client.listCreators(request, new Callback<ServiceResponse<Event>>() {
            @Override
            public void success(ServiceResponse<Event> eventServiceResponse, Response response) {
                eventList.addAll(eventServiceResponse.data.results);
                Log.i("tag", String.valueOf(eventServiceResponse.data.total));

                if (eventList.size() > 60) {
                    adapter.notifyDataSetChanged();
                    loadingText.setVisibility(View.GONE);
                }
            }
</code>```

But I want the RecyclerView to be invisible while the data is loading and I want the progress bar ontop of where the RecyclerView is, and I don't want it to be a textview

答:
For centering user of Progress bar use</p>

```<code>android:layout_centerVertical="true"
android:layout_centerHorizontal="true"
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I want to have a loading icon that is displayed on top of where a RecyclerView would be, and disappear once the data is finished loading

It would look like:

Can anyone help me out?

I have the code which shows a TextView above the RecyclerView that says "Loading..." and disappears after the data is loaded, but the RecyclerView is still visible.

My XML:

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/loaderTV"
    android:text="Loading..."
    android:layout_above="@+id/eventListRV"/>

<android.support.v7.widget.RecyclerView
    android:scrollbars="vertical"
    android:id="@+id/eventListRV"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_below="@+id/spinner">

    </android.support.v7.widget.RecyclerView>

And then in my code

client.listCreators(request, new Callback<ServiceResponse<Event>>() {
            @Override
            public void success(ServiceResponse<Event> eventServiceResponse, Response response) {
                eventList.addAll(eventServiceResponse.data.results);
                Log.i("tag", String.valueOf(eventServiceResponse.data.total));

                if (eventList.size() > 60) {
                    adapter.notifyDataSetChanged();
                    loadingText.setVisibility(View.GONE);
                }
            }

But I want the RecyclerView to be invisible while the data is loading and I want the progress bar ontop of where the RecyclerView is, and I don't want it to be a textview

Body:
For centering user of Progress bar use

android:layout_centerVertical="true"
android:layout_centerHorizontal="true"


问:
Entity Framework BulkInsert not inserting child entities
I have 2 tables INS_Staging_UMLERTransaction(Parent) and INS_Staging_UMLERBlueCard(Child).

I need to insert 1000 records, when I use bulk insert it is inserting only parent table. The following is my code.

```<code> _indnCon.BulkInsert(_DataToTrans);
 _indnCon.BulkInsert(_DataToTrans.SelectMany(m =>
                      m.INS_Staging_UMLERBlueCard));
 _indnCon.BulkSaveChanges();
</code>```

答:
There is no BulkInsert or BulkSaveChanges method in Entity Framework Extended.

So in my answer, I will assume you are using Entity Framework Extensions library.

Since the v3.12.6 (Release Note), a IncludeGraph option has been added to include child entities.

Example

```<code>_indnCon.BulkInsert(_DataToTrans, operation => operation.IncludeGraph = true);
</code>```

Note: You don't have to call BulkSaveChanges after calling BulkInsert. Bulk Operation is performed directly in the database.

Answer Sub-Question:

I'm getting an exception when I use IncludeGraph. The exception is "A
  default DbContext context must exist, or a context factory must be
  provided (EntityFrameworkManager.ContextFactory). This setting is
  required for some features like IncludeGraph."

This error mean you don’t have a default constructor for your context. A way to build a new context is required for this feature.

Here is an example how to specify a context factory when no default constructors exists:

```<code>EntityFrameworkManager.ContextFactory = context => new CurrentContext(My.ConnectionString);
</code>```

Body:
I have 2 tables INS_Staging_UMLERTransaction(Parent) and INS_Staging_UMLERBlueCard(Child).

I need to insert 1000 records, when I use bulk insert it is inserting only parent table. The following is my code.

 _indnCon.BulkInsert(_DataToTrans);
 _indnCon.BulkInsert(_DataToTrans.SelectMany(m =>
                      m.INS_Staging_UMLERBlueCard));
 _indnCon.BulkSaveChanges();

Body:
There is no BulkInsert or BulkSaveChanges method in Entity Framework Extended.

So in my answer, I will assume you are using Entity Framework Extensions library.

Since the v3.12.6 (Release Note), a IncludeGraph option has been added to include child entities.

Example

_indnCon.BulkInsert(_DataToTrans, operation => operation.IncludeGraph = true);

Note: You don't have to call BulkSaveChanges after calling BulkInsert. Bulk Operation is performed directly in the database.

Answer Sub-Question:

I'm getting an exception when I use IncludeGraph. The exception is "A
  default DbContext context must exist, or a context factory must be
  provided (EntityFrameworkManager.ContextFactory). This setting is
  required for some features like IncludeGraph."

This error mean you don’t have a default constructor for your context. A way to build a new context is required for this feature.

Here is an example how to specify a context factory when no default constructors exists:

EntityFrameworkManager.ContextFactory = context => new CurrentContext(My.ConnectionString);


答:
I do not think you can do this.  Because elision requires the compiler to have an intrinsic knowledge of where the objects are being constructed.  And with that information, it can just avoid moves and copies and simply place the object where it needs to go.  For example when you return something from the stack of one function back to another, the compiler can elide the move/copy.

But in your case placement new allows you to construct an object into any arbitrary buffer.  And that buffer can really be anywhere, for example it can be on the stack (like in your case) or it can be allocated on the heap with new.  So the compiler does not elide the move/copy here.

Strictly speaking, this can happen through some analysis of the code since the compiler already knows where the buffer is, but I doubt most compilers implement this.

Note  note that you have declared an array of character pointers and not characters, so the buffer is more than 1024 bytes in length if that is what you were expecting

Note  Also note that calling std::move explicitly can prevent elision

The best you can do in this case is make an in place constructor or a move constructor (as you have above) to construct that object into the buffer.  An in place constructor would look something like this

```<code>template <typename... args>
void construct(std::in_place_t, Args&&... args) {
    new (buffer) Type{std::forward<Args>(args)...};
}
</code>```

Title: Is there any way to achieve move elision

Body:
I do not think you can do this.  Because elision requires the compiler to have an intrinsic knowledge of where the objects are being constructed.  And with that information, it can just avoid moves and copies and simply place the object where it needs to go.  For example when you return something from the stack of one function back to another, the compiler can elide the move/copy.

But in your case placement new allows you to construct an object into any arbitrary buffer.  And that buffer can really be anywhere, for example it can be on the stack (like in your case) or it can be allocated on the heap with new.  So the compiler does not elide the move/copy here.

Strictly speaking, this can happen through some analysis of the code since the compiler already knows where the buffer is, but I doubt most compilers implement this.

Note  note that you have declared an array of character pointers and not characters, so the buffer is more than 1024 bytes in length if that is what you were expecting

Note  Also note that calling std::move explicitly can prevent elision

The best you can do in this case is make an in place constructor or a move constructor (as you have above) to construct that object into the buffer.  An in place constructor would look something like this

template <typename... args>
void construct(std::in_place_t, Args&&... args) {
    new (buffer) Type{std::forward<Args>(args)...};
}


问:
WSO2 API Manager server managing users using API
I need to create/remove and manage users in WSO2 AM 2.0.0 through API. Is there any way of managing users and roles without the WSO2 carbon (or store) user interface?</p>

答:
You can use RemoteUserStoreManagerService SOAP service for this.

https://docs.wso2.com/display/IS530/Managing+Users+and+Roles+with+APIs


问:
Counting unique / distinct values by group in a data frame
Let's say I have the following data frame:

```<code>> myvec
    name order_no
1    Amy       12
2   Jack       14
3   Jack       16
4   Dave       11
5    Amy       12
6   Jack       16
7    Tom       19
8  Larry       22
9    Tom       19
10  Dave       11
11  Jack       17
12   Tom       20
13   Amy       23
14  Jack       16
</code>```

I want to count the number of distinct order_no values for each name. It should produce the following result:

```<code>name    number_of_distinct_orders
Amy     2
Jack    3
Dave    1
Tom     2
Larry   1
</code>```

How can I do that?

答:
Using table :

```<code>library(magrittr)
myvec %>% unique %>% '['(1) %>% table %>% as.data.frame %>%
  setNames(c("name","number_of_distinct_orders"))

#    name number_of_distinct_orders
# 1   Amy                         2
# 2  Dave                         1
# 3  Jack                         3
# 4 Larry                         1
# 5   Tom                         2
</code>```

Body:
Let's say I have the following data frame:

> myvec
    name order_no
1    Amy       12
2   Jack       14
3   Jack       16
4   Dave       11
5    Amy       12
6   Jack       16
7    Tom       19
8  Larry       22
9    Tom       19
10  Dave       11
11  Jack       17
12   Tom       20
13   Amy       23
14  Jack       16

I want to count the number of distinct order_no values for each name. It should produce the following result:

name    number_of_distinct_orders
Amy     2
Jack    3
Dave    1
Tom     2
Larry   1

How can I do that?

Body:
Using table :

library(magrittr)
myvec %>% unique %>% '['(1) %>% table %>% as.data.frame %>%
  setNames(c("name","number_of_distinct_orders"))

#    name number_of_distinct_orders
# 1   Amy                         2
# 2  Dave                         1
# 3  Jack                         3
# 4 Larry                         1
# 5   Tom                         2


问:
Cannot swipe from bottom to top on ios - appium
I would like to set the wifi status on ios and in order to do that, I need to to swipe up from the bottom the Control Center.

```<code>    dimension = driverWrapper.getIosDriver().manage().window().getSize();
    int middleX = dimension.getWidth() / 2;
    int y = dimension.getHeight();
   driverWrapper.getIosDriver().swipe(middleX,y-10,middleX,150,600);
</code>```

Before I upgraded java client to 4.0.0 and appium to 1.5.2 it worked correctly.

I get an error of:
Error: VerboseError: point is not within the bounds of the screen

The logs are:

```<code>[debug] [UIAuto] Socket data received (49 bytes)
[debug] [UIAuto] Got result from instruments: {"status":0,"value":{"width":320,"height":568}}
[MJSONWP] Responding to client with driver.getWindowSize() result: {"width":320,"height":568}
[HTTP] <-- GET /wd/hub/session/31411e39-f408-418f-b9b8-e28b80ba1b35/window/current/size 200 1071 ms - 98
[HTTP] --> POST /wd/hub/session/31411e39-f408-418f-b9b8-e28b80ba1b35/touch/perform {"actions":[{"action":"press","options":{"x":160,"y":558}},{"action":"wait","options":{"ms":100}},{"action":"moveTo","options":{"x":160,"y":284}},{"action":"release","options":{}}]}
[MJSONWP] Calling AppiumDriver.performTouch() with args: [[{"action":"press","options":{"x":160,"y":558}},{"action":"wait","options":{"ms":100}},{"action":"moveTo","options":{"x":160,"y":284}},{"action":"...
[debug] [iOS] Executing iOS command 'performTouch'
[debug] [UIAuto] Sending command to instruments: target.touch([{"touch":[{"x":160,"y":558}],"time":0.2},{"touch":[{"x":160,"y":558}],"time":0.30000000000000004},{"touch":[{"x":320,"y":842}],"time":0.5}])

[debug] [Instruments] [INST] 2016-06-19 07:39:13 +0000 Debug: Got new command 6 from instruments: target.touch([{"touch":[{"x":160,"y":558}],"time":0.2},{"touch":[{"x":160,"y":558}],"time":0.30000000000000004},{"touch":[{"x":320,"y":842}],"time":0.5}])

[debug] [Instruments] [INST] 2016-06-19 07:39:13 +0000 Debug: evaluating target.touch([{"touch":[{"x":160,"y":558}],"time":0.2},{"touch":[{"x":160,"y":558}],"time":0.30000000000000004},{"touch":[{"x":320,"y":842}],"time":0.5}])

[debug] [Instruments] [INST] 2016-06-19 07:39:13 +0000 Debug: target.touch(__NSCFArray)

[debug] [Instruments] [INST] 2016-06-19 07:39:13 +0000 Debug: point is not within the bounds of the screen
</code>```

Any idea what is going on?

Thanks

答:
Python version for iOS10 with Appium 1.6.5:

```<code>def swipe_up(self):

logging.info("swipe up")
sleep(1)
window_size = self.driver.get_window_size()  # this returns dictionary
sleep(1)
el = self.driver.find_element(*self.configuration.CommonScreen.WEB_VIEW)
action = TouchAction(self.driver)
sleep(1)
start_x = window_size["width"] * 0.5
start_y = window_size["height"]
end_x = window_size["width"] * 0.5
end_y = window_size["height"] * 0.5
action.press(el, start_x, start_y).wait(100).move_to(el, end_x, end_y).release().perform()
sleep(1)
</code>```

For iOS9 You need to change wait to 1000.

Body:
I would like to set the wifi status on ios and in order to do that, I need to to swipe up from the bottom the Control Center.

    dimension = driverWrapper.getIosDriver().manage().window().getSize();
    int middleX = dimension.getWidth() / 2;
    int y = dimension.getHeight();
   driverWrapper.getIosDriver().swipe(middleX,y-10,middleX,150,600);

Before I upgraded java client to 4.0.0 and appium to 1.5.2 it worked correctly.

I get an error of:
Error: VerboseError: point is not within the bounds of the screen

The logs are:

[debug] [UIAuto] Socket data received (49 bytes)
[debug] [UIAuto] Got result from instruments: {"status":0,"value":{"width":320,"height":568}}
[MJSONWP] Responding to client with driver.getWindowSize() result: {"width":320,"height":568}
[HTTP] <-- GET /wd/hub/session/31411e39-f408-418f-b9b8-e28b80ba1b35/window/current/size 200 1071 ms - 98
[HTTP] --> POST /wd/hub/session/31411e39-f408-418f-b9b8-e28b80ba1b35/touch/perform {"actions":[{"action":"press","options":{"x":160,"y":558}},{"action":"wait","options":{"ms":100}},{"action":"moveTo","options":{"x":160,"y":284}},{"action":"release","options":{}}]}
[MJSONWP] Calling AppiumDriver.performTouch() with args: [[{"action":"press","options":{"x":160,"y":558}},{"action":"wait","options":{"ms":100}},{"action":"moveTo","options":{"x":160,"y":284}},{"action":"...
[debug] [iOS] Executing iOS command 'performTouch'
[debug] [UIAuto] Sending command to instruments: target.touch([{"touch":[{"x":160,"y":558}],"time":0.2},{"touch":[{"x":160,"y":558}],"time":0.30000000000000004},{"touch":[{"x":320,"y":842}],"time":0.5}])

[debug] [Instruments] [INST] 2016-06-19 07:39:13 +0000 Debug: Got new command 6 from instruments: target.touch([{"touch":[{"x":160,"y":558}],"time":0.2},{"touch":[{"x":160,"y":558}],"time":0.30000000000000004},{"touch":[{"x":320,"y":842}],"time":0.5}])

[debug] [Instruments] [INST] 2016-06-19 07:39:13 +0000 Debug: evaluating target.touch([{"touch":[{"x":160,"y":558}],"time":0.2},{"touch":[{"x":160,"y":558}],"time":0.30000000000000004},{"touch":[{"x":320,"y":842}],"time":0.5}])

[debug] [Instruments] [INST] 2016-06-19 07:39:13 +0000 Debug: target.touch(__NSCFArray)

[debug] [Instruments] [INST] 2016-06-19 07:39:13 +0000 Debug: point is not within the bounds of the screen

Any idea what is going on?

Thanks

Body:
Python version for iOS10 with Appium 1.6.5:

def swipe_up(self):

logging.info("swipe up")
sleep(1)
window_size = self.driver.get_window_size()  # this returns dictionary
sleep(1)
el = self.driver.find_element(*self.configuration.CommonScreen.WEB_VIEW)
action = TouchAction(self.driver)
sleep(1)
start_x = window_size["width"] * 0.5
start_y = window_size["height"]
end_x = window_size["width"] * 0.5
end_y = window_size["height"] * 0.5
action.press(el, start_x, start_y).wait(100).move_to(el, end_x, end_y).release().perform()
sleep(1)

For iOS9 You need to change wait to 1000.


问:
How do next track AVPlayer
I tried for a few days to make a button which includes the next song but I can not

Here is my question

How to put the next екфсл at the click of a button with avPlayer

it is my code

```<code>class ViewControllerAudioDetail: UIViewController {

var avPlayer:AVQueuePlayer?
var status = false
fileprivate let seekDuration: Float64 = 10
fileprivate let seekDurationThirty: Float64 = 30

var mod = [Modal]()

@IBOutlet weak var ImageView: UIImageView!

@IBOutlet weak var startTime: UILabel!
@IBOutlet weak var endTime: UILabel!
@IBOutlet weak var sliderSong: UISlider!
@IBOutlet weak var name: UILabel!

@IBOutlet weak var Volume: UISlider!
@IBOutlet weak var iconChange: UIButton!

override func viewDidLoad() {
    super.viewDidLoad()

    Volume.setThumbImage(UIImage(named:"Play.png"), for: .normal)
    sliderSong.minimumValue = 0
    sliderSong.maximumValue = 1

    name.text = mod[thisSong].AudioName
    ImageView.image = mod[0].ImageViewAudio

    let url = URL(string: mod[thisSong].UrlName!)
    let playerItem = AVPlayerItem(url: url!)
    avPlayer = AVQueuePlayer(playerItem:playerItem)

    let _ = avPlayer!.addPeriodicTimeObserver(forInterval: CMTime(seconds: 1, preferredTimescale: CMTimeScale(NSEC_PER_SEC)), queue: DispatchQueue.main) { [weak self] (time) in

        let duration = CMTimeGetSeconds((self?.avPlayer!.currentItem!.asset.duration)!)
        self?.sliderSong.value = Float(CMTimeGetSeconds(time)) / Float(duration)

    }

    let duration = CMTimeGetSeconds(avPlayer!.currentItem!.asset.duration)
    let minutesTextOut = Int(duration) / 60 % 60
    let secondsTextOut = Int(duration) % 60
    let strDuration = String(format:"%02d:%02d", minutesTextOut, secondsTextOut)
    endTime.text = strDuration

}

@IBAction func sliderSong(_ sender: UISlider) {

        //перемотка аудиозвука
        let duration = CMTimeGetSeconds(avPlayer!.currentItem!.asset.duration)
        let value = sliderSong.value
        let durationToSeek = Float(duration) * value

        avPlayer?.seek(to: CMTimeMakeWithSeconds(Float64(durationToSeek),avPlayer!.currentItem!.duration.timescale)) { [](state) in

            if (self.iconChange.currentImage?.isEqual(UIImage(named: "Play.png")))! {
                self.avPlayer?.pause()
            } else if (self.iconChange.currentImage?.isEqual(UIImage(named: "Pause.png")))!{
                self.avPlayer?.play()
            }
        }
}

@IBAction func volume(_ sender: UISlider) {

    avPlayer?.volume = sender.value
}

@IBAction func minusThirtySec(_ sender: Any) {

    let playerCurrentTime = CMTimeGetSeconds((avPlayer?.currentTime())!)
    var newTime = playerCurrentTime - seekDurationThirty

    if newTime < 0 {
        newTime = 0
    }
    let time2: CMTime = CMTimeMake(Int64(newTime * 1000 as Float64), 1000)
    avPlayer?.seek(to: time2, toleranceBefore: kCMTimeZero, toleranceAfter: kCMTimeZero)

}
@IBAction func minusTenSec(_ sender: Any) {

    let playerCurrentTime = CMTimeGetSeconds((avPlayer?.currentTime())!)
    var newTime = playerCurrentTime - seekDuration

    if newTime < 0 {
        newTime = 0
    }
    let time2: CMTime = CMTimeMake(Int64(newTime * 1000 as Float64), 1000)
    avPlayer?.seek(to: time2, toleranceBefore: kCMTimeZero, toleranceAfter: kCMTimeZero)

}

@IBAction func plusTenSec(_ sender: Any) {

    guard let duration = avPlayer?.currentItem?.duration else{
        return
    }
    let playerCurrentTime = CMTimeGetSeconds((avPlayer?.currentTime())!)
    let newTime = playerCurrentTime + seekDuration

    if newTime < (CMTimeGetSeconds(duration) - seekDuration) {

        let time2: CMTime = CMTimeMake(Int64(newTime * 1000 as Float64), 1000)
        avPlayer?.seek(to: time2, toleranceBefore: kCMTimeZero, toleranceAfter: kCMTimeZero)

    }

}
@IBAction func plusThirtySec(_ sender: Any) {

    guard let duration = avPlayer?.currentItem?.duration else{
        return
    }
    let playerCurrentTime = CMTimeGetSeconds((avPlayer?.currentTime())!)
    let newTime = playerCurrentTime + seekDurationThirty

    if newTime < (CMTimeGetSeconds(duration) - seekDuration) {

        let time2: CMTime = CMTimeMake(Int64(newTime * 1000 as Float64), 1000)
        avPlayer?.seek(to: time2, toleranceBefore: kCMTimeZero, toleranceAfter: kCMTimeZero)

    }

}

@IBAction func Next(_ sender: Any) {

    let url = URL(string: mod[thisSong].UrlName!)
    let playerItem = AVPlayerItem(url: url!)
    avPlayer = AVQueuePlayer(playerItem:playerItem)

    avPlayer?.insert(playerItem, after: playerItem)
    avPlayer?.advanceToNextItem()

 //        if thisSong + 1 > mod.count {
 //            thisSong = 0
 //        } else {
 //            thisSong += 1
  //        }
  //
  //
  //        if thisSong != mod.count{
  //
 //            name.text = mod[thisSong].AudioName
 //            player(urlSong:mod[thisSong].UrlName!)
 //            avPlayer?.play()
 //
 //
 //
 //        }

}
@IBAction func Back(_ sender: Any) {

 //        if thisSong != 0{
 //            thisSong -= 1
 //            name.text = mod[thisSong].AudioName
 //            player(urlSong:mod[thisSong].UrlName!)
 //            avPlayer?.play()
 //
 //
 //        }

}

@IBAction func Play(_ sender: Any) {

    if avPlayer?.rate == 0 {
        avPlayer?.play()
        avPlayer?.rate = 1.0
        iconChange.setImage(UIImage(named:"Pause.png"), for: .normal)

        avPlayer?.addPeriodicTimeObserver(forInterval: CMTimeMakeWithSeconds(1, 1), queue: nil, using: {
            (CMTime) -> Void in

            self.updateProgressBar()
        })

    } else {
        avPlayer?.rate = 0.0
        avPlayer?.pause()
        iconChange.setImage(UIImage(named:"Play.png"), for: .normal)

    }

}

func player(urlSong:String) {

}

func updateProgressBar(){
    let timeNow = Int(avPlayer!.currentTime().value) / Int(avPlayer!.currentTime().timescale)

    let minutesText = timeNow / 60
    let secondsText = timeNow % 60

    let duration = String(format:"%02d:%02d", minutesText, secondsText)
    startTime.text = duration

}
</code>```

And tableview from here I get the data

```<code>var thisSong = 0

 class TableViewControllerAudioList: UITableViewController {

override func viewDidLoad() {
    super.viewDidLoad()

    tableView.estimatedRowHeight = 50
    tableView.rowHeight = UITableViewAutomaticDimension

}

override func numberOfSections(in tableView: UITableView) -> Int {
    // #warning Incomplete implementation, return the number of sections
    return 1
}

override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    // #warning Incomplete implementation, return the number of rows
    return modalsF.count
}

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! TableViewCellAudioList

    cell.name.text = modalsF[indexPath.row].AudioName
    cell.number.text = "\(indexPath.row + 1)"

    thisSong = indexPath.row

    return cell
}

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    let vc  = segue.destination as? ViewControllerAudioDetail

    vc?.mod = [modalsF[(tableView.indexPathForSelectedRow?.row)!]]

}
</code>```

答:
Play the selected / current song

```<code>func play(at index: Int) {
    audioPlayer.removeAllItems()
    playerItem = audioItems[index]
    playerItem?.seek(to: kCMTimeZero)
    audioPlayer.insert(playerItem!, after: nil)
    audioPlayer.play()
    isPlaying = true

    self.playAllSongsTableView.reloadData()
}
</code>```

To play previuos song....

```<code>@IBAction func backWordAction(_ sender: UIButton) {
   var index =  audioItems.index(of: audioPlayer.currentItem!) ?? 0
    if index > 0 {
        index = index - 1
    }
    play(at: index)
}
</code>```

To play next song....

```<code>@IBAction func forwordAction(_ sender: UIButton) {
    var index =  audioItems.index(of: audioPlayer.currentItem!) ?? 0
    if index < (audioItems.count - 1) {
        index = index + 1
    }
    play(at: index)

}
</code>```

Title: How do next track AVPlayer

Body:
I tried for a few days to make a button which includes the next song but I can not

Here is my question

How to put the next екфсл at the click of a button with avPlayer

it is my code

class ViewControllerAudioDetail: UIViewController {

var avPlayer:AVQueuePlayer?
var status = false
fileprivate let seekDuration: Float64 = 10
fileprivate let seekDurationThirty: Float64 = 30

var mod = [Modal]()

@IBOutlet weak var ImageView: UIImageView!

@IBOutlet weak var startTime: UILabel!
@IBOutlet weak var endTime: UILabel!
@IBOutlet weak var sliderSong: UISlider!
@IBOutlet weak var name: UILabel!

@IBOutlet weak var Volume: UISlider!
@IBOutlet weak var iconChange: UIButton!

override func viewDidLoad() {
    super.viewDidLoad()

    Volume.setThumbImage(UIImage(named:"Play.png"), for: .normal)
    sliderSong.minimumValue = 0
    sliderSong.maximumValue = 1

    name.text = mod[thisSong].AudioName
    ImageView.image = mod[0].ImageViewAudio

    let url = URL(string: mod[thisSong].UrlName!)
    let playerItem = AVPlayerItem(url: url!)
    avPlayer = AVQueuePlayer(playerItem:playerItem)

    let _ = avPlayer!.addPeriodicTimeObserver(forInterval: CMTime(seconds: 1, preferredTimescale: CMTimeScale(NSEC_PER_SEC)), queue: DispatchQueue.main) { [weak self] (time) in

        let duration = CMTimeGetSeconds((self?.avPlayer!.currentItem!.asset.duration)!)
        self?.sliderSong.value = Float(CMTimeGetSeconds(time)) / Float(duration)

    }

    let duration = CMTimeGetSeconds(avPlayer!.currentItem!.asset.duration)
    let minutesTextOut = Int(duration) / 60 % 60
    let secondsTextOut = Int(duration) % 60
    let strDuration = String(format:"%02d:%02d", minutesTextOut, secondsTextOut)
    endTime.text = strDuration

}

@IBAction func sliderSong(_ sender: UISlider) {

        //перемотка аудиозвука
        let duration = CMTimeGetSeconds(avPlayer!.currentItem!.asset.duration)
        let value = sliderSong.value
        let durationToSeek = Float(duration) * value

        avPlayer?.seek(to: CMTimeMakeWithSeconds(Float64(durationToSeek),avPlayer!.currentItem!.duration.timescale)) { [](state) in

            if (self.iconChange.currentImage?.isEqual(UIImage(named: "Play.png")))! {
                self.avPlayer?.pause()
            } else if (self.iconChange.currentImage?.isEqual(UIImage(named: "Pause.png")))!{
                self.avPlayer?.play()
            }
        }
}

@IBAction func volume(_ sender: UISlider) {

    avPlayer?.volume = sender.value
}

@IBAction func minusThirtySec(_ sender: Any) {

    let playerCurrentTime = CMTimeGetSeconds((avPlayer?.currentTime())!)
    var newTime = playerCurrentTime - seekDurationThirty

    if newTime < 0 {
        newTime = 0
    }
    let time2: CMTime = CMTimeMake(Int64(newTime * 1000 as Float64), 1000)
    avPlayer?.seek(to: time2, toleranceBefore: kCMTimeZero, toleranceAfter: kCMTimeZero)

}
@IBAction func minusTenSec(_ sender: Any) {

    let playerCurrentTime = CMTimeGetSeconds((avPlayer?.currentTime())!)
    var newTime = playerCurrentTime - seekDuration

    if newTime < 0 {
        newTime = 0
    }
    let time2: CMTime = CMTimeMake(Int64(newTime * 1000 as Float64), 1000)
    avPlayer?.seek(to: time2, toleranceBefore: kCMTimeZero, toleranceAfter: kCMTimeZero)

}

@IBAction func plusTenSec(_ sender: Any) {

    guard let duration = avPlayer?.currentItem?.duration else{
        return
    }
    let playerCurrentTime = CMTimeGetSeconds((avPlayer?.currentTime())!)
    let newTime = playerCurrentTime + seekDuration

    if newTime < (CMTimeGetSeconds(duration) - seekDuration) {

        let time2: CMTime = CMTimeMake(Int64(newTime * 1000 as Float64), 1000)
        avPlayer?.seek(to: time2, toleranceBefore: kCMTimeZero, toleranceAfter: kCMTimeZero)

    }

}
@IBAction func plusThirtySec(_ sender: Any) {

    guard let duration = avPlayer?.currentItem?.duration else{
        return
    }
    let playerCurrentTime = CMTimeGetSeconds((avPlayer?.currentTime())!)
    let newTime = playerCurrentTime + seekDurationThirty

    if newTime < (CMTimeGetSeconds(duration) - seekDuration) {

        let time2: CMTime = CMTimeMake(Int64(newTime * 1000 as Float64), 1000)
        avPlayer?.seek(to: time2, toleranceBefore: kCMTimeZero, toleranceAfter: kCMTimeZero)

    }

}

@IBAction func Next(_ sender: Any) {

    let url = URL(string: mod[thisSong].UrlName!)
    let playerItem = AVPlayerItem(url: url!)
    avPlayer = AVQueuePlayer(playerItem:playerItem)

    avPlayer?.insert(playerItem, after: playerItem)
    avPlayer?.advanceToNextItem()

 //        if thisSong + 1 > mod.count {
 //            thisSong = 0
 //        } else {
 //            thisSong += 1
  //        }
  //
  //
  //        if thisSong != mod.count{
  //
 //            name.text = mod[thisSong].AudioName
 //            player(urlSong:mod[thisSong].UrlName!)
 //            avPlayer?.play()
 //
 //
 //
 //        }

}
@IBAction func Back(_ sender: Any) {

 //        if thisSong != 0{
 //            thisSong -= 1
 //            name.text = mod[thisSong].AudioName
 //            player(urlSong:mod[thisSong].UrlName!)
 //            avPlayer?.play()
 //
 //
 //        }

}

@IBAction func Play(_ sender: Any) {

    if avPlayer?.rate == 0 {
        avPlayer?.play()
        avPlayer?.rate = 1.0
        iconChange.setImage(UIImage(named:"Pause.png"), for: .normal)

        avPlayer?.addPeriodicTimeObserver(forInterval: CMTimeMakeWithSeconds(1, 1), queue: nil, using: {
            (CMTime) -> Void in

            self.updateProgressBar()
        })

    } else {
        avPlayer?.rate = 0.0
        avPlayer?.pause()
        iconChange.setImage(UIImage(named:"Play.png"), for: .normal)

    }

}

func player(urlSong:String) {

}

func updateProgressBar(){
    let timeNow = Int(avPlayer!.currentTime().value) / Int(avPlayer!.currentTime().timescale)

    let minutesText = timeNow / 60
    let secondsText = timeNow % 60

    let duration = String(format:"%02d:%02d", minutesText, secondsText)
    startTime.text = duration

}

And tableview from here I get the data

var thisSong = 0

 class TableViewControllerAudioList: UITableViewController {

override func viewDidLoad() {
    super.viewDidLoad()

    tableView.estimatedRowHeight = 50
    tableView.rowHeight = UITableViewAutomaticDimension

}

override func numberOfSections(in tableView: UITableView) -> Int {
    // #warning Incomplete implementation, return the number of sections
    return 1
}

override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    // #warning Incomplete implementation, return the number of rows
    return modalsF.count
}

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! TableViewCellAudioList

    cell.name.text = modalsF[indexPath.row].AudioName
    cell.number.text = "\(indexPath.row + 1)"

    thisSong = indexPath.row

    return cell
}

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    let vc  = segue.destination as? ViewControllerAudioDetail

    vc?.mod = [modalsF[(tableView.indexPathForSelectedRow?.row)!]]

}

Body:
Play the selected / current song

func play(at index: Int) {
    audioPlayer.removeAllItems()
    playerItem = audioItems[index]
    playerItem?.seek(to: kCMTimeZero)
    audioPlayer.insert(playerItem!, after: nil)
    audioPlayer.play()
    isPlaying = true

    self.playAllSongsTableView.reloadData()
}

To play previuos song....

@IBAction func backWordAction(_ sender: UIButton) {
   var index =  audioItems.index(of: audioPlayer.currentItem!) ?? 0
    if index > 0 {
        index = index - 1
    }
    play(at: index)
}

To play next song....

@IBAction func forwordAction(_ sender: UIButton) {
    var index =  audioItems.index(of: audioPlayer.currentItem!) ?? 0
    if index < (audioItems.count - 1) {
        index = index + 1
    }
    play(at: index)

}


问:
Updating LINQ to SQL but the query i have is from a join? Can't update using query that uses a join?
I have a query that returns IQueryable, my query consists of join. the end user needs to be able to update certain fields. Rememeber that the fields don't come from 1 table but are the result of 2 joins.

Hence how do i use the data that i returned from my query and change it and update back to the database?

Do i need to do a futher 2 select queries which would obviosly return an LINQ2SQL CLASS so i can then just change the values in the class and then update the database?

I am little confused the best way around this problem.

答: When you want to alter some data, you need to work with the classes that LINQ to SQL generated for you. Only this way, LINQ to SQL knows what was changed (change tracking) and how to update the corresponding database record. In other words, a change on an anonymous object or custom object won't get noticed. The join however, has nothing to do with it.</p>


问:
Shibboleth Testshib IDP is not logging out When i browse "https://www.testshib.org/Shibboleth.sso/Logout"
I have installed Shibboleth SP in local. I am trying to test it with TestShib IDP. Ii was succeded to regiter with Testshib and able to login.

When i am trying to Logout from testshib IDP(https://www.testshib.org/Shibboleth.sso/Logout). It is giving Status of Local Logout: Logout completed successfully.

But when i am trying to login again it is not asking for Login page it is automatically logging the user.

Can you please tell me solution.

答:
Well unfortunately there is no solution to this flow.

It is not in SP's hand to get user logged out. Shibboleth may keep session on or it is possible for idP to keep the session on.

So it is safe to keep in mind that it will never be logged out manually.


问:
Best practice to make S3 file accessible for Redshift through COPY operation for anyone
I want to publish a tutorial where a data from sample tsv file S3 is used by Redshift. Ideally I want it to be simple copy paste operation required to follow the exercises step by step, similar to what's in Load Sample Data from Amazon S3. The problem is with the first data import task using COPY command as it only supports S3, or EMR based load.

This seems like a simple requirement but no hassle-free way to really do it with Redshift COPY (I can make the file available for browser download without any problem but COPY requires CREDENTIALS parameter…)

Variety of options for Redshift COPY Authorization parameters is quite rich:

Should I ask user to  Create an IAM Role for Amazon Redshift
himself?

Should I create it myself and publish the IAM role ARN? Sounds most hassle
free (copy paste) but security wise doesn't sound well…? Do I need to restrict S3 permissions to limit the access to only that particular file for that role?

Should I try temporary access instead?

答:
You are correct:

Data can be imported into Amazon Redshift from Amazon S3 via the COPY command

The COPY command requires permission to access the data stored in Amazon S3. This can be granted either via:

Credentials (Access Key + Secret Key) associated with an IAM User, or

An IAM Role

You cannot create a Role for people and let them use it, because their Amazon Redshift cluster will be running in a different AWS Account than your IAM Role. You could possibly grant trust access so that other accounts can use the role, but this is not necessarily a wise thing to do.

As for credentials, they could either use their own or ones the you supply. They can access their own Access Key + Secret Key in the IAM console.

If you wish to supply credentials for them to use, you could create an IAM User that has permission only to access the Amazon S3 files they need. It is normally unwise to publish your AWS credentials because they might expose a security hole, so you should think carefully before doing this.

At the end of the day, it's probably best to show them the correct process so they understand how to obtain their own credentials. Security is very important in the cloud, so you would also be teaching them good security practice, in additional to Amazon Redshift itself.