问:
C# Not all data passes from one Form to another
I have problems passing all data I need from one form to another. Below you can see the data I want to pass, but what happens is, it passes only (_12nc, BID, device, orderNr) but not List<>steps.

```<code>Steps stepsForm = new Steps(ref steps, _12nc, BID, device, orderNr);
</code>```

But if I try to pass only List<>steps, than steps is passed:

```<code>Steps stepsForm = new Steps(ref steps)
</code>```

How can I pass both List and individual values?

This is code from where I want to pass data:

```<code>private void btn_start_Click(object sender, EventArgs e)
    {
        List<Step> steps = new List<Step>();
        int device;
        string _12nc;
        int BID;
        int orderNr;

        device = Convert.ToInt32(txt_device.Text);
        _12nc = txt_12nc.Text;
        BID = Convert.ToInt32(txt_BID.Text);
        orderNr = Convert.ToInt32(txt_OrderNr.Text);

        // Get list of steps (ID and Description)
        steps = myDBHelper.GetSteps(_12nc,device, BID);

        // Open new form and pass steps to it
        Steps stepsForm = new Steps(ref steps, _12nc, BID, device, orderNr); //, _12nc, BID, device, orderNr
        stepsForm.Show();
        this.Hide();
    }
</code>```

And this is where I want to pass it to:

```<code>    public partial class Steps : Form
{
    private List<Step> steps = new List<Step>();
    private List<Parameter> param = new List<Parameter>();

    private String _12nc;
    private int BID;
    private int device;
    private int orderNr;

    public Steps(ref List<Step> steps, string _12nc, int BID, int device, int orderNr)
    {
        InitializeComponent();
        this.steps = steps;
        this._12nc = _12nc;
        this.BID = BID;
        this.device = device;
        this.orderNr = orderNr;
        RefreshLabels();
    }
</code>```

答:
Modify below code as per your requirement, I have check it is working fine.

```<code>public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    private void button1_Click(object sender, EventArgs e)
    {
        List<Step> steps = new List<Step>();
        Step objStep = new Step();
        int device;

        device = 32;
        objStep._12nc = "dsfdsF";
        objStep.BID = 3;
        objStep.orderNr = 12;

        // Get list of steps (ID and Description)
        //steps = myDBHelper.GetSteps(_12nc, device, BID);
        steps.Add(objStep);
        // Open new form and pass steps to it
        Form2 stepsForm = new Form2(steps, objStep, device); //, _12nc, BID, device, orderNr
        stepsForm.Show();
        this.Hide();
    }
}
</code>```

Second form

```<code>public partial class Form2 : Form
{
    public Form2()
    {
        InitializeComponent();
    }
     private List<Step> steps = new List<Step>();
private List<Parameter> param = new List<Parameter>();

private String _12nc;
private int BID;
private int device;
private int orderNr;

public Form2(List<Step> steps, Step objStep, int device)
{
    InitializeComponent();
    this.steps = steps;
    this._12nc = objStep._12nc;
    this.BID = objStep.BID;
    this.device = device;
    this.orderNr = objStep.orderNr;
    //RefreshLabels();
}
}
public class Step
{
    public string _12nc { get; set; }
    public int BID { get; set; }
    public int orderNr { get; set; }
}
public class Parameter
{
}
</code>```

Body:
I have problems passing all data I need from one form to another. Below you can see the data I want to pass, but what happens is, it passes only (_12nc, BID, device, orderNr) but not List<>steps.

Steps stepsForm = new Steps(ref steps, _12nc, BID, device, orderNr);

But if I try to pass only List<>steps, than steps is passed:

Steps stepsForm = new Steps(ref steps)

How can I pass both List and individual values?

This is code from where I want to pass data:

private void btn_start_Click(object sender, EventArgs e)
    {
        List<Step> steps = new List<Step>();
        int device;
        string _12nc;
        int BID;
        int orderNr;

        device = Convert.ToInt32(txt_device.Text);
        _12nc = txt_12nc.Text;
        BID = Convert.ToInt32(txt_BID.Text);
        orderNr = Convert.ToInt32(txt_OrderNr.Text);

        // Get list of steps (ID and Description)
        steps = myDBHelper.GetSteps(_12nc,device, BID);

        // Open new form and pass steps to it
        Steps stepsForm = new Steps(ref steps, _12nc, BID, device, orderNr); //, _12nc, BID, device, orderNr
        stepsForm.Show();
        this.Hide();
    }

And this is where I want to pass it to:

    public partial class Steps : Form
{
    private List<Step> steps = new List<Step>();
    private List<Parameter> param = new List<Parameter>();

    private String _12nc;
    private int BID;
    private int device;
    private int orderNr;

    public Steps(ref List<Step> steps, string _12nc, int BID, int device, int orderNr)
    {
        InitializeComponent();
        this.steps = steps;
        this._12nc = _12nc;
        this.BID = BID;
        this.device = device;
        this.orderNr = orderNr;
        RefreshLabels();
    }

Body:
Modify below code as per your requirement, I have check it is working fine.

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    private void button1_Click(object sender, EventArgs e)
    {
        List<Step> steps = new List<Step>();
        Step objStep = new Step();
        int device;

        device = 32;
        objStep._12nc = "dsfdsF";
        objStep.BID = 3;
        objStep.orderNr = 12;

        // Get list of steps (ID and Description)
        //steps = myDBHelper.GetSteps(_12nc, device, BID);
        steps.Add(objStep);
        // Open new form and pass steps to it
        Form2 stepsForm = new Form2(steps, objStep, device); //, _12nc, BID, device, orderNr
        stepsForm.Show();
        this.Hide();
    }
}

Second form

public partial class Form2 : Form
{
    public Form2()
    {
        InitializeComponent();
    }
     private List<Step> steps = new List<Step>();
private List<Parameter> param = new List<Parameter>();

private String _12nc;
private int BID;
private int device;
private int orderNr;

public Form2(List<Step> steps, Step objStep, int device)
{
    InitializeComponent();
    this.steps = steps;
    this._12nc = objStep._12nc;
    this.BID = objStep.BID;
    this.device = device;
    this.orderNr = objStep.orderNr;
    //RefreshLabels();
}
}
public class Step
{
    public string _12nc { get; set; }
    public int BID { get; set; }
    public int orderNr { get; set; }
}
public class Parameter
{
}


来源: stackexchange

问:
View - Return 0 if no rows found in a grouped by query
Let's say I have the following MySQL view:

```<code>create or replace view total_transactions(account_id, total) as
select
  t.account_id,
  ifnull(sum(t.value), 0) as total
from transactions t
where t.paid IS TRUE
group by t.bank_account_id;
</code>```

Let's say the account doesn't have any transaction yet, I want the view to return 0.
Right now, if I do a select like:

```<code>select * from total_transactions where account_id = 2060;
</code>```

And account 2060 didn't had any transaction, it will return me nothing, instead of 0.

How could I fix that?

Thanks in advance.

EDIT

I think it could be something with the group by...

If I execute the query that I'm using for the view without the group by, it works (return 0 even with no results), but if I use group by it comes null:

```<code>select
  t.account_id,
  ifnull(sum(t.value), 0) as total
from transactions t
where t.paid IS TRUE
and account_id = 2060;
</code>```

Returns 0, and

```<code>create or replace view total_transactions(account_id, total) as
select
  t.account_id,
  ifnull(sum(t.value), 0) as total
from transactions t
where t.paid IS TRUE
and account_id = 2060
group by t.bank_account_id;
</code>```

Return an empty set.

答:
For positive values I use

```<code>select max(x.cnt) as cnt
from (
select ifnull(meta_value, 0) as cnt from wp_postmeta where post_id = 5543 and meta_key = '_bbp_voice_count'
union
select 0 as cnt) x
</code>```

or for any

```<code>select x.cnt
from (
select ifnull(meta_value, 0) as cnt from wp_postmeta where post_id = 5543 and meta_key = '_bbp_voice_count'
union
select 0 as cnt
) x
limit 1
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Let's say I have the following MySQL view:

create or replace view total_transactions(account_id, total) as
select
  t.account_id,
  ifnull(sum(t.value), 0) as total
from transactions t
where t.paid IS TRUE
group by t.bank_account_id;

Let's say the account doesn't have any transaction yet, I want the view to return 0.
Right now, if I do a select like:

select * from total_transactions where account_id = 2060;

And account 2060 didn't had any transaction, it will return me nothing, instead of 0.

How could I fix that?

Thanks in advance.

EDIT

I think it could be something with the group by...

If I execute the query that I'm using for the view without the group by, it works (return 0 even with no results), but if I use group by it comes null:

select
  t.account_id,
  ifnull(sum(t.value), 0) as total
from transactions t
where t.paid IS TRUE
and account_id = 2060;

Returns 0, and

create or replace view total_transactions(account_id, total) as
select
  t.account_id,
  ifnull(sum(t.value), 0) as total
from transactions t
where t.paid IS TRUE
and account_id = 2060
group by t.bank_account_id;

Return an empty set.

Body:
For positive values I use

select max(x.cnt) as cnt
from (
select ifnull(meta_value, 0) as cnt from wp_postmeta where post_id = 5543 and meta_key = '_bbp_voice_count'
union
select 0 as cnt) x

or for any

select x.cnt
from (
select ifnull(meta_value, 0) as cnt from wp_postmeta where post_id = 5543 and meta_key = '_bbp_voice_count'
union
select 0 as cnt
) x
limit 1


问:
My JQuery post data to 'textbox' how to post it to 'div'?
I'm very new to JQuery.
I already can, get the data from textbox and do some calculation and show it to other 'textbox' though I want to post it to 'div' or 'p' whatever it is as long as not textbox.

here's my code

Participant fee (IDR):

Populi fee (IDR):

<input type="text" id="popcost">

Total Estimated Cost (IDR):

<input type="text" id="totcost">

$(document).ready(function(){
$('#calc').click(function(){
        var num_participant = parseInt($("num_participant").val());
        var reward = parseInt($("reward").val());
        var esttime = parseInt($("esttime").val());
        var parcost = num_participant*reward;
        var popcost = (parcost*0.1)+(num_participant*150);
        var totcost = parcost+popcost;
        /*
        document.getElementById("result").style.display = "block";
        document.getElementById("parcost").value = parcost;
        document.getElementById("popcost").value = popcost;
        document.getElementById("totcost").value = totcost;*/

        document.getElementById("result").style.display = "block";
        $("#parcost").html(parcost);
        $("#popcost").html(popcost);
        $("#totcost").html(totcost);

        return false;
});

});
```

Still wont work, if I change it from "document.getelementById" to "$".
and even using "document.getelementById" it won't showed on the "div".

any ideas?

答:
If you wish to add a result in a div try with:</p>

```<code>jQuery("#divID").append("<p>" + data + "<p>");
</code>```

Body:
I'm very new to JQuery.
I already can, get the data from textbox and do some calculation and show it to other 'textbox' though I want to post it to 'div' or 'p' whatever it is as long as not textbox.

here's my code

Participant fee (IDR):

Populi fee (IDR):

<input type="text" id="popcost">

Total Estimated Cost (IDR):

<input type="text" id="totcost">

$(document).ready(function(){
$('#calc').click(function(){
        var num_participant = parseInt($("num_participant").val());
        var reward = parseInt($("reward").val());
        var esttime = parseInt($("esttime").val());
        var parcost = num_participant*reward;
        var popcost = (parcost*0.1)+(num_participant*150);
        var totcost = parcost+popcost;
        /*
        document.getElementById("result").style.display = "block";
        document.getElementById("parcost").value = parcost;
        document.getElementById("popcost").value = popcost;
        document.getElementById("totcost").value = totcost;*/

        document.getElementById("result").style.display = "block";
        $("#parcost").html(parcost);
        $("#popcost").html(popcost);
        $("#totcost").html(totcost);

        return false;
});

});

Still wont work, if I change it from "document.getelementById" to "$".
and even using "document.getelementById" it won't showed on the "div".

any ideas?

Body:
If you wish to add a result in a div try with:

jQuery("#divID").append("<p>" + data + "<p>");


问:
Showing only actual column data in SQL*Plus
I'm spooling out delimited text files from SQL*Plus, but every column is printed as the full size per its definition, rather than the data actually in that row.

For instance, a column defined as 10 characters, with a row value of "test", is printing out as "test      " instead of "test". I can confirm this by selecting the column along with the value of its LENGTH function. It prints "test      |4".

It kind of defeats the purpose of a delimiter if it forces me into fixed-width. Is there a SET option that will fix this, or some other way to make it print only the actual column data.

I don't want to add TRIM to every column, because if a value is actually stored with spaces I want to be able to keep them.

Thanks

答:
I have seen many SQL*plus script, that create text files like this:

```<code>select A || ';' || B || ';' || C || ';' || D
from T
where ...
</code>```

It's a strong indication to me that you can't just switch to variable length output with a SET command.

Instead of ';' you can of course use any other delimiter. And it's up to your query to properly escape any characters that could be confused with a delimiter or a line feed.

ContentLicense: CC BY-SA 2.5

Body:
I have seen many SQL*plus script, that create text files like this:

select A || ';' || B || ';' || C || ';' || D
from T
where ...

It's a strong indication to me that you can't just switch to variable length output with a SET command.

Instead of ';' you can of course use any other delimiter. And it's up to your query to properly escape any characters that could be confused with a delimiter or a line feed.


问:
Failed to resolve: com.google.firebase:firebase-core:11.0.0
I've seen this question asked and replies along the lines of re-syncing the project and updating the SDK.  I am right at the beginning of a new project and trying to set up authentication with firebase and I'm getting the following errors

Does android studio just hate me?

Error:Failed to resolve: com.google.firebase:firebase-core:11.0.0 Open
  File
Show in
  Project Structure dialog
      Error:Error:line (29)Failed to resolve: com.google.firebase:firebase-auth:11.0.0 Show in
  File
Show in
  Project Structure dialog

答:
I was able to resolve this by using 10.0.0

Thanks all for your help

Nick


问:
Validate a SQL WHERE Clause in javascript
How can I validate a string and know if it is a valid SQL where clause.
Ex of invalid string: WHERE 1=1  AND EMPRESA = 'CMIP' AND CD_MAQ ==="jjj"
Ex of valid string :WHERE 1=1  AND EMPRESA = 'CMIP' AND CD_MAQ ="jjj"

Appreciate your help.

答:
This is a complicated problem, you're essentially wanting to do is write an SQL interpreter. Obviously these already exist (on database systems of course) but also there are libraries that can do this for you. For Javascript see:

https://github.com/forward/sql-parser

Although, you probably don't want to perform security critical validation only on the client side, although it won't hurt to do it there and then also validate in on the server side before running it (if that is the end goal).


问:
Pyorient: how to parse json objects in pyorient?
I have a value in orientdb, which is a JSON object.
Assume that JSON object is :

```<code>a = {"abc":123}
</code>```

When I am sending a query using pyorient, it is not able to get this value in the select query, and hangs.
In the orientdb console, this JSON object seems to be converted in some other format like

```<code>a = {abc=123}
</code>```

I guess it is hanging because of the same issue.
The query from pyorient is:

```<code>client.query("select a from <tablename>")
</code>```

This hangs and doesn't seems to be working.
Could you please help ho to parse this JSON object in pyorient?

答:
pyorient gives you the output something like:

a = {'abc': '123'}

and json.loads() function works with " and not with ', so to solve it, you need to do this:

```<code>b=str(a)
b.replace("'",'"')
json_data = json.loads(b)
print(json_data.keys())
</code>```

Body:
I have a value in orientdb, which is a JSON object.
Assume that JSON object is :

a = {"abc":123}

When I am sending a query using pyorient, it is not able to get this value in the select query, and hangs.
In the orientdb console, this JSON object seems to be converted in some other format like

a = {abc=123}

I guess it is hanging because of the same issue.
The query from pyorient is:

client.query("select a from <tablename>")

This hangs and doesn't seems to be working.
Could you please help ho to parse this JSON object in pyorient?

Body:
pyorient gives you the output something like:

a = {'abc': '123'}

and json.loads() function works with " and not with ', so to solve it, you need to do this:

b=str(a)
b.replace("'",'"')
json_data = json.loads(b)
print(json_data.keys())


问:
How to simulate modifier key combination (Alt-Shift-P) in Capybara / Selenium?
I'm using Selenium-webdriver within Capybara.

Is there a way to simulate pressing altshiftp together?

答:
You could use send_keys method on an element.

```<code>my_element.send_keys [:alt, :shift, "p"]
</code>```

or, if you want it on the page:

```<code>page.send_keys [:alt, :shift, "p"]
</code>```

See: Capybara::Node::Element#send_keys

Body:
You could use send_keys method on an element.

my_element.send_keys [:alt, :shift, "p"]

or, if you want it on the page:

page.send_keys [:alt, :shift, "p"]

See: Capybara::Node::Element#send_keys


问:
Working sample code for button.performClick()
Can someone please put a working code example of button.performClick() assigned to a OnClickListener. The following code which I have used returns false for button.performClick()-

```<code>myButton.performClick()
 myButton.setOnClickListener ( new View.OnClickListener()
      {
           @Override
           public void onClick ( View view )
           {
              .............
           }
});
</code>```

答:
```<code> final Button button= (Button) findViewById(R.id.button);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //TODO handle click
            }
        });

        button.post(new Runnable() {
            @Override
            public void run() {
                button.performClick();
            }
        });
</code>```

Body:
Can someone please put a working code example of button.performClick() assigned to a OnClickListener. The following code which I have used returns false for button.performClick()-

myButton.performClick()
 myButton.setOnClickListener ( new View.OnClickListener()
      {
           @Override
           public void onClick ( View view )
           {
              .............
           }
});


问:
Splash won't render all contents of page
I am using Splash v2.3.2 and I am trying to render a page but it is not rendering everything. It won't render images or dynamically loaded content.

I am using my http://localhost:8050/ with script:

```<code>function main(splash)
  local url = splash.args.url
  assert(splash:go(url))
  assert(splash:wait(10))
  return {
    html = splash:html(),
    png = splash:png(),
    har = splash:har(),
  }
end
</code>```

Here is a browser rendering:

Here is a screenshot of the Splash rendering:

I have tried to change the wait time and also tried to allow plugins. None of this will work. I am assuming that the dynamically loaded content is being restricted but I am unsure. Any help is appreciated.

答:
I'm assuming that you are trying to scrape property description text. In your code you have just added splash:wait(10), My suggestion is you should try and implement wait for a specific css element. In you case, span#listingpropertydescription.
You can write a function to wait for this particular element and then return the html page.

Note you can find a sample wait-for-element code in   http://localhost:8050/

Hope this will help you

Body:
I am using Splash v2.3.2 and I am trying to render a page but it is not rendering everything. It won't render images or dynamically loaded content.

I am using my http://localhost:8050/ with script:

function main(splash)
  local url = splash.args.url
  assert(splash:go(url))
  assert(splash:wait(10))
  return {
    html = splash:html(),
    png = splash:png(),
    har = splash:har(),
  }
end

Here is a browser rendering:

Here is a screenshot of the Splash rendering:

I have tried to change the wait time and also tried to allow plugins. None of this will work. I am assuming that the dynamically loaded content is being restricted but I am unsure. Any help is appreciated.


问:
JOIN the record with the most similar name with each row from multiple tables
Platform: PostgreSQL

Tables:

```<code>shortlist:  name (text), city (text)...
data1:      name (text), ranking (integer), score1 (double)...
data2:      name (text), ranking (integer), score1 (double)...
data3:      name (text), ranking (integer), score1 (double)...
data4:      name (text), ranking (integer), score1 (double)...
</code>```

There is a limited number of data tables of similar format.

I would like to join each row in shortlist with the row in each data table that has the most similar name determined by similarity(shortlist.name, data#.name).

Pseudo code of the same idea:

```<code>for each s_row in shortlist:
    select shortlist.*
    join (SELECT data1.*, similarity(s_row.name, data1.name) AS sim FROM data1 ORDER BY sim DESC LIMIT 1)
    join (SELECT data2.*, similarity(s_row.name, data2.name) AS sim FROM data2 ORDER BY sim DESC LIMIT 1)
    join (SELECT data3.*, similarity(s_row.name, data3.name) AS sim FROM data3 ORDER BY sim DESC LIMIT 1)
    join (SELECT data4.*, similarity(s_row.name, data4.name) AS sim FROM data4 ORDER BY sim DESC LIMIT 1)
</code>```

Is there a way to do this in SQL?

答:
I am not entirely sure what you are after but something like this:

```<code>select s.name,
       d1.name as d1_name,
       d2.name as d2_name
from shortlist s
  left join lateral (
    SELECT data1.*, similarity(s.name, data1.name) AS sim
    FROM data1
    ORDER BY sim
    DESC LIMIT 1
  ) d1 on true
  left join lateral (
    SELECT data2.*, similarity(s.name, data2.name) AS sim
    FROM data2
    ORDER BY sim DESC
    LIMIT 1
  ) d2 on true
</code>```

You want an outer join (left join) for each table because otherwise you would not see anything if there is no match in at least one of the tables.

Body:
Platform: PostgreSQL

Tables:

shortlist:  name (text), city (text)...
data1:      name (text), ranking (integer), score1 (double)...
data2:      name (text), ranking (integer), score1 (double)...
data3:      name (text), ranking (integer), score1 (double)...
data4:      name (text), ranking (integer), score1 (double)...

There is a limited number of data tables of similar format.

I would like to join each row in shortlist with the row in each data table that has the most similar name determined by similarity(shortlist.name, data#.name).

Pseudo code of the same idea:

for each s_row in shortlist:
    select shortlist.*
    join (SELECT data1.*, similarity(s_row.name, data1.name) AS sim FROM data1 ORDER BY sim DESC LIMIT 1)
    join (SELECT data2.*, similarity(s_row.name, data2.name) AS sim FROM data2 ORDER BY sim DESC LIMIT 1)
    join (SELECT data3.*, similarity(s_row.name, data3.name) AS sim FROM data3 ORDER BY sim DESC LIMIT 1)
    join (SELECT data4.*, similarity(s_row.name, data4.name) AS sim FROM data4 ORDER BY sim DESC LIMIT 1)

Is there a way to do this in SQL?

Body:
I am not entirely sure what you are after but something like this:

select s.name,
       d1.name as d1_name,
       d2.name as d2_name
from shortlist s
  left join lateral (
    SELECT data1.*, similarity(s.name, data1.name) AS sim
    FROM data1
    ORDER BY sim
    DESC LIMIT 1
  ) d1 on true
  left join lateral (
    SELECT data2.*, similarity(s.name, data2.name) AS sim
    FROM data2
    ORDER BY sim DESC
    LIMIT 1
  ) d2 on true

You want an outer join (left join) for each table because otherwise you would not see anything if there is no match in at least one of the tables.


问:
Navigating options are not working in Selenium
After long time i was working today on Selenium webdriver and i observed that navigating options arent working in Selenium.
I am woring in WIN10
I tried with all jar files, 2.53,3.01 with geckodriver.
Example: driver. is not displaying any autocomplete options and also it is throwing error if typed manually.

Also i observed a strange behaviour that, navigating options are working in my previously created project class file and if i create another class inside same project, navigating options or autocomplete options are not displayed and not working.enter image description here

答:
Sometimes the issues occur related to .jar file which you have imported in your Eclipse ide. so you can use the project clean option
Project->clean

OR

You can remove the imported .jar file from your build path and reimport it again


问:
Do in While loop in Ruby
I´m all new to programming and I´m learning some basics of Ruby.

Could someone please tell me the difference between these loops.

```<code>while i < 51
  # ...
end
</code>```

and

```<code>while i < 51 do
  # ...
end
</code>```

Both of them works fine for me.

答:
They are identical. From the documentation for while:

The do keyword is optional.

Same for until and for.

Title: Do in While loop in Ruby

Body:
I´m all new to programming and I´m learning some basics of Ruby.

Could someone please tell me the difference between these loops.

while i < 51
  # ...
end

and

while i < 51 do
  # ...
end

Both of them works fine for me.


问:
Python 3d Pyramid
I'm new to 3d plotting. I just want to build a pyramid out of 5 Points and cut a plane through  it. My problem is I don't know how to fill the sides.

```<code>points = np.array([[-1, -1, -1],
                   [1, -1, -1 ],
                    [1, 1, -1],
                   [-1, 1, -1],
                   [0, 0 , 1]])
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
r = [-1,1]

X, Y = np.meshgrid(r, r)

ax.plot_surface(X,Y,-1, alpha=0.5)
ax.plot_surface(X,Y,0.5, alpha=0.5,  facecolors='r')

ax.scatter3D(points[:, 0], points[:, 1], points[:, 2])
ax.set_xlabel('X')
ax.set_ylabel('Y')
ax.set_zlabel('Z')
plt.show()
</code>```

Any help is appreciated.

答:
You have to use polygons:

```<code>from matplotlib import pyplot as plt
from mpl_toolkits.mplot3d.art3d import Poly3DCollection, Line3DCollection
import numpy as np

fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')

# vertices of a pyramid
v = np.array([[-1, -1, -1], [1, -1, -1], [1, 1, -1],  [-1, 1, -1], [0, 0, 1]])
ax.scatter3D(v[:, 0], v[:, 1], v[:, 2])

# generate list of sides' polygons of our pyramid
verts = [ [v[0],v[1],v[4]], [v[0],v[3],v[4]],
 [v[2],v[1],v[4]], [v[2],v[3],v[4]], [v[0],v[1],v[2],v[3]]]

# plot sides
ax.add_collection3d(Poly3DCollection(verts,
 facecolors='cyan', linewidths=1, edgecolors='r', alpha=.25))

plt.show()
</code>```

Title: Python 3d Pyramid

Body:
I'm new to 3d plotting. I just want to build a pyramid out of 5 Points and cut a plane through  it. My problem is I don't know how to fill the sides.

points = np.array([[-1, -1, -1],
                   [1, -1, -1 ],
                    [1, 1, -1],
                   [-1, 1, -1],
                   [0, 0 , 1]])
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
r = [-1,1]

X, Y = np.meshgrid(r, r)

ax.plot_surface(X,Y,-1, alpha=0.5)
ax.plot_surface(X,Y,0.5, alpha=0.5,  facecolors='r')

ax.scatter3D(points[:, 0], points[:, 1], points[:, 2])
ax.set_xlabel('X')
ax.set_ylabel('Y')
ax.set_zlabel('Z')
plt.show()

Any help is appreciated.

Body:
You have to use polygons:

from matplotlib import pyplot as plt
from mpl_toolkits.mplot3d.art3d import Poly3DCollection, Line3DCollection
import numpy as np

fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')

# vertices of a pyramid
v = np.array([[-1, -1, -1], [1, -1, -1], [1, 1, -1],  [-1, 1, -1], [0, 0, 1]])
ax.scatter3D(v[:, 0], v[:, 1], v[:, 2])

# generate list of sides' polygons of our pyramid
verts = [ [v[0],v[1],v[4]], [v[0],v[3],v[4]],
 [v[2],v[1],v[4]], [v[2],v[3],v[4]], [v[0],v[1],v[2],v[3]]]

# plot sides
ax.add_collection3d(Poly3DCollection(verts,
 facecolors='cyan', linewidths=1, edgecolors='r', alpha=.25))

plt.show()


问:
Problems when saving keyboard input to CArray and outputting to static text
I used CArray to do Static Text with SetWindowText(arr.GetDate()) and the result is something like this

The result when inputting 1 is the above image. The upper part uses CString and the lower part uses CArray. You can use CString, but I want to know why.

Thanks for answers
In the subclass.h file of CFormView, define the CArray  m_arr variable and add wm_char as the keystroke event in the .cpp file

```<code>Void CMyCalcView :: OnChar (UINT nChar, UINT nRepCnt, UINT nFlags)
{
M_arr.Add (nChar);
CFormView :: OnChar (nChar, nRepCnt, nFlags);
}
</code>```

Using wm_paint as a drawing event

```<code>Void CMyCalcView :: OnPaint ()
{
CPaintDC dc (this);
M_staticText.SetWindowText (m_arr.GetData ()); // m_staticText is a resource
}
</code>```

答:
CArray must be of type TCHAR, and be aware that SetWindowText will not work without a terminating 0 character.

And you have to delimiter so SetWindowText takes all data behind your char.

Using CString would be the better solution.

Body:
I used CArray to do Static Text with SetWindowText(arr.GetDate()) and the result is something like this

The result when inputting 1 is the above image. The upper part uses CString and the lower part uses CArray. You can use CString, but I want to know why.

Thanks for answers
In the subclass.h file of CFormView, define the CArray  m_arr variable and add wm_char as the keystroke event in the .cpp file

Void CMyCalcView :: OnChar (UINT nChar, UINT nRepCnt, UINT nFlags)
{
M_arr.Add (nChar);
CFormView :: OnChar (nChar, nRepCnt, nFlags);
}

Using wm_paint as a drawing event

Void CMyCalcView :: OnPaint ()
{
CPaintDC dc (this);
M_staticText.SetWindowText (m_arr.GetData ()); // m_staticText is a resource
}


问:
Xamarin.Android.Support.Compat not found
I am createing MvvmCross Xamarin Application. Everything were working great untill today. I dont know what happens but all the time I am getting build error:

Severity  Code    Description Project File    Line    Suppression State
  Error     Did not find reference matching RestoreAssemblyResources
  AssemblyName metadata 'Xamarin.Android.Support.Compat

I am totally wasted. I spent whole day reading google and nothing helped. Does someone faced similar problem ?

答:
For anyone still struggling with this.

Close visual studio and msbuild.exe (you can find it at task manager)

Delete all your packages.

Open again visual studio

Right-click in your Android project's References

Click Manage NuGet Packages

Click Restore packages

That's what works for me. But it's really frustrating that for a simple work as package addition I have to lose about 10 minutes of my life.


问:
Comments in Embedded Coffeescript (ECO) templates
Is there a way to put comments (single and multiline) in ECO templates such that they do not appear in the rendered output?

For example, Django templates let you do this on a single line:

```<code>{# greeting #}hello
</code>```

or on multiple lines:

```<code><p>Rendered text with {{ pub_date|date:"c" }}</p>
{% comment %}
    <p>Commented out text with {{ create_date|date:"c" }}</p>
{% endcomment %}
</code>```

答:
There is a special tag for commenting, namely, <%# %>

Example:

```<code><%# This is a single line comment %>
</code>```

Body:
Is there a way to put comments (single and multiline) in ECO templates such that they do not appear in the rendered output?

For example, Django templates let you do this on a single line:

{# greeting #}hello

or on multiple lines:

Rendered text with {{ pub_date|date:"c" }}

{% comment %}

Commented out text with {{ create_date|date:"c" }}

{% endcomment %}

Body:
There is a special tag for commenting, namely, <%# %>

Example:

<%# This is a single line comment %>


问:
Dart async/await internals
I'm searching for the source of async/await implementations.

I would like to know how do they truly works in order to hack into future.then() to detect if there is code awaiting for execution or not.

Edit

This is what I'm willing to accomplish:

```<code>TrackingCompleter completer = new TrackingCompleter();
TrackingFuture future = completer.future;
print("isAwaited: ${future.isAwaited} (F)");
new Future.delayed(new Duration(milliseconds: 500), () {
  future.then((_) {
    print("executing sorping");
    print("isThenExecuted: ${future.thenExecuted} (F)");
    new Future.delayed(new Duration(milliseconds: 500), () {
      print("isThenExecuted: ${future.thenExecuted} (T)");
      exit(1);
    });
  });
  print("isAwaited: ${future.isAwaited} (T)");
  print("isThenExecuted: ${future.thenExecuted} (F)");
  completer.complete();
});
</code>```

As far, that's working. What I'd like to do now is to detect if future.then is called manually in the code or automatically with an await statement.

答:
The async/await implementation is based on futures.
Basically, await creates a function that contains the rest of the current function (the "continuation" of the await expression), and then calls then on the future you await with that function as argument.
There are more details needed to handle errors, but that's basically it.

In your case, if you want to know if future.then is called, I recommend just wrapping that particular future. Example:

import "package:async/async.dart";

class ThenWrapper<T> extends DelegatingFuture<T> {
  void Function(S Function(T), S Function(Object, StackTrace)) _callback;
  ThenWrapper(Future<T> future, this._callback): super(future);
  Future<S> then<S>(S onValue(T), {S onError(error, StackTrace st)}) {
    _callback(onValue, onError);
    return super.super(onValue, onError);
  }
}
...

TrackingFuture future = new ThenWrapper(completer.future, ...);
```

You can change the callback to do whatever you want.

Title: Dart async/await internals

Body:
I'm searching for the source of async/await implementations.

I would like to know how do they truly works in order to hack into future.then() to detect if there is code awaiting for execution or not.

Edit

This is what I'm willing to accomplish:

TrackingCompleter completer = new TrackingCompleter();
TrackingFuture future = completer.future;
print("isAwaited: ${future.isAwaited} (F)");
new Future.delayed(new Duration(milliseconds: 500), () {
  future.then((_) {
    print("executing sorping");
    print("isThenExecuted: ${future.thenExecuted} (F)");
    new Future.delayed(new Duration(milliseconds: 500), () {
      print("isThenExecuted: ${future.thenExecuted} (T)");
      exit(1);
    });
  });
  print("isAwaited: ${future.isAwaited} (T)");
  print("isThenExecuted: ${future.thenExecuted} (F)");
  completer.complete();
});

As far, that's working. What I'd like to do now is to detect if future.then is called manually in the code or automatically with an await statement.

Body:
The async/await implementation is based on futures.
Basically, await creates a function that contains the rest of the current function (the "continuation" of the await expression), and then calls then on the future you await with that function as argument.
There are more details needed to handle errors, but that's basically it.

In your case, if you want to know if future.then is called, I recommend just wrapping that particular future. Example:

import "package:async/async.dart";

class ThenWrapper<T> extends DelegatingFuture<T> {
  void Function(S Function(T), S Function(Object, StackTrace)) _callback;
  ThenWrapper(Future<T> future, this._callback): super(future);
  Future<S> then<S>(S onValue(T), {S onError(error, StackTrace st)}) {
    _callback(onValue, onError);
    return super.super(onValue, onError);
  }
}
...

TrackingFuture future = new ThenWrapper(completer.future, ...);

You can change the callback to do whatever you want.


问:
Angular location search does not work with &
/course-home#/search?q=my%20lab%20%26%20mastering&%20kamal&ref=%2Ftab%2Factive

```<code>$scope.keyword = $location.search().q;
</code>```

In my angular app when I search for "my lab & mastering" $location.search().q returns only "my lab" and does not return full string. after the "&" it does not work properly. What is the best way to get query string from above URL ?

答:
create a $scope which is set to an array of symbols. Include in this array the & symbol and add it to your data.

I think that is because it has the url encoding of  %26. Check out the W3C cheat sheet about URL encoding to see how exactly to reference them:

URL encoding cheat sheet

Body:
/course-home#/search?q=my%20lab%20%26%20mastering&%20kamal&ref=%2Ftab%2Factive

$scope.keyword = $location.search().q;

In my angular app when I search for "my lab & mastering" $location.search().q returns only "my lab" and does not return full string. after the "&" it does not work properly. What is the best way to get query string from above URL ?


问:
I am trying to create a new column that is conditional upon the contents of existing columns
I am trying to make several new columns in my data frame that are conditional upon the contents of a few existing columns.

In pseudo-code, the arguments basically go "If VariableA is 1 and either VariableB is 2 or VariableC is 3, then make VariableD = 1, and if it does not meet these conditions make it a zero.

I have tried using for loops and ifelse statements, but have had no luck. I know that the logic of my commands are correct, but I am making some error translating it into R syntax, which isn't surprising because I just started using R about a week ago.

Below is a simplified version of what I have tried doing...

Data$VariableD <- ifelse(Data$VariableA == 'Jim' && (Data$VariableB == 2 || Data$VariableC == 3), 1, 0)

It runs without error, but upon examining the contents of VariableD, all cells are filled with "NA"

Here is an example using a similar dataset, notice row 1 meets the criteria. (I can't make a proper table to save my life, but I think it's interpretable.

 |Variable A|Variable B|Variable C|Variable D|

|1|    Jim   |     2    |     4    |    NA    |

|2|    Tom   |     2    |     3    |    NA    |

|3|    Tom   |     3    |     4    |    NA    |

答:
Could you please provide the class of your variables? Could be a problem of class...(by example you put ==1 for variableA, but if variableA is a class chr should be == "1").

Could you please also provide your full loop?

Otherwise, please try that:

```<code>Data$VariableD <- ifelse(Data$VariableA == 1 & (Data$VariableB == 2 | Data$VariableA == 3), 1, 0)
</code>```

Body:
Could you please provide the class of your variables? Could be a problem of class...(by example you put ==1 for variableA, but if variableA is a class chr should be == "1").

Could you please also provide your full loop?

Otherwise, please try that:

Data$VariableD <- ifelse(Data$VariableA == 1 & (Data$VariableB == 2 | Data$VariableA == 3), 1, 0)


问:
Compare passwords if hashed using random salt with sha512?
I think there is a contradiction about the recommendations how to store password in database.
We hash the password and store it in DB, and when a user tries login, we hash his input string the same way and compare to the DB. that's fine.
But there are recommendations to strengthen that hash by adding a random salt.
here is the problem:
So we lose the whole point of comparison, because the salt values will be different between the first hash to store in DB and the salt when login??
If to store in Db the salt, so what is the benefit is salting at all?</p>

答: You also store the salt. Comparison is between stored hash value and HASH(salt + input). The purpose of the salt is to prevent two users that use the same password to generate the same hash.


问:
Bars on chartjs superimpose when using type: 'time'
I'm trying to build a bar chart where the X-axis represents time.

However, when I use the option xAxes: [{type: 'time'}], the bars start to superimpose, making a weird render.

When removing the option, the bars are displayed correctly, but the X-Axis labels are not displayed as dates

Am I missing something, or is it a bug ?

Demo here

Body:
It looks like chartjs is having a tough time getting the bar widths right on a dynamic x scale. A quick method to achieve what you want is to use the normal category scale on the x-axis and format the label at display time. To do that you options will look something like;

 options: {
     scales: {
       xAxes: [{
         ticks: {
           userCallback: function(label, index, labels) {
             return moment(label, "YYYYMMDD").format("MMM DD, YYYY");
           },
         },
       }],
     }
   }

The userCallback function in ticks just has to return a string so you can format it however you want.

 var labels = ["20170601", "20170602", "20170403", "20170503", "20170703", "20170404", "20170504", "20170704", "20170405", "20170505", "20170605", "20170705", "20170406", "20170606", "20170607", "20170608", "20170509", "20170609", "20170510", "20170511", "20170412", "20170512", "20170612", "20170413", "20170613", "20170414", "20170614", "20170515", "20170615", "20170516", "20170616", "20170517", "20170418", "20170518", "20170419", "20170519", "20170619", "20170420", "20170620", "20170421", "20170621", "20170522", "20170622", "20170523", "20170623", "20170424", "20170524", "20170425", "20170426", "20170526", "20170626", "20170427", "20170627", "20170328", "20170428", "20170628", "20170329", "20170529", "20170629", "20170330", "20170530", "20170630", "20170331", "20170531"],
   values = [5.79, 7.41, 7.08, 7.25, 7.46, 6.79, 7.01, 5.38, 7.35, 7.4, 7.1, 0.49, 7.57, 5.63, 4.15, 7.32, 5.55, 5, 3.26, 6.78, 2.75, 7.27, 7.33, 5.69, 7.1, 7.28, 6.85, 7.27, 6.4, 6.8, 6.9, 7.19, 3.97, 7.11, 6.89, 6.6, 4.03, 7.11, 5.49, 5.31, 2.43, 6.09, 6.14, 5.4, 3.7, 7.13, 5.72, 5.56, 5.4, 7.18, 7.08, 7.19, 7.39, 5.38, 6.96, 7.16, 5.34, 7.21, 5.98, 7.05, 7.32, 3.23, 6.88, 6.86];

 var ctx = document.getElementById("chart");
 var myChart = new Chart(ctx, {
   type: 'bar',
   data: {
     labels: labels,
     datasets: [{
       label: "Time",
       data: values,
     }]
   },
   options: {
     scales: {
       xAxes: [{
         ticks: {
           userCallback: function(label, index, labels) {
             return moment(label, "YYYYMMDD").format("MMM DD, YYYY");
           },
         },
       }],
     }
   }
 });

<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.6.0/Chart.bundle.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>
<div id="chart-wrapper">
  <canvas id="chart"></canvas>
</div>


问:
Omnet++, NED file, Can I access display parameters for each node created?
i simply want to position the nodes every time its created here in both loops
can anyone help me with the syntax?

```<code>network Network
{
   parameters:
    int noOfSources = default(2);
    int noOfSinks = default(2);
    double field_x;
    double field_y;
    //int noOfConnections;
submodules:
    source[noOfSources]: Source;
    sink[noOfSinks]: Sink;
    operator: Operator;
connections:
    for i=0..noOfSources-1 {
        source[i].gate <--> Link <--> operator.gate++;
    }
    for i=0..noOfSinks-1 {
        sink[i].gate <--> Link <--> operator.gate++;
    }
</code>```

}

答:
I don't think you can position the nodes in the NED iteration, but you can arrange the module vectors in rows/columns/rings/matrices using the @display property (display string).
Take a look at this section of the manual: https://omnetpp.org/doc/omnetpp/manual/#sec:display-strings:module-and-connection-display-strings

For example this:

```<code>source[noOfSources]: Source @display("p=50,40,r,25");
</code>```

Will position the Sources in a row, with the first one at 50:40 and with a spacing of 25.

You can also move them around from C++, similarly using their cDisplayString objects (just like the mobility models of component libraries like INET do) but that is a lot less convenient.

Body:
i simply want to position the nodes every time its created here in both loops
can anyone help me with the syntax?

network Network
{
   parameters:
    int noOfSources = default(2);
    int noOfSinks = default(2);
    double field_x;
    double field_y;
    //int noOfConnections;
submodules:
    source[noOfSources]: Source;
    sink[noOfSinks]: Sink;
    operator: Operator;
connections:
    for i=0..noOfSources-1 {
        source[i].gate <--> Link <--> operator.gate++;
    }
    for i=0..noOfSinks-1 {
        sink[i].gate <--> Link <--> operator.gate++;
    }

}

Body:
I don't think you can position the nodes in the NED iteration, but you can arrange the module vectors in rows/columns/rings/matrices using the @display property (display string).
Take a look at this section of the manual: https://omnetpp.org/doc/omnetpp/manual/#sec:display-strings:module-and-connection-display-strings

For example this:

source[noOfSources]: Source @display("p=50,40,r,25");

Will position the Sources in a row, with the first one at 50:40 and with a spacing of 25.

You can also move them around from C++, similarly using their cDisplayString objects (just like the mobility models of component libraries like INET do) but that is a lot less convenient.


问:
Symfony 3.3.3 - default controller and container
I downloaded last stable version of Symfony (3.3.3) and on start I have error:

```<code>Attempted to call an undefined method named "getParameter" of class "AppBundle\Controller\DefaultController".
</code>```

This is:

```<code>'base_dir' => realpath($this->getParameter('kernel.project_dir')).DIRECTORY_SEPARATOR,
</code>```

Before 3.3.3 version Symfony controllers extended

Symfony\Bundle\FrameworkBundle\Controller\Controller.php

Now extends:

Symfony\Bundle\FrameworkBundle\Controller\AbstractController\AbstractController.php

So... How can I get data from container? In documentation (3.3 and 4.0 versions) Controller extends Controller, not AbstractController.

If I change AbstractController to Controller application works well, but do I should this change?

答:
You may create project with working version with this command:
    php symfony new project_name 3.3.2
Current version is broken now.

Body:
I downloaded last stable version of Symfony (3.3.3) and on start I have error:

Attempted to call an undefined method named "getParameter" of class "AppBundle\Controller\DefaultController".

This is:

'base_dir' => realpath($this->getParameter('kernel.project_dir')).DIRECTORY_SEPARATOR,

Before 3.3.3 version Symfony controllers extended

Symfony\Bundle\FrameworkBundle\Controller\Controller.php

Now extends:

Symfony\Bundle\FrameworkBundle\Controller\AbstractController\AbstractController.php

So... How can I get data from container? In documentation (3.3 and 4.0 versions) Controller extends Controller, not AbstractController.

If I change AbstractController to Controller application works well, but do I should this change?


问:
Oracle loop through CLOB to get string
I want to convert all data in CLOB to string. DBMC_LOB.SUBSTR provides a way to fetch 4000 characters at once. I am from MS SQL background and not aware of Oracle queries. Can someone help me with the syntax.

I want to make a function and do something like

```<code>// Get the length of CLOB
// totalIterationsRequired = length/4000;
// LOOP around the CLOB and fetch 4000 char at once
For i in 1..totalIterationsRequired
LOOP
// Insert the substring into a varchar2
//  DBMC_LOB.SUBSTR(xml_value,4000*i,(4000*(i-1)+1)
END LOOP
// The function will return the varchar2
</code>```

答:
Below is the function definition</p>

```<code>create or replace function getclobastable (id IN VARCHAR2)
  return clob_table
is
    l_length             INTEGER;
    l_start              INTEGER := 1;
    l_recsize   CONSTANT INTEGER := 4000;
    i_clob                 CLOB;
    n BINARY_INTEGER := 0;
    save_table clob_table := clob_table();
BEGIN

    save_table := clob_table();
    -- Get the CLOB data into i_clob
    l_length := DBMS_LOB.getlength (i_clob);

    WHILE l_start <= l_length
    LOOP
        n := n + 1;

        save_table.EXTEND();
        save_table(n) := DBMS_LOB.SUBSTR (i_clob, l_recsize, l_start);

        l_start   := l_start + l_recsize;
    END LOOP;
    RETURN save_table;
END;
</code>```

Title: Oracle loop through CLOB to get string

Body:
I want to convert all data in CLOB to string. DBMC_LOB.SUBSTR provides a way to fetch 4000 characters at once. I am from MS SQL background and not aware of Oracle queries. Can someone help me with the syntax.

I want to make a function and do something like

// Get the length of CLOB
// totalIterationsRequired = length/4000;
// LOOP around the CLOB and fetch 4000 char at once
For i in 1..totalIterationsRequired
LOOP
// Insert the substring into a varchar2
//  DBMC_LOB.SUBSTR(xml_value,4000*i,(4000*(i-1)+1)
END LOOP
// The function will return the varchar2

Body:
Below is the function definition

create or replace function getclobastable (id IN VARCHAR2)
  return clob_table
is
    l_length             INTEGER;
    l_start              INTEGER := 1;
    l_recsize   CONSTANT INTEGER := 4000;
    i_clob                 CLOB;
    n BINARY_INTEGER := 0;
    save_table clob_table := clob_table();
BEGIN

    save_table := clob_table();
    -- Get the CLOB data into i_clob
    l_length := DBMS_LOB.getlength (i_clob);

    WHILE l_start <= l_length
    LOOP
        n := n + 1;

        save_table.EXTEND();
        save_table(n) := DBMS_LOB.SUBSTR (i_clob, l_recsize, l_start);

        l_start   := l_start + l_recsize;
    END LOOP;
    RETURN save_table;
END;


问:
android Toolbar can not show shadow
Here is my xml code:
```</p>

```<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
                                                 xmlns:app="http://schemas.android.com/apk/res-auto"
                                                 xmlns:tools="http://schemas.android.com/tools"
                                                 android:layout_width="match_parent"
                                                 android:layout_height="match_parent"
                                                 tools:context="xxxxxxxxx">

    <android.support.design.widget.AppBarLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:theme="@style/AppThemeMD.NoActionBar.AppBarOverlay">

        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:background="@color/white"
            app:theme="@style/AppThemeBase"/>

    </android.support.design.widget.AppBarLayout>

    <include layout="@layout/content_vehicle_info"/>
</android.support.design.widget.CoordinatorLayout>
```

<p>```

1.When I run my app.I Can't see shadow of Toolbar.

2.But when I switch to another app,then switch back to my app.The shadow appeared.

Anyway to show shadow default?thx!

And here is my phone: Huawei 6x,Android7.0

答:
You should add android:elevation = "4dp" to your Toolbar to make it elevated always as in:

```<code><android.support.design.widget.AppBarLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:theme="@style/AppThemeMD.NoActionBar.AppBarOverlay">

    <android.support.v7.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:elevation = "4dp"
        android:layout_height="?attr/actionBarSize"
        android:background="@color/white"
        app:theme="@style/AppThemeBase"/>

</android.support.design.widget.AppBarLayout>
</code>```

Title: android Toolbar can not show shadow

Body:
Here is my xml code:
```</p>

<pre><code><?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
                                                 xmlns:app="http://schemas.android.com/apk/res-auto"
                                                 xmlns:tools="http://schemas.android.com/tools"
                                                 android:layout_width="match_parent"
                                                 android:layout_height="match_parent"
                                                 tools:context="xxxxxxxxx">

    <android.support.design.widget.AppBarLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:theme="@style/AppThemeMD.NoActionBar.AppBarOverlay">

        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:background="@color/white"
            app:theme="@style/AppThemeBase"/>

    </android.support.design.widget.AppBarLayout>

    <include layout="@layout/content_vehicle_info"/>
</android.support.design.widget.CoordinatorLayout>
</code></pre>

<p>```

1.When I run my app.I Can't see shadow of Toolbar.

2.But when I switch to another app,then switch back to my app.The shadow appeared.

Anyway to show shadow default?thx!

And here is my phone: Huawei 6x,Android7.0

Body:
You should add android:elevation = "4dp" to your Toolbar to make it elevated always as in:

<android.support.design.widget.AppBarLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:theme="@style/AppThemeMD.NoActionBar.AppBarOverlay">

    <android.support.v7.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:elevation = "4dp"
        android:layout_height="?attr/actionBarSize"
        android:background="@color/white"
        app:theme="@style/AppThemeBase"/>

</android.support.design.widget.AppBarLayout>

ContentLicense: CC BY-SA 4.0


问:
Why does MATLAB native function cov (covariance matrix computation) use a different divisor than I expect?
Given a data matrix data of M dimensions and N samples, say,

```<code>data = randn(N, M);
</code>```

I could compute the covariance matrix with

```<code>data_mu = data - ones(N, 1)*mean(data);
cov_matrix = (data_mu'*data_mu)./N
</code>```

If I use the native MATLAB function

```<code>cov_matrix2 = cov(data)
</code>```

this will always be equal to

```<code>cov_matrix = (data_mu'*data_mu)./(N-1)
</code>```

That is, the denominator is (N - 1) is one less.

Why?? Can you reproduce it? Is this a bug??

I use MATLAB version 7.6.0.324 (2008).

答:
n-1 is the correct denominator to use in computation of variance.
It is what's known as Bessel's correction (http://en.wikipedia.org/wiki/Bessel%27s_correction)
Simply put, 1/(n-1) produces a more accurate expected estimate of the variance than 1/n.</p>

Body:
Given a data matrix data of M dimensions and N samples, say,

data = randn(N, M);

I could compute the covariance matrix with

data_mu = data - ones(N, 1)*mean(data);
cov_matrix = (data_mu'*data_mu)./N

If I use the native MATLAB function

cov_matrix2 = cov(data)

this will always be equal to

cov_matrix = (data_mu'*data_mu)./(N-1)

That is, the denominator is (N - 1) is one less.

Why?? Can you reproduce it? Is this a bug??

I use MATLAB version 7.6.0.324 (2008).


问:
Perform a translation / rotation of a CMSampleBuffer OpenGL Swift
I'm trying to read an AVAsset and in every frame of the asset, do a translation or a rotation operation, using the GPU.

From my researches, I found out a way to convert a CMSampleBuffer to a GPU texture. I'm using the following method to do it:

```<code>func texture(fromBuffer sampleBuffer: CMSampleBuffer) -> GLuint {
        var texture : GLuint = 0
        glGenTextures(1, &texture)
        glBindTexture(GLenum(GL_TEXTURE_2D), texture)
        glTexParameteri(GLenum(GL_TEXTURE_2D), GLenum(GL_TEXTURE_MIN_FILTER), GL_LINEAR)
        glTexParameteri(GLenum(GL_TEXTURE_2D), GLenum(GL_TEXTURE_MAG_FILTER), GL_LINEAR)
        glTexParameteri(GLenum(GL_TEXTURE_2D), GLenum(GL_TEXTURE_WRAP_S), GL_CLAMP_TO_EDGE)
        glTexParameteri(GLenum(GL_TEXTURE_2D), GLenum(GL_TEXTURE_WRAP_T), GL_CLAMP_TO_EDGE)

        if let pixelBuffer = CMSampleBufferGetImageBuffer(sampleBuffer) {
            CVPixelBufferLockBaseAddress(pixelBuffer, CVPixelBufferLockFlags(rawValue: 0))
            let width = CVPixelBufferGetWidth(pixelBuffer)
            let height = CVPixelBufferGetHeight(pixelBuffer)
            glTexImage2D(GLenum(GL_TEXTURE_2D), 0, GL_RGBA, GLsizei(width), GLsizei(height), 0, GLenum(GL_BGRA), GLenum(GL_UNSIGNED_BYTE), CVPixelBufferGetBaseAddress(pixelBuffer))
            CVPixelBufferUnlockBaseAddress(pixelBuffer, CVPixelBufferLockFlags(rawValue: 0))
        }
        return texture
}
</code>```

Now I need to do my desired operations with this texture, but this is the point I'm stuck. From a Objc example, I translated a function that receive as a param a texture and return a CGImage.

Here's the method:

```<code>func processTexture(_ texture: GLuint, width: Int, height: Int) -> CGImage? {
        var newImage : CGImage?
        var frameBuffer : GLuint = 0

        glGenFramebuffers(1, &frameBuffer)
        glBindFramebuffer(GLenum(GL_FRAMEBUFFER), frameBuffer)

        var colorRenderbuffer : GLuint = 0

        glGenRenderbuffers(1, &colorRenderbuffer)
        glBindRenderbuffer(GLenum(GL_RENDERBUFFER), colorRenderbuffer)
        glRenderbufferStorage(GLenum(GL_RENDERBUFFER), GLenum(GL_RGBA8_OES), GLsizei(width), GLsizei(height))
        glFramebufferRenderbuffer(GLenum(GL_FRAMEBUFFER), GLenum(GL_COLOR_ATTACHMENT0), GLenum(GL_RENDERBUFFER), colorRenderbuffer)

        let status = glCheckFramebufferStatus(GLenum(GL_FRAMEBUFFER))
        if status != GLenum(GL_FRAMEBUFFER_COMPLETE) {
            print("ERROR")
        } else {
            glViewport(0, 0, GLsizei(width), GLsizei(height))
            glClearColor(0.0, 0.0, 0.0, 1.0)
            glClear(GLbitfield(GL_COLOR_BUFFER_BIT))

            let data = UnsafeMutablePointer<Data>.allocate(capacity: width * height * 4)

            glReadPixels(0, 0, GLsizei(width), GLsizei(height), GLenum(GL_RGBA), GLenum(GL_UNSIGNED_BYTE), data)

            let cgDataProviderReleaseDataCallback: CGDataProviderReleaseDataCallback = { (info: UnsafeMutableRawPointer?, data: UnsafeRawPointer, size: Int) -> () in
                return
            }

            if let dataProvider = CGDataProvider(dataInfo: nil, data: data, size: width * height * 4, releaseData: cgDataProviderReleaseDataCallback) {
                let colorSpace = CGColorSpaceCreateDeviceRGB()
                newImage = CGImage(width: width, height: height, bitsPerComponent: 8, bitsPerPixel: 32, bytesPerRow: width * 4, space: colorSpace, bitmapInfo:  .byteOrder32Big, provider: dataProvider, decode: nil, shouldInterpolate: true, intent: .defaultIntent)
            }
        }
        return newImage
    }
</code>```

But I can't find where I can perform the operations of translation and rotation on this code, or how could I do it.

Glad if anyone that already worked with OpenGL on iOS, could give me a help with it or even tell me where I can find examples of such operations.

答: You need to have a quad (two triangles) with your texture on it. You apply transformations (rotation, translation, scale, etc) to that quad. Take a look on GPUImage library source code.</p>

Body:
I'm trying to read an AVAsset and in every frame of the asset, do a translation or a rotation operation, using the GPU.

From my researches, I found out a way to convert a CMSampleBuffer to a GPU texture. I'm using the following method to do it:

func texture(fromBuffer sampleBuffer: CMSampleBuffer) -> GLuint {
        var texture : GLuint = 0
        glGenTextures(1, &texture)
        glBindTexture(GLenum(GL_TEXTURE_2D), texture)
        glTexParameteri(GLenum(GL_TEXTURE_2D), GLenum(GL_TEXTURE_MIN_FILTER), GL_LINEAR)
        glTexParameteri(GLenum(GL_TEXTURE_2D), GLenum(GL_TEXTURE_MAG_FILTER), GL_LINEAR)
        glTexParameteri(GLenum(GL_TEXTURE_2D), GLenum(GL_TEXTURE_WRAP_S), GL_CLAMP_TO_EDGE)
        glTexParameteri(GLenum(GL_TEXTURE_2D), GLenum(GL_TEXTURE_WRAP_T), GL_CLAMP_TO_EDGE)

        if let pixelBuffer = CMSampleBufferGetImageBuffer(sampleBuffer) {
            CVPixelBufferLockBaseAddress(pixelBuffer, CVPixelBufferLockFlags(rawValue: 0))
            let width = CVPixelBufferGetWidth(pixelBuffer)
            let height = CVPixelBufferGetHeight(pixelBuffer)
            glTexImage2D(GLenum(GL_TEXTURE_2D), 0, GL_RGBA, GLsizei(width), GLsizei(height), 0, GLenum(GL_BGRA), GLenum(GL_UNSIGNED_BYTE), CVPixelBufferGetBaseAddress(pixelBuffer))
            CVPixelBufferUnlockBaseAddress(pixelBuffer, CVPixelBufferLockFlags(rawValue: 0))
        }
        return texture
}

Now I need to do my desired operations with this texture, but this is the point I'm stuck. From a Objc example, I translated a function that receive as a param a texture and return a CGImage.

Here's the method:

func processTexture(_ texture: GLuint, width: Int, height: Int) -> CGImage? {
        var newImage : CGImage?
        var frameBuffer : GLuint = 0

        glGenFramebuffers(1, &frameBuffer)
        glBindFramebuffer(GLenum(GL_FRAMEBUFFER), frameBuffer)

        var colorRenderbuffer : GLuint = 0

        glGenRenderbuffers(1, &colorRenderbuffer)
        glBindRenderbuffer(GLenum(GL_RENDERBUFFER), colorRenderbuffer)
        glRenderbufferStorage(GLenum(GL_RENDERBUFFER), GLenum(GL_RGBA8_OES), GLsizei(width), GLsizei(height))
        glFramebufferRenderbuffer(GLenum(GL_FRAMEBUFFER), GLenum(GL_COLOR_ATTACHMENT0), GLenum(GL_RENDERBUFFER), colorRenderbuffer)

        let status = glCheckFramebufferStatus(GLenum(GL_FRAMEBUFFER))
        if status != GLenum(GL_FRAMEBUFFER_COMPLETE) {
            print("ERROR")
        } else {
            glViewport(0, 0, GLsizei(width), GLsizei(height))
            glClearColor(0.0, 0.0, 0.0, 1.0)
            glClear(GLbitfield(GL_COLOR_BUFFER_BIT))

            let data = UnsafeMutablePointer<Data>.allocate(capacity: width * height * 4)

            glReadPixels(0, 0, GLsizei(width), GLsizei(height), GLenum(GL_RGBA), GLenum(GL_UNSIGNED_BYTE), data)

            let cgDataProviderReleaseDataCallback: CGDataProviderReleaseDataCallback = { (info: UnsafeMutableRawPointer?, data: UnsafeRawPointer, size: Int) -> () in
                return
            }

            if let dataProvider = CGDataProvider(dataInfo: nil, data: data, size: width * height * 4, releaseData: cgDataProviderReleaseDataCallback) {
                let colorSpace = CGColorSpaceCreateDeviceRGB()
                newImage = CGImage(width: width, height: height, bitsPerComponent: 8, bitsPerPixel: 32, bytesPerRow: width * 4, space: colorSpace, bitmapInfo:  .byteOrder32Big, provider: dataProvider, decode: nil, shouldInterpolate: true, intent: .defaultIntent)
            }
        }
        return newImage
    }

But I can't find where I can perform the operations of translation and rotation on this code, or how could I do it.

Glad if anyone that already worked with OpenGL on iOS, could give me a help with it or even tell me where I can find examples of such operations.


问:
Apple rejected my app due to use of non public api UIRotatingAlertController, WKActionSheet

Guideline 2.5.1 - Performance - Software Requirements

Your app uses the "prefs:root=" non-public URL scheme, which is a private entity. The use of non-public APIs is not permitted on the App Store because it can lead to a poor user experience should these APIs change. Specifically:

OS_dispatch_group, _UIRotatingAlertController, WKActionSheet

Next Steps

To resolve this issue, please revise your app to provide the associated functionality using public APIs or remove the functionality using the "prefs:root" or "App-Prefs:root" URL scheme.

Blockquote

I have resolved two out of them which I able to find out in my code this are "prefs:root" and "OS_dispatch_group" but other two are not detecting in code. here I am using command grep -R '_UIRotatingAlertController' *. Please suggest if need run any other commands for nm tool or otool.

答:
Blockquote
  These two selectors are both present in the [JSQMessagesViewController initialize]-> JSQInstallWorkaroundForSheetPresentationIssue26295020() method and are directly obfuscating their use to avoid static detection (https://github.com/jessesquires/JSQMessagesViewController/blob/f52e83bdb4d5c19ecfd5b6e54cdb9f2efa66cfcf/JSQMessagesViewController/Controllers/JSQMessagesViewController.m). It would be appropriate to remove the library entirely before resubmitting for review.

This is a reply from apple as this API is used with some trick so i have unable to observe the problem but apple easily observe with their tools.


问:
VBA for aligning the pivot table
I am using an VBA to generate the Pivot Table.

I wanted to Center align my values in the Pivot table, I used the follwing line, in my code, I am getting object required error.

I researched in net, and everywhere it is the same, that we use

DataLabel.HorizontalAlignment = xlCenter

Below is the code, i am using to generate my Pivot table and trying to align the data values in the cell Center, Could someone suggest, where i am going wrong and how i could correct it.

```<code>Sub sum2017()
Dim ws9 As Worksheet
Dim pc9 As PivotCache
Dim pt9 As PivotTable
Dim ct9 As Integer
Set ws9 = Sheets("Sum2017")
Set pc9 = ActiveWorkbook.PivotCaches.Create(xlDatabase, "'Result'!R1C1:R1048576C6")
Set pt9 = pc9.CreatePivotTable(ws9.Range("A3"))
pt9.AddDataField pt9.PivotFields("Overdue"), "Sum of Overdue", xlSum
pt9.AddDataField pt9.PivotFields("OK"), "Sum of OK", xlSum
pt9.AddDataField pt9.PivotFields("Total"), "Sum of Total", xlSum
pt9.AddDataField pt9.PivotFields("Overdue %"), "Sum of Overdue %", xlSum
pt9.AddDataField pt9.PivotFields("OK %"), "Sum of OK %", xlSum
ws.pt9.PivotSelect "Sum of overdue", xlDataOnly
DataLabel.HorizontalAlignment = xlCenter

End Sub
</code>```

答:
The code below will align your PivotTable to the center.

```<code>pt9.TableRange2.HorizontalAlignment = xlCenter
</code>```

If you want to align only certain part of your PivotTable, you can use the code below with combining the Offset and Resize commands.

Title: VBA for aligning the pivot table

Body:
I am using an VBA to generate the Pivot Table.

I wanted to Center align my values in the Pivot table, I used the follwing line, in my code, I am getting object required error.

I researched in net, and everywhere it is the same, that we use

DataLabel.HorizontalAlignment = xlCenter

Below is the code, i am using to generate my Pivot table and trying to align the data values in the cell Center, Could someone suggest, where i am going wrong and how i could correct it.

Sub sum2017()
Dim ws9 As Worksheet
Dim pc9 As PivotCache
Dim pt9 As PivotTable
Dim ct9 As Integer
Set ws9 = Sheets("Sum2017")
Set pc9 = ActiveWorkbook.PivotCaches.Create(xlDatabase, "'Result'!R1C1:R1048576C6")
Set pt9 = pc9.CreatePivotTable(ws9.Range("A3"))
pt9.AddDataField pt9.PivotFields("Overdue"), "Sum of Overdue", xlSum
pt9.AddDataField pt9.PivotFields("OK"), "Sum of OK", xlSum
pt9.AddDataField pt9.PivotFields("Total"), "Sum of Total", xlSum
pt9.AddDataField pt9.PivotFields("Overdue %"), "Sum of Overdue %", xlSum
pt9.AddDataField pt9.PivotFields("OK %"), "Sum of OK %", xlSum
ws.pt9.PivotSelect "Sum of overdue", xlDataOnly
DataLabel.HorizontalAlignment = xlCenter

End Sub

Body:
The code below will align your PivotTable to the center.

pt9.TableRange2.HorizontalAlignment = xlCenter

If you want to align only certain part of your PivotTable, you can use the code below with combining the Offset and Resize commands.


问:
Delphi generic runtime
I want to get generic class from deserialization a lot of times.
How can I simplify it?

I know what classes I want to have but I'm lazy and do not want to duplicate the code.

sample:

```<code>procedure Do;
var
cl:tclass1;
cl2:tclass2;
..... N classes;
begin
 cl:=tserialization.deserialize<tclass1>(json/xml);
    try
      DoSmthWithMyClass(cl);
    finally
      cl.free;
    end;

  clN:=tserialization.deserialize<tclassN>(json/xml);
    try
      DoSmthWithMyClass(clN);
    finally
      clN.free;
    end;

end;
</code>```

How can I do deserializing my classes for example in Loops?
I know what classes I want to get in advance

Updated:

Real code and error:
[dcc32 Error] uMainForm.pas(68): E2250 There is no overloaded version of 'Deserialize' that can be called with these arguments

```<code>for iSupportClass := Low(TSupportedClasses)
      to high(TSupportedClasses) do
    begin
      if db.GetRef(SupportedClasses[iSupportClass].GetTableName, xml,
        error) = 0 then
      begin
//here an error
        iClass := txmlserializer.Deserialize < SupportedClasses
          [iSupportClass] > (xml);

      end;
    end;
</code>```

答:
Here is how I do something very similar, assuming all classes have common ancestor - in my case TQSI2Common).

```<code>type
  TSupportedClass = class of TQSI2Common;
  TSupportedClasses = ( scQSI2SessionRequest,
                        scQSI2ErrorReply,
                        scQSI2SessionRequestReply,
                        scQSI2LoginRequest,
                        scQSI2LoginReply,
                        scQSI2CloseSessionRequest,
                        scQSI2CloseSessionReply,
                        scQSI2SiteListRequest,
                        scQSI2SiteListReply,
                        scReportCountRequest,
                        scReportCountReply,
                        scReportAverageTimeRequest,
                        scReportAverageTimeReply,
                        scReportRequest,
                        scReportReply,
                        scGetRecsFromKeysRequest,
                        scGetRecsFromKeysReply );

const
  SupportedClasses : array[ TSupportedClasses ] of TSupportedClass =  ( TQSI2SessionRequest,
                                                                        TQSI2ErrorReply,
                                                                        TQSI2SessionRequestReply,
                                                                        TQSI2LoginRequest,
                                                                        TQSI2LoginReply,
                                                                        TQSI2CloseSessionRequest,
                                                                        TQSI2CloseSessionReply,
                                                                        TQSI2SiteListRequest,
                                                                        TQSI2SiteListReply,
                                                                        TReportCountRequest,
                                                                        TReportCountReply,
                                                                        TReportAverageTimeRequest,
                                                                        TReportAverageTimeReply,
                                                                        TReportRequest,
                                                                        TReportReply,
                                                                        TGetRecsFromKeysRequest,
                                                                        TGetRecsFromKeysReply );
</code>```

You can then look through the supported SupportedClasses array - something like, in your case

```<code>procedure Do;
var
  iSupportedClass : TSupportedClasses;
  iClass : TSupportedClass;
begin
  for iSupportedClass := Low( TSupportedClasses) to High(TSupportedClasses)
   iClass:=tserialization.deserialize<SupportedClasses[iSupportedClass]>(json/xml);
    try
      iClass.DoSmthWithMyClass; // this will be an inherited function
    finally
      iClass.free;
    end;
  end;

end;
</code>```

Obviously this last bit is for illustration purposes only and not tested, but the rest is in real code.

Edit

The untested code of course does not work, because the generic is a compile time  not a run time action.

Instead you can create a class function to deserialize, like:

```<code>type
TQSI2Common = class
public
  class function Deserialize : TQSI2Common; virtual; abstract;
  //...
end;

type
TQSI2Example = class(TQSI2Common)
public
  class function Deserialize : TQSI2Common; override;
end;

//....

class function TQSI2Example.Deserialize : TQSI2Common;
begin
  Result := tserialization.deserialize<TQSI2Example>(json/xml);
end;

//....

procedure Do;
var
  iSupportedClass : TSupportedClasses;
  iClass : TSupportedClass;
begin
  for iSupportedClass := Low( TSupportedClasses) to High(TSupportedClasses)
   iClass:=SupportedClasses[iSupportedClass].Deserialize;
    try
      iClass.DoSmthWithMyClass; // this will be an inherited function
    finally
      iClass.free;
    end;
  end;

end;
</code>```

Edit2

In the context you provided in your new question, generics can be handled, but it is getting a bit messy. The modified class definitions below show this:

```<code>type
TQSI2Common = class // Note NOT a Generic
public
  class function Deserialize : TQSI2Common; virtual; abstract;
  //...
end;

type
TQSI2Example<T : class> = class(TQSI2Common)  // note IS generic.
public
end;

type TFirms = class( TQSI2Example<TFirm> )
public
  class function Deserialize : TQSI2Common; override;
end;

type TDiscounts = class( TRefTable<TDiscount> )
public
  class function Deserialize : TQSI2Common; override;
end;
//....

class function TFirms.Deserialize : TQSI2Common; override;
begin
  Result := tserialization.deserialize<TFirms>(json/xml);
end;
</code>```

etc.

Title: Delphi generic runtime

Body:
I want to get generic class from deserialization a lot of times.
How can I simplify it?

I know what classes I want to have but I'm lazy and do not want to duplicate the code.

sample:

procedure Do;
var
cl:tclass1;
cl2:tclass2;
..... N classes;
begin
 cl:=tserialization.deserialize<tclass1>(json/xml);
    try
      DoSmthWithMyClass(cl);
    finally
      cl.free;
    end;

  clN:=tserialization.deserialize<tclassN>(json/xml);
    try
      DoSmthWithMyClass(clN);
    finally
      clN.free;
    end;

end;

How can I do deserializing my classes for example in Loops?
I know what classes I want to get in advance

Updated:

Real code and error:
[dcc32 Error] uMainForm.pas(68): E2250 There is no overloaded version of 'Deserialize' that can be called with these arguments

for iSupportClass := Low(TSupportedClasses)
      to high(TSupportedClasses) do
    begin
      if db.GetRef(SupportedClasses[iSupportClass].GetTableName, xml,
        error) = 0 then
      begin
//here an error
        iClass := txmlserializer.Deserialize < SupportedClasses
          [iSupportClass] > (xml);

      end;
    end;

Body:
Here is how I do something very similar, assuming all classes have common ancestor - in my case TQSI2Common).

type
  TSupportedClass = class of TQSI2Common;
  TSupportedClasses = ( scQSI2SessionRequest,
                        scQSI2ErrorReply,
                        scQSI2SessionRequestReply,
                        scQSI2LoginRequest,
                        scQSI2LoginReply,
                        scQSI2CloseSessionRequest,
                        scQSI2CloseSessionReply,
                        scQSI2SiteListRequest,
                        scQSI2SiteListReply,
                        scReportCountRequest,
                        scReportCountReply,
                        scReportAverageTimeRequest,
                        scReportAverageTimeReply,
                        scReportRequest,
                        scReportReply,
                        scGetRecsFromKeysRequest,
                        scGetRecsFromKeysReply );

const
  SupportedClasses : array[ TSupportedClasses ] of TSupportedClass =  ( TQSI2SessionRequest,
                                                                        TQSI2ErrorReply,
                                                                        TQSI2SessionRequestReply,
                                                                        TQSI2LoginRequest,
                                                                        TQSI2LoginReply,
                                                                        TQSI2CloseSessionRequest,
                                                                        TQSI2CloseSessionReply,
                                                                        TQSI2SiteListRequest,
                                                                        TQSI2SiteListReply,
                                                                        TReportCountRequest,
                                                                        TReportCountReply,
                                                                        TReportAverageTimeRequest,
                                                                        TReportAverageTimeReply,
                                                                        TReportRequest,
                                                                        TReportReply,
                                                                        TGetRecsFromKeysRequest,
                                                                        TGetRecsFromKeysReply );

You can then look through the supported SupportedClasses array - something like, in your case

procedure Do;
var
  iSupportedClass : TSupportedClasses;
  iClass : TSupportedClass;
begin
  for iSupportedClass := Low( TSupportedClasses) to High(TSupportedClasses)
   iClass:=tserialization.deserialize<SupportedClasses[iSupportedClass]>(json/xml);
    try
      iClass.DoSmthWithMyClass; // this will be an inherited function
    finally
      iClass.free;
    end;
  end;

end;

Obviously this last bit is for illustration purposes only and not tested, but the rest is in real code.

Edit

The untested code of course does not work, because the generic is a compile time  not a run time action.

Instead you can create a class function to deserialize, like:

type
TQSI2Common = class
public
  class function Deserialize : TQSI2Common; virtual; abstract;
  //...
end;

type
TQSI2Example = class(TQSI2Common)
public
  class function Deserialize : TQSI2Common; override;
end;

//....

class function TQSI2Example.Deserialize : TQSI2Common;
begin
  Result := tserialization.deserialize<TQSI2Example>(json/xml);
end;

//....

procedure Do;
var
  iSupportedClass : TSupportedClasses;
  iClass : TSupportedClass;
begin
  for iSupportedClass := Low( TSupportedClasses) to High(TSupportedClasses)
   iClass:=SupportedClasses[iSupportedClass].Deserialize;
    try
      iClass.DoSmthWithMyClass; // this will be an inherited function
    finally
      iClass.free;
    end;
  end;

end;

Edit2

In the context you provided in your new question, generics can be handled, but it is getting a bit messy. The modified class definitions below show this:

type
TQSI2Common = class // Note NOT a Generic
public
  class function Deserialize : TQSI2Common; virtual; abstract;
  //...
end;

type
TQSI2Example<T : class> = class(TQSI2Common)  // note IS generic.
public
end;

type TFirms = class( TQSI2Example<TFirm> )
public
  class function Deserialize : TQSI2Common; override;
end;

type TDiscounts = class( TRefTable<TDiscount> )
public
  class function Deserialize : TQSI2Common; override;
end;
//....

class function TFirms.Deserialize : TQSI2Common; override;
begin
  Result := tserialization.deserialize<TFirms>(json/xml);
end;

etc.


答:
put this in your code (onCreate() )</p>

```<code>if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
    // Call some material design APIs here
    toolbar.setElevation(3)
}
</code>```

Title: android Toolbar can not show shadow

Body:
put this in your code (onCreate() )

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
    // Call some material design APIs here
    toolbar.setElevation(3)
}


问:
Is salting with a hashed version of the user's password just as secure as salting with a pre-defined string?
Basically, what I'm asking is if salting a password by appending a hashed version of it to the end of it is just as secure as salting with a different string. So:

Is this:

```<code>$pass = "pass";
$salt = sha1(md5($pass));
$pass = md5($pass.$salt);
</code>```

As secure as this?

```<code>$pass = "pass";
$salt = "4D9ds*^dkrUI45^#dkd*3fD8&!dlvd*";
$pass = md5($pass.$salt);
</code>```

答:
If the salt is based on the value to be hashed, then you lose the value of the salt.

If a password hash salt is based only on the value of the password, then two users using the same password is very visible in the database, for example.

You should instead add a salt on a different determinable value. Common options are fields like the username, email, etc.

Body:
Basically, what I'm asking is if salting a password by appending a hashed version of it to the end of it is just as secure as salting with a different string. So:

Is this:

$pass = "pass";
$salt = sha1(md5($pass));
$pass = md5($pass.$salt);

As secure as this?

$pass = "pass";
$salt = "4D9ds*^dkrUI45^#dkd*3fD8&!dlvd*";
$pass = md5($pass.$salt);


问:
Pure CSS tab containers active tab
I've got a problem. I have a pure CSS tab container. But when I click on a tab, it should become active in some way.

I already tried it with a <input type="radio" /> and a
But then the anchor  does not work anymore.

Any ideas?

JSFIDDLE

答:
For those who want a script version, I've just edited the source code as the snippet and added some jQuery functions.

$(document).ready(function(){
  var currentTab = $("#buttonTab1")

  $("#buttonTab1").click(function(){
    currentTab.removeClass();
    currentTab = $(this);
   $(this).addClass("tab1")
  });

 $("#buttonTab2").click(function(){
    currentTab.removeClass();
    currentTab = $(this);
   $(this).addClass("tab2")
  });

  $("#buttonTab3").click(function(){
    currentTab.removeClass();
    currentTab = $(this);
   $(this).addClass("tab3")
  });

  $("#buttonTab4").click(function(){
    currentTab.removeClass();
    currentTab = $(this);
   $(this).addClass("tab4")
  });

});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>ul {
  margin: 0;
  padding: 0;
  width: 100%;
  display: inline-block;
}
ul li {
  list-style: none;
  float: left;
  background: #333;
}
ul li a {
   color: #FFF;
   display: block;
   padding: 10px;
   text-decoration: none;
}
.tabcontainer {
  width: 100%;
}
.tab:not(:first-child) {
  display: none;
}
.tab {
  position: absolute;
}
.tab:target {
  display: block;
}
.tab1 {
  background: #638DB2;
}
.tab2 {
  background: #FF4C43;
}
.tab3 {
  background: #C1CC14;
}
.tab4 {
  background: #ADB257;
}</code>```

Tab 1

Tab 2

Tab 3

Tab 4

  Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

  Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

  Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

  Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

```

Title: Pure CSS tab containers active tab

Body:
For those who want a script version, I've just edited the source code as the snippet and added some jQuery functions.

$(document).ready(function(){
  var currentTab = $("#buttonTab1")

  $("#buttonTab1").click(function(){
    currentTab.removeClass();
    currentTab = $(this);
   $(this).addClass("tab1")
  });

 $("#buttonTab2").click(function(){
    currentTab.removeClass();
    currentTab = $(this);
   $(this).addClass("tab2")
  });

  $("#buttonTab3").click(function(){
    currentTab.removeClass();
    currentTab = $(this);
   $(this).addClass("tab3")
  });

  $("#buttonTab4").click(function(){
    currentTab.removeClass();
    currentTab = $(this);
   $(this).addClass("tab4")
  });

});

ul {
  margin: 0;
  padding: 0;
  width: 100%;
  display: inline-block;
}
ul li {
  list-style: none;
  float: left;
  background: #333;
}
ul li a {
   color: #FFF;
   display: block;
   padding: 10px;
   text-decoration: none;
}
.tabcontainer {
  width: 100%;
}
.tab:not(:first-child) {
  display: none;
}
.tab {
  position: absolute;
}
.tab:target {
  display: block;
}
.tab1 {
  background: #638DB2;
}
.tab2 {
  background: #FF4C43;
}
.tab3 {
  background: #C1CC14;
}
.tab4 {
  background: #ADB257;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
  <li><a id="buttonTab1" class = "tab1" href="#tab1">Tab 1</a></li>
  <li><a id="buttonTab2" href="#tab2">Tab 2</a></li>
  <li><a id="buttonTab3" href="#tab3">Tab 3</a></li>
  <li><a id="buttonTab4" href="#tab4">Tab 4</a></li>
</ul>
<div class="tabcontainer">
  <div id="tab1" class="tab tab1">
  Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
  </div>
  <div id="tab2" class="tab tab2">
  Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
  </div>
  <div id="tab3" class="tab tab3">
  Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
  </div>
  <div id="tab4" class="tab tab4">
  Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
  </div>
</div>


问:
How to loop through JSON object retrieved via Http Angular 2/ Typescript
I'm trying to fetch some specific data from my JSON file via http. JSON looks like this:

```<code>[{"name":"Name1","perc":33},{"name":"Name2","perc":22},{"name":"Name3","perc":41}]
</code>```

I'm trying to loop through this retrieved object, I'm retrieving it like so:

```<code>  this._postService.getParams(_url).subscribe(
  data => {
    this.results = data.Results
  },
  error => console.log(error),
  () => console.log('Done')
  );
</code>```

getParams() fetches the data like this

```<code>    getParams(url: string) {
    return this._http.get(url)
        .map(res => res.json());
}
</code>```

I made an interface for data retrieved, placed it in the same .component.ts file where the service is being called

```<code>/*Interface for Stats */
interface stats {
name: string;
percent: number;
}
</code>```

I plan to loop through the object I retrieved and store them in a local array and then loop through that and display them. How can I iterate through the JSON object in my component file? I tried many different for loops and they all failed.

I attempted this one and it failed, json was not being recognized by typescript

```<code>let list: string[] = [];
json.Results.forEach(element => {
list.push(element.Id);
});
</code>```

I'm perfectly able to retrieve the data, because I console logged the 3 objects I received.

答:
Class stats :

```<code>export class Stats {
    name: string;
    perc: string;
    constructor(n, p) {
        this.name = n;
        this.perc = p;
    }
}
</code>```

Assuming your service works and returns data, don't change it.

Component :

```<code>getStats(_url: string) {
    let list: Stats[] = [];
    this._postService.getParams(_url).subscribe(
        data => {
            for (let res of data.Results) {
                let stat = new Stats(res.name, res.perc);
                list.push(stat);
            }
        }, err => { /* Error handling */}
    );
}
</code>```

Body:
I'm trying to fetch some specific data from my JSON file via http. JSON looks like this:

[{"name":"Name1","perc":33},{"name":"Name2","perc":22},{"name":"Name3","perc":41}]

I'm trying to loop through this retrieved object, I'm retrieving it like so:

  this._postService.getParams(_url).subscribe(
  data => {
    this.results = data.Results
  },
  error => console.log(error),
  () => console.log('Done')
  );

getParams() fetches the data like this

    getParams(url: string) {
    return this._http.get(url)
        .map(res => res.json());
}

I made an interface for data retrieved, placed it in the same .component.ts file where the service is being called

/*Interface for Stats */
interface stats {
name: string;
percent: number;
}

I plan to loop through the object I retrieved and store them in a local array and then loop through that and display them. How can I iterate through the JSON object in my component file? I tried many different for loops and they all failed.

I attempted this one and it failed, json was not being recognized by typescript

let list: string[] = [];
json.Results.forEach(element => {
list.push(element.Id);
});

I'm perfectly able to retrieve the data, because I console logged the 3 objects I received.

Body:
Class stats :

export class Stats {
    name: string;
    perc: string;
    constructor(n, p) {
        this.name = n;
        this.perc = p;
    }
}

Assuming your service works and returns data, don't change it.

Component :

getStats(_url: string) {
    let list: Stats[] = [];
    this._postService.getParams(_url).subscribe(
        data => {
            for (let res of data.Results) {
                let stat = new Stats(res.name, res.perc);
                list.push(stat);
            }
        }, err => { /* Error handling */}
    );
}


问:
XCode HealthThermometer example compile error
Hy to all! I'm newbie in coding with Xcode and objective-c. I'm using 8.2 Xcode and i tried to compile the HealthThermometer example from there
https://developer.apple.com/library/content/samplecode/HealthThermometer/Introduction/Intro.html
and it's gives a lots of error:

What can be wrong?

Thanks in advance!

答:
That is quite old example code.  It is missing the #import required for Core Bluetooth and attempts to link to the older IOBluetooth library.

In order to compile it you will need to change the top of HealthThermometerClientAppDelegate.h to read:

```<code>#import <Cocoa/Cocoa.h>
#import <CoreBluetooth/CoreBluetooth.h>
</code>```

You will also need to go into the project settings and remove the IOBluetooth framework and add a reference to CoreBluetooth.framework

Body:
That is quite old example code.  It is missing the #import required for Core Bluetooth and attempts to link to the older IOBluetooth library.

In order to compile it you will need to change the top of HealthThermometerClientAppDelegate.h to read:

#import <Cocoa/Cocoa.h>
#import <CoreBluetooth/CoreBluetooth.h>

You will also need to go into the project settings and remove the IOBluetooth framework and add a reference to CoreBluetooth.framework


问:
Trying to stop removing `div` if it's length at `0` or `1`. can someone help me?
Trying to stop removing div if it's length at 0 or 1. can someone help me?

Here is link: https://jsfiddle.net/Issact/ncqnv8zs/

HTML & JS:

$(document).ready(function() {

  $('.div').click(function() {
    $(this).remove();
    var divLength = $('.main div').length;
    $('.mainLength').text(divLength + " " + 'divs');

    if (divLength === 1) {
      $(this).stop().remove();
    }

  });
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="main">
  <div class="div">Div one</div>
  <div class="div">Div Two</div>
  <div class="div">Div Three</div>
  <div class="div">Div Four</div>
</div>

<div class="mainLength">
</div></code>```

答:
I have tested this in your fiddle and i believe that this is the behavior you want to achieve.</p>

```<code>$(document).ready(function() {

  $('.div').click(function() {

    var divLength = $('.main div').length;
    $('.mainLength').text(divLength + " " + 'divs');

    if (divLength > 1) {
      $(this).remove();
    }

  });
});
</code>```

Body:
Trying to stop removing div if it's length at 0 or 1. can someone help me?

Here is link: https://jsfiddle.net/Issact/ncqnv8zs/

HTML & JS:

$(document).ready(function() {

  $('.div').click(function() {
    $(this).remove();
    var divLength = $('.main div').length;
    $('.mainLength').text(divLength + " " + 'divs');

    if (divLength === 1) {
      $(this).stop().remove();
    }

  });
});

Div one

Div Two

Div Three

Div Four

Body:
I have tested this in your fiddle and i believe that this is the behavior you want to achieve.

$(document).ready(function() {

  $('.div').click(function() {

    var divLength = $('.main div').length;
    $('.mainLength').text(divLength + " " + 'divs');

    if (divLength > 1) {
      $(this).remove();
    }

  });
});


问:
TypeScript typings give me "index.d.ts is not a module"
I am getting File node_modules/@types/webrtc/index.d.ts is not a module with this code:

```<code>import * as webrtc from "webrtc";
const peerConnection1 = new RTCPeerConnection();
</code>```

I have installed the typings using npm i @types/webrtc --save-dev. Hovering over RTCPeerConnection in const peerConnection1 = new RTCPeerConnection(); display type annotations in Visual Studio Code so at least the code editor sees the types. Running tsc (or webpack with ts-loader) fails with the error.

I have tried npm i webrtc --save in a misguided attempt for solving this, but it did not change anything and I really only want the typings anyway, WebRTC is right there in the browser, I don't need a package for that. (Support aside.)

The index.d.ts file indeed is not a module, it just references two other files with interfaces in them. So I thought to remove import * as webrtc from "webrtc"; hoping the typings will still be visible by tsc somehow. (But that's impossible since I exclude node_modules in TypeScript config file.) When I do that RTCPeerConnection is no longer recognized.

Adding /// <reference src="node_modules/@types/webrtc/" /> did not help, tsc says Invalid reference directive syntax.

You can view a repository with minimal repro here on GitLab. I am not too well versed in TypeScript typings acquisition so please forgive my ignorance if I'm going about this all wrong.

答:
No need to import anything, run following:

npm install --save @types/webrtc

update tsconfig.json -

"types": [
      "@types/webrtc"
    ]

Body:
I am getting File node_modules/@types/webrtc/index.d.ts is not a module with this code:

import * as webrtc from "webrtc";
const peerConnection1 = new RTCPeerConnection();

I have installed the typings using npm i @types/webrtc --save-dev. Hovering over RTCPeerConnection in const peerConnection1 = new RTCPeerConnection(); display type annotations in Visual Studio Code so at least the code editor sees the types. Running tsc (or webpack with ts-loader) fails with the error.

I have tried npm i webrtc --save in a misguided attempt for solving this, but it did not change anything and I really only want the typings anyway, WebRTC is right there in the browser, I don't need a package for that. (Support aside.)

The index.d.ts file indeed is not a module, it just references two other files with interfaces in them. So I thought to remove import * as webrtc from "webrtc"; hoping the typings will still be visible by tsc somehow. (But that's impossible since I exclude node_modules in TypeScript config file.) When I do that RTCPeerConnection is no longer recognized.

Adding /// <reference src="node_modules/@types/webrtc/" /> did not help, tsc says Invalid reference directive syntax.

You can view a repository with minimal repro here on GitLab. I am not too well versed in TypeScript typings acquisition so please forgive my ignorance if I'm going about this all wrong.