问:
Can I store a list of objects to SQLite instead on breaking up the list and adding the objects individually?
I am storing a list of objects of a class to a SQLite table. The class has 30 strings and I have roughly 6000 objects of the class in my List. It's only 6MB. Breaking up this list and storing that takes almost a minute. But can I store the entire list as one? Here is my code so far: </p>

```<code>    List<TheClass> ListOfObjects;

    public static void AddAllObjects() {
        for (int i = 0; i < ListOfObjects.Count; i++) {
            AddObject(ListOfObjects[i]);
        }
    }

    public static void AddObject(Object obj) {
        database.SaveItem(obj);
    }

    public void SaveItem<T>(T item) {
        connection.Insert(item);
    }
</code>```

答:
Object SQLiteConnection of sqlite-net has the method InsertAll.

```<code>List<Object> models = new List<Object>();
// ...
// LocalConnection conn = ...;
SQLiteConnection db = conn.GetSQLiteConnection();
db.InsertAll(models,true); // the true means "run in transaction"
</code>```

https://github.com/oysteinkrog/SQLite.Net-PCL/blob/master/src/SQLite.Net/SQLiteConnection.cs

By the way it's implemented as a foreach inside a transaction, so I guess it's the only way, at least using sqlite-net.

Body:
I am storing a list of objects of a class to a SQLite table. The class has 30 strings and I have roughly 6000 objects of the class in my List. It's only 6MB. Breaking up this list and storing that takes almost a minute. But can I store the entire list as one? Here is my code so far:

    List<TheClass> ListOfObjects;

    public static void AddAllObjects() {
        for (int i = 0; i < ListOfObjects.Count; i++) {
            AddObject(ListOfObjects[i]);
        }
    }

    public static void AddObject(Object obj) {
        database.SaveItem(obj);
    }

    public void SaveItem<T>(T item) {
        connection.Insert(item);
    }

Body:
Object SQLiteConnection of sqlite-net has the method InsertAll.

List<Object> models = new List<Object>();
// ...
// LocalConnection conn = ...;
SQLiteConnection db = conn.GetSQLiteConnection();
db.InsertAll(models,true); // the true means "run in transaction"

https://github.com/oysteinkrog/SQLite.Net-PCL/blob/master/src/SQLite.Net/SQLiteConnection.cs

By the way it's implemented as a foreach inside a transaction, so I guess it's the only way, at least using sqlite-net.


来源: stackexchange

问:
Codeigniter : how to update mulitiple record where id
I have been looking for ways but find suitable speckle. so, i have table product and I show along with his ID. and I put in a form. and when I press the update button then what had been updated in the form of their corresponding id.

my view :

```<code><?php echo form_open('stock/updating_stock');?>
  <div class="panel-body scroll-menu" style="margin-top:0px;height:170px;padding-top:5px;">
    <?php foreach($critical_plus_warning as $data){?>
      <input type="hidden" name="id_product[]" value="<?php echo $data->id_product;?>">
      <h5 class="hidden-xs"><b><?php echo $data->product_name;?></b> <input type="text" class="pull-right" style="width:10%;margin-left:10px;text-align:center;" name="update_stock[]" value="<?php echo $data->stock?>">
      <?php
      $stock = $data->stocks;
      if($stock < 10){
        echo "<label style='font-size:13px;' class='label label-danger pull-right'>$stock</label>";
      }else{
        echo "<label style='font-size:13px;' class='label label-warning pull-right'>$stock</label>";
      }
      ?>
      </h5>
      <h5 class="hidden-lg"><b><?php $limited_word = word_limiter($data->product_name,3); echo $limited_word; ?></b> <input class="pull-right" type="text" style="width:10%;margin-left:10px;text-align:center;" name="update_stock[]" value="<?php echo $data->stocks?>">
      <?php
      $stock = $data->stocks;
      if($stock < 10){
        echo "<label style='font-size:13px;' class='label label-danger pull-right'>$stock</label>";
      }else{
        echo "<label style='font-size:13px;' class='label label-warning pull-right'>$stock</label>";
      }
      ?>
      </h5>
    <?php }?>
  </div>
  <div class="col-xs-12" style="margin-top:-5px;background-color:white;padding:6px;background-color:white;box-shadow:0px 0px 8px 0px #bababa;"><button type="submit" name="submit" class="btn btn-success">Save data</button></div>
  <?php echo form_close();?>
</code>```

and my controller :

```<code>function updating_stock(){

    $id = $this->input->post('id_product');
    $stok = $this->input->post('update_stock');
    $user = $this->data['id'];

    for($i=0;$i<count($id);$i++){
    $data = array(
       array(
        'id'        => $id,
        'stok'      => $stok,
        'diubah'    => $user,
        'tgl_diubah'=> date('Y:m:d H:i:s'),
        ),
    );
    }
    //print_r($data);
    $this->stok_adm->update_stok($data);
}
</code>```

and my models :

```<code>function update_stok($data){
    $this->db->update_batch($this->table, $data,'id_product');
    return $this->db->affected_rows();
}
</code>```

答:
```<code>$data = array(
   array(
      'title' => 'My title' ,
      'name' => 'My Name 2' ,
      'date' => 'My date 2'
   ),
   array(
      'title' => 'Another title' ,
      'name' => 'Another Name 2' ,
      'date' => 'Another date 2'
   )
);

$this->db->update_batch('mytable', $data, 'title');
</code>```

http://www.codeigniter.com/user_guide/database/query_builder.html?highlight=update_batch

ContentLicense: CC BY-SA 3.0

Body:
I have been looking for ways but find suitable speckle. so, i have table product and I show along with his ID. and I put in a form. and when I press the update button then what had been updated in the form of their corresponding id.

my view :

<?php echo form_open('stock/updating_stock');?>

    <?php foreach($critical_plus_warning as $data){?>
      <input type="hidden" name="id_product[]" value="<?php echo $data->id_product;?>">

<?php echo $data->product_name;?> <input type="text" class="pull-right" style="width:10%;margin-left:10px;text-align:center;" name="update_stock[]" value="<?php echo $data->stock?>">
      <?php
      $stock = $data->stocks;
      if($stock < 10){
        echo "$stock";
      }else{
        echo "$stock";
      }
      ?>

<?php $limited_word = word_limiter($data->product_name,3); echo $limited_word; ?> <input class="pull-right" type="text" style="width:10%;margin-left:10px;text-align:center;" name="update_stock[]" value="<?php echo $data->stocks?>">
      <?php
      $stock = $data->stocks;
      if($stock < 10){
        echo "$stock";
      }else{
        echo "$stock";
      }
      ?>

    <?php }?>

<button type="submit" name="submit" class="btn btn-success">Save data</button>

  <?php echo form_close();?>

and my controller :

function updating_stock(){

    $id = $this->input->post('id_product');
    $stok = $this->input->post('update_stock');
    $user = $this->data['id'];

    for($i=0;$i<count($id);$i++){
    $data = array(
       array(
        'id'        => $id,
        'stok'      => $stok,
        'diubah'    => $user,
        'tgl_diubah'=> date('Y:m:d H:i:s'),
        ),
    );
    }
    //print_r($data);
    $this->stok_adm->update_stok($data);
}

and my models :

function update_stok($data){
    $this->db->update_batch($this->table, $data,'id_product');
    return $this->db->affected_rows();
}

Body:
$data = array(
   array(
      'title' => 'My title' ,
      'name' => 'My Name 2' ,
      'date' => 'My date 2'
   ),
   array(
      'title' => 'Another title' ,
      'name' => 'Another Name 2' ,
      'date' => 'Another date 2'
   )
);

$this->db->update_batch('mytable', $data, 'title');

http://www.codeigniter.com/user_guide/database/query_builder.html?highlight=update_batch


问:
" where in " mysql clause
i used a mysql query where there is "where id in ("22,20,21") "
but when i get the result its like array ordered in asecending order ie  20,21,20

but i need it in the same order as i gave the clause

答: You cannot specify the order results will be returned in in a WHERE clause. If you want to specify order, you need to add an ORDER BY clause to your query. For a solution that uses FIND_IN_SET see this answer.

ContentLicense: CC BY-SA 2.5

Title: " where in " mysql clause


问:
Python3 'ascii' codec can't encode character
I am trying to rename a file with non unicode chars in name.

```<code>import os

dir = b'/tr2'

for file_name in os.listdir(dir):
    file_name = file_name.decode('utf8','replace')
    print(file_name)
    os.rename(file_name,'11.txt')
</code>```

Can only print this name, but when I try to rename, I get the error:

```<code>UnicodeEncodeError: 'ascii' codec can't encode character '\xf1' in position 11: ordinal not in range(128)
</code>```

答:
The problem was in that I needed to display the value of the file_name and work with it later in the program. So thanks to Martin Evans the decision in the next:</p>

```<code>import os

dir = b'/tr2'

for file_name in os.listdir(dir):

print(file_name.decode('utf8','replace'))

os.rename(os.path.join(dir, file_name), os.path.join(dir, b'11.txt'))
</code>```

Body:
I am trying to rename a file with non unicode chars in name.

import os

dir = b'/tr2'

for file_name in os.listdir(dir):
    file_name = file_name.decode('utf8','replace')
    print(file_name)
    os.rename(file_name,'11.txt')

Can only print this name, but when I try to rename, I get the error:

UnicodeEncodeError: 'ascii' codec can't encode character '\xf1' in position 11: ordinal not in range(128)

Body:
The problem was in that I needed to display the value of the file_name and work with it later in the program. So thanks to Martin Evans the decision in the next:

import os

dir = b'/tr2'

for file_name in os.listdir(dir):

print(file_name.decode('utf8','replace'))

os.rename(os.path.join(dir, file_name), os.path.join(dir, b'11.txt'))


问:
C# Broadcast is UDP message, listen for multiple replies
I am trying to write some code that does a UDP broadcast, and then listens to replies from remote servers saying they exist. It's used to identify machines running a server app on the subnet so basically sends out a "who's there?" and listens for all the replies.

I have this in Java (works perfectly) where it sends a DatagramPacket broadcasting to a group address of 224.168.101.200. and then has a worker thread that keeps listening for incoming DatagramPackets coming in on the same socket.

This and this are not the answer as they say how to have the send and listen on different machines.

答:
Just made a working example for you, you could compare what went wrong. I created a windows forms applications with 2 textboxes and a button.</p>

```<code>public partial class Form1 : Form
{
    private int _port = 28000;

    private string _multicastGroupAddress = "239.1.1.1";

    private UdpClient _sender;
    private UdpClient _receiver;

    private Thread _receiveThread;

    private void UpdateMessages(IPEndPoint sender, string message)
    {
        textBox1.Text += $"{sender} | {message}\r\n";
    }

    public Form1()
    {
        InitializeComponent();

        _receiver = new UdpClient();
        _receiver.JoinMulticastGroup(IPAddress.Parse(_multicastGroupAddress));
        _receiver.Client.Bind(new IPEndPoint(IPAddress.Any, _port));

        _receiveThread = new Thread(() =>
        {
            while (true)
            {
                IPEndPoint sentBy = new IPEndPoint(IPAddress.Any, _port);
                var dataGram = _receiver.Receive(ref sentBy);

                textBox1.BeginInvoke(
                    new Action<IPEndPoint, string>(UpdateMessages),
                    sentBy,
                    Encoding.UTF8.GetString(dataGram));
            }
        });
        _receiveThread.IsBackground = true;
        _receiveThread.Start();

        _sender = new UdpClient();
        _sender.JoinMulticastGroup(IPAddress.Parse(_multicastGroupAddress));
    }

    private void button1_Click(object sender, EventArgs e)
    {
        var data = Encoding.UTF8.GetBytes(textBox2.Text);
        _sender.Send(data, data.Length, new IPEndPoint(IPAddress.Broadcast, _port));
    }
}
</code>```

Body:
Just made a working example for you, you could compare what went wrong. I created a windows forms applications with 2 textboxes and a button.

public partial class Form1 : Form
{
    private int _port = 28000;

    private string _multicastGroupAddress = "239.1.1.1";

    private UdpClient _sender;
    private UdpClient _receiver;

    private Thread _receiveThread;

    private void UpdateMessages(IPEndPoint sender, string message)
    {
        textBox1.Text += $"{sender} | {message}\r\n";
    }

    public Form1()
    {
        InitializeComponent();

        _receiver = new UdpClient();
        _receiver.JoinMulticastGroup(IPAddress.Parse(_multicastGroupAddress));
        _receiver.Client.Bind(new IPEndPoint(IPAddress.Any, _port));

        _receiveThread = new Thread(() =>
        {
            while (true)
            {
                IPEndPoint sentBy = new IPEndPoint(IPAddress.Any, _port);
                var dataGram = _receiver.Receive(ref sentBy);

                textBox1.BeginInvoke(
                    new Action<IPEndPoint, string>(UpdateMessages),
                    sentBy,
                    Encoding.UTF8.GetString(dataGram));
            }
        });
        _receiveThread.IsBackground = true;
        _receiveThread.Start();

        _sender = new UdpClient();
        _sender.JoinMulticastGroup(IPAddress.Parse(_multicastGroupAddress));
    }

    private void button1_Click(object sender, EventArgs e)
    {
        var data = Encoding.UTF8.GetBytes(textBox2.Text);
        _sender.Send(data, data.Length, new IPEndPoint(IPAddress.Broadcast, _port));
    }
}


问:
special characters and chinese fonts inserting in jsp page not working in spring controller
abc.jsp page.   i  am trying to insert chines fonts in the form.

```<code><!DOCTYPE html>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@ taglib prefix="spring" uri="http://www.springframework.org/tags" %>
<%@ page language="java" contentType="text/html; charset=utf-8"
    pageEncoding="utf-8"%>
<html lang="en">

<head>
 <meta http-equiv="content-type" content="text/html; charset=utf-8" />
</code>```

```<code><form id="bform"  action="addemo" method="POST" enctype="multipart/form-data"  class='form-group' accept-charset="utf-8">
                            <div class='form-group'>
                                <label>Book Image</label> <input type='file' name="file"
                                    class='btn' required="required" id="image_file"
                                    onchange="return validateimage();"> <img
                                    src="img/user_default_large.png" alt="" id="uploadPreview"
                                    style="height: 130px; width: 21%;">
                            </div>
                            <div class='form-group'>
                                <label>Book Title</label> <input type='text' name='title'
                                    class='form-control'  placeholder='Title' required="required">
                            </div>
                            <div class='form-group'>
                                <input type='Submit' name='cat_img' value='Add'
                                    class='btn btn-success'> <input type='reset'
                                    name='cat_img' value='Cancel' class='btn btn-primary'>
                            </div>
                        </form>
</code>```

In the above form when i am  adding chinese fonts "你好"
and submitting the form request goes to controller.

```<code>@RequestMapping(value = "addemo", method = RequestMethod.POST)
    public JSONObject view(HttpServletRequest request,@Valid Books model, BindingResult results,
            @RequestPart(name = "file", required = false) MultipartFile image) throws ExecutionException, UnsupportedEncodingException {
        request.setCharacterEncoding("utf-8");
        String username = request.getParameter("title");
        System.out.println("encoding: "+request.getCharacterEncoding());
        System.out.println("received: "+username);
        System.out.println("received: "+username);
        JSONObject jsonObject = new JSONObject();
        System.out.println(model.getTitle());
</code>```

i am getting this on my console
encoding: utf-8
received: ä½ å¥½
received: ä½ å¥½
ä½ å¥½
ä½ å¥½

How should i get the utf-8 encoded data in a string params .
please explain.

答:
You need to look at UTF-8 support in the following areas:

URLs,
Apache,
HTML,
JavaScript,
POST data
File download,
JSPs,
Java code,
Tomcat,
Oracle,
File system

Go through the following link that might help u :- http://blogs.warwick.ac.uk/kieranshaw/entry/utf-8_internationalisation_with/

Body:
abc.jsp page.   i  am trying to insert chines fonts in the form.

<!DOCTYPE html>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@ taglib prefix="spring" uri="http://www.springframework.org/tags" %>
<%@ page language="java" contentType="text/html; charset=utf-8"
    pageEncoding="utf-8"%>

 <meta http-equiv="content-type" content="text/html; charset=utf-8" />

<form id="bform"  action="addemo" method="POST" enctype="multipart/form-data"  class='form-group' accept-charset="utf-8">

                                Book Image <input type='file' name="file"
                                    class='btn' required="required" id="image_file"
                                    onchange="return validateimage();">

                                Book Title <input type='text' name='title'
                                    class='form-control'  placeholder='Title' required="required">

                                <input type='Submit' name='cat_img' value='Add'
                                    class='btn btn-success'> <input type='reset'
                                    name='cat_img' value='Cancel' class='btn btn-primary'>

                        </form>

In the above form when i am  adding chinese fonts "你好"
and submitting the form request goes to controller.

@RequestMapping(value = "addemo", method = RequestMethod.POST)
    public JSONObject view(HttpServletRequest request,@Valid Books model, BindingResult results,
            @RequestPart(name = "file", required = false) MultipartFile image) throws ExecutionException, UnsupportedEncodingException {
        request.setCharacterEncoding("utf-8");
        String username = request.getParameter("title");
        System.out.println("encoding: "+request.getCharacterEncoding());
        System.out.println("received: "+username);
        System.out.println("received: "+username);
        JSONObject jsonObject = new JSONObject();
        System.out.println(model.getTitle());

i am getting this on my console
encoding: utf-8
received: ä½ å¥½
received: ä½ å¥½
ä½ å¥½
ä½ å¥½

How should i get the utf-8 encoded data in a string params .
please explain.


问:
First occurrence in numpy logics
Let's say I have a numpy.ndarray:

```<code>a = np.array([0,4,10,0,11,10])
</code>```

I compared this with 10.

```<code>a >= 10
# array([False, False,  True, False,  True,  True], dtype=bool)
</code>```

I would like to have a single True, i.e. True only at the first occurrence.

I would like to apply this to a given axis in n-D numpy.ndarray.(say, 1000*1000*10)

```<code>a_2d = np.array([[0,4,10],[0,11,10]])
#if axis == 1: array([[False, False, True], [False, True, False]])
</code>```

What I have done:

As for a 1-D array, I managed to do it by using this.

```<code>b=np.zeros(a.size)
b[np.argmax(a>=10)]=True
#b=array([ 0.,  0.,  1.,  0.,  0.,  0.])
</code>```

However, I have no idea how to apply this to a large n-D array.

答:
You can try the following:

```<code>>>> import numpy as np
>>> a_2d = np.array([[0,4,10],[0,11,10]])
>>> r, c = np.where( a_2d >= 10 )
>>> mask = r+c == (r+c).min()
>>> highMask = np.zeros(np.shape(a_2d))
>>> highMask[r[mask], c[mask]] = 1
>>> highMask
    array([[ 0.,  0.,  1.],
           [ 0.,  1.,  0.]])
</code>```

There is no such thing as the 'first' one in a 2D array. In a 2D array, the minimum indices will form a line on the 2D axis, the both of which will have minimum indices values. For a 3D matrix, this will be a surface, etc ..

Example of such a line would be:

```<code> 0 0 0 0 0 1
 0 0 0 0 1 0
 0 0 0 1 0 0
 0 0 1 0 0 0
 0 1 0 0 0 0
 1 0 0 0 0 0
</code>```

All of which are equidistant from the [0,0] location ...

ContentLicense: CC BY-SA 4.0

Title: First occurrence in numpy logics

Body:
Let's say I have a numpy.ndarray:

a = np.array([0,4,10,0,11,10])

I compared this with 10.

a >= 10
# array([False, False,  True, False,  True,  True], dtype=bool)

I would like to have a single True, i.e. True only at the first occurrence.

I would like to apply this to a given axis in n-D numpy.ndarray.(say, 1000*1000*10)

a_2d = np.array([[0,4,10],[0,11,10]])
#if axis == 1: array([[False, False, True], [False, True, False]])

What I have done:

As for a 1-D array, I managed to do it by using this.

b=np.zeros(a.size)
b[np.argmax(a>=10)]=True
#b=array([ 0.,  0.,  1.,  0.,  0.,  0.])

However, I have no idea how to apply this to a large n-D array.

Body:
You can try the following:

>>> import numpy as np
>>> a_2d = np.array([[0,4,10],[0,11,10]])
>>> r, c = np.where( a_2d >= 10 )
>>> mask = r+c == (r+c).min()
>>> highMask = np.zeros(np.shape(a_2d))
>>> highMask[r[mask], c[mask]] = 1
>>> highMask
    array([[ 0.,  0.,  1.],
           [ 0.,  1.,  0.]])

There is no such thing as the 'first' one in a 2D array. In a 2D array, the minimum indices will form a line on the 2D axis, the both of which will have minimum indices values. For a 3D matrix, this will be a surface, etc ..

Example of such a line would be:

 0 0 0 0 0 1
 0 0 0 0 1 0
 0 0 0 1 0 0
 0 0 1 0 0 0
 0 1 0 0 0 0
 1 0 0 0 0 0

All of which are equidistant from the [0,0] location ...


问:
Symfony2 functional test to select checkboxes
I'm having trouble writing a Symfony 2 functional test to set checkboxes that are part of an array (i.e. a multiple and expanded select widget)

In the documentation the example is

```<code>$form['registration[interests]']->select(array('symfony', 'cookies'));
</code>```

But it doesn't show what html that will work with and it doesn't work with mine. Here is a cutdown version of my form

```<code><form class="proxy" action="/proxy/13/update" method="post" >
    <input type="checkbox" id="niwa_pictbundle_proxytype_chronologyControls_1" name="niwa_pictbundle_proxytype[chronologyControls][]" value="1" />

    <input type="checkbox" id="niwa_pictbundle_proxytype_chronologyControls_2" name="niwa_pictbundle_proxytype[chronologyControls][]" value="2" />

    <input type="checkbox" id="niwa_pictbundle_proxytype_chronologyControls_3" name="niwa_pictbundle_proxytype[chronologyControls][]" value="3" />
</form>
</code>```

Once it get it working there I'm going to move on to a manually made form

```<code><input type="checkbox" id="13" name="proxyIDs[]" value="13">
<input type="checkbox" id="14" name="proxyIDs[]" value="14">
<input type="checkbox" id="15" name="proxyIDs[]" value="15">
</code>```

I have tried things like

```<code>$form = $crawler->selectButton('Save')->form();
$form['niwa_pictbundle_proxytype[chronologyControls]']->select(array('3'));
$form['niwa_pictbundle_proxytype[chronologyControls][]']->select(array('3'));
</code>```

but the first fails saying select is being run on a non-object and the second says  Unreachable field "".

答:
I think the most bulletproof solution working in 2017 is to extend your test class:

```<code>/**
 * Find checkbox
 *
 * @param \Symfony\Component\DomCrawler\Form $form
 * @param string $name Field name without trailing '[]'
 * @param string $value
 */
protected function findCheckbox($form, $name, $value)
{
    foreach ($form->offsetGet($name) as $field) {
        $available = $field->availableOptionValues();
        if (strval($value) == reset($available)) {
            return $field;
        }
    }
}
</code>```

And in the test call:

```<code>$this->findCheckbox($form, 'niwa_pictbundle_proxytype[chronologyControls]', 3)->tick();
</code>```

Body:
I'm having trouble writing a Symfony 2 functional test to set checkboxes that are part of an array (i.e. a multiple and expanded select widget)

In the documentation the example is

$form['registration[interests]']->select(array('symfony', 'cookies'));

But it doesn't show what html that will work with and it doesn't work with mine. Here is a cutdown version of my form

<form class="proxy" action="/proxy/13/update" method="post" >
    <input type="checkbox" id="niwa_pictbundle_proxytype_chronologyControls_1" name="niwa_pictbundle_proxytype[chronologyControls][]" value="1" />

    <input type="checkbox" id="niwa_pictbundle_proxytype_chronologyControls_2" name="niwa_pictbundle_proxytype[chronologyControls][]" value="2" />

    <input type="checkbox" id="niwa_pictbundle_proxytype_chronologyControls_3" name="niwa_pictbundle_proxytype[chronologyControls][]" value="3" />
</form>

Once it get it working there I'm going to move on to a manually made form

<input type="checkbox" id="13" name="proxyIDs[]" value="13">
<input type="checkbox" id="14" name="proxyIDs[]" value="14">
<input type="checkbox" id="15" name="proxyIDs[]" value="15">

I have tried things like

$form = $crawler->selectButton('Save')->form();
$form['niwa_pictbundle_proxytype[chronologyControls]']->select(array('3'));
$form['niwa_pictbundle_proxytype[chronologyControls][]']->select(array('3'));

but the first fails saying select is being run on a non-object and the second says  Unreachable field "".

Body:
I think the most bulletproof solution working in 2017 is to extend your test class:

/**
 * Find checkbox
 *
 * @param \Symfony\Component\DomCrawler\Form $form
 * @param string $name Field name without trailing '[]'
 * @param string $value
 */
protected function findCheckbox($form, $name, $value)
{
    foreach ($form->offsetGet($name) as $field) {
        $available = $field->availableOptionValues();
        if (strval($value) == reset($available)) {
            return $field;
        }
    }
}

And in the test call:

$this->findCheckbox($form, 'niwa_pictbundle_proxytype[chronologyControls]', 3)->tick();


问:
How to make a drag & drop for NSTableCellView like this
I'm trying to implement a drag & drop for NSTableCellView look like screenshot, but the only thing i can do just the text, not a whole cell like screenshot bellow :(

答:
Here is my answer for my question :)

NSView to NSImage: link

Override draggingImageComponents in NSTableCellView subclass

```<code>-(NSArray *) draggingImageComponents{
    self.layer.opacity = 0.5;
    NSImage *image = [self imageRepresentation];
    self.layer.opacity = 1;

    NSDraggingImageComponent *draggingImage = [NSDraggingImageComponent draggingImageComponentWithKey:@"background"];
    draggingImage.contents = image;
    draggingImage.frame = self.bounds;
    return @[draggingImage];
}
</code>```

Body:
Here is my answer for my question :)

NSView to NSImage: link

Override draggingImageComponents in NSTableCellView subclass

-(NSArray *) draggingImageComponents{
    self.layer.opacity = 0.5;
    NSImage *image = [self imageRepresentation];
    self.layer.opacity = 1;

    NSDraggingImageComponent *draggingImage = [NSDraggingImageComponent draggingImageComponentWithKey:@"background"];
    draggingImage.contents = image;
    draggingImage.frame = self.bounds;
    return @[draggingImage];
}


问:
Tableview Cell Is override from bottom
I am Creating One tableview with tableview cell fro XIB.
When I integrate tableview cell with Tableview and run it it is not showing perfectly ,It shows me override.

Image is

Code is

```<code>static NSString *cellIdentifier =@"DiscussionTableViewCell";

            DiscussionTableViewCell *cell = (DiscussionTableViewCell *)[tableView dequeueReusableCellWithIdentifier:cellIdentifier];
            if (cell == nil) {

                NSArray *topLevelObjects = [[NSBundle mainBundle] loadNibNamed:@"DiscussionTableViewCell" owner:self options:nil];
                cell = [topLevelObjects objectAtIndex:0];
                cell.selectionStyle=UITableViewCellSelectionStyleNone;
                // [cell.btnConnect addTarget:self action:@selector(btnUserConnectClick:) forControlEvents:UIControlEventTouchUpInside];
                // [cell.btnNotnow addTarget:self action:@selector(btnNotNowClick:) forControlEvents:UIControlEventTouchUpInside];
                 self.cellHeight  += cell.frame.size.height;
                NSLog(@"Cell height is %f",self.cellHeight);
</code>```

答:
The code I have used to calculate cell content height dynamically is:</p>

```<code>- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (_arrMainTable.count && (indexPath.row < _arrMainTable.count))
    {
        NSDictionary *dict = [_arrMainTable objectAtIndex:indexPath.row];
        return [self expectedLabelHeight:dict];
    }
    return 0;
}

- (CGFloat)expectedLabelHeight:(NSDictionary *)dict
{
    CGSize boundingSize = CGSizeMake(CGRectGetWidth(_faqTableView.bounds)-20.0, CGFLOAT_MAX);
    UIFont *font = [UIFont fontWithName:@"Roboto-Regular" size:17];
    CGRect qstnRect = [dict[@"question"] boundingRectWithSize:boundingSize options:NSStringDrawingUsesLineFragmentOrigin|NSStringDrawingUsesFontLeading attributes: @{NSFontAttributeName:font} context:nil];

    font = [UIFont fontWithName:@"Roboto-Light" size:14];
    CGRect ansRect = [dict[@"answer"] boundingRectWithSize:boundingSize options:NSStringDrawingUsesLineFragmentOrigin|NSStringDrawingUsesFontLeading attributes: @{NSFontAttributeName:font} context:nil];

    return (qstnRect.size.height+ansRect.size.height+30); // 30 is the height of another label whose height is fixed to 30pts.
}
</code>```

Title: Tableview Cell Is override from bottom

Body:
I am Creating One tableview with tableview cell fro XIB.
When I integrate tableview cell with Tableview and run it it is not showing perfectly ,It shows me override.

Image is

Code is

static NSString *cellIdentifier =@"DiscussionTableViewCell";

            DiscussionTableViewCell *cell = (DiscussionTableViewCell *)[tableView dequeueReusableCellWithIdentifier:cellIdentifier];
            if (cell == nil) {

                NSArray *topLevelObjects = [[NSBundle mainBundle] loadNibNamed:@"DiscussionTableViewCell" owner:self options:nil];
                cell = [topLevelObjects objectAtIndex:0];
                cell.selectionStyle=UITableViewCellSelectionStyleNone;
                // [cell.btnConnect addTarget:self action:@selector(btnUserConnectClick:) forControlEvents:UIControlEventTouchUpInside];
                // [cell.btnNotnow addTarget:self action:@selector(btnNotNowClick:) forControlEvents:UIControlEventTouchUpInside];
                 self.cellHeight  += cell.frame.size.height;
                NSLog(@"Cell height is %f",self.cellHeight);

Body:
The code I have used to calculate cell content height dynamically is:

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (_arrMainTable.count && (indexPath.row < _arrMainTable.count))
    {
        NSDictionary *dict = [_arrMainTable objectAtIndex:indexPath.row];
        return [self expectedLabelHeight:dict];
    }
    return 0;
}

- (CGFloat)expectedLabelHeight:(NSDictionary *)dict
{
    CGSize boundingSize = CGSizeMake(CGRectGetWidth(_faqTableView.bounds)-20.0, CGFLOAT_MAX);
    UIFont *font = [UIFont fontWithName:@"Roboto-Regular" size:17];
    CGRect qstnRect = [dict[@"question"] boundingRectWithSize:boundingSize options:NSStringDrawingUsesLineFragmentOrigin|NSStringDrawingUsesFontLeading attributes: @{NSFontAttributeName:font} context:nil];

    font = [UIFont fontWithName:@"Roboto-Light" size:14];
    CGRect ansRect = [dict[@"answer"] boundingRectWithSize:boundingSize options:NSStringDrawingUsesLineFragmentOrigin|NSStringDrawingUsesFontLeading attributes: @{NSFontAttributeName:font} context:nil];

    return (qstnRect.size.height+ansRect.size.height+30); // 30 is the height of another label whose height is fixed to 30pts.
}


问:
if condition is not working properly it is not checking properly
I have created a function to create automatic username on the bassis of name if name already exist then username will be creted on the basis of user id but when I created a user and tested if the name is already not present into the database it is creating username alongwith user id as it shouldn't be because test name is not already in the database. here is my code</p>

```<code>// $user_id is the last inserted id
$check_username = $this->db->where('name', $name);
        $check_username = $this->db->where('id !=', $user_id);
        $check_username = $this->db->get('users');

        if($check_username >= 1) {
            $username = strtolower(str_replace(" ", ".", $name)) . $user_id;
        } else {
            $username = strtolower(str_replace(" ", ".", $name));
        }

        $this->db->where('id', $user_id);
        $this->db->update('users', array("username" => $username));
</code>```

答:
You can use $this->db->count_all_results()

```<code>$check_username = $this->db->where('name', $name);
    $check_username = $this->db->where('id !=', $user_id);
    $check_username = $this->db->get('users');

    if($this->db->count_all_results() >= 1) {
        $username = strtolower(str_replace(" ", ".", $name)) . $user_id;
    } else {
        $username = strtolower(str_replace(" ", ".", $name));
    }

    $this->db->where('id', $user_id);
    $this->db->update('users', array("username" => $username));
</code>```

Body:
I have created a function to create automatic username on the bassis of name if name already exist then username will be creted on the basis of user id but when I created a user and tested if the name is already not present into the database it is creating username alongwith user id as it shouldn't be because test name is not already in the database. here is my code

// $user_id is the last inserted id
$check_username = $this->db->where('name', $name);
        $check_username = $this->db->where('id !=', $user_id);
        $check_username = $this->db->get('users');

        if($check_username >= 1) {
            $username = strtolower(str_replace(" ", ".", $name)) . $user_id;
        } else {
            $username = strtolower(str_replace(" ", ".", $name));
        }

        $this->db->where('id', $user_id);
        $this->db->update('users', array("username" => $username));

Body:
You can use $this->db->count_all_results()

$check_username = $this->db->where('name', $name);
    $check_username = $this->db->where('id !=', $user_id);
    $check_username = $this->db->get('users');

    if($this->db->count_all_results() >= 1) {
        $username = strtolower(str_replace(" ", ".", $name)) . $user_id;
    } else {
        $username = strtolower(str_replace(" ", ".", $name));
    }

    $this->db->where('id', $user_id);
    $this->db->update('users', array("username" => $username));


答:
Try This..

```<code>declare @table table (ZoneId nvarchar(2),VehId int,TimeFirst datetime ,[state] int
)

 insert into @table
      select    'X',       1,'2016-07-01 00:39:25',                 0
union all select     'x',       2,'2016-07-01 00:50:25',                 0
union all select     'x',       1,'2016-07-01 00:52:25',                 0
union all select     'x',       2,'2016-07-01 00:53:25',                 0
union all select     'A',       1,'2016-07-02 12:50:25',                 1
union all select     'A',       1,'2016-07-02 14:50:25',                 1
union all select     'A',       1,'2016-07-04 15:50:25',                 1
union all select     'f',       3,'2016-07-03 14:50:25',                 0
union all select     'A',       3,'2016-07-04 14:50:25',                 1
union all select     'B',       2,'2016-07-02 00:50:25',                 1

    SELECT t1.ZoneId AS fromZone
    ,t1.vehId
    ,t2.ZoneId AS ToZone
    ,max(t1.TimeFirst) AS FromTime
    ,min(t2.TimeFirst) AS ToTime
FROM @table t1
INNER JOIN @table t2 ON t1.VehId = t2.VehId
WHERE t1.ZoneId = 'X'
    AND t2.ZoneId IN ('A', 'B', 'f')
GROUP BY t1.ZoneId
    ,t1.vehId
    ,t2.ZoneId
</code>```

OUTPUT

```<code>fromZone     vehId  ToZone          FromTime                ToTime
    X           1       A   2016-07-01 00:52:25.000     2016-07-02 12:50:25.000
    x           2       B   2016-07-01 00:53:25.000     2016-07-02 00:50:25.000
</code>```

Title: Get specific from Zone - To Zone data - Sql server 2012

Body:
I have one table name entrystate i only want those vehicle data which left X zone and Enter in (A,B,C,D,E) zone, O state mean left and 1 mean Enter in Zone

  ZoneId  VehId      TimeFirst                     State
    X       1    2016-07-01 00:39:25                 0
    x       2    2016-07-01 00:50:25                 0
    x       1    2016-07-01 00:52:25                 0
    x       2    2016-07-01 00:53:25                 0
    A       1    2016-07-02 12:50:25                 1
    A       1    2016-07-02 14:50:25                 1
    A       1    2016-07-04 15:50:25                 1
    f       3    2016-07-03 14:50:25                 0
    A       3    2016-07-04 14:50:25                 1
    B       2    2016-07-02 00:50:25                 1

required result

  fromZone  Tozone VehId      FromTime                   ToTime
    X        A       1    2016-07-01 00:52:25         2016-07-02 12:50:25
    x        B       2    2016-07-01 00:53:25         2016-07-02 00:50:25

Body:
Try This..

declare @table table (ZoneId nvarchar(2),VehId int,TimeFirst datetime ,[state] int
)

 insert into @table
      select    'X',       1,'2016-07-01 00:39:25',                 0
union all select     'x',       2,'2016-07-01 00:50:25',                 0
union all select     'x',       1,'2016-07-01 00:52:25',                 0
union all select     'x',       2,'2016-07-01 00:53:25',                 0
union all select     'A',       1,'2016-07-02 12:50:25',                 1
union all select     'A',       1,'2016-07-02 14:50:25',                 1
union all select     'A',       1,'2016-07-04 15:50:25',                 1
union all select     'f',       3,'2016-07-03 14:50:25',                 0
union all select     'A',       3,'2016-07-04 14:50:25',                 1
union all select     'B',       2,'2016-07-02 00:50:25',                 1

    SELECT t1.ZoneId AS fromZone
    ,t1.vehId
    ,t2.ZoneId AS ToZone
    ,max(t1.TimeFirst) AS FromTime
    ,min(t2.TimeFirst) AS ToTime
FROM @table t1
INNER JOIN @table t2 ON t1.VehId = t2.VehId
WHERE t1.ZoneId = 'X'
    AND t2.ZoneId IN ('A', 'B', 'f')
GROUP BY t1.ZoneId
    ,t1.vehId
    ,t2.ZoneId

OUTPUT

fromZone     vehId  ToZone          FromTime                ToTime
    X           1       A   2016-07-01 00:52:25.000     2016-07-02 12:50:25.000
    x           2       B   2016-07-01 00:53:25.000     2016-07-02 00:50:25.000


问:
Add Line Number to existing HTML
I'm trying to add line numbers to existing html with unequal line height - many types of font size and also images.
each line look like -

```<code><div id="1"><right><span>line 1</span></right></div>
<div id="2"><right><span>line 2</span></right></div>
<div id="3"><right><span>line 3</span></right></div>
</code>```

is there simple way to add line numbers that will be vertically align?
thanks

答:
if you have requirement listing automatically use
    tag
other way is no add deffrent tag like this

div span {
    float: right;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code>    <ol>
    <li> list </li>
    <li> list </li>
    <li> list </li>
    <li> list </li>
    </ol>

 <div id="1"><right>line <span>1</span></right></div>
<div id="2"><right>line <span>2</span></right></div>
<div id="3"><right>line <span>3</span></right></div>
    </code>```

Title: Add Line Number to existing HTML

Body:
I'm trying to add line numbers to existing html with unequal line height - many types of font size and also images.
each line look like -

<right>line 1</right>

<right>line 2</right>

<right>line 3</right>

is there simple way to add line numbers that will be vertically align?
thanks

Body:
if you have requirement listing automatically use <OL>    tag
other way is no add deffrent tag like this

div span {
    float: right;
}

    <ol>
    <li> list </li>
    <li> list </li>
    <li> list </li>
    <li> list </li>
    </ol>

 <div id="1"><right>line <span>1</span></right></div>
<div id="2"><right>line <span>2</span></right></div>
<div id="3"><right>line <span>3</span></right></div>


问:
Alternative way for using forms from ProjectA in ProjectB other than referencing method in vb.net
I have a scenario where in need to make use of the vb.net forms in ProjectA by other projects. All these projects are under single solution.

I know to achieve this by adding reference to ProjectA in other projects. Want to know if there are any other way to achieve this.

I basically want to eliminate the dependency on this DLL.

Thanks in advance for your assistance.

答:
One way to do this would be to use the Managed Extensibility Framework:

The Managed Extensibility Framework or MEF is a library for creating lightweight, extensible applications. It allows application developers to discover and use extensions with no configuration required

However, this would require quite a lot of extra work and the creation of more assemblies (e.g. assemblies to contain interface definitions), so may be overkill for you here.


问:
How to set up Beanstalk + Nginx to redirect http to https?
My domain is pointing to a Beanstalk app (DNS ALIAS).
I have already set up SSL certificates properly on my Beanstalk instance.
So now:
http://www.mysite.com -> Beanstalk app with http
https://www.mysite.com -> Beanstalk app with https

I would like to redirect all http requests to https. So http://www.mysite.com -> https://www.mysite.com

I already tried to create an AWS container to implement something like "server { listen 80; return 301 https://www.mysite.com/$request_uri;}" but it is not working.

I have already spent several hours on Google trying to find some guidance on how to do that. I found some clues such as the 301 redirect, rewrite... but I am not being able to apply any solution to my Beanstalk EC2 instance.

Perhaps I need a more detailed explanation on how to do that.
Could someone help me, please?

PS: one thing that I am struggling to understand is the fact that the Load Balancer says that Load Balancer Port 80 is pointing to Instance Port 80 and Load Balancer Port 443 (HTTPS) is also pointing to Instance Port 80, but with Cipher/SSL cert.
Well, when I examine the nginx configuration files on my EC2 instance I only find a "server { listen 8080", not "listen 80".

Thank you all.

答:
For those, who don't use the Load Balancer, the if block from user3888643's answer wouldn't work. So I've removed it completely (not sure if this solution has any problems) and it works for me:

```<code>  sed -i '/listen 8080;/a \    if ($http_x_forwarded_proto = "http") { return 301 https://$host$request_uri; }\n' /etc/nginx/conf.d/00_elastic_beanstalk_proxy.conf
</code>```

to:

```<code>  sed -i '/listen 8080;/a \    return 301 https://$host$request_uri;\n' /etc/nginx/conf.d/00_elastic_beanstalk_proxy.conf
</code>```

Body:
For those, who don't use the Load Balancer, the if block from user3888643's answer wouldn't work. So I've removed it completely (not sure if this solution has any problems) and it works for me:

  sed -i '/listen 8080;/a \    if ($http_x_forwarded_proto = "http") { return 301 https://$host$request_uri; }\n' /etc/nginx/conf.d/00_elastic_beanstalk_proxy.conf

to:

  sed -i '/listen 8080;/a \    return 301 https://$host$request_uri;\n' /etc/nginx/conf.d/00_elastic_beanstalk_proxy.conf


问:
Turning Firebase Analytics on on Xcode
I am trying to test the implementation of my Firebase Analytics. In their documentation they state that:

Enable debug mode by passing the -FIRDebugEnabled argument to the
  application. You can add this argument in the application’s Xcode
  scheme. When debug mode is enabled via -FIRDebugEnabled, further
  executions of the application will also be in debug mode. In order to
  return to default mode, you must explicitly disable the debug mode
  with the application argument -FIRDebugDisabled.

Unfortunately I do not understand where it is that I set this scheme. In Android this was easy. Help would be appreciated.

答:
I have found the answer on this alternative page of Google:

https://firebase.google.com/docs/analytics/ios/start

In Xcode, select Product > Scheme > Edit scheme...

Select Run from the left menu.

Select the Arguments tab.

In the Arguments Passed On Launch section, add -FIRAnalyticsDebugEnabled.

I wish Google would stop releasing half baked products and documentation. Could save hundreds of thousands of hours worldwide

Title: Turning Firebase Analytics on on Xcode


问:
How to add margins to the grid view through CSS

* {
  box-sizing: border-box;
}

h1 {
  text-align: center;
  font-family: sans-serif;
  font-weight: normal;
  padding-bottom: 20px;
}

#section1{
 margin-right: 10px;
}
#section2{
 margin-right: 10px;
}

div div {
  border: 1px solid;
  width: 90%;
  background-color: #9E9E9E;
  position: relative;
  margin-bottom: 10px;
  margin-left: auto;
  margin-right: auto;
}

div div div {
  text-align: center;
  position: absolute;
  right: 0;
  top: 0;
  margin: 0px;
  font-weight: bold;
}

#Chicken {
  background-color: #EF9A9A;
  width: 25%;
  border: 1px solid;
}

#Beef {
  background-color: #F44336;
  width: 25%;
  border: 1px solid;
  color: white;
  border-color: black;
}

#Sushi {
  background-color: #CDDC39;
  width: 25%;
  border: 1px solid;
}

p {
  padding: 10px;
}

.row {
  width: 100%;
}

@media (min-width: 992px) {
  .col-lg-1,
  .col-lg-2,
  .col-lg-3,
  .col-lg-4,
  .col-lg-5,
  .col-lg-6,
  .col-lg-7,
  .col-lg-8,
  .col-lg-9,
  .col-lg-10,
  .col-lg-11,
  .col-lg-12 {
    float: left;
  }
  .col-lg-1 {
    width: 8.33%;
  }
  .col-lg-2 {
    width: 16.66%;
  }
  .col-lg-3 {
    width: 25%;
  }
  .col-lg-4 {
    width: 33.33%;
  }
  .col-lg-5 {
    width: 41.66%;
  }
  .col-lg-6 {
    width: 50%;
  }
  .col-lg-7 {
    width: 58.33%;
  }
  .col-lg-8 {
    width: 66.66%;
  }
  .col-lg-9 {
    width: 74.99%;
  }
  .col-lg-10 {
    width: 83.33%;
  }
  .col-lg-11 {
    width: 91.66%;
  }
  .col-lg-12 {
    width: 100%;
  }
}

@media (min-width: 767px) and (max-width: 991px) {
  .col-md-1,
  .col-md-2,
  .col-md-3,
  .col-md-4,
  .col-md-5,
  .col-md-6,
  .col-md-7,
  .col-md-8,
  .col-md-9,
  .col-md-10,
  .col-md-11,
  .col-md-12 {
    float: left;
  }
  .col-md-1 {
    width: 8.33%;
  }
  .col-md-2 {
    width: 16.66%;
  }
  .col-md-3 {
    width: 25%;
  }
  .col-md-4 {
    width: 33.33%;
  }
  .col-md-5 {
    width: 41.66%;
  }
  .col-md-6 {
    width: 50%;
  }
  .col-md-7 {
    width: 58.33%;
  }
  .col-md-8 {
    width: 66.66%;
  }
  .col-md-9 {
    width: 74.99%;
  }
  .col-md-10 {
    width: 83.33%;
  }
  .col-md-11 {
    width: 91.66%;
  }
  .col-md-12 {
    width: 100%;
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html>

<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Assignment solution for module 2</title>
  <link rel="stylesheet" href="css">
</head>

<body>
  <h1> Our Menu</h1>
  <div class="row">
    <div id="section1" class="col-lg-4 col-md-6 col-xs-12">
      <div id="Chicken">Chicken</div>
      <p> lorem ipsum dolor sit amet, concectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad
      </p>
    </div>
    <div id="section2" class="col-lg-4 col-md-6">
      <div id="Beef">Beef</div>
      <p> lorem ipsum dolor sit amet, concectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad
      </p>
    </div>
    <div id="section3" class="col-lg-4 col-md-12">
      <div id="Sushi">Sushi</div>
      <p> lorem ipsum dolor sit amet, concectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad
      </p>
    </div>
  </div>
</body>

</html></code>```

How do I add margins between the boxes in the large screen view  Can anybody see how can it be done. I have tried to add the margin between boxes in the large screen view but it simply doesn't show, It just breaks the line and shows in the next line.
It must also view correctly like specified in other sizes too.

答:
Use display:flex

* {
  box-sizing: border-box;
}

h1 {
  text-align: center;
  font-family: sans-serif;
  font-weight: normal;
  padding-bottom: 20px;
}

#section1 {
  margin-right: 10px;
}

#section2 {
  margin-right: 10px;
}

div div {
  border: 1px solid;
  width: 90%;
  background-color: #9E9E9E;
  position: relative;
  margin-bottom: 10px;
  margin-left: auto;
  margin-right: auto;
}

div div div {
  text-align: center;
  position: absolute;
  right: 0;
  top: 0;
  margin: 0px;
  font-weight: bold;
}

#Chicken {
  background-color: #EF9A9A;
  width: auto;
  border: 1px solid;
}

#Beef {
  background-color: #F44336;
  width: 25%;
  border: 1px solid;
  color: white;
  border-color: black;
}

#Sushi {
  background-color: #CDDC39;
  width: 25%;
  border: 1px solid;
}

p {
  padding: 10px;
}

.row {
  width: 100%;
  display:flex;
}

@media (min-width: 992px) {
  .col-lg-1,
  .col-lg-2,
  .col-lg-3,
  .col-lg-4,
  .col-lg-5,
  .col-lg-6,
  .col-lg-7,
  .col-lg-8,
  .col-lg-9,
  .col-lg-10,
  .col-lg-11,
  .col-lg-12 {
    float: left;
  }
  .col-lg-1 {
    width: 8.33%;
  }
  .col-lg-2 {
    width: 16.66%;
  }
  .col-lg-3 {
    width: 25%;
  }
  .col-lg-4 {
    width: 33.33%;
  }
  .col-lg-5 {
    width: 41.66%;
  }
  .col-lg-6 {
    width: 50%;
  }
  .col-lg-7 {
    width: 58.33%;
  }
  .col-lg-8 {
    width: 66.66%;
  }
  .col-lg-9 {
    width: 74.99%;
  }
  .col-lg-10 {
    width: 83.33%;
  }
  .col-lg-11 {
    width: 91.66%;
  }
  .col-lg-12 {
    width: 100%;
  }
}

@media (min-width: 767px) and (max-width: 991px) {
  .col-md-1,
  .col-md-2,
  .col-md-3,
  .col-md-4,
  .col-md-5,
  .col-md-6,
  .col-md-7,
  .col-md-8,
  .col-md-9,
  .col-md-10,
  .col-md-11,
  .col-md-12 {
    float: left;
  }
  .col-md-1 {
    width: 8.33%;
  }
  .col-md-2 {
    width: 16.66%;
  }
  .col-md-3 {
    width: 25%;
  }
  .col-md-4 {
    width: 33.33%;
  }
  .col-md-5 {
    width: 41.66%;
  }
  .col-md-6 {
    width: 50%;
  }
  .col-md-7 {
    width: 58.33%;
  }
  .col-md-8 {
    width: 66.66%;
  }
  .col-md-9 {
    width: 74.99%;
  }
  .col-md-10 {
    width: 83.33%;
  }
  .col-md-11 {
    width: 91.66%;
  }
  .col-md-12 {
    width: 100%;
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html>

<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Assignment solution for module 2</title>
  <link rel="stylesheet" href="css">
</head>

<body>
  <h1> Our Menu</h1>
  <div class="row">
    <div id="section1" class="col-lg-4 col-md-6 col-xs-12">
      <div id="Chicken">Chicken</div>
      <p> lorem ipsum dolor sit amet, concectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad
      </p>
    </div>
    <div id="section2" class="col-lg-4 col-md-6">
      <div id="Beef">Beef</div>
      <p> lorem ipsum dolor sit amet, concectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad
      </p>
    </div>
    <div id="section3" class="col-lg-4 col-md-12">
      <div id="Sushi">Sushi</div>
      <p> lorem ipsum dolor sit amet, concectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad
      </p>
    </div>
  </div>
</body>

</html></code>```

Body:
* {
  box-sizing: border-box;
}

h1 {
  text-align: center;
  font-family: sans-serif;
  font-weight: normal;
  padding-bottom: 20px;
}

#section1{
 margin-right: 10px;
}
#section2{
 margin-right: 10px;
}

div div {
  border: 1px solid;
  width: 90%;
  background-color: #9E9E9E;
  position: relative;
  margin-bottom: 10px;
  margin-left: auto;
  margin-right: auto;
}

div div div {
  text-align: center;
  position: absolute;
  right: 0;
  top: 0;
  margin: 0px;
  font-weight: bold;
}

#Chicken {
  background-color: #EF9A9A;
  width: 25%;
  border: 1px solid;
}

#Beef {
  background-color: #F44336;
  width: 25%;
  border: 1px solid;
  color: white;
  border-color: black;
}

#Sushi {
  background-color: #CDDC39;
  width: 25%;
  border: 1px solid;
}

p {
  padding: 10px;
}

.row {
  width: 100%;
}

@media (min-width: 992px) {
  .col-lg-1,
  .col-lg-2,
  .col-lg-3,
  .col-lg-4,
  .col-lg-5,
  .col-lg-6,
  .col-lg-7,
  .col-lg-8,
  .col-lg-9,
  .col-lg-10,
  .col-lg-11,
  .col-lg-12 {
    float: left;
  }
  .col-lg-1 {
    width: 8.33%;
  }
  .col-lg-2 {
    width: 16.66%;
  }
  .col-lg-3 {
    width: 25%;
  }
  .col-lg-4 {
    width: 33.33%;
  }
  .col-lg-5 {
    width: 41.66%;
  }
  .col-lg-6 {
    width: 50%;
  }
  .col-lg-7 {
    width: 58.33%;
  }
  .col-lg-8 {
    width: 66.66%;
  }
  .col-lg-9 {
    width: 74.99%;
  }
  .col-lg-10 {
    width: 83.33%;
  }
  .col-lg-11 {
    width: 91.66%;
  }
  .col-lg-12 {
    width: 100%;
  }
}

@media (min-width: 767px) and (max-width: 991px) {
  .col-md-1,
  .col-md-2,
  .col-md-3,
  .col-md-4,
  .col-md-5,
  .col-md-6,
  .col-md-7,
  .col-md-8,
  .col-md-9,
  .col-md-10,
  .col-md-11,
  .col-md-12 {
    float: left;
  }
  .col-md-1 {
    width: 8.33%;
  }
  .col-md-2 {
    width: 16.66%;
  }
  .col-md-3 {
    width: 25%;
  }
  .col-md-4 {
    width: 33.33%;
  }
  .col-md-5 {
    width: 41.66%;
  }
  .col-md-6 {
    width: 50%;
  }
  .col-md-7 {
    width: 58.33%;
  }
  .col-md-8 {
    width: 66.66%;
  }
  .col-md-9 {
    width: 74.99%;
  }
  .col-md-10 {
    width: 83.33%;
  }
  .col-md-11 {
    width: 91.66%;
  }
  .col-md-12 {
    width: 100%;
  }
}

<!DOCTYPE html>

  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Assignment solution for module 2</title>
  <link rel="stylesheet" href="css">

 Our Menu

Chicken

 lorem ipsum dolor sit amet, concectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad

Beef

 lorem ipsum dolor sit amet, concectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad

Sushi

 lorem ipsum dolor sit amet, concectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad

How do I add margins between the boxes in the large screen view  Can anybody see how can it be done. I have tried to add the margin between boxes in the large screen view but it simply doesn't show, It just breaks the line and shows in the next line.
It must also view correctly like specified in other sizes too.

Body:
Use display:flex

* {
  box-sizing: border-box;
}

h1 {
  text-align: center;
  font-family: sans-serif;
  font-weight: normal;
  padding-bottom: 20px;
}

#section1 {
  margin-right: 10px;
}

#section2 {
  margin-right: 10px;
}

div div {
  border: 1px solid;
  width: 90%;
  background-color: #9E9E9E;
  position: relative;
  margin-bottom: 10px;
  margin-left: auto;
  margin-right: auto;
}

div div div {
  text-align: center;
  position: absolute;
  right: 0;
  top: 0;
  margin: 0px;
  font-weight: bold;
}

#Chicken {
  background-color: #EF9A9A;
  width: auto;
  border: 1px solid;
}

#Beef {
  background-color: #F44336;
  width: 25%;
  border: 1px solid;
  color: white;
  border-color: black;
}

#Sushi {
  background-color: #CDDC39;
  width: 25%;
  border: 1px solid;
}

p {
  padding: 10px;
}

.row {
  width: 100%;
  display:flex;
}

@media (min-width: 992px) {
  .col-lg-1,
  .col-lg-2,
  .col-lg-3,
  .col-lg-4,
  .col-lg-5,
  .col-lg-6,
  .col-lg-7,
  .col-lg-8,
  .col-lg-9,
  .col-lg-10,
  .col-lg-11,
  .col-lg-12 {
    float: left;
  }
  .col-lg-1 {
    width: 8.33%;
  }
  .col-lg-2 {
    width: 16.66%;
  }
  .col-lg-3 {
    width: 25%;
  }
  .col-lg-4 {
    width: 33.33%;
  }
  .col-lg-5 {
    width: 41.66%;
  }
  .col-lg-6 {
    width: 50%;
  }
  .col-lg-7 {
    width: 58.33%;
  }
  .col-lg-8 {
    width: 66.66%;
  }
  .col-lg-9 {
    width: 74.99%;
  }
  .col-lg-10 {
    width: 83.33%;
  }
  .col-lg-11 {
    width: 91.66%;
  }
  .col-lg-12 {
    width: 100%;
  }
}

@media (min-width: 767px) and (max-width: 991px) {
  .col-md-1,
  .col-md-2,
  .col-md-3,
  .col-md-4,
  .col-md-5,
  .col-md-6,
  .col-md-7,
  .col-md-8,
  .col-md-9,
  .col-md-10,
  .col-md-11,
  .col-md-12 {
    float: left;
  }
  .col-md-1 {
    width: 8.33%;
  }
  .col-md-2 {
    width: 16.66%;
  }
  .col-md-3 {
    width: 25%;
  }
  .col-md-4 {
    width: 33.33%;
  }
  .col-md-5 {
    width: 41.66%;
  }
  .col-md-6 {
    width: 50%;
  }
  .col-md-7 {
    width: 58.33%;
  }
  .col-md-8 {
    width: 66.66%;
  }
  .col-md-9 {
    width: 74.99%;
  }
  .col-md-10 {
    width: 83.33%;
  }
  .col-md-11 {
    width: 91.66%;
  }
  .col-md-12 {
    width: 100%;
  }
}

<!DOCTYPE html>
<html>

<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Assignment solution for module 2</title>
  <link rel="stylesheet" href="css">
</head>

<body>
  <h1> Our Menu</h1>
  <div class="row">
    <div id="section1" class="col-lg-4 col-md-6 col-xs-12">
      <div id="Chicken">Chicken</div>
      <p> lorem ipsum dolor sit amet, concectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad
      </p>
    </div>
    <div id="section2" class="col-lg-4 col-md-6">
      <div id="Beef">Beef</div>
      <p> lorem ipsum dolor sit amet, concectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad
      </p>
    </div>
    <div id="section3" class="col-lg-4 col-md-12">
      <div id="Sushi">Sushi</div>
      <p> lorem ipsum dolor sit amet, concectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad
      </p>
    </div>
  </div>
</body>

</html>


问:
How to close a session in PHP when the browser is closed?
I need to close a session when the browser is closed, when it crashes, when a PC restarts, and so on.

I know there is cookie solution, but I need something secure, server side, because the user can delete the cookie.

答:
Hi You don't need to close session. because its default behavior of session that it destroy the session when user close the browser. And we can alter this behavior by changing lifetime of session in php.ini file by doing
session.cookie_lifetime = 0. Otherwise by default
 when you reopen the browser there will be no data in session.</p>


问:
Ionic serve not working with ionic2
I have started a clean project with ionic2 based on tabs template, by following the next steps:

```<code>$ ionic start <myapp> --v2
$ cd <myapp>
$ ionic serve
</code>```

Then the output from ionic serve is just:

```<code>> ionic-hello-world@ ionic:serve /home/luan/<myapp>
> ionic-app-scripts serve "--v2" "--address" "0.0.0.0" "--port" "8100" "--livereload-port" "35729"
</code>```

If I try to open localhost:8100 there's no response.

The files and code of the project are just the same as one using tabs template, but it's just don't wonking.
Could someone help?

UPDATE:
My ionic info

```<code>My system information:
Cordova CLI: 6.5.0
Ionic Framework Version: 2.3.0
Ionic CLI Version: 2.2.1
Ionic App Lib Version: 2.2.0
Ionic App Scripts Version: 1.2.2
ios-deploy version: Not installed
ios-sim version: Not installed
OS: Linux 4.4
Node Version: v6.10.0
Xcode version: Not installed
</code>```

答:
I had the same error when I updated Ionic. I worked around it by using:

```<code>ionic serve --address localhost
</code>```

The above solution to use "@ionic/app-script": "1.2.2" works to have it use localhost instead of 0.0.0.0. However it created other errors that were easily fixed by following the addition warnings.

"devDependencies": {
      "@ionic/app-scripts": "1.2.2",

The one new error I still couldn't pinpoint yet is:

Error Close Runtime Error timeStamp.getDate is not a function Stack
  TypeError: timeStamp.getDate is not a function
      at HomePage.timeSince (http://localhost:8100/build/main.js:70141:33)
      at SafeSubscriber._next (http://localhost:8100/build/main.js:70088:42)
      at SafeSubscriber.__tryOrUnsub (http://localhost:8100/build/main.js:69844:16)
      at SafeSubscriber.next (http://localhost:8100/build/main.js:69793:22)
      at Subscriber._next (http://localhost:8100/build/main.js:69746:26)
      at Subscriber.next (http://localhost:8100/build/main.js:69710:18)
      at XMLHttpRequest.onLoad (http://localhost:8100/build/main.js:44518:38)
      at t.invokeTask (http://localhost:8100/build/polyfills.js:3:14051)
      at Object.onInvokeTask (http://localhost:8100/build/main.js:27788:37)
      at t.invokeTask (http://localhost:8100/build/polyfills.js:3:13987) Ionic Framework: 2.0.0-rc.2 Ionic Native: 2.2.3 Ionic App Scripts:
  1.2.2 Angular Core: 2.1.1 Angular Compiler CLI: 2.1.1 Node: 6.9.1 OS Platform: Windows 10 Navigator Platform: Win32 User Agent: Mozilla/5.0
  (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko)
  Chrome/56.0.2924.87 Safari/537.36

The app does run but that window popped up on Chrome and I had to close it before I could see the output of the app.

Title: Ionic serve not working with ionic2

Body:
I have started a clean project with ionic2 based on tabs template, by following the next steps:

$ ionic start <myapp> --v2
$ cd <myapp>
$ ionic serve

Then the output from ionic serve is just:

> ionic-hello-world@ ionic:serve /home/luan/<myapp>
> ionic-app-scripts serve "--v2" "--address" "0.0.0.0" "--port" "8100" "--livereload-port" "35729"

If I try to open localhost:8100 there's no response.

The files and code of the project are just the same as one using tabs template, but it's just don't wonking.
Could someone help?

UPDATE:
My ionic info

My system information:
Cordova CLI: 6.5.0
Ionic Framework Version: 2.3.0
Ionic CLI Version: 2.2.1
Ionic App Lib Version: 2.2.0
Ionic App Scripts Version: 1.2.2
ios-deploy version: Not installed
ios-sim version: Not installed
OS: Linux 4.4
Node Version: v6.10.0
Xcode version: Not installed

Body:
I had the same error when I updated Ionic. I worked around it by using:

ionic serve --address localhost

The above solution to use "@ionic/app-script": "1.2.2" works to have it use localhost instead of 0.0.0.0. However it created other errors that were easily fixed by following the addition warnings.

"devDependencies": {
      "@ionic/app-scripts": "1.2.2",

The one new error I still couldn't pinpoint yet is:

Error Close Runtime Error timeStamp.getDate is not a function Stack
  TypeError: timeStamp.getDate is not a function
      at HomePage.timeSince (http://localhost:8100/build/main.js:70141:33)
      at SafeSubscriber._next (http://localhost:8100/build/main.js:70088:42)
      at SafeSubscriber.__tryOrUnsub (http://localhost:8100/build/main.js:69844:16)
      at SafeSubscriber.next (http://localhost:8100/build/main.js:69793:22)
      at Subscriber._next (http://localhost:8100/build/main.js:69746:26)
      at Subscriber.next (http://localhost:8100/build/main.js:69710:18)
      at XMLHttpRequest.onLoad (http://localhost:8100/build/main.js:44518:38)
      at t.invokeTask (http://localhost:8100/build/polyfills.js:3:14051)
      at Object.onInvokeTask (http://localhost:8100/build/main.js:27788:37)
      at t.invokeTask (http://localhost:8100/build/polyfills.js:3:13987) Ionic Framework: 2.0.0-rc.2 Ionic Native: 2.2.3 Ionic App Scripts:
  1.2.2 Angular Core: 2.1.1 Angular Compiler CLI: 2.1.1 Node: 6.9.1 OS Platform: Windows 10 Navigator Platform: Win32 User Agent: Mozilla/5.0
  (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko)
  Chrome/56.0.2924.87 Safari/537.36

The app does run but that window popped up on Chrome and I had to close it before I could see the output of the app.


问:
How to Open Attachments of blob content in Cordova iOS app
I am using the below code to get the attachments content and creating a blob to open the attachments. The content is fetched successfully and blob is also created, but the attachment is not opening though it works in chrome as web app but not in Cordova iOs APP.

Is there something to be added in addition.

```<code>{
var details =
    "Username=username&Password=Password";
var http = new XMLHttpRequest();
http.open("POST", url, true,
    "username",
    "password");
http.setRequestHeader(
    "Content-type",
    "application/x-www-form-urlencoded"
);
http.onreadystatechange = function() { //Call a function when the state changes.
    if (http.readyState == 4 &&
        http.status == 200) {
        var ticket = JSON.parse(
            http.responseText
        ).ticket;
        var xhr = new XMLHttpRequest();
        xhr.open('GET',
            "http://hostname/url",
            true);
        xhr.setRequestHeader(
            "header",
            ticket);
        xhr.responseType =
            'arraybuffer';
        xhr.onload = function() {
            if (this.status ===
                200) {
                var blob =
                    new Blob(
                        [
                            xhr
                            .response
                        ], {
                            type: "application/pdf"
                        });
                var
                    objectUrl =
                    URL.createObjectURL(
                        blob
                    );
                window.open(
                    objectUrl
                ); // blob:file:///835fce36-9a25-4dbb-9e16-d3fcb9d27fef"
            }
        };
        xhr.send();
    }
}
http.send(details);
</code>```

}

```<code>Error : [Error] url ->file:///1811f4d5-17f0-4124-a761-70a4b4d9f361
(anonymous function) (console-via-logger.js:173)
(anonymous function) (logger.js:754)
(anonymous function) (attachmentviewer.js:80)
(anonymous function) (i18n.js:55)
callbackFromNative (cordova.js:293)
nc2 (cordova.js:1022)
[Error] current window.location -
>file:///Users/myname/Library/Developer/CoreSimulator/Devices/D2891D9A-
E669-4F16-849E-
D63532979F00/data/Containers/Bundle/Application/0A917ACE-
9F1B-42B8-B745-C351BAA3A369/Equip%20R2.0.app/www/index.html#/Attachment/30
(anonymous function) (console-via-logger.js:173)
(anonymous function) (logger.js:754)
(anonymous function) (attachmentviewer.js:81)
(anonymous function) (i18n.js:55)
callbackFromNative (cordova.js:293)
nc2 (cordova.js:1022)
</code>```

答:
Using the InApp browser has worked.
InApp Browser : Link </p>

```<code>cordova.InAppBrowser.open(objectUrl, '_blank', 'location=yes');
</code>```

Body:
I am using the below code to get the attachments content and creating a blob to open the attachments. The content is fetched successfully and blob is also created, but the attachment is not opening though it works in chrome as web app but not in Cordova iOs APP.

Is there something to be added in addition.

{
var details =
    "Username=username&Password=Password";
var http = new XMLHttpRequest();
http.open("POST", url, true,
    "username",
    "password");
http.setRequestHeader(
    "Content-type",
    "application/x-www-form-urlencoded"
);
http.onreadystatechange = function() { //Call a function when the state changes.
    if (http.readyState == 4 &&
        http.status == 200) {
        var ticket = JSON.parse(
            http.responseText
        ).ticket;
        var xhr = new XMLHttpRequest();
        xhr.open('GET',
            "http://hostname/url",
            true);
        xhr.setRequestHeader(
            "header",
            ticket);
        xhr.responseType =
            'arraybuffer';
        xhr.onload = function() {
            if (this.status ===
                200) {
                var blob =
                    new Blob(
                        [
                            xhr
                            .response
                        ], {
                            type: "application/pdf"
                        });
                var
                    objectUrl =
                    URL.createObjectURL(
                        blob
                    );
                window.open(
                    objectUrl
                ); // blob:file:///835fce36-9a25-4dbb-9e16-d3fcb9d27fef"
            }
        };
        xhr.send();
    }
}
http.send(details);

}

Error : [Error] url ->file:///1811f4d5-17f0-4124-a761-70a4b4d9f361
(anonymous function) (console-via-logger.js:173)
(anonymous function) (logger.js:754)
(anonymous function) (attachmentviewer.js:80)
(anonymous function) (i18n.js:55)
callbackFromNative (cordova.js:293)
nc2 (cordova.js:1022)
[Error] current window.location -
>file:///Users/myname/Library/Developer/CoreSimulator/Devices/D2891D9A-
E669-4F16-849E-
D63532979F00/data/Containers/Bundle/Application/0A917ACE-
9F1B-42B8-B745-C351BAA3A369/Equip%20R2.0.app/www/index.html#/Attachment/30
(anonymous function) (console-via-logger.js:173)
(anonymous function) (logger.js:754)
(anonymous function) (attachmentviewer.js:81)
(anonymous function) (i18n.js:55)
callbackFromNative (cordova.js:293)
nc2 (cordova.js:1022)

Body:
Using the InApp browser has worked.
InApp Browser : Link

cordova.InAppBrowser.open(objectUrl, '_blank', 'location=yes');


问:
OneLogin for Java - Beginner Issues
A few days ago I downloaded java-saml-2.0.1 in the hope of using it to implement SSO via SAML in my (SP) app. I am actually not a Java developer (I am C#) but working on this nonetheless. Also very little familiar with SSO/SAML, so please forgive stupid questions.

1) How do I add a dependency to my project? I have this in my POM.xml file. Is this enough ?

```<code><dependency>
    <groupId>com.onelogin</groupId>
    <artifactId>java-saml</artifactId>
    <version>2.0.0</version>
</dependency>
</code>```

2) I am reading this article: Code Your Java App to Provide SSO via OneLogin. Assuming this applies to java-saml-2.0.1, why does it say that I need the files under /com ? Am I supposed to copy those files in my project ? Do I not reference the whole package?

3) Looking at dologin.jsp, what does this code do?

```<code>Auth auth = new Auth(request, response);
if (request.getParameter("attrs") == null) {
    auth.login();
} else {
    String x = request.getPathInfo();
    auth.login("/java-saml-tookit-jspsample/attrs.jsp");
}
</code>```

It checks for request.getParameter("attrs"), but then does not use it.
It sets String x, but then does not use it.
Why?

4) When setting up AccountSettings, can I skip the certificate and do that later or is it always needed ?

5) Essentially we are implementing this and the first step is for my SP app to implement Step 2: (SP--> UA) Redirect to IdP SSO Service. So, when the user is trying to access my SP, I need to create a SAML Token (?) and send that to IdP. How do I do that? This is where I get stuck.

I looked at the sample, but I don't know hoe to config the settings so it does not work.

BTW: the IdP is an internal app managed by a different division.

答:
1) As described here: https://mvnrepository.com/artifact/com.onelogin/java-saml/2.0.1

You need to add:

    com.onelogin
    java-saml
    2.0.1

2) That documentation is old and belong the 1.X version of the java-saml.

On the github repository of java-saml
https://github.com/onelogin/java-saml
You will find the right documentation.

3) That code initiates the login process (send an AuthNrequest to the Identity Provider).

Initiates the Auth object and later calling the login method does the redirection.

The attrs parameter is a get parameter that can be send to the index view to set a custom RelayState to the attrs.jsp page.

4) AccountSettings object belong the 1.X code.

But you need to set the x509cert on the settings property before deploy your service.

5) On SP-initiate SSO flow, the SP sends to the IdP an AuthNRequest and the IdP replies  a SAMLResponse.
(Previously IdP and SP must exchange its metadata in order to set the circle of trust.

Title: OneLogin for Java - Beginner Issues

Body:
A few days ago I downloaded java-saml-2.0.1 in the hope of using it to implement SSO via SAML in my (SP) app. I am actually not a Java developer (I am C#) but working on this nonetheless. Also very little familiar with SSO/SAML, so please forgive stupid questions.

1) How do I add a dependency to my project? I have this in my POM.xml file. Is this enough ?

<dependency>
    <groupId>com.onelogin</groupId>
    <artifactId>java-saml</artifactId>
    <version>2.0.0</version>
</dependency>

2) I am reading this article: Code Your Java App to Provide SSO via OneLogin. Assuming this applies to java-saml-2.0.1, why does it say that I need the files under /com ? Am I supposed to copy those files in my project ? Do I not reference the whole package?

3) Looking at dologin.jsp, what does this code do?

Auth auth = new Auth(request, response);
if (request.getParameter("attrs") == null) {
    auth.login();
} else {
    String x = request.getPathInfo();
    auth.login("/java-saml-tookit-jspsample/attrs.jsp");
}

It checks for request.getParameter("attrs"), but then does not use it.
It sets String x, but then does not use it.
Why?

4) When setting up AccountSettings, can I skip the certificate and do that later or is it always needed ?

5) Essentially we are implementing this and the first step is for my SP app to implement Step 2: (SP--> UA) Redirect to IdP SSO Service. So, when the user is trying to access my SP, I need to create a SAML Token (?) and send that to IdP. How do I do that? This is where I get stuck.

I looked at the sample, but I don't know hoe to config the settings so it does not work.

BTW: the IdP is an internal app managed by a different division.


问:
Operator '!' cannot be applied to operand of type '<null>
I am using MVC 5 ViewBag and trying to do

```<code>@if (!ViewBag.UserLoggedIn) {
   <a onclick="javascript:UserSessionManager.UserLogout()">LogOut</a>
}
</code>```

but getting an error:

```<code>Operator '!' cannot be applied to operand of type '<null>'
</code>```

答:
In an if-statement you can only have true or false (boolean's basically) but the property UserLoggedIn wont exist on the ViewBag if it's not set and will therefor be null. So ViewBag.UserLoggedIn can be null or a string. You have to cast the string (which can also be null) to a boolean in order to use it in the if-statement. Something like this will work:

```<code>@{
    bool isUserLoggedIn = ViewBag.UserLoggedIn ?? false;
}

@if (!isUserLoggedIn) {
   <a onclick="javascript:UserSessionManager.UserLogout()">LogOut</a>
}
</code>```

Body:
I am using MVC 5 ViewBag and trying to do

@if (!ViewBag.UserLoggedIn) {
   LogOut
}

but getting an error:

Operator '!' cannot be applied to operand of type '<null>'

Body:
In an if-statement you can only have true or false (boolean's basically) but the property UserLoggedIn wont exist on the ViewBag if it's not set and will therefor be null. So ViewBag.UserLoggedIn can be null or a string. You have to cast the string (which can also be null) to a boolean in order to use it in the if-statement. Something like this will work:

@{
    bool isUserLoggedIn = ViewBag.UserLoggedIn ?? false;
}

@if (!isUserLoggedIn) {
   <a onclick="javascript:UserSessionManager.UserLogout()">LogOut</a>
}


问:
Angular bootstrap modal
I'm using ui-bootstrap-tpl version 2.4.0 with Angular Dialog Service, and I have a problem with modal.

Problem occurs when I close modal:

If I click OK, it closed and no error.

If I click Cancel, it closed but have an error in console window:

Possibly unhandled rejection: cancel

If I click outside modal, it closed but have an error:

Possibly unhandled rejection: backdrop click

Anyway to fix it? Thanks alot!

答:
You forgot to handle the dismiss case of the modal.

Here's an updated plunker: https://plnkr.co/edit/M5OnOcJJG65pinWe2iKt

Essentially, you need to do something like this:

```<code>dialog.result.then(
    function () {
        // success case
        console.log('ok');
    },
    function () {
        // dismiss case
        console.log('cancel');
    }
);
</code>```

Title: Angular bootstrap modal

Body:
You forgot to handle the dismiss case of the modal.

Here's an updated plunker: https://plnkr.co/edit/M5OnOcJJG65pinWe2iKt

Essentially, you need to do something like this:

dialog.result.then(
    function () {
        // success case
        console.log('ok');
    },
    function () {
        // dismiss case
        console.log('cancel');
    }
);


问:
Illegal Break Statement. NodeJs
While Executing the below code. it shows illegal break statement error. I am new to nodejs kindly help me to resolve this.

Code Is:

```<code>describe('Locating elements using JS', function () {
            it('Locate H1 tags', function () {
                browser.get("http://angularjs.org");
                element.all(by.js(function () {
                    //This is javascript code which will get h1 elements
                    var elementsArray = new Array();
                    var anchors = document.querySelectorAll('h3');
                    for (var i = 0; i < anchors.length; ++i) {
                        if (anchors[i].textContent != '') {
                            elementsArray.push(anchors[i]);
                        }
                    }
                    return elementsArray;
                })).then(function (webElements) {
                    //prints Number of h1 tags identified
                    console.log(webElements.length);
                    for (var i = 0; i < webElements.length; i++) {
                        webElements[i].getText().then(function (text) {
                            //prints text of each H1 tag
                            console.log(text);
                            //Verifying the text of each h1 tag should not be empty
                            expect(text).not.toBe('');
                            if(text=="Directives"){
                                break;
                            }

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

答:
The problem is you are using a break NOT directly inside a for/while - but inside a promise resolution function which is incorrect.

By the way as a side note if you are trying to filter one element out of elementArray Protractor API provides a beautiful method - ElementArrayFinder.prototype.filter which does the exact job for you.

Apply a filter function to each element within the ElementArrayFinder.
  Returns a new ElementArrayFinder with all elements that pass the
  filter function. The filter function receives the ElementFinder as the
  first argument and the index as a second arg. This does not actually
  retrieve the underlying list of elements, so it can be used in page
  objects.

```<code>describe('Locating elements using JS', function () {
    it('Locate H1 tags', function () {
        browser.get("http://angularjs.org");
        element.all(by.js(function () {
            //Your existing JS Code to identify elements
        })).filter(function(elem, index) {
            return elem.getText().then(function(text) {
                return text === 'Directives';
            });
        }).first().click()
    });
});
</code>```

BTW In case you want to checkout more ways to play around with elements inside an elementArray like each,map,reduce so on .. check this link

Title: Illegal Break Statement. NodeJs

Body:
While Executing the below code. it shows illegal break statement error. I am new to nodejs kindly help me to resolve this.

Code Is:

describe('Locating elements using JS', function () {
            it('Locate H1 tags', function () {
                browser.get("http://angularjs.org");
                element.all(by.js(function () {
                    //This is javascript code which will get h1 elements
                    var elementsArray = new Array();
                    var anchors = document.querySelectorAll('h3');
                    for (var i = 0; i < anchors.length; ++i) {
                        if (anchors[i].textContent != '') {
                            elementsArray.push(anchors[i]);
                        }
                    }
                    return elementsArray;
                })).then(function (webElements) {
                    //prints Number of h1 tags identified
                    console.log(webElements.length);
                    for (var i = 0; i < webElements.length; i++) {
                        webElements[i].getText().then(function (text) {
                            //prints text of each H1 tag
                            console.log(text);
                            //Verifying the text of each h1 tag should not be empty
                            expect(text).not.toBe('');
                            if(text=="Directives"){
                                break;
                            }

                        })
                    }
                });
            });
        });

Body:
The problem is you are using a break NOT directly inside a for/while - but inside a promise resolution function which is incorrect.

By the way as a side note if you are trying to filter one element out of elementArray Protractor API provides a beautiful method - ElementArrayFinder.prototype.filter which does the exact job for you.

Apply a filter function to each element within the ElementArrayFinder.
  Returns a new ElementArrayFinder with all elements that pass the
  filter function. The filter function receives the ElementFinder as the
  first argument and the index as a second arg. This does not actually
  retrieve the underlying list of elements, so it can be used in page
  objects.

describe('Locating elements using JS', function () {
    it('Locate H1 tags', function () {
        browser.get("http://angularjs.org");
        element.all(by.js(function () {
            //Your existing JS Code to identify elements
        })).filter(function(elem, index) {
            return elem.getText().then(function(text) {
                return text === 'Directives';
            });
        }).first().click()
    });
});

BTW In case you want to checkout more ways to play around with elements inside an elementArray like each,map,reduce so on .. check this link


问:
" where in " mysql clause
i used a mysql query where there is "where id in ("22,20,21") "
but when i get the result its like array ordered in asecending order ie  20,21,20

but i need it in the same order as i gave the clause

答:
i think you should be able to use the FIELD keyword like so:

```<code>SELECT * FROM table
WHERE id in (22,20,21)
ORDER BY FIELD(id,22,20,21);
</code>```

this is mysql specific, and seems magical, but it works.

Title: " where in " mysql clause

Body:
i think you should be able to use the FIELD keyword like so:

SELECT * FROM table
WHERE id in (22,20,21)
ORDER BY FIELD(id,22,20,21);

this is mysql specific, and seems magical, but it works.


问:
unit testing using mock
I'm trying to conduct unit test on my app.
This is my test:

```<code>class CustomerControllerTest
{
    [Test]
    public void GetAuctionsByJson_works()
    {
        // Arrange
        Mock<IAuctionRespository> mockAuction = new Mock<IAuctionRespository>();
        mockAuction.Setup(m => m.Auctions).Returns(new Auction[]
            {
                new Auction { a_id=1, auctionname="computer", deadLine=DateTime.Today},
                new Auction { a_id=2, auctionname="keyboard", deadLine=DateTime.Today},
                new Auction { a_id=3, auctionname="mouse", deadLine=DateTime.Today}
            }.AsQueryable());
        CustomerController controller = new CustomerController(mockAuction.Object);
        var actual = controller.GetAuctionsByJson() as JsonResult;
        //parse result
        List<Auction> result = actual.Data as List<Auction>; //null
        Assert.AreEqual(3, result.Count);
        Assert.AreEqual(1, result[0].a_id);
        Assert.AreEqual("computer", result[0].auctionname);
        Assert.AreEqual(DateTime.Today, result[0].deadLine);

    }
}
</code>```

var actual has values (as seen in image)
actual val
but i get that var result is null
result val
why?
how can i get actual values in a list?
Thank

答:
Thanks Andre! My solution was to add this lines:</p>

```<code>JavaScriptSerializer serializer = new JavaScriptSerializer();
List<Auction> result = serializer.Deserialize<List<Auction>>(serializer.Serialize(actual.Data));
</code>```

Title: unit testing using mock

Body:
I'm trying to conduct unit test on my app.
This is my test:

class CustomerControllerTest
{
    [Test]
    public void GetAuctionsByJson_works()
    {
        // Arrange
        Mock<IAuctionRespository> mockAuction = new Mock<IAuctionRespository>();
        mockAuction.Setup(m => m.Auctions).Returns(new Auction[]
            {
                new Auction { a_id=1, auctionname="computer", deadLine=DateTime.Today},
                new Auction { a_id=2, auctionname="keyboard", deadLine=DateTime.Today},
                new Auction { a_id=3, auctionname="mouse", deadLine=DateTime.Today}
            }.AsQueryable());
        CustomerController controller = new CustomerController(mockAuction.Object);
        var actual = controller.GetAuctionsByJson() as JsonResult;
        //parse result
        List<Auction> result = actual.Data as List<Auction>; //null
        Assert.AreEqual(3, result.Count);
        Assert.AreEqual(1, result[0].a_id);
        Assert.AreEqual("computer", result[0].auctionname);
        Assert.AreEqual(DateTime.Today, result[0].deadLine);

    }
}

var actual has values (as seen in image)
actual val
but i get that var result is null
result val
why?
how can i get actual values in a list?
Thank

Body:
Thanks Andre! My solution was to add this lines:

JavaScriptSerializer serializer = new JavaScriptSerializer();
List<Auction> result = serializer.Deserialize<List<Auction>>(serializer.Serialize(actual.Data));


问:
Java mapper recursively with lists
I have a mapper method which takes list of entities called Claim iterates over them and maps to CompensationDTO and adds to list, but entity can contain lists of children entities which type is also Claim and those children can also contain list of Claims, so to iterate over them all is best to use recursion but i'm not sure how it should be written

```<code>    private List<CompensationDTO> mapToDTO(List<Claims> claims) {
    List<CompensationsDTO> compensations = new ArrayList<>();
    if (claims.isEmpty()) {
        return new ArrayList<>();
    }
    for (Claim claim : claims) {
        CompensationDTO compensationDTO = new CompensationDTO();
        compensationDTO.setId(claim.getId());
        compensationDTO.setAmount(claim.getAmount());
        compensationDTO.setType(claim.getType());
        compensations.add(compensationDTO);
        mapToDTO(claim.getChildrenClaims());
    }
    return compensations;
}
</code>```

I understand that the base case should return empty list but i don't know where to put the recursive function call mapToDTO(claim.getChildrenClaims());

答:
Did you try to add compansations.addAll()?:

```<code>private List<CompensationDTO> mapToDTO(List<Claims> claims) {
List<CompensationsDTO> compensations = new ArrayList<>();
if (claims.isEmpty()) {
    return new ArrayList<>();
}
for (Claim claim : claims) {
    CompensationDTO compensationDTO = new CompensationDTO();
    compensationDTO.setId(claim.getId());
    compensationDTO.setAmount(claim.getAmount());
    compensationDTO.setType(claim.getType());
    compensations.add(compensationDTO);
    compensations.addAll(mapToDTO(claim.getChildrenClaims()));
}
return compensations;
</code>```

}

Title: Java mapper recursively with lists

Body:
I have a mapper method which takes list of entities called Claim iterates over them and maps to CompensationDTO and adds to list, but entity can contain lists of children entities which type is also Claim and those children can also contain list of Claims, so to iterate over them all is best to use recursion but i'm not sure how it should be written

    private List<CompensationDTO> mapToDTO(List<Claims> claims) {
    List<CompensationsDTO> compensations = new ArrayList<>();
    if (claims.isEmpty()) {
        return new ArrayList<>();
    }
    for (Claim claim : claims) {
        CompensationDTO compensationDTO = new CompensationDTO();
        compensationDTO.setId(claim.getId());
        compensationDTO.setAmount(claim.getAmount());
        compensationDTO.setType(claim.getType());
        compensations.add(compensationDTO);
        mapToDTO(claim.getChildrenClaims());
    }
    return compensations;
}

I understand that the base case should return empty list but i don't know where to put the recursive function call mapToDTO(claim.getChildrenClaims());

Body:
Did you try to add compansations.addAll()?:

private List<CompensationDTO> mapToDTO(List<Claims> claims) {
List<CompensationsDTO> compensations = new ArrayList<>();
if (claims.isEmpty()) {
    return new ArrayList<>();
}
for (Claim claim : claims) {
    CompensationDTO compensationDTO = new CompensationDTO();
    compensationDTO.setId(claim.getId());
    compensationDTO.setAmount(claim.getAmount());
    compensationDTO.setType(claim.getType());
    compensations.add(compensationDTO);
    compensations.addAll(mapToDTO(claim.getChildrenClaims()));
}
return compensations;

}


问:
Traceback (most recent call last): Python
When I am trying to run my python code in eclipse I am getting this error:

Here is my code:

```<code>"""
Module Name:  deviceManager.py
Project:      IoTHubRestSample
Copyright (c) Microsoft Corporation.

Using [Device Indentities REST APIs](https://msdn.microsoft.com/en-us/library/azure/mt548489.aspx) to create a new device identity, retrieve a device identity, and list device identities.

This source is subject to the Microsoft Public License.
See http://www.microsoft.com/en-us/openness/licenses.aspx#MPL
All other rights reserved.

THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND,
EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR PURPOSE.
"""

import base64
import hmac
import hashlib
import time
import requests
import urllib

class DeviceManager:
    API_VERSION = '2016-02-03'
    TOKEN_VALID_SECS = 365 * 24 * 60 * 60
    TOKEN_FORMAT = 'SharedAccessSignature sr=%s&sig=%s&se=%s&skn=%s'

    def __init__(self, connectionString=None):
        if connectionString != None:
            iotHost, keyName, keyValue = [sub[sub.index('=') + 1:] for sub in connectionString.split(";")]
            self.iotHost = iotHost
            self.keyName = keyName
            self.keyValue = keyValue

    def _buildExpiryOn(self):
        return '%d' % (time.time() + self.TOKEN_VALID_SECS)

    def _buildSasToken(self):
        targetUri = self.iotHost.lower()
        expiryTime = self._buildExpiryOn()
        toSign = '%s\n%s' % (targetUri, expiryTime)
        key = base64.b64decode(self.keyValue.encode('utf-8'))
        signature = urllib.quote(
            base64.b64encode(
                hmac.HMAC(key, toSign.encode('utf-8'), hashlib.sha256).digest()
                )
        ).replace('/', '%2F')
        return self.TOKEN_FORMAT % (targetUri, signature, expiryTime, self.keyName)

    def createDeviceId(self, deviceId):
        sasToken = self._buildSasToken()
        url = 'https://%s/devices/%s?api-version=%s' % (self.iotHost, deviceId, self.API_VERSION)
        body = '{deviceId: "%s"}' % deviceId
        r = requests.put(url, headers={'Content-Type': 'application/json', 'Authorization': sasToken}, data=body)
        return r.text, r.status_code

    def retrieveDeviceId(self, deviceId):
        sasToken = self._buildSasToken()
        url = 'https://%s/devices/%s?api-version=%s' % (self.iotHost, deviceId, self.API_VERSION)
        r = requests.get(url, headers={'Content-Type': 'application/json', 'Authorization': sasToken})
        return r.text, r.status_code

    def listDeviceIds(self, top=None):
        if top == None:
            top = 1000
        sasToken = self._buildSasToken()
        url = 'https://%s/devices?top=%d&api-version=%s' % (self.iotHost, top, self.API_VERSION)
        r = requests.get(url, headers={'Content-Type': 'application/json', 'Authorization': sasToken})
        return r.text, r.status_code

    def deleteDeviceId(self, deviceId):
        sasToken = self._buildSasToken()
        url = 'https://%s/devices/%s?api-version=%s' % (self.iotHost, deviceId, self.API_VERSION)
        r = requests.delete(url, headers={'Content-Type': 'application/json', 'Authorization': sasToken, 'If-Match': '*' })
        # If-Match Etag, but if * is used, no need to precise the Etag of the device. The Etag of the device can be seen in the header requests.text response
        return r.text, r.status_code

if __name__ == '__main__':
    connectionString = 'HostName=<iot-hub-name>.azure-devices.net;SharedAccessKeyName=iothubowner;SharedAccessKey=<iothubowner-policy-key>'
    dm = DeviceManager(connectionString)
    deviceId='iotdevice1'
    print(dm.createDeviceId(deviceId))
    print(dm.retrieveDeviceId(deviceId))
    print(dm.listDeviceIds())
</code>```

How to fix this?

答: It seems that your linking code is an Azure code sample written by me, which comes from here and its introduction at here. According to your error screenshot, I see the code connectionString = 'HostName=<iot-hub-name>.azure-devices.net;SharedAccessKeyName=iothubowner;SharedAccessKey=<iothubowner-policy-key>' was not changed. Please follow the offical tutorial Create an IoT hub using the Azure portal to create an IoTHub if you had not, and copy your IoT hub name & key(as below) instead of <iot-hub-name> & <iothubowner-policy-key>.

Body:
When I am trying to run my python code in eclipse I am getting this error:

Here is my code:

"""
Module Name:  deviceManager.py
Project:      IoTHubRestSample
Copyright (c) Microsoft Corporation.

Using [Device Indentities REST APIs](https://msdn.microsoft.com/en-us/library/azure/mt548489.aspx) to create a new device identity, retrieve a device identity, and list device identities.

This source is subject to the Microsoft Public License.
See http://www.microsoft.com/en-us/openness/licenses.aspx#MPL
All other rights reserved.

THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND,
EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR PURPOSE.
"""

import base64
import hmac
import hashlib
import time
import requests
import urllib

class DeviceManager:
    API_VERSION = '2016-02-03'
    TOKEN_VALID_SECS = 365 * 24 * 60 * 60
    TOKEN_FORMAT = 'SharedAccessSignature sr=%s&sig=%s&se=%s&skn=%s'

    def __init__(self, connectionString=None):
        if connectionString != None:
            iotHost, keyName, keyValue = [sub[sub.index('=') + 1:] for sub in connectionString.split(";")]
            self.iotHost = iotHost
            self.keyName = keyName
            self.keyValue = keyValue

    def _buildExpiryOn(self):
        return '%d' % (time.time() + self.TOKEN_VALID_SECS)

    def _buildSasToken(self):
        targetUri = self.iotHost.lower()
        expiryTime = self._buildExpiryOn()
        toSign = '%s\n%s' % (targetUri, expiryTime)
        key = base64.b64decode(self.keyValue.encode('utf-8'))
        signature = urllib.quote(
            base64.b64encode(
                hmac.HMAC(key, toSign.encode('utf-8'), hashlib.sha256).digest()
                )
        ).replace('/', '%2F')
        return self.TOKEN_FORMAT % (targetUri, signature, expiryTime, self.keyName)

    def createDeviceId(self, deviceId):
        sasToken = self._buildSasToken()
        url = 'https://%s/devices/%s?api-version=%s' % (self.iotHost, deviceId, self.API_VERSION)
        body = '{deviceId: "%s"}' % deviceId
        r = requests.put(url, headers={'Content-Type': 'application/json', 'Authorization': sasToken}, data=body)
        return r.text, r.status_code

    def retrieveDeviceId(self, deviceId):
        sasToken = self._buildSasToken()
        url = 'https://%s/devices/%s?api-version=%s' % (self.iotHost, deviceId, self.API_VERSION)
        r = requests.get(url, headers={'Content-Type': 'application/json', 'Authorization': sasToken})
        return r.text, r.status_code

    def listDeviceIds(self, top=None):
        if top == None:
            top = 1000
        sasToken = self._buildSasToken()
        url = 'https://%s/devices?top=%d&api-version=%s' % (self.iotHost, top, self.API_VERSION)
        r = requests.get(url, headers={'Content-Type': 'application/json', 'Authorization': sasToken})
        return r.text, r.status_code

    def deleteDeviceId(self, deviceId):
        sasToken = self._buildSasToken()
        url = 'https://%s/devices/%s?api-version=%s' % (self.iotHost, deviceId, self.API_VERSION)
        r = requests.delete(url, headers={'Content-Type': 'application/json', 'Authorization': sasToken, 'If-Match': '*' })
        # If-Match Etag, but if * is used, no need to precise the Etag of the device. The Etag of the device can be seen in the header requests.text response
        return r.text, r.status_code

if __name__ == '__main__':
    connectionString = 'HostName=<iot-hub-name>.azure-devices.net;SharedAccessKeyName=iothubowner;SharedAccessKey=<iothubowner-policy-key>'
    dm = DeviceManager(connectionString)
    deviceId='iotdevice1'
    print(dm.createDeviceId(deviceId))
    print(dm.retrieveDeviceId(deviceId))
    print(dm.listDeviceIds())

How to fix this?


问:
" iframe.contentDocument" Not Working in IE8 and FF(3.5 and below) any other steps to solve this?
I used this "iframe.contentDocument" in js file-uploader , But it not working in IE8 ,Firefox(3.5 and below versions.
How can i solve this by using other DOM's for working with iframe ?

Thanks to all

答:
Try</p>

```<code>var doc;
var iframeObject = document.getElementById('iframeID'); // MUST have an ID
if (iframeObject.contentDocument) { // DOM
  doc = iframeObject.contentDocument;
}
else if (iframeObject.contentWindow) { // IE win
  doc = iframeObject.contentWindow.document;
}
if (doc) {
  var something = doc.getElementById('someId');
}
else {
  alert('Wonder what browser this is...'+navigator.userAgent);
}
</code>```

Body:
Try

var doc;
var iframeObject = document.getElementById('iframeID'); // MUST have an ID
if (iframeObject.contentDocument) { // DOM
  doc = iframeObject.contentDocument;
}
else if (iframeObject.contentWindow) { // IE win
  doc = iframeObject.contentWindow.document;
}
if (doc) {
  var something = doc.getElementById('someId');
}
else {
  alert('Wonder what browser this is...'+navigator.userAgent);
}