问:
read and write files open() read()
i need  to make a program that read a file(arg[1]) and show it content but, with a specific number of bytes[arg2]. If no bytes are specified whole file will be printed.

```<code>void read(char *arg[]){
        int fh;
        char buffer[100];
        int rd;

        fh = open(arg[1],O_RDONLY);
        printf ("Printing %s\n",arg[1]);
        while (rd = read(fh,buffer,100)) {
                buffer[rd] = '\0';
                printf("%s",buffer);
                }
        }
</code>```

I need to use open(),read() at least.
Can someone help me?

答:
```<code>#include <stdio.h>
#include <stdlib.h>

void print(char* buff, int size)
{
  int i;
  for(i = 0; i < size ; i++)
  {
    printf("%c",buff[i]);
  }
  printf("\n");
}

int main(int argc, char* argv[])
{
    FILE * pFile;
    long lSize;
    char * buffer;
    size_t result;

    pFile = open ( argv[1] , O_RDONLY );
    if (pFile==NULL) {fputs ("File error",stderr); exit (1);}
    if(argv[2])
    {
      lSize = argv[2];
    }
    else
    {
      fseek (pFile , 0 , SEEK_END);
      lSize = ftell (pFile);
      rewind (pFile);
    }

    buffer = (char*) malloc (sizeof(char)*lSize);
    if (buffer == NULL) {fputs ("Memory error",stderr); exit (2);}
    result = read (pFile,buffer,lSize);
    if (result != lSize) {fputs ("Reading error",stderr); exit (3);}
    print(buffer,lSize);

    fclose (pFile);
    free (buffer);
    return 0;
}
</code>```

Title: read and write files open() read()

Body:
i need  to make a program that read a file(arg[1]) and show it content but, with a specific number of bytes[arg2]. If no bytes are specified whole file will be printed.

void read(char *arg[]){
        int fh;
        char buffer[100];
        int rd;

        fh = open(arg[1],O_RDONLY);
        printf ("Printing %s\n",arg[1]);
        while (rd = read(fh,buffer,100)) {
                buffer[rd] = '\0';
                printf("%s",buffer);
                }
        }

I need to use open(),read() at least.
Can someone help me?


来源: stackexchange

问:
Total sum of all multiplied values of textboxes
I want to multiply the textbox values and after multiplication sum of all answer values. Example:

```<code>SUM (NSP * Current Sales)
</code>```

This program is working fine but when I change any value it adds the change not replace the values. It should replace the value of array.

And if possible, please minimize the code logic also. Thanks.

$(document).ready(function() {
  var val1;
  var val2;
  var multi;
  one();
  second();
});

function one() {
  $(document).on("change", ".qty1", function() {
    var sumqty1 = 0;
    sumqty1 += $(this).val();
    val1 = sumqty1;
  });
}

function second() {
  $(document).on("change", ".qty2", function() {
    var sumqty1 = 0;
    var sumqty2 = 0;
    sumqty1 += $(this).closest('tr').find('.qty1').val();
    sumqty2 += $(this).val();
    val1 = sumqty1;
    val2 = sumqty2;
    mul(val1, val2);
  });
}
var arr = [];

function mul(a, b) {
  var hh;
  multi = a * b;
  arr.push(multi);
  var totalsum = 0;
  for (var i in arr) {
    var value = arr[i];
    totalsum = parseInt(totalsum, 10) + parseInt(value, 10);
    $("#totalvalue").text(totalsum);
  }
  console.log(arr);
}```
<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>
<table style="width: 100%;" width="100%" cellspacing="0">
  <thead>
    <tr>
      <th>Product Name</th>
      <th>NSP</th>
      <th>Current Sales</th>
      <th>Closing Balance</th>
    </tr>
  </thead>
  <tfoot>
    <tr>
      <th>Product Name</th>
      <th>NSP</th>
      <th>Current Sales</th>
      <th><span id='totalvalue'></span></th>
    </tr>
  </tfoot>
  <tbody>
    <tr>

      <td>Satou</td>
      <td><input type="text" class="qty1" value="1" disabled /></td>
      <td><input type="text" class="qty2" value="" /></td>
      <td>23</td>
    </tr>
    <tr>
      <td>panadol</td>
      <td><input type="text" class="qty1" value="2" disabled /></td>
      <td><input type="text" class="qty2" value="" /></td>
      <td>131</td>
    </tr>
    <tr>
      <td>disprine</td>
      <td><input type="text" class="qty1" value="3" disabled/></td>
      <td><input type="text" class="qty2" value="" /></td>
      <td>37</td>
    </tr>
    <tr>
      <td>panadol</td>
      <td><input type="text" class="qty1" value="4" disabled /></td>
      <td><input type="text" class="qty2" value="" /></td>
      <td>173</td>
    </tr>
  </tbody>
</table></code>```

答:
The way you have it right now, you're adding new elements to the array in the order they're created, which doesn't allow you to access them later to change them because they could be stored in any order.

The code below saves each value in the array based on the value of val1 so that each element has a designated place in the array.  Because of that, you can update any of the values when they are changed, like so:

var arr = [];

function one() {
  $(document).on("change", ".qty1", function() {
    var sumqty1 = $(this).val();
  });
}

function second() {
  $(document).on("change", ".qty2", function() {
    var val1 = $(this).closest('tr').find('.qty1').val();;
    var val2 = $(this).val();
    mul(val1, val2);
  });
}

function mul(a, b) {
  arr[a - 1] = a * b;
  var totalsum = 0;
  for (var i in arr) {
    var value = arr[i];
    totalsum = parseInt(totalsum, 10) + parseInt(value, 10);
    $("#totalvalue").text(totalsum);
  }
  console.log(arr);
}

$(document).ready(function() {
  one();
  second();
});```
<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>
<table style="width: 100%;" width="100%" cellspacing="0">
  <thead>
    <tr>
      <th>Product Name</th>
      <th>NSP</th>
      <th>Current Sales</th>
      <th>Closing Balance</th>
    </tr>
  </thead>
  <tfoot>
    <tr>
      <th>Product Name</th>
      <th>NSP</th>
      <th>Current Sales</th>
      <th><span id='totalvalue'></span></th>
    </tr>
  </tfoot>
  <tbody>
    <tr>

      <td>Satou</td>
      <td><input type="text" class="qty1" value="1" disabled /></td>
      <td><input type="text" class="qty2" value="" /></td>
      <td>23</td>
    </tr>
    <tr>
      <td>panadol</td>
      <td><input type="text" class="qty1" value="2" disabled /></td>
      <td><input type="text" class="qty2" value="" /></td>
      <td>131</td>
    </tr>
    <tr>
      <td>disprine</td>
      <td><input type="text" class="qty1" value="3" disabled/></td>
      <td><input type="text" class="qty2" value="" /></td>
      <td>37</td>
    </tr>
    <tr>
      <td>panadol</td>
      <td><input type="text" class="qty1" value="4" disabled /></td>
      <td><input type="text" class="qty2" value="" /></td>
      <td>173</td>
    </tr>
  </tbody>
</table></code>```

I also took out some unnecessary code, including:

The hh declaration (since that variable isn't used) in your second() function

a couple of extraneous lines in your one() function

the multi variable

the sumqty1 and sumqty2 variables (you can just use val1 and val2)

Your val1 and val2 variables didn't need to be global, since you are only using them in one function and passing them as parameters to another.

You could also remove the one() function if you want, since those values seem to be static -- but I'm not sure if you allow that value to be changed in your original code.

ContentLicense: CC BY-SA 3.0

Body:
I want to multiply the textbox values and after multiplication sum of all answer values. Example:

SUM (NSP * Current Sales)

This program is working fine but when I change any value it adds the change not replace the values. It should replace the value of array.

And if possible, please minimize the code logic also. Thanks.

$(document).ready(function() {
  var val1;
  var val2;
  var multi;
  one();
  second();
});

function one() {
  $(document).on("change", ".qty1", function() {
    var sumqty1 = 0;
    sumqty1 += $(this).val();
    val1 = sumqty1;
  });
}

function second() {
  $(document).on("change", ".qty2", function() {
    var sumqty1 = 0;
    var sumqty2 = 0;
    sumqty1 += $(this).closest('tr').find('.qty1').val();
    sumqty2 += $(this).val();
    val1 = sumqty1;
    val2 = sumqty2;
    mul(val1, val2);
  });
}
var arr = [];

function mul(a, b) {
  var hh;
  multi = a * b;
  arr.push(multi);
  var totalsum = 0;
  for (var i in arr) {
    var value = arr[i];
    totalsum = parseInt(totalsum, 10) + parseInt(value, 10);
    $("#totalvalue").text(totalsum);
  }
  console.log(arr);
}

      Product Name
      NSP
      Current Sales
      Closing Balance

      Product Name
      NSP
      Current Sales

      Satou
      <input type="text" class="qty1" value="1" disabled />
      <input type="text" class="qty2" value="" />
      23

      panadol
      <input type="text" class="qty1" value="2" disabled />
      <input type="text" class="qty2" value="" />
      131

      disprine
      <input type="text" class="qty1" value="3" disabled/>
      <input type="text" class="qty2" value="" />
      37

      panadol
      <input type="text" class="qty1" value="4" disabled />
      <input type="text" class="qty2" value="" />
      173

Body:
The way you have it right now, you're adding new elements to the array in the order they're created, which doesn't allow you to access them later to change them because they could be stored in any order.

The code below saves each value in the array based on the value of val1 so that each element has a designated place in the array.  Because of that, you can update any of the values when they are changed, like so:

var arr = [];

function one() {
  $(document).on("change", ".qty1", function() {
    var sumqty1 = $(this).val();
  });
}

function second() {
  $(document).on("change", ".qty2", function() {
    var val1 = $(this).closest('tr').find('.qty1').val();;
    var val2 = $(this).val();
    mul(val1, val2);
  });
}

function mul(a, b) {
  arr[a - 1] = a * b;
  var totalsum = 0;
  for (var i in arr) {
    var value = arr[i];
    totalsum = parseInt(totalsum, 10) + parseInt(value, 10);
    $("#totalvalue").text(totalsum);
  }
  console.log(arr);
}

$(document).ready(function() {
  one();
  second();
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table style="width: 100%;" width="100%" cellspacing="0">
  <thead>
    <tr>
      <th>Product Name</th>
      <th>NSP</th>
      <th>Current Sales</th>
      <th>Closing Balance</th>
    </tr>
  </thead>
  <tfoot>
    <tr>
      <th>Product Name</th>
      <th>NSP</th>
      <th>Current Sales</th>
      <th><span id='totalvalue'></span></th>
    </tr>
  </tfoot>
  <tbody>
    <tr>

      <td>Satou</td>
      <td><input type="text" class="qty1" value="1" disabled /></td>
      <td><input type="text" class="qty2" value="" /></td>
      <td>23</td>
    </tr>
    <tr>
      <td>panadol</td>
      <td><input type="text" class="qty1" value="2" disabled /></td>
      <td><input type="text" class="qty2" value="" /></td>
      <td>131</td>
    </tr>
    <tr>
      <td>disprine</td>
      <td><input type="text" class="qty1" value="3" disabled/></td>
      <td><input type="text" class="qty2" value="" /></td>
      <td>37</td>
    </tr>
    <tr>
      <td>panadol</td>
      <td><input type="text" class="qty1" value="4" disabled /></td>
      <td><input type="text" class="qty2" value="" /></td>
      <td>173</td>
    </tr>
  </tbody>
</table>

I also took out some unnecessary code, including:

The hh declaration (since that variable isn't used) in your second() function

a couple of extraneous lines in your one() function

the multi variable

the sumqty1 and sumqty2 variables (you can just use val1 and val2)

Your val1 and val2 variables didn't need to be global, since you are only using them in one function and passing them as parameters to another.

You could also remove the one() function if you want, since those values seem to be static -- but I'm not sure if you allow that value to be changed in your original code.


问:
What is Mocking?
What is Mocking?                                                                                .</p>

答: Mocking is generating pseudo-objects that simulate real objects behaviour for tests</p>

Title: What is Mocking?

Body: What is Mocking?                                                                                .


问:
SQL or procedure to conditionally insert or update in Oracle database
I don't have much of a hands-on in SQL and procedures. I need a migration script wherein I need to update or insert a table based on data in other two tables.

Organization:
id   name  pid
1   org1  null
2
    org2  null
3
    org3  1
4
    org4  2

Org_Channel:
org_id   channel
1         CH_100
2
          CH_101

Organization table has a parent-child self referenced relation. (pid null in case of parent). Org_Channel is a mapping table for parent organizations only.

Now I have a third table Org_Settings in which I need to migrate the data based on the above two tables. Each record here indicates a organization id, a setting name which is prefixed by channel name(for child org.this will be parent org.channel), and a flag. I need a migration SQL script / procedure for a setting Sign_On to be enabled as 'Y' for every organization

The current table is something like this:

Org_Settings:
org_id   s_name              enabled
1       CH_100_Sign_On    N
1       CH_100_X_O          Y

4       CH_101_Sign_On   Y

Now Org_Settings may or may not contain entry for each org. Also I need to migrate such that, if entry is present for Sign_On then need to update enabled = Y. Such that the result would be:

Org_Settings:
org_id   s_name              enabled
1       CH_100_Sign_On    Y
2       CH_101_Sign_On    Y

3       CH_100_Sign_On    Y
4       CH_101_Sign_On    Y

I could think of pseudo code like:

```<code>for i in each org
    var pid = getPid(i)
    var id = (null == pid) ? i : pid
    var channel = getChannel(id);
    var sname = channel + "_Sign_On"
    if(settingsEntryExists(i, sname))
        updateSettingsEnable(i, sname, 'Y')
    else
        insertSettings(i, sname, 'Y')
</code>```

答:
Try this MERGE INTO statement. I did not understand the logic behind updating to 'Y' if entry exists and also inserting 'Y' if it does not exist. Isn't it same as simple insert?. or am I missing something? . You may tweak this query slightly if there is some missing info to clarify my question above.

SQLFiddle

```<code>MERGE
INTO    Org_Settings d
USING   ( select
                org.id org_id,
                ch.channel||
                '_Sign_On' s_name ,
                'Y'        enabled
        FROM
                Organization org
        JOIN    Org_Channel  ch ON NVL(org.pid,id) = ch.org_id
        )s
ON ( d.org_id  = s.org_id
                AND d.s_name = s.s_name )
WHEN MATCHED THEN
UPDATE SET d.enabled = 'Y'
WHEN NOT MATCHED THEN
INSERT
        (org_id,s_name,enabled
        ) VALUES
        (s.org_id,s.s_name,s.enabled
        );
</code>```

Body:
I don't have much of a hands-on in SQL and procedures. I need a migration script wherein I need to update or insert a table based on data in other two tables.

Organization:
id   name  pid
1   org1  null
2
    org2  null
3
    org3  1
4
    org4  2

Org_Channel:
org_id   channel
1         CH_100
2
          CH_101

Organization table has a parent-child self referenced relation. (pid null in case of parent). Org_Channel is a mapping table for parent organizations only.

Now I have a third table Org_Settings in which I need to migrate the data based on the above two tables. Each record here indicates a organization id, a setting name which is prefixed by channel name(for child org.this will be parent org.channel), and a flag. I need a migration SQL script / procedure for a setting Sign_On to be enabled as 'Y' for every organization

The current table is something like this:

Org_Settings:
org_id   s_name              enabled
1       CH_100_Sign_On    N
1       CH_100_X_O          Y

4       CH_101_Sign_On   Y

Now Org_Settings may or may not contain entry for each org. Also I need to migrate such that, if entry is present for Sign_On then need to update enabled = Y. Such that the result would be:

Org_Settings:
org_id   s_name              enabled
1       CH_100_Sign_On    Y
2       CH_101_Sign_On    Y

3       CH_100_Sign_On    Y
4       CH_101_Sign_On    Y

I could think of pseudo code like:

for i in each org
    var pid = getPid(i)
    var id = (null == pid) ? i : pid
    var channel = getChannel(id);
    var sname = channel + "_Sign_On"
    if(settingsEntryExists(i, sname))
        updateSettingsEnable(i, sname, 'Y')
    else
        insertSettings(i, sname, 'Y')

Body:
Try this MERGE INTO statement. I did not understand the logic behind updating to 'Y' if entry exists and also inserting 'Y' if it does not exist. Isn't it same as simple insert?. or am I missing something? . You may tweak this query slightly if there is some missing info to clarify my question above.

SQLFiddle

MERGE
INTO    Org_Settings d
USING   ( select
                org.id org_id,
                ch.channel||
                '_Sign_On' s_name ,
                'Y'        enabled
        FROM
                Organization org
        JOIN    Org_Channel  ch ON NVL(org.pid,id) = ch.org_id
        )s
ON ( d.org_id  = s.org_id
                AND d.s_name = s.s_name )
WHEN MATCHED THEN
UPDATE SET d.enabled = 'Y'
WHEN NOT MATCHED THEN
INSERT
        (org_id,s_name,enabled
        ) VALUES
        (s.org_id,s.s_name,s.enabled
        );


问:
Get Username from login form and set it to a control label in another form after connected
Please I'm new in C# and I'm facing this problem. I have 2 forms , one is the login form and the other is the form after login connection. I want to get the user name from the User-textbox in the login form and set it on a Label in the Second form when the user connect. Like " Welcome User1" and set a timer to start. Thank in advance for any suggestion.
Below is My login code

```<code>namespace KPI_TRANSPORT
{
    public partial class LOGIN : Form
    {
        public LOGIN()
        {
            InitializeComponent();
        }

        private void txtUsername_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar==(char)13)
                textBox2.Focus();
        }

        private void textBox2_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == (char)13)
               btnLogin.PerformClick();
        }

        private void btnLogin_Click(object sender, EventArgs e)
        {
            if(string.IsNullOrEmpty(txtUsername.Text))
            {
                MessageBox.Show("SVP Entrée votre nom d'utilisateur","Message",MessageBoxButtons.OK,MessageBoxIcon.Warning);
                txtUsername.Focus();
                return;
            }
            try {
                KPI_DATABASEDataSet5TableAdapters.LoginTableAdapter login = new KPI_DATABASEDataSet5TableAdapters.LoginTableAdapter();
                KPI_DATABASEDataSet5.LoginDataTable dt = login.GetDataByUsernamePassword(txtUsername.Text,textBox2.Text);
                if (dt.Rows.Count > 0)
                {
                //MessageBox.Show("Connecté avec succès", "Message", MessageBoxButtons.OK, MessageBoxIcon.Information);
                this.Hide();
                PagePrin f1 = new PagePrin();
                LOGIN lg = new LOGIN();
                lg.Closed += (s, args) => lg.Close();
                f1.Show();

            }
            else
            {
                MessageBox.Show("Nom d'utilisateur ou Mot de pass incorrect", "Message", MessageBoxButtons.OK, MessageBoxIcon.Information);
                txtUsername.Text = "";
                textBox2.Text = "";
                txtUsername.Focus();
            }
        }
        catch (Exception ex)
        { MessageBox.Show("Error"+ex); }

    }

        private void ExitBtn_Click(object sender, EventArgs e)
        {
            System.Windows.Forms.Application.Exit();
            this.Close();
        }

        private void LOGIN_Load(object sender, EventArgs e)
        {
            this.Location = new Point(0, 0);
            this.Size = Screen.PrimaryScreen.WorkingArea.Size;

            //UsernameText
            txtUsername.AutoSize = false;
            txtUsername.Height = 40;
            txtUsername.Width = 200;

            //password Text
            textBox2.AutoSize = false;
            textBox2.Height = 40;
            textBox2.Width = 200;
        }

        private void check_Text_content()
        {
            if (txtUsername.Text !=string.Empty && textBox2.Text !=string.Empty)
            { btnLogin.Enabled=true; }
            else if (txtUsername.Text==string.Empty)
            { btnLogin.Enabled=false; }
            else if (textBox2.Text==string.Empty)
            { btnLogin.Enabled = false; }
        }
    }
}
</code>```

答:
Just pass it to another form like this:

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

private void btnLogin_Click(object sender, EventArgs e)
{
    string someString = "TestingString";
    int someInt = 123;
    SecondFrom sf = new SecondForm(someString, someInt);
    sf.Show();
}
</code>```

Another form:

```<code>public partial class SecondForm : Form
{
    private string myString;
    private int myInt;

    public SecondForm(string passingString, int passingInt)
    {
        myString = passingString;
        myInt = passingInt;
    }
}
</code>```

Like this you have passed values from someString and someInt from LOGIN form to SecondForm's myString and myInt

Body:
Please I'm new in C# and I'm facing this problem. I have 2 forms , one is the login form and the other is the form after login connection. I want to get the user name from the User-textbox in the login form and set it on a Label in the Second form when the user connect. Like " Welcome User1" and set a timer to start. Thank in advance for any suggestion.
Below is My login code

namespace KPI_TRANSPORT
{
    public partial class LOGIN : Form
    {
        public LOGIN()
        {
            InitializeComponent();
        }

        private void txtUsername_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar==(char)13)
                textBox2.Focus();
        }

        private void textBox2_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == (char)13)
               btnLogin.PerformClick();
        }

        private void btnLogin_Click(object sender, EventArgs e)
        {
            if(string.IsNullOrEmpty(txtUsername.Text))
            {
                MessageBox.Show("SVP Entrée votre nom d'utilisateur","Message",MessageBoxButtons.OK,MessageBoxIcon.Warning);
                txtUsername.Focus();
                return;
            }
            try {
                KPI_DATABASEDataSet5TableAdapters.LoginTableAdapter login = new KPI_DATABASEDataSet5TableAdapters.LoginTableAdapter();
                KPI_DATABASEDataSet5.LoginDataTable dt = login.GetDataByUsernamePassword(txtUsername.Text,textBox2.Text);
                if (dt.Rows.Count > 0)
                {
                //MessageBox.Show("Connecté avec succès", "Message", MessageBoxButtons.OK, MessageBoxIcon.Information);
                this.Hide();
                PagePrin f1 = new PagePrin();
                LOGIN lg = new LOGIN();
                lg.Closed += (s, args) => lg.Close();
                f1.Show();

            }
            else
            {
                MessageBox.Show("Nom d'utilisateur ou Mot de pass incorrect", "Message", MessageBoxButtons.OK, MessageBoxIcon.Information);
                txtUsername.Text = "";
                textBox2.Text = "";
                txtUsername.Focus();
            }
        }
        catch (Exception ex)
        { MessageBox.Show("Error"+ex); }

    }

        private void ExitBtn_Click(object sender, EventArgs e)
        {
            System.Windows.Forms.Application.Exit();
            this.Close();
        }

        private void LOGIN_Load(object sender, EventArgs e)
        {
            this.Location = new Point(0, 0);
            this.Size = Screen.PrimaryScreen.WorkingArea.Size;

            //UsernameText
            txtUsername.AutoSize = false;
            txtUsername.Height = 40;
            txtUsername.Width = 200;

            //password Text
            textBox2.AutoSize = false;
            textBox2.Height = 40;
            textBox2.Width = 200;
        }

        private void check_Text_content()
        {
            if (txtUsername.Text !=string.Empty && textBox2.Text !=string.Empty)
            { btnLogin.Enabled=true; }
            else if (txtUsername.Text==string.Empty)
            { btnLogin.Enabled=false; }
            else if (textBox2.Text==string.Empty)
            { btnLogin.Enabled = false; }
        }
    }
}

Body:
Just pass it to another form like this:

public partial class LOGIN : Form
{
    public Login()
    {
        InitializeComponent();
    }
}

private void btnLogin_Click(object sender, EventArgs e)
{
    string someString = "TestingString";
    int someInt = 123;
    SecondFrom sf = new SecondForm(someString, someInt);
    sf.Show();
}

Another form:

public partial class SecondForm : Form
{
    private string myString;
    private int myInt;

    public SecondForm(string passingString, int passingInt)
    {
        myString = passingString;
        myInt = passingInt;
    }
}

Like this you have passed values from someString and someInt from LOGIN form to SecondForm's myString and myInt


问:
Selenium exits with errors (chromewebdriver)
When I run my script (which tests the subscribe feature on my friends website)
It exits with this error:

```<code>  File "subtest.py", line 3, in <module>
driver = webdriver.Chrome('/usr/local/bin/chromedriver')
File "/usr/local/lib/python2.7/dist-packages/selenium/webdriver/chrome/webdriver.py", line 62, in __init__
self.service.start()
File "/usr/local/lib/python2.7/dist-packages/selenium/webdriver/common/service.py", line 96, in start
self.assert_process_still_running()
File "/usr/local/lib/python2.7/dist-packages/selenium/webdriver/common/service.py", line 109, in assert_process_still_running
% (self.path, return_code)
selenium.common.exceptions.WebDriverException: Message: Service /usr/local/bin/chromedriver unexpectedly exited. Status code was: 127
</code>```

I should also mention that I am using python2.7

答:
Try running the chromedriver binary by itself, in the case of a missing library like @Joao Vitorino has mentioned it will log.

In my case I needed to install libgconf-2-4 on Ubuntu 14.04

ContentLicense: CC BY-SA 4.0

Body:
When I run my script (which tests the subscribe feature on my friends website)
It exits with this error:

  File "subtest.py", line 3, in <module>
driver = webdriver.Chrome('/usr/local/bin/chromedriver')
File "/usr/local/lib/python2.7/dist-packages/selenium/webdriver/chrome/webdriver.py", line 62, in __init__
self.service.start()
File "/usr/local/lib/python2.7/dist-packages/selenium/webdriver/common/service.py", line 96, in start
self.assert_process_still_running()
File "/usr/local/lib/python2.7/dist-packages/selenium/webdriver/common/service.py", line 109, in assert_process_still_running
% (self.path, return_code)
selenium.common.exceptions.WebDriverException: Message: Service /usr/local/bin/chromedriver unexpectedly exited. Status code was: 127

I should also mention that I am using python2.7


问:
How can I restrict my iOS Project to iPhone 4 Only
I'm using a barcode scanner library within my iOS project that currently only supports iPhone 4 devices. Is it possible to restrict the application submission so that only iPhone 4 users can load it, is this a cause for rejection from the App Store?</p>

答: I would check out the UIRequiredDeviceCapabilities in the SDK. It is generally Apple's policy to try to make your app available to all devices. I can't remember off the top of my head if the App store will only show Apps that are made to work on the device or if the App store does a blanket view.

ContentLicense: CC BY-SA 2.5


问:
java.io.FileNotFoundException for Cloud Iot core Code
I am presently working on program on Android Things for connecting to Google Cloud IoT Core. I used to sample maven code provided by Google and modified it for Gradle(with all the imports and stuff). After doing every kind of check, whenever I am trying to run the program on a Raspberry Pi3 running Android Things it keeps giving this error

```<code>W/System.err: java.io.FileNotFoundException: com/example/adityaprakash/test/rsa_private.pem (No such file or directory)
</code>```

telling me that the private key file that I am supposed to use for the JWT doesn't exist despite the fact it does and I have given the path for the pem file.Here are my java codes

```<code>package com.example.adityaprakash.test;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //setContentView(R.layout.activity_main);
        Log.i("#########","######");
        MqttExample mqtt = new MqttExample();
        try {
            mqtt.Start();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
</code>```

The MqttExample.java

```<code>package com.example.adityaprakash.test;
// [END cloudiotcore_mqtt_imports]
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;

import org.joda.time.DateTime;

import java.io.BufferedReader;
import java.io.FileReader;

import java.security.KeyFactory;
import java.security.spec.PKCS8EncodedKeySpec;

import android.util.Base64;

import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

public class MqttExample {

    // [START cloudiotcore_mqtt_createjwt]
    /** Create a Cloud IoT Core JWT for the given project id, signed with the given RSA key. */
    public static String createJwtRsa(String projectId, String privateKeyFile) throws Exception {
        DateTime now = new DateTime();

        String strKeyPEM = "";
        BufferedReader br = new BufferedReader(new FileReader(privateKeyFile));
        String line;
        while ((line = br.readLine()) != null) {
            strKeyPEM += line + "\n";
        }
        br.close();
        // Create a JWT to authenticate this device. The device will be disconnected after the token
        // expires, and will have to reconnect with a new token. The audience field should always be set
        // to the GCP project id.
        JwtBuilder jwtBuilder =
                Jwts.builder()
                        .setIssuedAt(now.toDate())
                        .setExpiration(now.plusMinutes(20).toDate())
                        .setAudience(projectId);
        String privateKeyPEM = strKeyPEM;
        privateKeyPEM = privateKeyPEM.replace("-----BEGIN PRIVATE KEY-----\n", "");
        privateKeyPEM = privateKeyPEM.replace("-----END PRIVATE KEY-----", "");
        byte[] encoded = Base64.decode(privateKeyPEM,Base64.DEFAULT);
        PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(encoded);
        KeyFactory kf = KeyFactory.getInstance("RSA");

        return jwtBuilder.signWith(SignatureAlgorithm.RS256, kf.generatePrivate(spec)).compact();
    }

    /** Parse arguments, configure MQTT, and publish messages. */
    public void Start() throws Exception {
        // [START cloudiotcore_mqtt_configuremqtt]
        MqttExampleOptions options = MqttExampleOptions.values();
        if (options == null) {
            // Could not parse.
            System.exit(1);
        }
        // Build the connection string for Google's Cloud IoT Core MQTT server. Only SSL
        // connections are accepted. For server authentication, the JVM's root certificates
        // are used.
        final String mqttServerAddress =
                String.format("ssl://%s:%s", options.mqttBridgeHostname, options.mqttBridgePort);

        // Create our MQTT client. The mqttClientId is a unique string that identifies this device. For
        // Google Cloud IoT Core, it must be in the format below.
        final String mqttClientId =
                String.format(
                        "projects/%s/locations/%s/registries/%s/devices/%s",
                        options.projectId, options.cloudRegion, options.registryId, options.deviceId);

        MqttConnectOptions connectOptions = new MqttConnectOptions();
        // Note that the the Google Cloud IoT Core only supports MQTT 3.1.1, and Paho requires that we
        // explictly set this. If you don't set MQTT version, the server will immediately close its
        // connection to your device.
        connectOptions.setMqttVersion(MqttConnectOptions.MQTT_VERSION_3_1_1);

        // With Google Cloud IoT Core, the username field is ignored, however it must be set for the
        // Paho client library to send the password field. The password field is used to transmit a JWT
        // to authorize the device.
        connectOptions.setUserName("unused");

        System.out.println(options.algorithm);
        if (options.algorithm.equals("RS256")) {
            connectOptions.setPassword(
                    createJwtRsa(options.projectId, options.privateKeyFile).toCharArray());
        }else {
            throw new IllegalArgumentException(
                    "Invalid algorithm " + options.algorithm + ". Should be one of 'RS256' or 'ES256'.");
        }
        // [END cloudiotcore_mqtt_configuremqtt]

        // [START cloudiotcore_mqtt_publish]
        // Create a client, and connect to the Google MQTT bridge.
        MqttClient client = new MqttClient(mqttServerAddress, mqttClientId, new MemoryPersistence());
        try {
            client.connect(connectOptions);

            // Publish to the events or state topic based on the flag.
            String subTopic = options.messageType.equals("event") ? "events" : options.messageType;

            // The MQTT topic that this device will publish telemetry data to. The MQTT topic name is
            // required to be in the format below. Note that this is not the same as the device registry's
            // Cloud Pub/Sub topic.
            String mqttTopic = String.format("/devices/%s/%s", options.deviceId, subTopic);

            // Publish numMessages messages to the MQTT bridge, at a rate of 1 per second.
            for (int i = 1; i <= options.numMessages; ++i) {
                String payload = String.format("%s/%s-payload number-%d", options.registryId, options.deviceId, i);
                System.out.format(
                        "Publishing %s message %d/%d: '%s'\n",
                        options.messageType, i, options.numMessages, payload);

                // Publish "payload" to the MQTT topic. qos=1 means at least once delivery. Cloud IoT Core
                // also supports qos=0 for at most once delivery.
                MqttMessage message = new MqttMessage(payload.getBytes());
                message.setQos(1);
                client.publish(mqttTopic, message);

                if (options.messageType.equals("event")) {
                    // Send telemetry events every second
                    Thread.sleep(1000);
                }
                else {
                    // Note: Update Device state less frequently than with telemetry events
                    Thread.sleep(5000);
                }
            }
        } finally {
            // Disconnect the client and finish the run.
            client.disconnect();
        }
        System.out.println("Finished loop successfully. Goodbye!");
        // [END cloudiotcore_mqtt_publish]
    }

}
</code>```

and the MqttExampleOptions.java code:

```<code>package com.example.adityaprakash.test;

public class MqttExampleOptions {
    String projectId;
    String registryId;
    String deviceId;
    String privateKeyFile;
    String algorithm;
    String cloudRegion;
    int numMessages;
    String mqttBridgeHostname;
    short mqttBridgePort;
    String messageType;

    /** Construct an MqttExampleOptions class. */
    public static MqttExampleOptions values() {

        try {

            MqttExampleOptions res = new MqttExampleOptions();

            res.projectId = "_";
            res.registryId = "_";
            res.deviceId = "_";
            res.privateKeyFile = "com/example/adityaprakash/test/rsa_private.pem";
            res.algorithm = "RS256";
            res.cloudRegion = "asia-east1";
            res.numMessages = 100;
            res.mqttBridgeHostname = "mqtt.googleapis.com";
            res.mqttBridgePort = 8883;
            res.messageType = "event";
            return res;

        } catch (Exception e) {
            System.err.println(e.getMessage());
            return null;
        }
    }
}
</code>```

Please can anyone give a solution to this problem.

P.S. I know the code looks totally crappy.I don't have experience with Android programming,so please let it go.

答: I'm pretty sure you're not doing the file I/O correctly. Your file, "com/example/adityaprakash/test/rsa_private.pem", doesn't correspond to an actual filepath on the device. The location of files on the device may be different than in your project. You will have to determine where on the device your file actually is.

Body:
I am presently working on program on Android Things for connecting to Google Cloud IoT Core. I used to sample maven code provided by Google and modified it for Gradle(with all the imports and stuff). After doing every kind of check, whenever I am trying to run the program on a Raspberry Pi3 running Android Things it keeps giving this error

W/System.err: java.io.FileNotFoundException: com/example/adityaprakash/test/rsa_private.pem (No such file or directory)

telling me that the private key file that I am supposed to use for the JWT doesn't exist despite the fact it does and I have given the path for the pem file.Here are my java codes

package com.example.adityaprakash.test;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //setContentView(R.layout.activity_main);
        Log.i("#########","######");
        MqttExample mqtt = new MqttExample();
        try {
            mqtt.Start();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

The MqttExample.java

package com.example.adityaprakash.test;
// [END cloudiotcore_mqtt_imports]
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;

import org.joda.time.DateTime;

import java.io.BufferedReader;
import java.io.FileReader;

import java.security.KeyFactory;
import java.security.spec.PKCS8EncodedKeySpec;

import android.util.Base64;

import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

public class MqttExample {

    // [START cloudiotcore_mqtt_createjwt]
    /** Create a Cloud IoT Core JWT for the given project id, signed with the given RSA key. */
    public static String createJwtRsa(String projectId, String privateKeyFile) throws Exception {
        DateTime now = new DateTime();

        String strKeyPEM = "";
        BufferedReader br = new BufferedReader(new FileReader(privateKeyFile));
        String line;
        while ((line = br.readLine()) != null) {
            strKeyPEM += line + "\n";
        }
        br.close();
        // Create a JWT to authenticate this device. The device will be disconnected after the token
        // expires, and will have to reconnect with a new token. The audience field should always be set
        // to the GCP project id.
        JwtBuilder jwtBuilder =
                Jwts.builder()
                        .setIssuedAt(now.toDate())
                        .setExpiration(now.plusMinutes(20).toDate())
                        .setAudience(projectId);
        String privateKeyPEM = strKeyPEM;
        privateKeyPEM = privateKeyPEM.replace("-----BEGIN PRIVATE KEY-----\n", "");
        privateKeyPEM = privateKeyPEM.replace("-----END PRIVATE KEY-----", "");
        byte[] encoded = Base64.decode(privateKeyPEM,Base64.DEFAULT);
        PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(encoded);
        KeyFactory kf = KeyFactory.getInstance("RSA");

        return jwtBuilder.signWith(SignatureAlgorithm.RS256, kf.generatePrivate(spec)).compact();
    }

    /** Parse arguments, configure MQTT, and publish messages. */
    public void Start() throws Exception {
        // [START cloudiotcore_mqtt_configuremqtt]
        MqttExampleOptions options = MqttExampleOptions.values();
        if (options == null) {
            // Could not parse.
            System.exit(1);
        }
        // Build the connection string for Google's Cloud IoT Core MQTT server. Only SSL
        // connections are accepted. For server authentication, the JVM's root certificates
        // are used.
        final String mqttServerAddress =
                String.format("ssl://%s:%s", options.mqttBridgeHostname, options.mqttBridgePort);

        // Create our MQTT client. The mqttClientId is a unique string that identifies this device. For
        // Google Cloud IoT Core, it must be in the format below.
        final String mqttClientId =
                String.format(
                        "projects/%s/locations/%s/registries/%s/devices/%s",
                        options.projectId, options.cloudRegion, options.registryId, options.deviceId);

        MqttConnectOptions connectOptions = new MqttConnectOptions();
        // Note that the the Google Cloud IoT Core only supports MQTT 3.1.1, and Paho requires that we
        // explictly set this. If you don't set MQTT version, the server will immediately close its
        // connection to your device.
        connectOptions.setMqttVersion(MqttConnectOptions.MQTT_VERSION_3_1_1);

        // With Google Cloud IoT Core, the username field is ignored, however it must be set for the
        // Paho client library to send the password field. The password field is used to transmit a JWT
        // to authorize the device.
        connectOptions.setUserName("unused");

        System.out.println(options.algorithm);
        if (options.algorithm.equals("RS256")) {
            connectOptions.setPassword(
                    createJwtRsa(options.projectId, options.privateKeyFile).toCharArray());
        }else {
            throw new IllegalArgumentException(
                    "Invalid algorithm " + options.algorithm + ". Should be one of 'RS256' or 'ES256'.");
        }
        // [END cloudiotcore_mqtt_configuremqtt]

        // [START cloudiotcore_mqtt_publish]
        // Create a client, and connect to the Google MQTT bridge.
        MqttClient client = new MqttClient(mqttServerAddress, mqttClientId, new MemoryPersistence());
        try {
            client.connect(connectOptions);

            // Publish to the events or state topic based on the flag.
            String subTopic = options.messageType.equals("event") ? "events" : options.messageType;

            // The MQTT topic that this device will publish telemetry data to. The MQTT topic name is
            // required to be in the format below. Note that this is not the same as the device registry's
            // Cloud Pub/Sub topic.
            String mqttTopic = String.format("/devices/%s/%s", options.deviceId, subTopic);

            // Publish numMessages messages to the MQTT bridge, at a rate of 1 per second.
            for (int i = 1; i <= options.numMessages; ++i) {
                String payload = String.format("%s/%s-payload number-%d", options.registryId, options.deviceId, i);
                System.out.format(
                        "Publishing %s message %d/%d: '%s'\n",
                        options.messageType, i, options.numMessages, payload);

                // Publish "payload" to the MQTT topic. qos=1 means at least once delivery. Cloud IoT Core
                // also supports qos=0 for at most once delivery.
                MqttMessage message = new MqttMessage(payload.getBytes());
                message.setQos(1);
                client.publish(mqttTopic, message);

                if (options.messageType.equals("event")) {
                    // Send telemetry events every second
                    Thread.sleep(1000);
                }
                else {
                    // Note: Update Device state less frequently than with telemetry events
                    Thread.sleep(5000);
                }
            }
        } finally {
            // Disconnect the client and finish the run.
            client.disconnect();
        }
        System.out.println("Finished loop successfully. Goodbye!");
        // [END cloudiotcore_mqtt_publish]
    }

}

and the MqttExampleOptions.java code:

package com.example.adityaprakash.test;

public class MqttExampleOptions {
    String projectId;
    String registryId;
    String deviceId;
    String privateKeyFile;
    String algorithm;
    String cloudRegion;
    int numMessages;
    String mqttBridgeHostname;
    short mqttBridgePort;
    String messageType;

    /** Construct an MqttExampleOptions class. */
    public static MqttExampleOptions values() {

        try {

            MqttExampleOptions res = new MqttExampleOptions();

            res.projectId = "_";
            res.registryId = "_";
            res.deviceId = "_";
            res.privateKeyFile = "com/example/adityaprakash/test/rsa_private.pem";
            res.algorithm = "RS256";
            res.cloudRegion = "asia-east1";
            res.numMessages = 100;
            res.mqttBridgeHostname = "mqtt.googleapis.com";
            res.mqttBridgePort = 8883;
            res.messageType = "event";
            return res;

        } catch (Exception e) {
            System.err.println(e.getMessage());
            return null;
        }
    }
}

Please can anyone give a solution to this problem.

P.S. I know the code looks totally crappy.I don't have experience with Android programming,so please let it go.


问:
How can i generate token in php using developer key , application id and username?
Anyone can describe how i generate token in php using developer key, application id and username.  Videyo provide only html js, they haven't any support for php.  Please  hint me. The token length is 200 plus.</p>

答:
Here is a sample php code to generate tokens. Don't forget to replace the $DEV_KEY and $APP_ID with your developer key and app Id, which you can find on - https://developer.vidyo.io/dashboard.
For username, don't add any special characters especially the "@" sysmbol. The code appends the appId to the username using "@", so if using that in the username that will mess up the decoding of the app Id.
For shorter or longer token duration change the $expiresInSecs value.</p>

```<code><!DOCTYPE html>
    <html>
      <head>
        <title>Token Generation php script</title>
      </head>
      <body>
        <p><?php echo "Token Generation Sample <br />";
        $DEV_KEY = "XXXXX" ;            // Copy your dev key from vidyo.io dashboard
        $APP_ID = "XXXXX.vidyo.io" ;    // Copy your app Id from vidyo.io dashboard
        $username = "Batman" ;          // Username, hard coded for debug purposes
        $expiresInSecs = 1000 ;         // Generated token will expire after these many seconds

        // time() by default subtracts datetime(1970, 1, 1) from the datetime
        // on which we call it, therefore the number of seconds is smaller
        // by (pseudocode!) seconds("1970-01-01").
        // In Erlang, on the other hand, we get the actual number of seconds,
        // hence we adjust for this difference here.
        // IMPORTANT! A 64bit architecture is assumed! Otherwise, the timestamp
        // might be stored as a 32bit integer, therefore limiting the "capacity"
        // to 2038 (see https://en.wikipedia.org/wiki/Year_2038_problem).
        $EPOCH_SECONDS = 62167219200 ;
        $expires = $EPOCH_SECONDS + $expiresInSecs + time();

        echo "<br />" ;
        echo "Developer key" . "\t" ."\t" ."\t" . ":" . $DEV_KEY . "<br />" ;
        echo "App ID          : " . $APP_ID . "<br />" ;
        echo "Username        : " . $username . "<br />" ;
        echo "Expires         : " . date("F j, Y, g:i a", $expiresInSecs + time()) . "<br />" ;

        $jid = $username . "@" . $APP_ID ;
        //echo "JID: " . $jid . "<br />" ;

        // Must place \0 within double quotes, not single quotes.
        $body = "provision" . "\0" . $jid . "\0" . $expires . "\0" . "" ;
        echo "BODY: " . $body . "<br />" ;

        // Important to convert to UTF8. I found this is what made the difference.
        $utf8_body = utf8_encode( $body ) ;
        echo "UTF8 BODY: " . $utf8_body . "<br />" ;

        // Ensure the SHA384 Algo is being used.
        $mac_hash = hash_hmac( "sha384", $utf8_body, $DEV_KEY ) ;
        echo "HMAC (384): " . $mac_hash . "<br />" ;

        // Again, ensure \0 are encapsulated with double quotes. Single quotes does not append the null character to the string
        $serialized = $utf8_body . "\0" . $mac_hash ;
        echo "SERIALIZED: " . $serialized . "<br />" ;

        // Base64 Encode the serialized string
        $b64_encoded = base64_encode( $serialized ) ;
        echo "<br /> B64 ENCODED TOKEN :<br /><br />" . $b64_encoded . "<br />" ;
    ?></p>
      </body>
    </html>
</code>```

Body:
Here is a sample php code to generate tokens. Don't forget to replace the $DEV_KEY and $APP_ID with your developer key and app Id, which you can find on - https://developer.vidyo.io/dashboard.
For username, don't add any special characters especially the "@" sysmbol. The code appends the appId to the username using "@", so if using that in the username that will mess up the decoding of the app Id.
For shorter or longer token duration change the $expiresInSecs value.

<!DOCTYPE html>
    <html>
      <head>
        <title>Token Generation php script</title>
      </head>
      <body>
        <p><?php echo "Token Generation Sample <br />";
        $DEV_KEY = "XXXXX" ;            // Copy your dev key from vidyo.io dashboard
        $APP_ID = "XXXXX.vidyo.io" ;    // Copy your app Id from vidyo.io dashboard
        $username = "Batman" ;          // Username, hard coded for debug purposes
        $expiresInSecs = 1000 ;         // Generated token will expire after these many seconds

        // time() by default subtracts datetime(1970, 1, 1) from the datetime
        // on which we call it, therefore the number of seconds is smaller
        // by (pseudocode!) seconds("1970-01-01").
        // In Erlang, on the other hand, we get the actual number of seconds,
        // hence we adjust for this difference here.
        // IMPORTANT! A 64bit architecture is assumed! Otherwise, the timestamp
        // might be stored as a 32bit integer, therefore limiting the "capacity"
        // to 2038 (see https://en.wikipedia.org/wiki/Year_2038_problem).
        $EPOCH_SECONDS = 62167219200 ;
        $expires = $EPOCH_SECONDS + $expiresInSecs + time();

        echo "<br />" ;
        echo "Developer key" . "\t" ."\t" ."\t" . ":" . $DEV_KEY . "<br />" ;
        echo "App ID          : " . $APP_ID . "<br />" ;
        echo "Username        : " . $username . "<br />" ;
        echo "Expires         : " . date("F j, Y, g:i a", $expiresInSecs + time()) . "<br />" ;

        $jid = $username . "@" . $APP_ID ;
        //echo "JID: " . $jid . "<br />" ;

        // Must place \0 within double quotes, not single quotes.
        $body = "provision" . "\0" . $jid . "\0" . $expires . "\0" . "" ;
        echo "BODY: " . $body . "<br />" ;

        // Important to convert to UTF8. I found this is what made the difference.
        $utf8_body = utf8_encode( $body ) ;
        echo "UTF8 BODY: " . $utf8_body . "<br />" ;

        // Ensure the SHA384 Algo is being used.
        $mac_hash = hash_hmac( "sha384", $utf8_body, $DEV_KEY ) ;
        echo "HMAC (384): " . $mac_hash . "<br />" ;

        // Again, ensure \0 are encapsulated with double quotes. Single quotes does not append the null character to the string
        $serialized = $utf8_body . "\0" . $mac_hash ;
        echo "SERIALIZED: " . $serialized . "<br />" ;

        // Base64 Encode the serialized string
        $b64_encoded = base64_encode( $serialized ) ;
        echo "<br /> B64 ENCODED TOKEN :<br /><br />" . $b64_encoded . "<br />" ;
    ?></p>
      </body>
    </html>


问:
Precisely scale image
I am trying to precisely and predictably scale an image in C# to a different resolution, both up and down. When I open the resulting images with external tools such as Gimp, the results are not satisfying with my current settings.

```<code>public Image Square(Image image, int res) {
    Bitmap sq = new Bitmap(res, res, image.PixelFormat);
    Graphics canvas = Graphics.FromImage(sq);
    canvas.CompositingQuality = CompositingQuality.HighQuality;
    canvas.SmoothingMode = SmoothingMode.None;
    canvas.InterpolationMode = InterpolationMode.Bicubic;
    canvas.DrawImage(sq, 0, 0, res, res);
    return sq;
}
</code>```

The results are okay when scaling down (but far from perfect), but there are side-effects when scaling up:

This picture has a resolution of 2x2 pixels. The alpha channel is set to opaque for all pixels.

After scaling it to 4x4 pixels, this is the result:

Apparently, the C# graphics library introduced transparency while scaling the picture. This method should still work if the given image has transparent pictures, so removing the alpha channel is not an option.

Similarly, when scaling pictures down, there are problems at the edges of the resulting images as well, usually either very dark or transparent.

Is there any way to circumvent this behavior?

Edit: I already tried NearestNeighbor for downscaling only, but it results in this:

Edit 2: With WrapMode.TileFlipXY, the transparent edge is gone, but red only makes up 25% of the image instead of 50% as it should be:

答:
I believe you need to combine NearestNeighbor interpolation with Half pixel offset. As pointed out in a similar question here.

```<code>canvas.InterpolationMode = InterpolationMode.NearestNeighbor;
canvas.PixelOffsetMode = PixelOffsetMode.Half;
</code>```

Title: Precisely scale image

Body:
I am trying to precisely and predictably scale an image in C# to a different resolution, both up and down. When I open the resulting images with external tools such as Gimp, the results are not satisfying with my current settings.

public Image Square(Image image, int res) {
    Bitmap sq = new Bitmap(res, res, image.PixelFormat);
    Graphics canvas = Graphics.FromImage(sq);
    canvas.CompositingQuality = CompositingQuality.HighQuality;
    canvas.SmoothingMode = SmoothingMode.None;
    canvas.InterpolationMode = InterpolationMode.Bicubic;
    canvas.DrawImage(sq, 0, 0, res, res);
    return sq;
}

The results are okay when scaling down (but far from perfect), but there are side-effects when scaling up:

This picture has a resolution of 2x2 pixels. The alpha channel is set to opaque for all pixels.

After scaling it to 4x4 pixels, this is the result:

Apparently, the C# graphics library introduced transparency while scaling the picture. This method should still work if the given image has transparent pictures, so removing the alpha channel is not an option.

Similarly, when scaling pictures down, there are problems at the edges of the resulting images as well, usually either very dark or transparent.

Is there any way to circumvent this behavior?

Edit: I already tried NearestNeighbor for downscaling only, but it results in this:

Edit 2: With WrapMode.TileFlipXY, the transparent edge is gone, but red only makes up 25% of the image instead of 50% as it should be:

Body:
I believe you need to combine NearestNeighbor interpolation with Half pixel offset. As pointed out in a similar question here.

canvas.InterpolationMode = InterpolationMode.NearestNeighbor;
canvas.PixelOffsetMode = PixelOffsetMode.Half;


问:
Compare 2 sets of data and paste any missing values on another sheet
So I have a master sheet with 1000+ rows and another sheet that "should" have the same data.  however, in reality sometimes some is missing from the master and sometimes some is missing from the query run.

for simplicity purposes let's say the unique ID is in column B.   here's my code but it's super slow and it only does a 1-way comparison.

My ideal code would be something that runs a little smoother and gives me the missing data from both the master and the query.

Is there's something wrong with the way I'm asking the question please let me know.

```<code>Sub FindMissing()

    Dim lastRowE As Integer
    Dim lastRowF As Integer
    Dim lastRowM As Integer
    Dim foundTrue As Boolean

    lastRowE = Sheets("Master").Cells(Sheets("Master").Rows.Count, "B").End(xlUp).Row
    lastRowF = Sheets("Qry").Cells(Sheets("Qry").Rows.Count, "B").End(xlUp).Row
    lastRowM = Sheets("Mismatch").Cells(Sheets("Mismatch").Rows.Count, "B").End(xlUp).Row

    For i = 1 To lastRowE
        foundTrue = False
        For j = 1 To lastRowF
            If Sheets("Master").Cells(i, 2).Value = Sheets("Qry").Cells(j, 2).Value Then
                foundTrue = True
                Exit For
            End If
        Next j
        If Not foundTrue Then
            Sheets("Master").Rows(i).Copy Destination:= _
            Sheets("Mismatch").Rows(lastRowM + 1)
            lastRowM = lastRowM + 1
        End If
    Next i

End Sub
</code>```

答:
Don't loop through the cells on the worksheet. Collect all of the values into variant arrays and process in-memory.

```<code>Option Explicit

Sub YouSuckAtVBA()

    Dim i As Long, mm As Long
    Dim valsM As Variant, valsQ As Variant, valsMM As Variant

    With Worksheets("Master")
        valsM = .Range(.Cells(1, "B"), .Cells(.Rows.Count, "B").End(xlUp)).Value2
    End With

    With Worksheets("Qry")
        valsQ = .Range(.Cells(1, "B"), .Cells(.Rows.Count, "B").End(xlUp)).Value2
    End With

    ReDim valsMM(1 To (UBound(valsM, 1) + UBound(valsQ, 1)), 1 To 2)
    mm = 1
    valsMM(mm, 1) = "value"
    valsMM(mm, 2) = "missing from"

    For i = LBound(valsM, 1) To UBound(valsM, 1)
        If IsError(Application.Match(valsM(i, 1), valsQ, 0)) Then
            mm = mm + 1
            valsMM(mm, 1) = valsM(i, 1)
            valsMM(mm, 2) = "qry"
        End If
    Next i

    For i = LBound(valsQ, 1) To UBound(valsQ, 1)
        If IsError(Application.Match(valsQ(i, 1), valsM, 0)) Then
            mm = mm + 1
            valsMM(mm, 1) = valsQ(i, 1)
            valsMM(mm, 2) = "master"
        End If
    Next i

    valsMM = helperResizeArray(valsMM, mm)

    With Worksheets("Mismatch")
        With .Cells(.Rows.Count, "A").End(xlUp).Offset(1, 0)
            .Resize(UBound(valsMM, 1), UBound(valsMM, 2)) = valsMM
        End With
    End With

End Sub

Function helperResizeArray(vals As Variant, x As Long)
    Dim arr As Variant, i As Long

    ReDim arr(1 To x, 1 To 2)

    For i = LBound(arr, 1) To UBound(arr, 1)
        arr(i, 1) = vals(i, 1)
        arr(i, 2) = vals(i, 2)
    Next i

    helperResizeArray = arr
End Function
</code>```

You cannot resize the first rank of a 2D array so I've added a helper function that will resize the results before putting them back into the Mismatch worksheet.

Body:
So I have a master sheet with 1000+ rows and another sheet that "should" have the same data.  however, in reality sometimes some is missing from the master and sometimes some is missing from the query run.

for simplicity purposes let's say the unique ID is in column B.   here's my code but it's super slow and it only does a 1-way comparison.

My ideal code would be something that runs a little smoother and gives me the missing data from both the master and the query.

Is there's something wrong with the way I'm asking the question please let me know.

Sub FindMissing()

    Dim lastRowE As Integer
    Dim lastRowF As Integer
    Dim lastRowM As Integer
    Dim foundTrue As Boolean

    lastRowE = Sheets("Master").Cells(Sheets("Master").Rows.Count, "B").End(xlUp).Row
    lastRowF = Sheets("Qry").Cells(Sheets("Qry").Rows.Count, "B").End(xlUp).Row
    lastRowM = Sheets("Mismatch").Cells(Sheets("Mismatch").Rows.Count, "B").End(xlUp).Row

    For i = 1 To lastRowE
        foundTrue = False
        For j = 1 To lastRowF
            If Sheets("Master").Cells(i, 2).Value = Sheets("Qry").Cells(j, 2).Value Then
                foundTrue = True
                Exit For
            End If
        Next j
        If Not foundTrue Then
            Sheets("Master").Rows(i).Copy Destination:= _
            Sheets("Mismatch").Rows(lastRowM + 1)
            lastRowM = lastRowM + 1
        End If
    Next i

End Sub

Body:
Don't loop through the cells on the worksheet. Collect all of the values into variant arrays and process in-memory.

Option Explicit

Sub YouSuckAtVBA()

    Dim i As Long, mm As Long
    Dim valsM As Variant, valsQ As Variant, valsMM As Variant

    With Worksheets("Master")
        valsM = .Range(.Cells(1, "B"), .Cells(.Rows.Count, "B").End(xlUp)).Value2
    End With

    With Worksheets("Qry")
        valsQ = .Range(.Cells(1, "B"), .Cells(.Rows.Count, "B").End(xlUp)).Value2
    End With

    ReDim valsMM(1 To (UBound(valsM, 1) + UBound(valsQ, 1)), 1 To 2)
    mm = 1
    valsMM(mm, 1) = "value"
    valsMM(mm, 2) = "missing from"

    For i = LBound(valsM, 1) To UBound(valsM, 1)
        If IsError(Application.Match(valsM(i, 1), valsQ, 0)) Then
            mm = mm + 1
            valsMM(mm, 1) = valsM(i, 1)
            valsMM(mm, 2) = "qry"
        End If
    Next i

    For i = LBound(valsQ, 1) To UBound(valsQ, 1)
        If IsError(Application.Match(valsQ(i, 1), valsM, 0)) Then
            mm = mm + 1
            valsMM(mm, 1) = valsQ(i, 1)
            valsMM(mm, 2) = "master"
        End If
    Next i

    valsMM = helperResizeArray(valsMM, mm)

    With Worksheets("Mismatch")
        With .Cells(.Rows.Count, "A").End(xlUp).Offset(1, 0)
            .Resize(UBound(valsMM, 1), UBound(valsMM, 2)) = valsMM
        End With
    End With

End Sub

Function helperResizeArray(vals As Variant, x As Long)
    Dim arr As Variant, i As Long

    ReDim arr(1 To x, 1 To 2)

    For i = LBound(arr, 1) To UBound(arr, 1)
        arr(i, 1) = vals(i, 1)
        arr(i, 2) = vals(i, 2)
    Next i

    helperResizeArray = arr
End Function

You cannot resize the first rank of a 2D array so I've added a helper function that will resize the results before putting them back into the Mismatch worksheet.


问:
passing a parameter to a service using ngclick AngularJS
Hey I have array of numbers, I am writing them using ng-repeat. When you click on some number should be pass to function passParameterToService parameter index and should be saved in service to variable this.whichBoard. But I have do something wrong, can someone tell me why ng-repeat don't work when I add service and why after click on some number, it's dont write to a variable?

```<code>demo
</code>```

https://codepen.io/Turqus/pen/WXEryN

答:
In your service you were declaring this.whichBoard but inside the function you again used the same named variable. If you set this.board inside, it would probably work:

```<code>app.service('serwis', ()=> {
  this.whichBoard = (index) => {
    this.board = index;
  };
});
</code>```

Also in the calling method, you have:

```<code><a href="#" ng-click="passParameterToService($index)">
  <span ng-repeat="item in arrayIndex">{{item}}</span>
</a>
</code>```

You're passing $index, which isn't a value. Also, you have the repeat inside the method call, so change it to:

```<code><div ng-repeat="item in arrayIndex track by $index">
  <a href="#" ng-click="passParameterToService(item)">{{item}}</a>
</div>
</code>```

Body:
Hey I have array of numbers, I am writing them using ng-repeat. When you click on some number should be pass to function passParameterToService parameter index and should be saved in service to variable this.whichBoard. But I have do something wrong, can someone tell me why ng-repeat don't work when I add service and why after click on some number, it's dont write to a variable?

demo

https://codepen.io/Turqus/pen/WXEryN

Body:
In your service you were declaring this.whichBoard but inside the function you again used the same named variable. If you set this.board inside, it would probably work:

app.service('serwis', ()=> {
  this.whichBoard = (index) => {
    this.board = index;
  };
});

Also in the calling method, you have:

<a href="#" ng-click="passParameterToService($index)">
  <span ng-repeat="item in arrayIndex">{{item}}</span>
</a>

You're passing $index, which isn't a value. Also, you have the repeat inside the method call, so change it to:

<div ng-repeat="item in arrayIndex track by $index">
  <a href="#" ng-click="passParameterToService(item)">{{item}}</a>
</div>


问:
Angularfire2 with firestore: delete specific fields from a document
As mentioned in the official documentation for web :

To delete specific fields from a document, use the FieldValue.delete() method when you update a document:

```<code>var cityRef = db.collection('cities').doc('BJ');

// Remove the 'capital' field from the document
var removeCapital = cityRef.update({
    capital: firebase.firestore.FieldValue.delete()
});
</code>```

I can't find a way to actually do it with angularfire2 (5.0.0-rc.3)

```<code>constructor(private firestore: AngularFirestore) {}

[...]

const cityRef = this.firestore.doc(`cities/BJ`);
cityRef.update({
  capital: this.firestore.FieldValue.delete()
});
</code>```

Cannot read property 'delete' of undefined

答:
Chances are you miss the imports

```<code>import * as firebase from 'firebase/app';
</code>```

now you can try

```<code>capital: firebase.firestore.FieldValue.delete()
</code>```

Body:
As mentioned in the official documentation for web :

To delete specific fields from a document, use the FieldValue.delete() method when you update a document:

var cityRef = db.collection('cities').doc('BJ');

// Remove the 'capital' field from the document
var removeCapital = cityRef.update({
    capital: firebase.firestore.FieldValue.delete()
});

I can't find a way to actually do it with angularfire2 (5.0.0-rc.3)

constructor(private firestore: AngularFirestore) {}

[...]

const cityRef = this.firestore.doc(`cities/BJ`);
cityRef.update({
  capital: this.firestore.FieldValue.delete()
});

Cannot read property 'delete' of undefined

Body:
Chances are you miss the imports

import * as firebase from 'firebase/app';

now you can try

capital: firebase.firestore.FieldValue.delete()


问:
How to delete a property from an Emberjs Object?
Plain old Javascript object properties can be deleted like so...

```<code>var foo = {bar: 'baz'};
delete foo.bar
</code>```

How do you delete (not just set to null) a property in an Ember object?

```<code>var foo = Ember.Object.create({bar: 'baz'});
</code>```

答:
```<code>foo.set('bar', undefined)
</code>```

This will delete the attribute and trigger any observer

Body:
Plain old Javascript object properties can be deleted like so...

var foo = {bar: 'baz'};
delete foo.bar

How do you delete (not just set to null) a property in an Ember object?

var foo = Ember.Object.create({bar: 'baz'});

Body:
foo.set('bar', undefined)

This will delete the attribute and trigger any observer


问:
how to stop opencv2 matrix from applying mod on arithmatic result
I have two opencv matrices A and B that have intensity values ranging from 0-255.
I am trying to do arithmetic operations on those matrices such that
C = A - B

```<code>A = cv2.imread('b.jpg',0)
B = cv2.imread('a.jpg',0)
C = np.zeros_like(A)
C = A - B
</code>```

The problem is that if I have A[0,0] =88 and B[0,0] = 184, then C[0,0] = 160.

I am assuming what happens is that it does (88-184)%256, but is there a way to make it so that it caps at 0 or 255?

Edit: Turns out I misunderstood how numpy works with opencv2. I didn't realize that numpy arrays can change type, and that what I was looking at was an overflow issue.
I casted my array into a float and it fixed my issues.

答: Use cv2.subtract() which doesn't roll over negative integer values.</p>

Body:
I have two opencv matrices A and B that have intensity values ranging from 0-255.
I am trying to do arithmetic operations on those matrices such that
C = A - B

A = cv2.imread('b.jpg',0)
B = cv2.imread('a.jpg',0)
C = np.zeros_like(A)
C = A - B

The problem is that if I have A[0,0] =88 and B[0,0] = 184, then C[0,0] = 160.

I am assuming what happens is that it does (88-184)%256, but is there a way to make it so that it caps at 0 or 255?

Edit: Turns out I misunderstood how numpy works with opencv2. I didn't realize that numpy arrays can change type, and that what I was looking at was an overflow issue.
I casted my array into a float and it fixed my issues.


问:
how solve merge dex?
i have this error when i try to run my android app

Error:Execution failed for task ':app:transformDexArchiveWithExternalLibsDexMergerForDebug'.
  java.lang.RuntimeException: java.lang.RuntimeException: com.android.builder.dexing.DexArchiveMergerException: Unable to merge dex

i tried to clean project and rebuild project and tried to remove project but the same error don't solve
  gradle

```<code>apply plugin: 'com.android.application'

android {
    compileSdkVersion 26
    defaultConfig {
        applicationId "com.example.lef.planeeye"
        minSdkVersion 14
        targetSdkVersion 26
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'com.android.support:appcompat-v7:26.1.0'
    implementation 'com.android.support.constraint:constraint-layout:1.0.2'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:1.0.1'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.1'
    compile 'com.google.android.gms:play-services:11.6.0'
    compile 'com.android.volley:volley:1.0.0'
    compile 'com.google.android.gms:play-services-location:11.6.0'
    compile 'com.google.android.gms:play-services-maps:11.6.0'
    compile 'com.android.support:design:26.1.0'
    compile 'com.google.firebase:firebase-core:11.6.0'
    compile 'com.google.firebase:firebase-messaging:11.6.0'
    compile 'com.firebase:firebase-client-android:2.5.2'
    compile 'com.firebaseui:firebase-ui:0.2.0'
}
</code>```

答:
You need to enable multidexing

set  multiDexEnabled true in your gradl.build file
and add compile 'com.android.support:multidex:1.0.1' to your dependencies
Here is an example from my app

```<code>android {
    compileSdkVersion 26
    buildToolsVersion '26.0.2'
    defaultConfig {
        multiDexEnabled true
        applicationId ""
        minSdkVersion 14
        targetSdkVersion 26
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
</code>```

Title: how solve merge dex?

Body:
i have this error when i try to run my android app

Error:Execution failed for task ':app:transformDexArchiveWithExternalLibsDexMergerForDebug'.
  java.lang.RuntimeException: java.lang.RuntimeException: com.android.builder.dexing.DexArchiveMergerException: Unable to merge dex

i tried to clean project and rebuild project and tried to remove project but the same error don't solve
  gradle

apply plugin: 'com.android.application'

android {
    compileSdkVersion 26
    defaultConfig {
        applicationId "com.example.lef.planeeye"
        minSdkVersion 14
        targetSdkVersion 26
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'com.android.support:appcompat-v7:26.1.0'
    implementation 'com.android.support.constraint:constraint-layout:1.0.2'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:1.0.1'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.1'
    compile 'com.google.android.gms:play-services:11.6.0'
    compile 'com.android.volley:volley:1.0.0'
    compile 'com.google.android.gms:play-services-location:11.6.0'
    compile 'com.google.android.gms:play-services-maps:11.6.0'
    compile 'com.android.support:design:26.1.0'
    compile 'com.google.firebase:firebase-core:11.6.0'
    compile 'com.google.firebase:firebase-messaging:11.6.0'
    compile 'com.firebase:firebase-client-android:2.5.2'
    compile 'com.firebaseui:firebase-ui:0.2.0'
}

Body:
You need to enable multidexing

set  multiDexEnabled true in your gradl.build file
and add compile 'com.android.support:multidex:1.0.1' to your dependencies
Here is an example from my app

android {
    compileSdkVersion 26
    buildToolsVersion '26.0.2'
    defaultConfig {
        multiDexEnabled true
        applicationId ""
        minSdkVersion 14
        targetSdkVersion 26
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }


问:
Write in memory object to S3 via boto3
I am attempting to write files directly to S3 without creating a local file which is then uploaded.

I am using cStringIO to generate a file in memory, but I am having trouble figuring out the proper way to upload it in boto3.

```<code>def writetos3(sourcedata, filename, folderpath):
     s3 = boto3.resource('s3')
     data = open(sourcedata, 'rb')
     s3.Bucket('bucketname').put_object(Key= folderpath + "/" + filename, Body=data)
</code>```

Above is the standard boto3 method that I was using previously with the local file, it does not work without a local file, I get the following error: coercing to Unicode: need string or buffer, cStringIO.StringO found
.

Because the in memory file (I believe) is already considered open, I tried changing it to the code below, but it still does not work, no error is given the script simply hangs on the last line of the method.

```<code>def writetos3(sourcedata, filename, folderpath):
    s3 = boto3.resource('s3')
    s3.Bucket('bucketname').put_object(Key= folderpath + "/" + filename, Body=sourcedata)
</code>```

Just for more info, the value I am attempting to write looks like this

(cStringIO.StringO object at 0x045DC540)

Does anyone have an idea of what I am doing wrong here?

答:
It looks like you want this:

```<code>    data = open(sourcedata, 'rb').decode()
</code>```

It defaults to utf8. Also, I encourage you to run your code under python3, and to use appropriate language tags for your question.

Title: Write in memory object to S3 via boto3

Body:
I am attempting to write files directly to S3 without creating a local file which is then uploaded.

I am using cStringIO to generate a file in memory, but I am having trouble figuring out the proper way to upload it in boto3.

def writetos3(sourcedata, filename, folderpath):
     s3 = boto3.resource('s3')
     data = open(sourcedata, 'rb')
     s3.Bucket('bucketname').put_object(Key= folderpath + "/" + filename, Body=data)

Above is the standard boto3 method that I was using previously with the local file, it does not work without a local file, I get the following error: coercing to Unicode: need string or buffer, cStringIO.StringO found
.

Because the in memory file (I believe) is already considered open, I tried changing it to the code below, but it still does not work, no error is given the script simply hangs on the last line of the method.

def writetos3(sourcedata, filename, folderpath):
    s3 = boto3.resource('s3')
    s3.Bucket('bucketname').put_object(Key= folderpath + "/" + filename, Body=sourcedata)

Just for more info, the value I am attempting to write looks like this

(cStringIO.StringO object at 0x045DC540)

Does anyone have an idea of what I am doing wrong here?

Body:
It looks like you want this:

    data = open(sourcedata, 'rb').decode()

It defaults to utf8. Also, I encourage you to run your code under python3, and to use appropriate language tags for your question.


问:
Model is not appearing in three.js
I have been trying various options for all day to solve my problem. I was also trying various examples posted here in previous years. Although my problem is still unsolved and my objects are not appearing.

I was trying 3 different formats: .json, .js and now .mtl with.obj. My current code looks like this:

```<code>function addModels() {
var mtlLoader = new THREE.MTLLoader();

mtlLoader.load("../models/lampa.mtl", function (materials) {
    materials.preload();

    var objLoader = new THREE.OBJLoader();

    objLoader.setMaterials(materials);
    objLoader.load("../models/lampa.obj", function (mesh) {
        mesh.scale.set(1,1,1);
        mesh.position.set(0,0,0);

        scene.add(mesh);
    })
})
</code>```

And this is html file with the script running canvas.

```<code>   var camera;
var scene;
var renderer = new THREE.WebGLRenderer();
var controls;

//Simple functions to initialise scene and render it.
initialise();
render();
//animate();

//add models
addModels();

function initialise() {

    // Create a scene
    scene = new THREE.Scene();

    // Add the camera
    camera = new THREE.PerspectiveCamera( 70, window.innerWidth / window.innerHeight, 1, 1000);
    camera.position.set(0, 100, 250);

    // Add scene elements
    addWalls();
    addKerbs();
    // Add lights
    addLights();
    // Create the WebGL Renderer
    renderer = new THREE.WebGLRenderer();
    renderer.setSize( window.innerWidth, window.innerHeight );

    //add Grass
    createGrass();
    addGrass();

    // Append the renderer to the body
    document.body.appendChild( renderer.domElement );

    // Add a resize event listener
    window.addEventListener( 'resize', Resize, false );

    // Add the orbit controls
    controls = new THREE.OrbitControls(camera, renderer.domElement);
    controls.target = new THREE.Vector3(0, 100, 0);
}

//rendering function
function render() {
    renderer.render( scene, camera );
    requestAnimationFrame( render );
    controls.update();
}

//Window resize.
function Resize() {
    camera.aspect = window.innerWidth / window.innerHeight;
    camera.updateProjectionMatrix();
    renderer.setSize( window.innerWidth, window.innerHeight );
}

function animate() {
    requestAnimationFrame(animate);
    render();
    status.update();
    renderer.render(scene,camera);
}
</code>```

When addModels() is in initialise function, but it throws an error like this:

Every answer is appreciated. Thank you.

答: I am really sorry for every trouble. It appears that everything is fine here, just three.js was out of date... </p>

Title: Model is not appearing in three.js

Body:
I have been trying various options for all day to solve my problem. I was also trying various examples posted here in previous years. Although my problem is still unsolved and my objects are not appearing.

I was trying 3 different formats: .json, .js and now .mtl with.obj. My current code looks like this:

function addModels() {
var mtlLoader = new THREE.MTLLoader();

mtlLoader.load("../models/lampa.mtl", function (materials) {
    materials.preload();

    var objLoader = new THREE.OBJLoader();

    objLoader.setMaterials(materials);
    objLoader.load("../models/lampa.obj", function (mesh) {
        mesh.scale.set(1,1,1);
        mesh.position.set(0,0,0);

        scene.add(mesh);
    })
})

And this is html file with the script running canvas.

   var camera;
var scene;
var renderer = new THREE.WebGLRenderer();
var controls;

//Simple functions to initialise scene and render it.
initialise();
render();
//animate();

//add models
addModels();

function initialise() {

    // Create a scene
    scene = new THREE.Scene();

    // Add the camera
    camera = new THREE.PerspectiveCamera( 70, window.innerWidth / window.innerHeight, 1, 1000);
    camera.position.set(0, 100, 250);

    // Add scene elements
    addWalls();
    addKerbs();
    // Add lights
    addLights();
    // Create the WebGL Renderer
    renderer = new THREE.WebGLRenderer();
    renderer.setSize( window.innerWidth, window.innerHeight );

    //add Grass
    createGrass();
    addGrass();

    // Append the renderer to the body
    document.body.appendChild( renderer.domElement );

    // Add a resize event listener
    window.addEventListener( 'resize', Resize, false );

    // Add the orbit controls
    controls = new THREE.OrbitControls(camera, renderer.domElement);
    controls.target = new THREE.Vector3(0, 100, 0);
}

//rendering function
function render() {
    renderer.render( scene, camera );
    requestAnimationFrame( render );
    controls.update();
}

//Window resize.
function Resize() {
    camera.aspect = window.innerWidth / window.innerHeight;
    camera.updateProjectionMatrix();
    renderer.setSize( window.innerWidth, window.innerHeight );
}

function animate() {
    requestAnimationFrame(animate);
    render();
    status.update();
    renderer.render(scene,camera);
}

When addModels() is in initialise function, but it throws an error like this:

Every answer is appreciated. Thank you.


问:
C# triangle of numbers descending
I am working on one job and i need your help. I need triangle of numbers, just like the one on the bottom. I know there is perhaps only one or maybe two steps to solution, but i am struggling with this problem for hours..

My code so far is:

```<code>        for (int i = 1; i <= 9; i++)
        {
            for (int k = 1; k <= i; k++)
            {
                Console.Write(k);
            }
            Console.WriteLine("");
        }
</code>```

1

21

321

4321

54321

654321

7654321

87654321

987654321

答:
If you want to print your numbers from the biggest to the smallest you have to make your second loop that way. Currently your second loop prints from 1 to i, but you want to print them in decreasing order, so it makes sense to print them from i to 1 like this:

```<code>for (int i = 1; i <= 9; i++)
{
    for (int k = i; k >= 1; k--)
    {
        Console.Write(k);
    }
    Console.WriteLine("");
}
</code>```

Title: C# triangle of numbers descending

Body:
I am working on one job and i need your help. I need triangle of numbers, just like the one on the bottom. I know there is perhaps only one or maybe two steps to solution, but i am struggling with this problem for hours..

My code so far is:

        for (int i = 1; i <= 9; i++)
        {
            for (int k = 1; k <= i; k++)
            {
                Console.Write(k);
            }
            Console.WriteLine("");
        }

1

21

321

4321

54321

654321

7654321

87654321

987654321

Body:
If you want to print your numbers from the biggest to the smallest you have to make your second loop that way. Currently your second loop prints from 1 to i, but you want to print them in decreasing order, so it makes sense to print them from i to 1 like this:

for (int i = 1; i <= 9; i++)
{
    for (int k = i; k >= 1; k--)
    {
        Console.Write(k);
    }
    Console.WriteLine("");
}


问:
xcode Resolve "Safe Area Layout" errors

What is the correct way to stop this error?

For now I'm merely unchecking "Use Safe Area Layout Guides" which allows me to compile the app without error.

答: Try closing and then reopening Xcode. </p>

Title: xcode Resolve "Safe Area Layout" errors

Body: Try closing and then reopening Xcode.


问:
ExtentReport is not generated in Selenium testNG
I have planned to customize the testNG reports. So I have used ExtentReports with the below codes.

Selenium runs properly without any issues but the report is not generated in the specified folder location.

I have added ExtentReport 2.41.2 maven dependency in my pom.xml file.

Sample Code:

```<code>public class ExtentA
{
     public static ExtentReports extent;
     public static ExtentTest logger;
     public static WebDriver driver;

     @BeforeSuite
     public void config()
     {
        extent = new ExtentReports("E:/Automation/MyReport.html", true);
        extent.loadConfig(new File("E:/Automation/extentreports-java-2.41.2/extentreports-java-2.41.2/extent-config.xml"));
     }

     @BeforeMethod
     public void beforeMtd(Method method)
     {
        logger = extent.startTest("sample", "test case desc");
        logger.assignAuthor("Mohan");

     }

     @Test
     public void sample()
     {
        System.setProperty("webdriver.chrome.driver", "C:/selenium/drivers/chromedriver.exe");
        driver = new ChromeDriver();
        driver.get("https://www.google.co.in");
        logger.log(LogStatus.PASS, "Browser Launched successfully");
        System.out.println("Browser launched");
        driver.manage().window().maximize();
     }

     @AfterMethod
     public void close()
     {
        driver.close();
        driver.quit();
        extent.endTest(logger);
     }
}
</code>```

Before running the test case, I have created the html file in loca, but the report is not generated.

答: Add extent.flush(); to the end of your close method.

Body:
I have planned to customize the testNG reports. So I have used ExtentReports with the below codes.

Selenium runs properly without any issues but the report is not generated in the specified folder location.

I have added ExtentReport 2.41.2 maven dependency in my pom.xml file.

Sample Code:

public class ExtentA
{
     public static ExtentReports extent;
     public static ExtentTest logger;
     public static WebDriver driver;

     @BeforeSuite
     public void config()
     {
        extent = new ExtentReports("E:/Automation/MyReport.html", true);
        extent.loadConfig(new File("E:/Automation/extentreports-java-2.41.2/extentreports-java-2.41.2/extent-config.xml"));
     }

     @BeforeMethod
     public void beforeMtd(Method method)
     {
        logger = extent.startTest("sample", "test case desc");
        logger.assignAuthor("Mohan");

     }

     @Test
     public void sample()
     {
        System.setProperty("webdriver.chrome.driver", "C:/selenium/drivers/chromedriver.exe");
        driver = new ChromeDriver();
        driver.get("https://www.google.co.in");
        logger.log(LogStatus.PASS, "Browser Launched successfully");
        System.out.println("Browser launched");
        driver.manage().window().maximize();
     }

     @AfterMethod
     public void close()
     {
        driver.close();
        driver.quit();
        extent.endTest(logger);
     }
}

Before running the test case, I have created the html file in loca, but the report is not generated.


问:
Total sum of all multiplied values of textboxes
I want to multiply the textbox values and after multiplication sum of all answer values. Example:

```<code>SUM (NSP * Current Sales)
</code>```

This program is working fine but when I change any value it adds the change not replace the values. It should replace the value of array.

And if possible, please minimize the code logic also. Thanks.

$(document).ready(function() {
  var val1;
  var val2;
  var multi;
  one();
  second();
});

function one() {
  $(document).on("change", ".qty1", function() {
    var sumqty1 = 0;
    sumqty1 += $(this).val();
    val1 = sumqty1;
  });
}

function second() {
  $(document).on("change", ".qty2", function() {
    var sumqty1 = 0;
    var sumqty2 = 0;
    sumqty1 += $(this).closest('tr').find('.qty1').val();
    sumqty2 += $(this).val();
    val1 = sumqty1;
    val2 = sumqty2;
    mul(val1, val2);
  });
}
var arr = [];

function mul(a, b) {
  var hh;
  multi = a * b;
  arr.push(multi);
  var totalsum = 0;
  for (var i in arr) {
    var value = arr[i];
    totalsum = parseInt(totalsum, 10) + parseInt(value, 10);
    $("#totalvalue").text(totalsum);
  }
  console.log(arr);
}```
<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>
<table style="width: 100%;" width="100%" cellspacing="0">
  <thead>
    <tr>
      <th>Product Name</th>
      <th>NSP</th>
      <th>Current Sales</th>
      <th>Closing Balance</th>
    </tr>
  </thead>
  <tfoot>
    <tr>
      <th>Product Name</th>
      <th>NSP</th>
      <th>Current Sales</th>
      <th><span id='totalvalue'></span></th>
    </tr>
  </tfoot>
  <tbody>
    <tr>

      <td>Satou</td>
      <td><input type="text" class="qty1" value="1" disabled /></td>
      <td><input type="text" class="qty2" value="" /></td>
      <td>23</td>
    </tr>
    <tr>
      <td>panadol</td>
      <td><input type="text" class="qty1" value="2" disabled /></td>
      <td><input type="text" class="qty2" value="" /></td>
      <td>131</td>
    </tr>
    <tr>
      <td>disprine</td>
      <td><input type="text" class="qty1" value="3" disabled/></td>
      <td><input type="text" class="qty2" value="" /></td>
      <td>37</td>
    </tr>
    <tr>
      <td>panadol</td>
      <td><input type="text" class="qty1" value="4" disabled /></td>
      <td><input type="text" class="qty2" value="" /></td>
      <td>173</td>
    </tr>
  </tbody>
</table></code>```

答:
Id say something like:

```<code>$(".qty1, .qty2").on("change", function(){
    var qty2 = $(".qty2"),
        total = 0;
    $(".qty1").each(function(ind){
        total += $(qty2[ind]).val() * $(this).val();
    })
    $("#totalvalue").text(total)
})
</code>```

Added at the end of the document.

Edited a little

Body:
I want to multiply the textbox values and after multiplication sum of all answer values. Example:

SUM (NSP * Current Sales)

This program is working fine but when I change any value it adds the change not replace the values. It should replace the value of array.

And if possible, please minimize the code logic also. Thanks.

$(document).ready(function() {
  var val1;
  var val2;
  var multi;
  one();
  second();
});

function one() {
  $(document).on("change", ".qty1", function() {
    var sumqty1 = 0;
    sumqty1 += $(this).val();
    val1 = sumqty1;
  });
}

function second() {
  $(document).on("change", ".qty2", function() {
    var sumqty1 = 0;
    var sumqty2 = 0;
    sumqty1 += $(this).closest('tr').find('.qty1').val();
    sumqty2 += $(this).val();
    val1 = sumqty1;
    val2 = sumqty2;
    mul(val1, val2);
  });
}
var arr = [];

function mul(a, b) {
  var hh;
  multi = a * b;
  arr.push(multi);
  var totalsum = 0;
  for (var i in arr) {
    var value = arr[i];
    totalsum = parseInt(totalsum, 10) + parseInt(value, 10);
    $("#totalvalue").text(totalsum);
  }
  console.log(arr);
}

      Product Name
      NSP
      Current Sales
      Closing Balance

      Product Name
      NSP
      Current Sales

      Satou
      <input type="text" class="qty1" value="1" disabled />
      <input type="text" class="qty2" value="" />
      23

      panadol
      <input type="text" class="qty1" value="2" disabled />
      <input type="text" class="qty2" value="" />
      131

      disprine
      <input type="text" class="qty1" value="3" disabled/>
      <input type="text" class="qty2" value="" />
      37

      panadol
      <input type="text" class="qty1" value="4" disabled />
      <input type="text" class="qty2" value="" />
      173

Body:
Id say something like:

$(".qty1, .qty2").on("change", function(){
    var qty2 = $(".qty2"),
        total = 0;
    $(".qty1").each(function(ind){
        total += $(qty2[ind]).val() * $(this).val();
    })
    $("#totalvalue").text(total)
})

Added at the end of the document.

Edited a little


问:
Converting Assembly Language to Python Code
I am trying to convert assembly language to Python.  I'm trying to follow the assembly code as literally as possible when I do this. I know this particular code will require nested conditional statements. I'm using a,b,c,d as memory locations.

Here is the assembly language:

```<code>    0   IN a
    1   LOAD d
    2   COMPARE a
    3   JUMPLT 6
    4   JUMPEQ 6
    5   JUMPGT 12
    6   OUT c
    7   LOAD a
    8   ADD b
    9   STORE c
    10  DECREMENT d
    11  JUMP 20
    12  DECREMENT c
    13  LOAD a
    14  COMPARE c
    15  JUMPLT 19
    16  JUMPEQ 19
    17  INCREMENT d
    18  CLEAR c
    19  OUT d
    20  OUT b
    21  HALT
</code>```

This is my literal translation of the code into Python.

```<code>      a = input()

      if a<=d:
        print c
        c = a+b
        d = d-1
        print b

      else:
        c = c-1
        if c<=a:
          print d
          print b

        else:
          d=d+1
          c=0
          print d
          print b
</code>```

I see that print d and print b are included in the if and else nested statements so if I'm not doing a literal translation of the code, maybe it should look like this?

```<code>      a = input()

      if a<=d:
        print c
        c = a+b
        d = d-1
        print b

      else:
        c = c-1
        print d
        print b

        if c>a:
          d=d+1
          c=0
</code>```

And my final questions: are either of these translations correct?  They don't evaluate the same way.  Also are there better ways to do this translation?

Any other tips or rules to keep in mind about these conversions would be welcome.

Thanks in advance for your help.

答:
Yeah the part I looked at looks correct to me.  However, it would be more accurate to put print b after the if/else block because all the execution paths merge before it.

The asm is clunky (e.g. leave out the first two conditional branches so JUMPGT 12 either jumps or falls through), so yes there's lots of room to simply it and/or the Python.  Beginners very frequently write inefficient branching that jumps one way or the other, instead of just jumping or falling through.

Body:
I am trying to convert assembly language to Python.  I'm trying to follow the assembly code as literally as possible when I do this. I know this particular code will require nested conditional statements. I'm using a,b,c,d as memory locations.

Here is the assembly language:

    0   IN a
    1   LOAD d
    2   COMPARE a
    3   JUMPLT 6
    4   JUMPEQ 6
    5   JUMPGT 12
    6   OUT c
    7   LOAD a
    8   ADD b
    9   STORE c
    10  DECREMENT d
    11  JUMP 20
    12  DECREMENT c
    13  LOAD a
    14  COMPARE c
    15  JUMPLT 19
    16  JUMPEQ 19
    17  INCREMENT d
    18  CLEAR c
    19  OUT d
    20  OUT b
    21  HALT

This is my literal translation of the code into Python.

      a = input()

      if a<=d:
        print c
        c = a+b
        d = d-1
        print b

      else:
        c = c-1
        if c<=a:
          print d
          print b

        else:
          d=d+1
          c=0
          print d
          print b

I see that print d and print b are included in the if and else nested statements so if I'm not doing a literal translation of the code, maybe it should look like this?

      a = input()

      if a<=d:
        print c
        c = a+b
        d = d-1
        print b

      else:
        c = c-1
        print d
        print b

        if c>a:
          d=d+1
          c=0

And my final questions: are either of these translations correct?  They don't evaluate the same way.  Also are there better ways to do this translation?

Any other tips or rules to keep in mind about these conversions would be welcome.

Thanks in advance for your help.


问:
How to add a custom column in Tasks section on Pulse in Magnolia
Good morning, i am a fairly new person at Magnolia and i have the need to improve a web by showing more data at the Task section of Pulse in Magnolia, to be able to do that i need to create a couple of columns but after trying to find some information at Magnolia documentation y have only been able to find this "Add custom column to Inbox", but unfortunately is outdated and the Inbox class that makes reference is not used anymore in the newers versions of Magnolia.

Could somebody help me and explain to me how to create these columns at the Tasks section of Pulse in Magnolia?, or point me in the rigth direction?.

Im using the Magnolia version 5.3 with a Maven setup, thanks in advance for the help.

答:
I'm not sure I yet follow what you're trying to achieve.  Do you want to add a column to a view, as in one of these images?

If not, could you please make some kind of mockup of what you hope to achieve?

Is there some reason you are using such an old (> 2 years) version of Magnolia? If not, perhaps I could also help you migrate to the latest and greatest (5.5.7)?

Thanks for the help,