问:
Hamburger menu doesnt show in responsive navbar
Hello I'm really new in this web programming, just learned a few days ago, and try to make responsive navbar of mine. And I found tutorial on w3school, I followed it, and change some code, but it didnt work as intended. The menu succeed to collapse on desired width, but the hamburger menu doesnt show up. I think I already change and match it with my classes, but I dont know what else is wrong.

Here is what I have tried so far:

.navSection {
    width: 100%;
    display: inline-table;
    line-height: 30px;
    background: #1c948a;
    z-index: 3;
    box-shadow: 0px 3px 5px 1px rgba(0, 0, 0, .3);
}

.navMenu .icon{
    display: none;
}

@media screen and (max-width: 700px) {
  .navMenu ul li:not(:first-child) {display: none;}
  .navMenu ul li.icon {
    float: right;
    display: block;
  }
}

@media screen and (max-width: 700px) {
  .navMenu.responsive {position: relative;}
  .navMenu.responsive .icon {
    position: absolute;
    right: 0;
    top: 0;
  }
  .navMenu.responsive ul li {
    float: none;
    display: block;
    text-align: left;
  }
}

.navSectionWrapper {
    width: 90%;
    margin: auto;
}

.homelink {
    text-decoration: none;
}

.navlogo {
    width: 30%;
    height: 70px;
    float: left;
}

.logo {
    display: inline-block;
    font-family: "Trebuchet MS", "Lucida Grande", "Lucida Sans Unicode", "Lucida Sans", Tahoma, sans-serif;
    color: #2C3E50;
    position: absolute;
}

.logoimg {
    height: 70px;
    float: left;
}

.logotext {
    font-weight: 600;
    float: right;
    line-height: 70px;
}

.logotext>span {
    color: white;
    text-shadow: 2px 2px 2px #33425B;
}

.navMenu {
    float: right;
    text-align: center;
    overflow: hidden;
}

.navMenu>ul {
    list-style: none;
}

.navMenu>ul>li {
    display: inline-block;
    line-height: 70px;
}

.navMenu>ul>li>a>span {
    color: white;
    font-weight: 700;
    font-size: 17px
}

.navMenu>ul>li>a {
    text-decoration: none;
    color: #2C3E50;
    font-family: "Trebuchet MS", "Lucida Grande", "Lucida Sans Unicode", "Lucida Sans", Tahoma, sans-serif;
    font-weight: 600;
    margin: 10px
}

.navMenu>ul>li>a:hover {
    color: snow;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="navSection">
        <div class="navSectionWrapper">
            <div class="navlogo">

                    <div class="logo">
                        <img src="img/logo.png" class="logoimg">
                        <h2 class="logotext">Let's<span>Go</span></h2>
                    </div>

            </div>
            <div class="navMenu" id="mynavMenu">
                <ul>
                    <li>Home</li>
                    <li>Features</li>
                    <li>About</li>
                    <li>+<span>Download</span></li>
                    <li>☰</li>
                </ul>
            </div>
        </div>
    </div>
<script>
        function myFunction() {
            var x = document.getElementById("mynavMenu");
            if (x.className === "navMenu") {
                x.className += " responsive";
            } else {
                x.className = "navMenu";
            }
        }
</script></code>```

ThankYou

答:
Your HTML uses a.icon but you're targeting in CSS with li.icon. Moved the class="icon" to the li instead of the a and modified the CSS for .icon a bit. You were hiding :not(:first-child()) in the responsive view, and you either want to use :not(:last-child) since .icon is the :last-child or just use :not(.icon) there instead.

.navSection {
    width: 100%;
    display: inline-table;
    line-height: 30px;
    background: #1c948a;
    z-index: 3;
    box-shadow: 0px 3px 5px 1px rgba(0, 0, 0, .3);
}

.navMenu .icon{
    display: none;
    float: right;
}

@media screen and (max-width: 700px) {
  .navMenu ul li:not(.icon) {display: none;}
  .navMenu ul li.icon {
    display: block;
  }
}

@media screen and (max-width: 700px) {
  .navMenu.responsive {position: relative;}
  .navMenu.responsive .icon {
    position: absolute;
    right: 0;
    top: 0;
  }
  .navMenu.responsive ul li {
    float: none;
    display: block;
    text-align: left;
  }
}

.navSectionWrapper {
    width: 90%;
    margin: auto;
}

.homelink {
    text-decoration: none;
}

.navlogo {
    width: 30%;
    height: 70px;
    float: left;
}

.logo {
    display: inline-block;
    font-family: "Trebuchet MS", "Lucida Grande", "Lucida Sans Unicode", "Lucida Sans", Tahoma, sans-serif;
    color: #2C3E50;
    position: absolute;
}

.logoimg {
    height: 70px;
    float: left;
}

.logotext {
    font-weight: 600;
    float: right;
    line-height: 70px;
}

.logotext>span {
    color: white;
    text-shadow: 2px 2px 2px #33425B;
}

.navMenu {
    float: right;
    text-align: center;
    overflow: hidden;
}

.navMenu>ul {
    list-style: none;
}

.navMenu>ul>li {
    display: inline-block;
    line-height: 70px;
}

.navMenu>ul>li>a>span {
    color: white;
    font-weight: 700;
    font-size: 17px
}

.navMenu>ul>li>a {
    text-decoration: none;
    color: #2C3E50;
    font-family: "Trebuchet MS", "Lucida Grande", "Lucida Sans Unicode", "Lucida Sans", Tahoma, sans-serif;
    font-weight: 600;
    margin: 10px
}

.navMenu>ul>li>a:hover {
    color: snow;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="navSection">
        <div class="navSectionWrapper">
            <div class="navlogo">

                    <div class="logo">
                        <img src="img/logo.png" class="logoimg">
                        <h2 class="logotext">Let's<span>Go</span></h2>
                    </div>

            </div>
            <div class="navMenu" id="mynavMenu">
                <ul>
                    <li>Home</li>
                    <li>Features</li>
                    <li>About</li>
                    <li>+<span>Download</span></li>
                    <li class="icon">☰</li>
                </ul>
            </div>
        </div>
    </div>
<script>
        function myFunction() {
            var x = document.getElementById("mynavMenu");
            if (x.className === "navMenu") {
                x.className += " responsive";
            } else {
                x.className = "navMenu";
            }
        }
</script></code>```

Body:
Hello I'm really new in this web programming, just learned a few days ago, and try to make responsive navbar of mine. And I found tutorial on w3school, I followed it, and change some code, but it didnt work as intended. The menu succeed to collapse on desired width, but the hamburger menu doesnt show up. I think I already change and match it with my classes, but I dont know what else is wrong.

Here is what I have tried so far:

.navSection {
    width: 100%;
    display: inline-table;
    line-height: 30px;
    background: #1c948a;
    z-index: 3;
    box-shadow: 0px 3px 5px 1px rgba(0, 0, 0, .3);
}

.navMenu .icon{
    display: none;
}

@media screen and (max-width: 700px) {
  .navMenu ul li:not(:first-child) {display: none;}
  .navMenu ul li.icon {
    float: right;
    display: block;
  }
}

@media screen and (max-width: 700px) {
  .navMenu.responsive {position: relative;}
  .navMenu.responsive .icon {
    position: absolute;
    right: 0;
    top: 0;
  }
  .navMenu.responsive ul li {
    float: none;
    display: block;
    text-align: left;
  }
}

.navSectionWrapper {
    width: 90%;
    margin: auto;
}

.homelink {
    text-decoration: none;
}

.navlogo {
    width: 30%;
    height: 70px;
    float: left;
}

.logo {
    display: inline-block;
    font-family: "Trebuchet MS", "Lucida Grande", "Lucida Sans Unicode", "Lucida Sans", Tahoma, sans-serif;
    color: #2C3E50;
    position: absolute;
}

.logoimg {
    height: 70px;
    float: left;
}

.logotext {
    font-weight: 600;
    float: right;
    line-height: 70px;
}

.logotext>span {
    color: white;
    text-shadow: 2px 2px 2px #33425B;
}

.navMenu {
    float: right;
    text-align: center;
    overflow: hidden;
}

.navMenu>ul {
    list-style: none;
}

.navMenu>ul>li {
    display: inline-block;
    line-height: 70px;
}

.navMenu>ul>li>a>span {
    color: white;
    font-weight: 700;
    font-size: 17px
}

.navMenu>ul>li>a {
    text-decoration: none;
    color: #2C3E50;
    font-family: "Trebuchet MS", "Lucida Grande", "Lucida Sans Unicode", "Lucida Sans", Tahoma, sans-serif;
    font-weight: 600;
    margin: 10px
}

.navMenu>ul>li>a:hover {
    color: snow;
}

Let'sGo

Home

Features

About

+Download

☰

ThankYou

Body:
Your HTML uses a.icon but you're targeting in CSS with li.icon. Moved the class="icon" to the li instead of the a and modified the CSS for .icon a bit. You were hiding :not(:first-child()) in the responsive view, and you either want to use :not(:last-child) since .icon is the :last-child or just use :not(.icon) there instead.

.navSection {
    width: 100%;
    display: inline-table;
    line-height: 30px;
    background: #1c948a;
    z-index: 3;
    box-shadow: 0px 3px 5px 1px rgba(0, 0, 0, .3);
}

.navMenu .icon{
    display: none;
    float: right;
}

@media screen and (max-width: 700px) {
  .navMenu ul li:not(.icon) {display: none;}
  .navMenu ul li.icon {
    display: block;
  }
}

@media screen and (max-width: 700px) {
  .navMenu.responsive {position: relative;}
  .navMenu.responsive .icon {
    position: absolute;
    right: 0;
    top: 0;
  }
  .navMenu.responsive ul li {
    float: none;
    display: block;
    text-align: left;
  }
}

.navSectionWrapper {
    width: 90%;
    margin: auto;
}

.homelink {
    text-decoration: none;
}

.navlogo {
    width: 30%;
    height: 70px;
    float: left;
}

.logo {
    display: inline-block;
    font-family: "Trebuchet MS", "Lucida Grande", "Lucida Sans Unicode", "Lucida Sans", Tahoma, sans-serif;
    color: #2C3E50;
    position: absolute;
}

.logoimg {
    height: 70px;
    float: left;
}

.logotext {
    font-weight: 600;
    float: right;
    line-height: 70px;
}

.logotext>span {
    color: white;
    text-shadow: 2px 2px 2px #33425B;
}

.navMenu {
    float: right;
    text-align: center;
    overflow: hidden;
}

.navMenu>ul {
    list-style: none;
}

.navMenu>ul>li {
    display: inline-block;
    line-height: 70px;
}

.navMenu>ul>li>a>span {
    color: white;
    font-weight: 700;
    font-size: 17px
}

.navMenu>ul>li>a {
    text-decoration: none;
    color: #2C3E50;
    font-family: "Trebuchet MS", "Lucida Grande", "Lucida Sans Unicode", "Lucida Sans", Tahoma, sans-serif;
    font-weight: 600;
    margin: 10px
}

.navMenu>ul>li>a:hover {
    color: snow;
}

<div class="navSection">
        <div class="navSectionWrapper">
            <div class="navlogo">
                <a href="#" class="homelink">
                    <div class="logo">
                        <img src="img/logo.png" class="logoimg">
                        <h2 class="logotext">Let's<span>Go</span></h2>
                    </div>
                </a>
            </div>
            <div class="navMenu" id="mynavMenu">
                <ul>
                    <li><a href="#">Home</a></li>
                    <li><a href="#">Features</a></li>
                    <li><a href="#">About</a></li>
                    <li><a href="#">+<span>Download</span></a></li>
                    <li class="icon"><a href="javascript:void(0);" onclick="myFunction()">&#9776;</a></li>
                </ul>
            </div>
        </div>
    </div>
<script>
        function myFunction() {
            var x = document.getElementById("mynavMenu");
            if (x.className === "navMenu") {
                x.className += " responsive";
            } else {
                x.className = "navMenu";
            }
        }
</script>


来源: stackexchange

问:
vim block copy between different SecureCRT sessions
I connect two SecureCRT sessions. Is there any ways or plugins to use vim's block copy paste between them?

Thanks for helping.

like this image

答:
Full disclosure, I've struggled with this in the past, and it's very platform specific.  One way to do this though would be to get all copying and pasting to go through the system clipboard by default. A similar question is here: How to make vim paste from (and copy to) system's clipboard?

To sum up, confirm your vim installation is compiled with clipboard support with :echo has('clipboard'), and if it is, then the "* register should work for communication between both windows.

If this works, you can use this register automatically by adding set clipboard=unnamed to your vimrc (http://vim.wikia.com/wiki/VimTip21)

ContentLicense: CC BY-SA 3.0


问:
Javascript: Inserting data from an array into function parameter
I have only been learning javascript for 2 weeks, so apologies if my question seems weird/doesn't make sense. I'm learning the basics of arrays, and to help me learn I like to practise and play around with the code but I can't seem to figure this one out.

I've created a simple function, and wanting to call upon the function to calculate the sum of variables in an array. Here is my code below:

```<code>//functions

function simpleCalc (a,b) {
    var result = a + b;
    return result;
}

//array

var myArray = [12,567];

//final calculation

var total = simpleCalc([0],[1]);

alert("The total is " + total);
</code>```

Can anyone please shed any light as to how I input the numbers "12" and "567" into the function parameters? The result here as it stands outputs to "01"

Thanks

答:
You have two options:

Your option but, it is very limited to only two values.

You need to pass reference to your array elements like so (myArray[0], myArray[1])

Create new function - let's call it sumValuesInArray(), pass an array and calculate all values inside an array using for loop.

See working example here:

//functions

function simpleCalc (a,b) {
    var result = a + b;
    return result;
}

//array

var myArray = [12,567];

//final calculation

var total = simpleCalc(myArray[0],myArray[1]);

//alert("The total is " + total);

// OR

function sumValuesInArray(array) {
  var total = 0;

  for(i = 0; i < array.length; i++) {
    var element = array[i];

    total += element;
  }

  return total;
}

console.log(sumValuesInArray(myArray));```

Body:
I have only been learning javascript for 2 weeks, so apologies if my question seems weird/doesn't make sense. I'm learning the basics of arrays, and to help me learn I like to practise and play around with the code but I can't seem to figure this one out.

I've created a simple function, and wanting to call upon the function to calculate the sum of variables in an array. Here is my code below:

//functions

function simpleCalc (a,b) {
    var result = a + b;
    return result;
}

//array

var myArray = [12,567];

//final calculation

var total = simpleCalc([0],[1]);

alert("The total is " + total);

Can anyone please shed any light as to how I input the numbers "12" and "567" into the function parameters? The result here as it stands outputs to "01"

Thanks


问:
How to merge PNGS with alpha channels into one larger image?
I am trying to layer these:

into this:

But what I keep getting is this:

This is the relevant code, Im not sure what Im missing:

```<code>    $sig_background = imagecreatefrompng("sanctum-signature.png");
imagealphablending($sig_background, false);
imagesavealpha($sig_background, true);
$sig_gamertile = imagecreatefrompng($gamertile_masked_file);
imagealphablending($sig_gamertile, false);
imagesavealpha($sig_gamertile, true);
$sig_gametile = imagecreatefrompng($gametile_masked_file);
imagealphablending($sig_gamertile, false);
imagesavealpha($sig_gamertile, true);
imagecopymerge($sig_background, $sig_gamertile, 175, 2, 0, 0, 64, 64, 100);
imagecopymerge($sig_background, $sig_gametile, 342, 20, 0, 0, 64, 64, 100);
</code>```

If any more information is missing, please let me know and Ill try to fill in the blanks. Thank you for your time.

edit - here are links to the files (hosted on photobucket)
gamertile
gametile

答:
There's a typo in your code, is it a copy/paste error or a real bug?

You do:

```<code>$sig_gamertile = imagecreatefrompng($gamertile_masked_file);
imagealphablending($sig_gamertile, false);
imagesavealpha($sig_gamertile, true);
</code>```

And then:

```<code>$sig_gametile = imagecreatefrompng($gametile_masked_file);
</code>```

But straight afterwards, you continue to call functions on $sig_gamertile instead of $sig_gametile:

```<code>imagealphablending($sig_gamertile, false);
imagesavealpha($sig_gamertile, true);
</code>```

Obviously radically renaming some vars would help guard against this.

ContentLicense: CC BY-SA 2.5

Body:
I am trying to layer these:

into this:

But what I keep getting is this:

This is the relevant code, Im not sure what Im missing:

    $sig_background = imagecreatefrompng("sanctum-signature.png");
imagealphablending($sig_background, false);
imagesavealpha($sig_background, true);
$sig_gamertile = imagecreatefrompng($gamertile_masked_file);
imagealphablending($sig_gamertile, false);
imagesavealpha($sig_gamertile, true);
$sig_gametile = imagecreatefrompng($gametile_masked_file);
imagealphablending($sig_gamertile, false);
imagesavealpha($sig_gamertile, true);
imagecopymerge($sig_background, $sig_gamertile, 175, 2, 0, 0, 64, 64, 100);
imagecopymerge($sig_background, $sig_gametile, 342, 20, 0, 0, 64, 64, 100);

If any more information is missing, please let me know and Ill try to fill in the blanks. Thank you for your time.

edit - here are links to the files (hosted on photobucket)
gamertile
gametile

Body:
There's a typo in your code, is it a copy/paste error or a real bug?

You do:

$sig_gamertile = imagecreatefrompng($gamertile_masked_file);
imagealphablending($sig_gamertile, false);
imagesavealpha($sig_gamertile, true);

And then:

$sig_gametile = imagecreatefrompng($gametile_masked_file);

But straight afterwards, you continue to call functions on $sig_gamertile instead of $sig_gametile:

imagealphablending($sig_gamertile, false);
imagesavealpha($sig_gamertile, true);

Obviously radically renaming some vars would help guard against this.


问:
Incorrect syntax near the keyword 'join' using asp.net part 2
take note im still a beginner in databases but willing to learn! This question is related to Incorrect syntax near the keyword 'JOIN'. using asp.net. But this time, i want to know how to update a data from database. I've tried this code but it is giving me an error "Incorrect syntax near the keyword 'JOIN'". Kindly help me on solving this one.

```<code>string queryGuitarItems = "UPDATE stringInstrumentItem JOIN brand ON stringInstrumentItem.brandId = brand.brandId SET stringInstrumentItem.brandId = @brandId IN (SELECT brand.brandId FROM brand WHERE name = @oldBrandName";
    using (SqlConnection connectionGuitarItems = new SqlConnection(ConfigurationManager.ConnectionStrings["musicStoreConnection"].ToString()))
    {
        using (SqlCommand commandGuitarItems = new SqlCommand(queryGuitarItems, connectionGuitarItems))
        {
            List<SqlParameter> parameterGuitarItems = new List<SqlParameter>();
            parameterGuitarItems.Add(new SqlParameter("@brandId", newName.Text));
            parameterGuitarItems.Add(new SqlParameter("@oldBrandName", oldName));

            connectionGuitarItems.Open();
            GetParameterGuitarItems(commandGuitarItems,parameterGuitarItems.ToArray());
            commandGuitarItems.ExecuteNonQuery();
            connectionGuitarItems.Close();
            commandGuitarItems.Parameters.Clear();
        }
    }
</code>```

Here is also the code for GerParameterGuitarItems method:

```<code>public void GetParameterGuitarItems(SqlCommand command, params SqlParameter[] parameterGuitarItems)
{
    if (parameterGuitarItems != null && parameterGuitarItems.Any())
    {
        command.Parameters.AddRange(parameterGuitarItems);
    }
}
</code>```

Additional Info:

Table stringInstrumentItem(The column brandId is the foreign key and references the primary key of table brand, which is also named brandId):

itemId     brandId     model

1             1               xyz

2             1               abc

3             2               hjk

Table brand(which has the primary key called brandId that is referencing by the table strinInstrumentItem):

brandId     name     image

1             Ibanez       xyz.jpg

2             Fender       abc.jpg

3             Gibson       hjk.jpg

Main goal is to update the column called name in table brand through my gridview. Like for example in brandId#1, name is equals to Ibanez, and I want to change it to Jackson. It should be able to work without the exception error. How to query this one?

答:
I'm going to guess that you are using SQL Server (something about the c# tag).  If so, the correct syntax is:

```<code>UPDATE sii
    SET brandId = @brandId
    FROM stringInstrumentItem sii JOIN
         brand b
         ON sii.brandId = b.brandId
    WHERE b.brandId IN (SELECT b2.brandId FROM brand b2 WHERE b2.name = @oldBrandName);
</code>```

If I understand what you are trying to do, then this is over-complicated, and this suffices:

```<code>UPDATE sii
    SET brandId = @brandId
    FROM stringInstrumentItem sii
    WHERE sii.brandId IN (SELECT b.brandId FROM brand b WHERE b.name = @oldBrandName);
</code>```

Or, in a version that should work in any database:

```<code>UPDATE stringInstrumentItem
    SET brandId = @brandId
    WHERE brandId IN (SELECT b.brandId FROM brand b WHERE b.name = @oldBrandName);
</code>```

Body:
take note im still a beginner in databases but willing to learn! This question is related to Incorrect syntax near the keyword 'JOIN'. using asp.net. But this time, i want to know how to update a data from database. I've tried this code but it is giving me an error "Incorrect syntax near the keyword 'JOIN'". Kindly help me on solving this one.

string queryGuitarItems = "UPDATE stringInstrumentItem JOIN brand ON stringInstrumentItem.brandId = brand.brandId SET stringInstrumentItem.brandId = @brandId IN (SELECT brand.brandId FROM brand WHERE name = @oldBrandName";
    using (SqlConnection connectionGuitarItems = new SqlConnection(ConfigurationManager.ConnectionStrings["musicStoreConnection"].ToString()))
    {
        using (SqlCommand commandGuitarItems = new SqlCommand(queryGuitarItems, connectionGuitarItems))
        {
            List<SqlParameter> parameterGuitarItems = new List<SqlParameter>();
            parameterGuitarItems.Add(new SqlParameter("@brandId", newName.Text));
            parameterGuitarItems.Add(new SqlParameter("@oldBrandName", oldName));

            connectionGuitarItems.Open();
            GetParameterGuitarItems(commandGuitarItems,parameterGuitarItems.ToArray());
            commandGuitarItems.ExecuteNonQuery();
            connectionGuitarItems.Close();
            commandGuitarItems.Parameters.Clear();
        }
    }

Here is also the code for GerParameterGuitarItems method:

public void GetParameterGuitarItems(SqlCommand command, params SqlParameter[] parameterGuitarItems)
{
    if (parameterGuitarItems != null && parameterGuitarItems.Any())
    {
        command.Parameters.AddRange(parameterGuitarItems);
    }
}

Additional Info:

Table stringInstrumentItem(The column brandId is the foreign key and references the primary key of table brand, which is also named brandId):

itemId     brandId     model

1             1               xyz

2             1               abc

3             2               hjk

Table brand(which has the primary key called brandId that is referencing by the table strinInstrumentItem):

brandId     name     image

1             Ibanez       xyz.jpg

2             Fender       abc.jpg

3             Gibson       hjk.jpg

Main goal is to update the column called name in table brand through my gridview. Like for example in brandId#1, name is equals to Ibanez, and I want to change it to Jackson. It should be able to work without the exception error. How to query this one?

Body:
I'm going to guess that you are using SQL Server (something about the c# tag).  If so, the correct syntax is:

UPDATE sii
    SET brandId = @brandId
    FROM stringInstrumentItem sii JOIN
         brand b
         ON sii.brandId = b.brandId
    WHERE b.brandId IN (SELECT b2.brandId FROM brand b2 WHERE b2.name = @oldBrandName);

If I understand what you are trying to do, then this is over-complicated, and this suffices:

UPDATE sii
    SET brandId = @brandId
    FROM stringInstrumentItem sii
    WHERE sii.brandId IN (SELECT b.brandId FROM brand b WHERE b.name = @oldBrandName);

Or, in a version that should work in any database:

UPDATE stringInstrumentItem
    SET brandId = @brandId
    WHERE brandId IN (SELECT b.brandId FROM brand b WHERE b.name = @oldBrandName);


问:
Getting value from combobox and send it as a parameter to a method
I have a combo box in my WinForms and it has values from 1 to 5. I wanted to know how to send the selected combobox value as a parameter to a method.

I am populating my combo box using the below code.

```<code>public class Form
{
    public Form()
    {
        this.InitializeComponent();
        const int maximumValue = 5;
        for (var i = 1; i <= maximumValue; i++)
        {
            this.comboBox1.Items.Add(i);
        }

        this.comboBox1.SelectedIndex = 4;
    }
}
</code>```

I wanted to use the above combo box selection as a parameter instead of declaring an int maxValue = 5 variable to the below function

```<code>private class Test
{
    private bool Check(int number, int maxValue = 7)
    {
       // Some logic here where I can use comboBox value;
    }

    // Test is an Enum
    public static Test Differentiate(string file1, string file2)
    {
       bool equal = true;
       var number = 1;

       // Some logic here;

      // currently I am just passing number as a parameter
      equal = Check(number);

      return Test.Ok;
    }
}
</code>```

Also, the comboBox code in one class and the method I want to use the comboBox.SelectedItem value is in another class. How do I call the comboBox code in the class where I want to use it?

Can anyone give me any suggestions as to how to achieve this?

答:
```<code>public object GetComboBoxItem(int index)
{
    if (index >= MyCombo.Items.Count)
        return null;

    return MyCombo.Items[index];
}
</code>```

Thus, you'll return the value and use it in another subroutine

Body:
I have a combo box in my WinForms and it has values from 1 to 5. I wanted to know how to send the selected combobox value as a parameter to a method.

I am populating my combo box using the below code.

public class Form
{
    public Form()
    {
        this.InitializeComponent();
        const int maximumValue = 5;
        for (var i = 1; i <= maximumValue; i++)
        {
            this.comboBox1.Items.Add(i);
        }

        this.comboBox1.SelectedIndex = 4;
    }
}

I wanted to use the above combo box selection as a parameter instead of declaring an int maxValue = 5 variable to the below function

private class Test
{
    private bool Check(int number, int maxValue = 7)
    {
       // Some logic here where I can use comboBox value;
    }

    // Test is an Enum
    public static Test Differentiate(string file1, string file2)
    {
       bool equal = true;
       var number = 1;

       // Some logic here;

      // currently I am just passing number as a parameter
      equal = Check(number);

      return Test.Ok;
    }
}

Also, the comboBox code in one class and the method I want to use the comboBox.SelectedItem value is in another class. How do I call the comboBox code in the class where I want to use it?

Can anyone give me any suggestions as to how to achieve this?

Body:
public object GetComboBoxItem(int index)
{
    if (index >= MyCombo.Items.Count)
        return null;

    return MyCombo.Items[index];
}

Thus, you'll return the value and use it in another subroutine


问:
DatePicker Widget Format
I have defined a xml layout with the DatePicker widget as follows:

```<code>     <DatePicker
        android:id="@+id/SelectDate"
        android:layout_marginTop="10dp"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:gravity="center|center_horizontal|center_vertical">
    </DatePicker>
</code>```

and it is being displayed in mm/dd/yyyy format, as below:

but how can I display the DatePicker widget in (dd/mm/yyyy) format, as below?

答:
The picker take the date format chosen by the user, which means you don't really have to format it, as probably the user enjoyes the most to see the format he's used to.

I've just tested the HelloDatePicker tutorial and in my phone, I have the date in (dd/mm/yyyy) format, so the picker shows the same format; in emulator, I've put the date in mm/dd/yyyy format, so the picker displays the same.

According to this answer there is no method to set the display format.

Title: DatePicker Widget Format

Body:
I have defined a xml layout with the DatePicker widget as follows:

     <DatePicker
        android:id="@+id/SelectDate"
        android:layout_marginTop="10dp"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:gravity="center|center_horizontal|center_vertical">
    </DatePicker>

and it is being displayed in mm/dd/yyyy format, as below:

but how can I display the DatePicker widget in (dd/mm/yyyy) format, as below?


问:
Get text between two integers Javascript
```<code>var string = "454 blah bah 78";
</code>```

How can I get the text between 454 and 78 when those two numbers are random? Like

```<code>var string = "randnumber blah bah randnumber2";
</code>```

Note those numbers will always be integers and 2-3 characters long.

答:
You can use a regular expression to select and remove the numbers from the string. The regexp that selects all numbers is /[0-9]/.
You can test regular expressions and practice with them in a variety of places online. Here is one: https://regex101.com/

So if your string is:

var string = "454 blah bah 78";,

you would want to:

string = string.replace(/[0-9]/g, '');.

The first part string = string... resets the var string as the result of calling the function .replace... on itself.

Note: this will take ALL of the numbers out of the string, so if there were  other numbers within that you wanted to keep, you'd have to work around it differently.

Body:
var string = "454 blah bah 78";

How can I get the text between 454 and 78 when those two numbers are random? Like

var string = "randnumber blah bah randnumber2";

Note those numbers will always be integers and 2-3 characters long.


问:
UCanAccess/Jackcess Create View/Save Query in Access
In Access you can save queries in a view.
In my Java project I use UCanAccess with the underlying Jackcess library.
The normal SQL Statement CREATE VIEW <name> AS <Select Statement> is not supported by UCanAccess at the moment and I don't know when it will support it.

Can Jackcess perform the equivalent of CREATE VIEW?

答: No. Jackcess can retrieve the SQL string of an existing saved query but it cannot create new ones.</p>


问:
PHP parsed error : unexpected '<<' (echo <<<_EOT)
I tried to use echo <<< syntax on my website, but it said parse error.

```<code><?php
echo <<<_EOT
<h1>Welcome to www.panthers.zone, TIS community.</h1>
<br><br> <h5>We are still building our website, Any interest about
<i>The Independent School</i> see:
</h5> <a href='www.theindependentschool.com'>
www.theindependentschool.com </a><br><br> Hope you have a good day! --- TIS Web Development club
_EOT;

?>
</code>```

I've tried many search the solution online but it doesn't appears to be the same problem.

Here is the error log:

2017/07/09 22:32:51 [error] 5439#0: *17 FastCGI sent in stderr: "PHP message: PHP Parse error:  syntax error, unexpected '<<' (T_SL) in /var/local/www/front/index.php on line 3" while reading response header from upstream, client: 13.59.195.100, server: panthers.zone, request: "GET / HTTP/1.1", upstream: "fastcgi://unix:/tmp/php-cgi.sock:", host: "panthers.zone"

答:
It appears as if you are using the PHP echo function incorrectly.

This is the best place to go to understand how to use it correctly. http://php.net/manual/en/function.echo.php

However, from what I can see in your screenshot - you are not using any php variables hence you do not need the php tags.

Body:
I tried to use echo <<< syntax on my website, but it said parse error.

<?php
echo <<<_EOT

Welcome to www.panthers.zone, TIS community.

We are still building our website, Any interest about
The Independent School see:

www.theindependentschool.com

 Hope you have a good day! --- TIS Web Development club
_EOT;

?>

I've tried many search the solution online but it doesn't appears to be the same problem.

Here is the error log:

2017/07/09 22:32:51 [error] 5439#0: *17 FastCGI sent in stderr: "PHP message: PHP Parse error:  syntax error, unexpected '<<' (T_SL) in /var/local/www/front/index.php on line 3" while reading response header from upstream, client: 13.59.195.100, server: panthers.zone, request: "GET / HTTP/1.1", upstream: "fastcgi://unix:/tmp/php-cgi.sock:", host: "panthers.zone"


问:
Reset button for flexdashboard in R
I have developed a flexdashboard in R. I have three drop down menu as input for the dashboard. Based upon the input to these drop down menu the dashboard changes accordingly.

Right, i need a reset button to reset my inputs in drop down menu to default values.

Any input is appreciated.

Regards,

Mohan

答:
Here's how you can set up input$reset to act as a reset button.

First you need the input on your sidebar:

selectizeInput("input_name", "My Input", c("Choose one" = "", c("Option 1","Option 2")))

Then set up the reset button UI:

actionButton("reset", "Reset Inputs")

Finally, set up an observer tied to the reset button that changes the inputs back to default (or whatever you specify):

observeEvent(input$reset, {
    updateSelectizeInput("input_name", "My Input", c("Choose one" = "", c("Option 1","Option 2")))
}

You can put all of this in your sidebar in flexdashboard. I hope this was helpful.

Title: Reset button for flexdashboard in R


问:
Receive asynchronous events from a web application to a desktop application in Actionscript 3
I want to build a simple web 2.0 collaborative website using asp.net MVC2 or Flash  and I want to  receive events from a web based interface to a desktop AIR application. For e.g, someone makes a comment on a blog post, I want that information to be passed on to a desktop air application showing that a new comment has been made. What would be a good technique to receive asynchronous events?</p>

答:
The easy way is to set a timer that will request the XML from your webservice each XXXX miliseconds.
An optimization tip could be ask if there are new items to load before call the complete XML.</p>


问:
HTML svg animation issues
I am trying to create simple animation with SVG and HTML only.
The goal is:

Take the first picture and move it from position (80,100) to (100,100)

Take the second picture and move it from position (80,100) to (95,100)

Take the third picture and move it from position (80,100) to (90,100)

Hide all three pictures

Repeat steps 1-4

I have something like this :

```<code><svg width="500" height="500">
   <image xlink:href="pic.png" height="30" width="30"/>
    <path id="path1" d="M 80 100 l 20 0" />
    <animateMotion dur="1" repeatCount="indefinite" rotate="0" >
       <mpath xlink:href="#path1"/>
    </animateMotion>
</svg>
</code>```

In this case, first picture moved from (80,100) to (100,100) but as soon as it reached the final position it started moving again from (80,100).

How can I make every following picture 'wait' for all the rest pics and then start moving first picture from (80,100) again?

答:
Note that if you are just moving in a straight line, you don't need to use <animateMotion>. You can just animate the x and y attributes.

<svg width="500" height="500" viewBox="0 0 150 150">

   <image xlink:href="http://lorempixel.com/output/cats-q-c-30-30-1.jpg" height="30" width="30" x="80" y="100">
     <animate id="one" attributeName="x" begin="0s;three.end+2s" dur="1s" fill="freeze"
              from="80" to="100"/>
     <animate attributeName="y" begin="0s;three.end+2s" dur="1s" fill="freeze"
              from="100" to="100"/>
     <set attributeName="opacity" to="1" begin="0s;three.end+2s" fill="freeze"/>
     <set attributeName="opacity" to="0" begin="three.end+1s"/>
   </image>

   <image xlink:href="http://lorempixel.com/output/food-q-c-30-30-3.jpg" height="30" width="30" x="80" y="100"
          opacity="0">
     <animate id="two" attributeName="x" begin="one.end" dur="1s" fill="freeze"
              from="80" to="100"/>
     <animate attributeName="y" begin="one.end" dur="1s" fill="freeze"
              from="100" to="70"/>
     <set attributeName="opacity" to="1" begin="one.end" fill="freeze"/>
     <set attributeName="opacity" to="0" begin="three.end+1s"/>
   </image>

   <image xlink:href="http://lorempixel.com/output/people-q-c-30-30-3.jpg" height="30" width="30" x="80" y="100"
          opacity="0">
     <animate id="three" attributeName="x" begin="two.end" dur="1s" fill="freeze"
              from="80" to="100"/>
     <animate attributeName="y" begin="two.end" dur="1s" fill="freeze"
              from="100" to="40"/>
     <set attributeName="opacity" to="1" begin="two.end" fill="freeze"/>
     <set attributeName="opacity" to="0" begin="three.end+1s"/>
   </image>

</svg>```

Title: HTML svg animation issues

Body:
I am trying to create simple animation with SVG and HTML only.
The goal is:

Take the first picture and move it from position (80,100) to (100,100)

Take the second picture and move it from position (80,100) to (95,100)

Take the third picture and move it from position (80,100) to (90,100)

Hide all three pictures

Repeat steps 1-4

I have something like this :

<svg width="500" height="500">
   <image xlink:href="pic.png" height="30" width="30"/>
    <path id="path1" d="M 80 100 l 20 0" />
    <animateMotion dur="1" repeatCount="indefinite" rotate="0" >
       <mpath xlink:href="#path1"/>
    </animateMotion>
</svg>

In this case, first picture moved from (80,100) to (100,100) but as soon as it reached the final position it started moving again from (80,100).

How can I make every following picture 'wait' for all the rest pics and then start moving first picture from (80,100) again?


问:
Recenter cursor in middle of screen when editing in Xcode
I dislike having to edit near the bottom of my screen. This happens a lot in Xcode when editing near the end of a file. In other editors (such as vim or sublime) you can recenter the editing point vertically to the middle of the screen.

Is there a shortcut to do this in Xcode?

答:
As far as I can tell, and as mentioned in the comments, Xcode won't scroll past the bottom of your content, so you won't be able to centre on your last line (unless you've added a load of newlines to the end of the file, which is obviously a bit gross).

However, there is a way to centre on a line that can be centred on which can be configured in the Key Bindings section of Xcode's Preferences (at least in Xcode 8.3, I haven't checked earlier ones). If you filter for "center" you'll see Center Selection in Visible Area, and you can assign it to something.

For example, I have assigned it to Cmd-Alt-Ctrl-K in the below screenshot.


问:
Django - overridden save function won't save parent fields
I'm creating a django app for an education company, and I created a custom user model and two classes (Student and Teacher) that will inherit from the User model through a one-to-one relationship.

I'm trying to avoid the situation where a teacher and a student both use the same user object. Thus, I have a user_type char field in my User object, and the idea is when a user is set to a teacher, the field will be updated. Then if I try to make the user a student, it should throw an error.

I'm trying to do the check in the clean function - after the clean() function is called in the save() function, the user_type seems to be updated, but when I actually test, it seems user_type is returning a blank string. I'm wondering if someone could point me the right direction.

```<code>class User(AbstractUser):
    user_type = models.CharField(max_length=20, choices=USER_TYPES, blank=True)

class Teacher(TimeStampedModel):
    user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)

    def clean(self):
        if self.user.user_type and self.user.user_type !='teacher':
            raise ValidationError('Some error')
        else:
            self.user.user_type = 'teacher'

    def save(self, *args, **kwargs):
        self.clean()
        #this prints 'teacher'
        print(self.user.user_type)
        super().save(*args, **kwargs)

tests.py
#this test fails
def test_should_set_user_type_automatically_to_teacher(self):
    user = User.objects.create(username='tangbj', first_name='Dan')
    Teacher.objects.create(user=user)
    teacher = Teacher.objects.get(user__username='tangbj')

    print(teacher.user.user_type)
    self.assertEqual(teacher.user.user_type, 'teacher')
</code>```

答:
You are saving the Teacher instance, not the User instance. When you assign the user_type, you should do a save(..) to the User instance. Records aren't magically updated.

Said in another way; you are modifying an instance attribute, but you are not saving the instance.

Body:
I'm creating a django app for an education company, and I created a custom user model and two classes (Student and Teacher) that will inherit from the User model through a one-to-one relationship.

I'm trying to avoid the situation where a teacher and a student both use the same user object. Thus, I have a user_type char field in my User object, and the idea is when a user is set to a teacher, the field will be updated. Then if I try to make the user a student, it should throw an error.

I'm trying to do the check in the clean function - after the clean() function is called in the save() function, the user_type seems to be updated, but when I actually test, it seems user_type is returning a blank string. I'm wondering if someone could point me the right direction.

class User(AbstractUser):
    user_type = models.CharField(max_length=20, choices=USER_TYPES, blank=True)

class Teacher(TimeStampedModel):
    user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)

    def clean(self):
        if self.user.user_type and self.user.user_type !='teacher':
            raise ValidationError('Some error')
        else:
            self.user.user_type = 'teacher'

    def save(self, *args, **kwargs):
        self.clean()
        #this prints 'teacher'
        print(self.user.user_type)
        super().save(*args, **kwargs)

tests.py
#this test fails
def test_should_set_user_type_automatically_to_teacher(self):
    user = User.objects.create(username='tangbj', first_name='Dan')
    Teacher.objects.create(user=user)
    teacher = Teacher.objects.get(user__username='tangbj')

    print(teacher.user.user_type)
    self.assertEqual(teacher.user.user_type, 'teacher')


问:
How to debug JavaScript code with mobile browsers
I know about firebug and the developer tools for the major modern desktop browsers, but I can't find any way of debugging JavaScript code on mobile browsers.

What are some high level techniques I can use to debug code on mobile browsers?

答:
Android provides a tool set for these purposes:
https://developers.google.com/web/tools/chrome-devtools/remote-debugging/?utm_source=dcc&utm_medium=redirect&utm_campaign=2016q3

Apple does it a similar way:
https://developer.apple.com/safari/tools/

Tutorial: https://css-tricks.com/using-chrome-devtools-to-debug-javascript-in-any-browser-with-ghostlab-2/


问:
Split string into array Shellscript
How can I split a string into array in shell script?

I tried with IFS='delimiter' and it works with loops (for, while) but I need an array from that string.

How can I make an array from a string?

Thanks!

答:
Combining the answers above into something that worked for me

```<code>set -- `echo $PATH|cut -d':' --output-delimiter=" " -f 1-`; for i in "$@"; do echo $i; done
</code>```

gives

```<code># set -- `echo $PATH|cut -d':' --output-delimiter=" " -f 1-`; for i in "$@"; do echo $i; done
/usr/local/sbin
/usr/local/bin
/usr/sbin
/usr/bin
/sbin
/bin
#
</code>```

Title: Split string into array Shellscript

Body:
Combining the answers above into something that worked for me

set -- `echo $PATH|cut -d':' --output-delimiter=" " -f 1-`; for i in "$@"; do echo $i; done

gives

# set -- `echo $PATH|cut -d':' --output-delimiter=" " -f 1-`; for i in "$@"; do echo $i; done
/usr/local/sbin
/usr/local/bin
/usr/sbin
/usr/bin
/sbin
/bin
#


问:
Are there cases where a singleton is the best option?
There is a lot of discussion on this site about why singletons should be avoided but are there any cases where a singleton makes sense and is the best option?

An example where I think that a singleton is the best option is when implementing an Identity Map where you need to keep track of all models that have already been loaded from the database in your mapping layer. In this case it is important that the map is effectively global so that all client code uses the same instance of the map and they are all accessing the same list of loaded models. The simplest solution seems to be to implement the class as a singleton (or as static methods). Is this the best approach or is there another way?

Are there any other cases where it is OK to use a singleton or are they always bad?

答:
My personal guideline is to never hardcode a class as a singleton if you can just instantiate one object of a class afterwards. This makes singletons very rare and often unnecessary in application code. This is especially true when using DI frameworks like Spring.

Singletons do have a use as 'entry points' in frameworks, but there the rule would be to use them as 'root singletons' (at the start of the dependency hierarchy) and let the rest of the code depend on that singleton as little as possible.


问:
Android AdMob - Ad without XML
Is there a simple way to add an add to the top of an app by code, without using XML layouts? I can't find anything in the documentation.</p>

答:
You can try doing the same as a normal View in Android.

From the code do an add() on a ViewGroup of the admob view.

Title: Android AdMob - Ad without XML


问:
Save sniffed packets into a variable or a file after keyboardInterrupt using scapy and python
Can someone please help me with saving sniffed packets into a file using scapy? I need to use scapy to sniff untill a keyboardInterrupt and save the sniffed packets into a pcap file, the problem is that the keyboardInterrupt makes the sniffed packets disapear, so is there a way to save the packets while sniffing? or save them into the variable even though there is an exception?

This is what I tried so far but the exeption prevented it from being saved:

```<code>from scapy.all import *
try:
    packets = sniff()
except KeyboardInterrupt as ki:
    pass
</code>```

答:
Maybe you can store them using a function

```<code>from scapy.all import *

packet_list = []

def storepkt(pkt):
    packet_list.append(pkt)

try:
    sniff(ptr=storepkt)
except KeyboardInterrupt as ki:
    #Here you should have access to the packet_list list and do whatever you need with them, i.e.:
    for pkt in packet_list:
        pkt.show()
</code>```

Note that this code is for Python 2.7.

Body:
Can someone please help me with saving sniffed packets into a file using scapy? I need to use scapy to sniff untill a keyboardInterrupt and save the sniffed packets into a pcap file, the problem is that the keyboardInterrupt makes the sniffed packets disapear, so is there a way to save the packets while sniffing? or save them into the variable even though there is an exception?

This is what I tried so far but the exeption prevented it from being saved:

from scapy.all import *
try:
    packets = sniff()
except KeyboardInterrupt as ki:
    pass

Body:
Maybe you can store them using a function

from scapy.all import *

packet_list = []

def storepkt(pkt):
    packet_list.append(pkt)

try:
    sniff(ptr=storepkt)
except KeyboardInterrupt as ki:
    #Here you should have access to the packet_list list and do whatever you need with them, i.e.:
    for pkt in packet_list:
        pkt.show()

Note that this code is for Python 2.7.


问:
HTML sections overlapping
I have the following simple HTML layout

.section1 {
  background: red;
}

.section2 {
  background: green;
}

.section3 {
  background: yellow;
}

article {
  float: left;
  width: 33%;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><section class="section1">
  <p>
    Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse id eros vel ex porta viverra ac sit amet quam. Morbi quis consequat dolor. Vestibulum ultricies leo ac orci fringilla, et congue erat euismod. Donec vestibulum nisi eu orci commodo congue.
    Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus pretium consectetur mi quis vehicula. Donec ac velit id mi facilisis luctus. Vivamus placerat eros vel quam placerat, a varius quam malesuada. Proin nec lectus ac augue varius hendrerit.
    Curabitur mattis dolor non arcu faucibus, at viverra purus feugiat. Suspendisse potenti. Nunc non metus eget ipsum efficitur tincidunt id eget elit. Donec ac molestie libero. In hac habitasse platea dictumst. Morbi eget fermentum orci, nec volutpat
    enim. Proin ac leo urna. Nam facilisis ut arcu eget interdum. Ut vulputate massa ut pretium accumsan. Nullam eros diam, elementum ac feugiat eu, hendrerit in sapien. Nullam accumsan arcu quis ante aliquam lacinia.
  </p>
</section>

<section class="section2">
  <p>
    Section 2 content
  </p>
  <article>
    Sed eget magna sit amet turpis elementum finibus. Mauris commodo porttitor nisl. Praesent dignissim vel mi quis vestibulum. Suspendisse porttitor magna sit amet eros semper, volutpat interdum nisl ultrices. Pellentesque habitant morbi tristique senectus
    et netus et malesuada fames ac turpis egestas. </article>
  <article>
    Fusce pretium neque non lorem scelerisque iaculis. Etiam porta gravida est rutrum porta. Nullam venenatis elit nec ipsum volutpat pretium. Nunc ut hendrerit est, in euismod sapien. Aliquam non nulla auctor, scelerisque ipsum id, mattis ex. </article>
  <article>
    Curabitur porta tincidunt erat ac sollicitudin. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos
  </article>
</section>

<section class="section3">
  Section 3 content
</section></code>```

The second and third sections are overlapping, what am I doing wrong?

答:
This is due to float nature. You'll need to use clearfix for section2:

```<code>/* clearfix */
.section2:after {
  content: "";
  display: table;
  clear: both;
}
</code>```

Demo:

.section1 {
  background: red;
}

.section2 {
  background: green;
}

/* clearfix */
.section2:after {
  content: "";
  display: table;
  clear: both;
}

.section3 {
  background: yellow;
}

article {
  float: left;
  width: 33%;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><section class="section1">
  <p>
    Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse id eros vel ex porta viverra ac sit amet quam. Morbi quis consequat dolor. Vestibulum ultricies leo ac orci fringilla, et congue erat euismod. Donec vestibulum nisi eu orci commodo congue.
    Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus pretium consectetur mi quis vehicula. Donec ac velit id mi facilisis luctus. Vivamus placerat eros vel quam placerat, a varius quam malesuada. Proin nec lectus ac augue varius hendrerit.
    Curabitur mattis dolor non arcu faucibus, at viverra purus feugiat. Suspendisse potenti. Nunc non metus eget ipsum efficitur tincidunt id eget elit. Donec ac molestie libero. In hac habitasse platea dictumst. Morbi eget fermentum orci, nec volutpat
    enim. Proin ac leo urna. Nam facilisis ut arcu eget interdum. Ut vulputate massa ut pretium accumsan. Nullam eros diam, elementum ac feugiat eu, hendrerit in sapien. Nullam accumsan arcu quis ante aliquam lacinia.
  </p>
</section>

<section class="section2">
  <p>
    Section 2 content
  </p>
  <article>
    Sed eget magna sit amet turpis elementum finibus. Mauris commodo porttitor nisl. Praesent dignissim vel mi quis vestibulum. Suspendisse porttitor magna sit amet eros semper, volutpat interdum nisl ultrices. Pellentesque habitant morbi tristique senectus
    et netus et malesuada fames ac turpis egestas. </article>
  <article>
    Fusce pretium neque non lorem scelerisque iaculis. Etiam porta gravida est rutrum porta. Nullam venenatis elit nec ipsum volutpat pretium. Nunc ut hendrerit est, in euismod sapien. Aliquam non nulla auctor, scelerisque ipsum id, mattis ex. </article>
  <article>
    Curabitur porta tincidunt erat ac sollicitudin. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos
  </article>
</section>

<section class="section3">
  Section 3 content
</section></code>```

But you can use much more modern and powerful flexbox approach instead of floats (so you can remove float styles):

.section1 {
  background: red;
}

.section2 {
  display: flex; /* new */
  flex-wrap: wrap; /* new */
  background: green;
}

.section2 p {
  width: 100%; /* new */
}

.section3 {
  background: yellow;
}

article {
  width: 33%;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><section class="section1">
  <p>
    Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse id eros vel ex porta viverra ac sit amet quam. Morbi quis consequat dolor. Vestibulum ultricies leo ac orci fringilla, et congue erat euismod. Donec vestibulum nisi eu orci commodo congue.
    Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus pretium consectetur mi quis vehicula. Donec ac velit id mi facilisis luctus. Vivamus placerat eros vel quam placerat, a varius quam malesuada. Proin nec lectus ac augue varius hendrerit.
    Curabitur mattis dolor non arcu faucibus, at viverra purus feugiat. Suspendisse potenti. Nunc non metus eget ipsum efficitur tincidunt id eget elit. Donec ac molestie libero. In hac habitasse platea dictumst. Morbi eget fermentum orci, nec volutpat
    enim. Proin ac leo urna. Nam facilisis ut arcu eget interdum. Ut vulputate massa ut pretium accumsan. Nullam eros diam, elementum ac feugiat eu, hendrerit in sapien. Nullam accumsan arcu quis ante aliquam lacinia.
  </p>
</section>

<section class="section2">
  <p>
    Section 2 content
  </p>
  <article>
    Sed eget magna sit amet turpis elementum finibus. Mauris commodo porttitor nisl. Praesent dignissim vel mi quis vestibulum. Suspendisse porttitor magna sit amet eros semper, volutpat interdum nisl ultrices. Pellentesque habitant morbi tristique senectus
    et netus et malesuada fames ac turpis egestas. </article>
  <article>
    Fusce pretium neque non lorem scelerisque iaculis. Etiam porta gravida est rutrum porta. Nullam venenatis elit nec ipsum volutpat pretium. Nunc ut hendrerit est, in euismod sapien. Aliquam non nulla auctor, scelerisque ipsum id, mattis ex. </article>
  <article>
    Curabitur porta tincidunt erat ac sollicitudin. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos
  </article>
</section>

<section class="section3">
  Section 3 content
</section></code>```

Title: HTML sections overlapping

Body:
I have the following simple HTML layout

.section1 {
  background: red;
}

.section2 {
  background: green;
}

.section3 {
  background: yellow;
}

article {
  float: left;
  width: 33%;
}

    Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse id eros vel ex porta viverra ac sit amet quam. Morbi quis consequat dolor. Vestibulum ultricies leo ac orci fringilla, et congue erat euismod. Donec vestibulum nisi eu orci commodo congue.
    Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus pretium consectetur mi quis vehicula. Donec ac velit id mi facilisis luctus. Vivamus placerat eros vel quam placerat, a varius quam malesuada. Proin nec lectus ac augue varius hendrerit.
    Curabitur mattis dolor non arcu faucibus, at viverra purus feugiat. Suspendisse potenti. Nunc non metus eget ipsum efficitur tincidunt id eget elit. Donec ac molestie libero. In hac habitasse platea dictumst. Morbi eget fermentum orci, nec volutpat
    enim. Proin ac leo urna. Nam facilisis ut arcu eget interdum. Ut vulputate massa ut pretium accumsan. Nullam eros diam, elementum ac feugiat eu, hendrerit in sapien. Nullam accumsan arcu quis ante aliquam lacinia.

    Section 2 content

    Sed eget magna sit amet turpis elementum finibus. Mauris commodo porttitor nisl. Praesent dignissim vel mi quis vestibulum. Suspendisse porttitor magna sit amet eros semper, volutpat interdum nisl ultrices. Pellentesque habitant morbi tristique senectus
    et netus et malesuada fames ac turpis egestas.

    Fusce pretium neque non lorem scelerisque iaculis. Etiam porta gravida est rutrum porta. Nullam venenatis elit nec ipsum volutpat pretium. Nunc ut hendrerit est, in euismod sapien. Aliquam non nulla auctor, scelerisque ipsum id, mattis ex.

    Curabitur porta tincidunt erat ac sollicitudin. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos

  Section 3 content

The second and third sections are overlapping, what am I doing wrong?

Body:
This is due to float nature. You'll need to use clearfix for section2:

/* clearfix */
.section2:after {
  content: "";
  display: table;
  clear: both;
}

Demo:

.section1 {
  background: red;
}

.section2 {
  background: green;
}

/* clearfix */
.section2:after {
  content: "";
  display: table;
  clear: both;
}

.section3 {
  background: yellow;
}

article {
  float: left;
  width: 33%;
}

<section class="section1">
  <p>
    Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse id eros vel ex porta viverra ac sit amet quam. Morbi quis consequat dolor. Vestibulum ultricies leo ac orci fringilla, et congue erat euismod. Donec vestibulum nisi eu orci commodo congue.
    Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus pretium consectetur mi quis vehicula. Donec ac velit id mi facilisis luctus. Vivamus placerat eros vel quam placerat, a varius quam malesuada. Proin nec lectus ac augue varius hendrerit.
    Curabitur mattis dolor non arcu faucibus, at viverra purus feugiat. Suspendisse potenti. Nunc non metus eget ipsum efficitur tincidunt id eget elit. Donec ac molestie libero. In hac habitasse platea dictumst. Morbi eget fermentum orci, nec volutpat
    enim. Proin ac leo urna. Nam facilisis ut arcu eget interdum. Ut vulputate massa ut pretium accumsan. Nullam eros diam, elementum ac feugiat eu, hendrerit in sapien. Nullam accumsan arcu quis ante aliquam lacinia.
  </p>
</section>

<section class="section2">
  <p>
    Section 2 content
  </p>
  <article>
    Sed eget magna sit amet turpis elementum finibus. Mauris commodo porttitor nisl. Praesent dignissim vel mi quis vestibulum. Suspendisse porttitor magna sit amet eros semper, volutpat interdum nisl ultrices. Pellentesque habitant morbi tristique senectus
    et netus et malesuada fames ac turpis egestas. </article>
  <article>
    Fusce pretium neque non lorem scelerisque iaculis. Etiam porta gravida est rutrum porta. Nullam venenatis elit nec ipsum volutpat pretium. Nunc ut hendrerit est, in euismod sapien. Aliquam non nulla auctor, scelerisque ipsum id, mattis ex. </article>
  <article>
    Curabitur porta tincidunt erat ac sollicitudin. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos
  </article>
</section>

<section class="section3">
  Section 3 content
</section>

But you can use much more modern and powerful flexbox approach instead of floats (so you can remove float styles):

.section1 {
  background: red;
}

.section2 {
  display: flex; /* new */
  flex-wrap: wrap; /* new */
  background: green;
}

.section2 p {
  width: 100%; /* new */
}

.section3 {
  background: yellow;
}

article {
  width: 33%;
}

<section class="section1">
  <p>
    Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse id eros vel ex porta viverra ac sit amet quam. Morbi quis consequat dolor. Vestibulum ultricies leo ac orci fringilla, et congue erat euismod. Donec vestibulum nisi eu orci commodo congue.
    Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus pretium consectetur mi quis vehicula. Donec ac velit id mi facilisis luctus. Vivamus placerat eros vel quam placerat, a varius quam malesuada. Proin nec lectus ac augue varius hendrerit.
    Curabitur mattis dolor non arcu faucibus, at viverra purus feugiat. Suspendisse potenti. Nunc non metus eget ipsum efficitur tincidunt id eget elit. Donec ac molestie libero. In hac habitasse platea dictumst. Morbi eget fermentum orci, nec volutpat
    enim. Proin ac leo urna. Nam facilisis ut arcu eget interdum. Ut vulputate massa ut pretium accumsan. Nullam eros diam, elementum ac feugiat eu, hendrerit in sapien. Nullam accumsan arcu quis ante aliquam lacinia.
  </p>
</section>

<section class="section2">
  <p>
    Section 2 content
  </p>
  <article>
    Sed eget magna sit amet turpis elementum finibus. Mauris commodo porttitor nisl. Praesent dignissim vel mi quis vestibulum. Suspendisse porttitor magna sit amet eros semper, volutpat interdum nisl ultrices. Pellentesque habitant morbi tristique senectus
    et netus et malesuada fames ac turpis egestas. </article>
  <article>
    Fusce pretium neque non lorem scelerisque iaculis. Etiam porta gravida est rutrum porta. Nullam venenatis elit nec ipsum volutpat pretium. Nunc ut hendrerit est, in euismod sapien. Aliquam non nulla auctor, scelerisque ipsum id, mattis ex. </article>
  <article>
    Curabitur porta tincidunt erat ac sollicitudin. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos
  </article>
</section>

<section class="section3">
  Section 3 content
</section>


问:
How to display Splash Screen in android
I want to display splash screen in android app. But I want to execute onCreate() method of MainActivity behind the splash screen. because i am doing huge work in this method. Anyone can tel me how to do that.

答:
You can try this for Splash Screen...</p>

```<code>public class SplashScreen extends Activity {

//Further Needed Declarations

     @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_splash);

        /**
         * Showing splashscreen while making network calls to download necessary
         * data before launching the app Will use AsyncTask to make http call
         */
        new PrefetchData().execute();
    }
}
</code>```

Title: How to display Splash Screen in android

Body:
You can try this for Splash Screen...

public class SplashScreen extends Activity {

//Further Needed Declarations

     @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_splash);

        /**
         * Showing splashscreen while making network calls to download necessary
         * data before launching the app Will use AsyncTask to make http call
         */
        new PrefetchData().execute();
    }
}


问:
exclude @Component from @ComponentScan
I have a component that I want to exclude from a @ComponentScan in a particular @Configuration:

```<code>@Component("foo") class Foo {
...
}
</code>```

Otherwise, it seems to clash with some other class in my project. I don't fully understand the collision, but if I comment out the @Component annotation, things work like I want them to. But other projects that rely on this library expect this class to be managed by Spring, so I want to skip it only in my project.

I tried using @ComponentScan.Filter:

```<code>@Configuration
@EnableSpringConfigured
@ComponentScan(basePackages = {"com.example"}, excludeFilters={
  @ComponentScan.Filter(type=FilterType.ASSIGNABLE_TYPE, value=Foo.class)})
public class MySpringConfiguration {}
</code>```

but it doesn't appear to work. If I try using FilterType.ASSIGNABLE_TYPE, I get a strange error about being unable to load some seemingly random class:

Caused by: java.io.FileNotFoundException: class path resource [junit/framework/TestCase.class] cannot be opened because it does not exist

I also tried using type=FilterType.CUSTOM as following:

```<code>class ExcludeFooFilter implements TypeFilter {
    @Override
    public boolean match(MetadataReader metadataReader,
            MetadataReaderFactory metadataReaderFactory) throws IOException {
        return metadataReader.getClass() == Foo.class;
    }
}

@Configuration @EnableSpringConfigured
@ComponentScan(basePackages = {"com.example"}, excludeFilters={
  @ComponentScan.Filter(type=FilterType.CUSTOM, value=ExcludeFooFilter.class)})
public class MySpringConfiguration {}
</code>```

But that doesn't seem to exclude the component from the scan like I want.

How do I exclude it?

答:
I had an issue when using @Configuration, @EnableAutoConfiguration and @ComponentScan while trying to exclude specific configuration classes, the thing is it didn't work!

Eventually I solved the problem by using @SpringBootApplication, which according to Spring documentation does the same functionality as the three above in one annotation.

Another Tip is to try first without refining your package scan (without the basePackages filter).

```<code>@SpringBootApplication(exclude= {Foo.class})
public class MySpringConfiguration {}
</code>```

ContentLicense: CC BY-SA 4.0

Title: exclude @Component from @ComponentScan

Body:
I have a component that I want to exclude from a @ComponentScan in a particular @Configuration:

@Component("foo") class Foo {
...
}

Otherwise, it seems to clash with some other class in my project. I don't fully understand the collision, but if I comment out the @Component annotation, things work like I want them to. But other projects that rely on this library expect this class to be managed by Spring, so I want to skip it only in my project.

I tried using @ComponentScan.Filter:

@Configuration
@EnableSpringConfigured
@ComponentScan(basePackages = {"com.example"}, excludeFilters={
  @ComponentScan.Filter(type=FilterType.ASSIGNABLE_TYPE, value=Foo.class)})
public class MySpringConfiguration {}

but it doesn't appear to work. If I try using FilterType.ASSIGNABLE_TYPE, I get a strange error about being unable to load some seemingly random class:

Caused by: java.io.FileNotFoundException: class path resource [junit/framework/TestCase.class] cannot be opened because it does not exist

I also tried using type=FilterType.CUSTOM as following:

class ExcludeFooFilter implements TypeFilter {
    @Override
    public boolean match(MetadataReader metadataReader,
            MetadataReaderFactory metadataReaderFactory) throws IOException {
        return metadataReader.getClass() == Foo.class;
    }
}

@Configuration @EnableSpringConfigured
@ComponentScan(basePackages = {"com.example"}, excludeFilters={
  @ComponentScan.Filter(type=FilterType.CUSTOM, value=ExcludeFooFilter.class)})
public class MySpringConfiguration {}

But that doesn't seem to exclude the component from the scan like I want.

How do I exclude it?

Body:
I had an issue when using @Configuration, @EnableAutoConfiguration and @ComponentScan while trying to exclude specific configuration classes, the thing is it didn't work!

Eventually I solved the problem by using @SpringBootApplication, which according to Spring documentation does the same functionality as the three above in one annotation.

Another Tip is to try first without refining your package scan (without the basePackages filter).

@SpringBootApplication(exclude= {Foo.class})
public class MySpringConfiguration {}


问:
ControllerAs not working with es6 syntax
I am receiving the right information in my template with the following setup. But when I am trying to use the controllerAs syntax and refer with

```<code>{{ app.User }}
</code>```

or

```<code>{{ $ctrl.app.User }}
</code>```

it's not working. I am using ES6 syntax with a transpiler fyi.

This setup is working:

Template:

```<code><div><h4>Current App Scope User: </h4> {{ $ctrl.User }}</div>
</code>```

Controller:

```<code>class AppController {

  constructor($state, $rootScope, SessionService) {
    this.$state = $state;
    this.User = null;

    $rootScope.$on('UserIsUpdated', (event, user) => {
      this.User = user;
    });

    SessionService.retrieve();
  }

}
AppController.$inject = ['$state', '$rootScope', 'SessionService'];

export const app = {
  controller: AppController,
  controllerAs: app,
  templateUrl: 'app/main/parent/app.html'
}
</code>```

答:
Here is an example of an AngularJS controller written using ES6 class syntax:

class AppController {

  constructor($scope) {
    this.$scope = $scope;
  };

  $onInit () {
    this.$scope.hello = "Hello, ";
    this.world = "world"
  }

}

AppController.$inject = ['$scope'];

angular.module("app",[])
.controller("AppController", AppController)```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="//unpkg.com/angular/angular.js"></script>
  <body ng-app="app" ng-controller="AppController as $ctrl">
    <h1>ES6 AngularJS</h1>
    <p>{{hello}} {{$ctrl.world}}</p>
  </body></code>```

See also, ToddMoto: AngularJS styleguide (ES2015)

Body:
I am receiving the right information in my template with the following setup. But when I am trying to use the controllerAs syntax and refer with

{{ app.User }}

or

{{ $ctrl.app.User }}

it's not working. I am using ES6 syntax with a transpiler fyi.

This setup is working:

Template:

Current App Scope User:
 {{ $ctrl.User }}

Controller:

class AppController {

  constructor($state, $rootScope, SessionService) {
    this.$state = $state;
    this.User = null;

    $rootScope.$on('UserIsUpdated', (event, user) => {
      this.User = user;
    });

    SessionService.retrieve();
  }

}
AppController.$inject = ['$state', '$rootScope', 'SessionService'];

export const app = {
  controller: AppController,
  controllerAs: app,
  templateUrl: 'app/main/parent/app.html'
}

Body:
Here is an example of an AngularJS controller written using ES6 class syntax:

class AppController {

  constructor($scope) {
    this.$scope = $scope;
  };

  $onInit () {
    this.$scope.hello = "Hello, ";
    this.world = "world"
  }

}

AppController.$inject = ['$scope'];

angular.module("app",[])
.controller("AppController", AppController)

<script src="//unpkg.com/angular/angular.js"></script>
  <body ng-app="app" ng-controller="AppController as $ctrl">
    <h1>ES6 AngularJS</h1>
    <p>{{hello}} {{$ctrl.world}}</p>
  </body>

See also, ToddMoto: AngularJS styleguide (ES2015)


问:
500 jquery.min.js:4 (internal server error) laravel ajax
im new in ajax, and im tried this tutorial but i get 500 jquery.min.js:4  (internal server error), i dont have any idea to solve this, here is the code :

view :

```<code>  <div class="secure">Secure Login form</div>
  {!! Form::open(array('url'=>'account/login','method'=>'POST', 'id'=>'myform')) !!}
  <div class="control-group">
    <div class="controls">
       {!! Form::text('email','',array('id'=>'','class'=>'form-control span6','placeholder' => 'Email')) !!}
    </div>
  </div>
  <div class="control-group">
    <div class="controls">
    {!! Form::password('password',array('class'=>'form-control span6', 'placeholder' => 'Please Enter your Password')) !!}
    </div>
  </div>
  {!! Form::button('Login', array('class'=>'send-btn')) !!}
  {!! Form::close() !!}
</code>```

jquery :

```<code>  <script type="text/javascript">
    $(document).ready(function(){
     $('.send-btn').click(function(){
      $.ajax({
       url: 'login',
       type: "post",
       cache: false,
       data: {'email':$('input[name=email]').val(), '_token':
       $('input[name=_token]').val()},
       success: function(data){
       alert(data);
      }
     });
    });
   });
  </script>
</code>```

controller :

```<code>  public function login() {
  // Getting all post data
  if(Request::ajax()) {
    $data = Input::all();
    print_r($data);die;
  }
}
</code>```

routes :

```<code>Route::get('account/login', function() {
  return View::make('login');
});
Route::post('account/login', 'AccountController@login');
</code>```

答:
I believe you get 500 error code because you´re not sending any csrf token with your ajax request, try this in your javascript

```<code>$('.send-btn').click(function(){

    $.ajaxSetup({
        headers: {
            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
        }
    });

    $.ajax({
        url: 'login',
        type: "post",
        cache: false,
        data: {'email':$('input[name=email]').val(), '_token':
        $('input[name=_token]').val()},
        success: function(data){
            alert(data);
        }
    });

});
</code>```

If this doenst work you should open your console->network->click in your request and give us the response preview so we can help you

Body:
im new in ajax, and im tried this tutorial but i get 500 jquery.min.js:4  (internal server error), i dont have any idea to solve this, here is the code :

view :

Secure Login form

  {!! Form::open(array('url'=>'account/login','method'=>'POST', 'id'=>'myform')) !!}

       {!! Form::text('email','',array('id'=>'','class'=>'form-control span6','placeholder' => 'Email')) !!}

    {!! Form::password('password',array('class'=>'form-control span6', 'placeholder' => 'Please Enter your Password')) !!}

  {!! Form::button('Login', array('class'=>'send-btn')) !!}
  {!! Form::close() !!}

jquery :

controller :

  public function login() {
  // Getting all post data
  if(Request::ajax()) {
    $data = Input::all();
    print_r($data);die;
  }
}

routes :

Route::get('account/login', function() {
  return View::make('login');
});
Route::post('account/login', 'AccountController@login');

Body:
I believe you get 500 error code because you´re not sending any csrf token with your ajax request, try this in your javascript

$('.send-btn').click(function(){

    $.ajaxSetup({
        headers: {
            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
        }
    });

    $.ajax({
        url: 'login',
        type: "post",
        cache: false,
        data: {'email':$('input[name=email]').val(), '_token':
        $('input[name=_token]').val()},
        success: function(data){
            alert(data);
        }
    });

});

If this doenst work you should open your console->network->click in your request and give us the response preview so we can help you


问:
Change Firebase data coming from angularfire2
I have a database which stores a node like this:

```<code>-KdFlSK9eqzRDPd_I71I
     address:
     heats:
     image: 2017-02-18T10:30:15.025Z.jpeg
     title:
</code>```

Inside the image tag, there is the filename of a file stored in Firebase Storage. What I would like to do is get the full path to get the file from Firebase Storage before 2017-02-18T10:30:15.025Z.jpeg is inserted inside the image source. So basically, alter the data before render.

[Answer]

Very simple - I did not change the data from firebase, I simple set the new data to a new variable which doesn't show if not set.

答:
You can do it as shown below.You just need to put downloadURL on your image property after the image has been saved in the firebase storage.

Note: This is just a sample code where I used.Please adjust it according to your situation.

```<code> takeBillPhoto(billId: string, imageURL: string) {
    const storageRef = firebase.storage().ref(this.userId);
    return storageRef.child(billId).child('billPicture')
      .putString(imageURL, 'base64', { contentType: 'image/png' })
      .then(pictureSnapshot => {
        this.billList.update(billId, { picture: pictureSnapshot.downloadURL });
      });
  }
</code>```

Body:
I have a database which stores a node like this:

-KdFlSK9eqzRDPd_I71I
     address:
     heats:
     image: 2017-02-18T10:30:15.025Z.jpeg
     title:

Inside the image tag, there is the filename of a file stored in Firebase Storage. What I would like to do is get the full path to get the file from Firebase Storage before 2017-02-18T10:30:15.025Z.jpeg is inserted inside the image source. So basically, alter the data before render.

[Answer]

Very simple - I did not change the data from firebase, I simple set the new data to a new variable which doesn't show if not set.

Body:
You can do it as shown below.You just need to put downloadURL on your image property after the image has been saved in the firebase storage.

Note: This is just a sample code where I used.Please adjust it according to your situation.

 takeBillPhoto(billId: string, imageURL: string) {
    const storageRef = firebase.storage().ref(this.userId);
    return storageRef.child(billId).child('billPicture')
      .putString(imageURL, 'base64', { contentType: 'image/png' })
      .then(pictureSnapshot => {
        this.billList.update(billId, { picture: pictureSnapshot.downloadURL });
      });
  }


问:
How to add slow log configuration in elasticsearch.yml?
In older version of elasticsearch the slowlog will be in elasticsearch.yml but
for new version like 5.1.1 we have to add like slowlog configs like
    index.search.slowlog.threshold.query.debug: 0s
    index.search.slowlog.threshold.fetch.debug: 0s
    index.indexing.slowlog.threshold.index.debug: 0s

I tried adding these configs in my elasticsearch.yml,when i started the elasticsearch service it is not starting it is throwing an error.

Can anyone help me to solve this problem?

答:
Since Elasticsearch 5, slow log settings are for each indices.

You can PUT the settings to a specific index /index_name/_settings

with a payload like the following. More details are available at Elasticsearch Reference

```<code>{
"index.search.slowlog.threshold.query.warn": "10s",
"index.search.slowlog.threshold.query.info": "5s",
"index.search.slowlog.threshold.query.debug": "2s",
"index.search.slowlog.threshold.query.trace": "300ms",
"index.search.slowlog.threshold.fetch.warn": "1s",
"index.search.slowlog.threshold.fetch.info": "800ms",
"index.search.slowlog.threshold.fetch.debug": "500ms",
"index.search.slowlog.threshold.fetch.trace": "300ms",
"index.indexing.slowlog.threshold.index.warn": "10s",
"index.indexing.slowlog.threshold.index.info": "5s",
"index.indexing.slowlog.threshold.index.debug": "2s",
"index.indexing.slowlog.threshold.index.trace": "300ms",
"index.indexing.slowlog.level": "trace",
"index.indexing.slowlog.source": "1000"
}
</code>```

Body:
Since Elasticsearch 5, slow log settings are for each indices.

You can PUT the settings to a specific index /index_name/_settings

with a payload like the following. More details are available at Elasticsearch Reference

{
"index.search.slowlog.threshold.query.warn": "10s",
"index.search.slowlog.threshold.query.info": "5s",
"index.search.slowlog.threshold.query.debug": "2s",
"index.search.slowlog.threshold.query.trace": "300ms",
"index.search.slowlog.threshold.fetch.warn": "1s",
"index.search.slowlog.threshold.fetch.info": "800ms",
"index.search.slowlog.threshold.fetch.debug": "500ms",
"index.search.slowlog.threshold.fetch.trace": "300ms",
"index.indexing.slowlog.threshold.index.warn": "10s",
"index.indexing.slowlog.threshold.index.info": "5s",
"index.indexing.slowlog.threshold.index.debug": "2s",
"index.indexing.slowlog.threshold.index.trace": "300ms",
"index.indexing.slowlog.level": "trace",
"index.indexing.slowlog.source": "1000"
}


问:
unable to exchange auth token with access token - redirect uri missmatch
I try to build below:

by following: this steps

however, i keep receiving redirect uri missmatch when i tried to exchange auth code (given by my mobile app) to google server - which i couldn't understand because technically there is no redirect uri required for my flow case...

here are the details:

in Android Client:

```<code>GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
        .requestScopes(new Scope(Scopes.DRIVE_APPFOLDER))
        .requestServerAuthCode(serverClientId, false)
        .build();
/**** bla.... ****/
GoogleSignInAccount acct = result.getSignInAccount();
String authCode = acct.getServerAuthCode();
/**** android app will send this authCode to my server ****/
/**** sample authCode: 4/Jny2Mxxx3x09sy4pqY3ZAwSTEz8rw2xxxxC-4VxxxxM
</code>```

in my backend server:

```<code>try:
    # i receive authCode correctly from android app.
    # and use authCode to exchange to Access Token to google server as below:
    credentials = client.credentials_from_clientsecrets_and_code(
                  app.config.get('GG_APP_SECRET'),
                  ['https://www.googleapis.com/auth/plus.me', 'profile', 'email'],
                  authCode)
except Exception as e:
    log.info('>>>>> I always receive: redirect uri missmatch here: %s <<<<<', e)
    return generate_response(code=400, error=False, type='Fail', message=str(e))
</code>```

this is curl from my backend server:

```<code>curl -X POST --header 'Content-Type: application/json' --header 'Accept: application/json' -d '{ \
   "authCode": "4/HP_cP_t70pgBrxxx7sjzCil7kaUHkxxxerdkMxxxrRg" \
 }' 'http://localhost:5005/api/user/register/gg'
</code>```

this is my console settings:

Questions:

is the serverClientId in android client suppose to be the clientID of above image?

what is the redirect uri that i should put in google console above?

what should i set/configure for my redirect uri? or is there any specific settings that i need to do?

答:
Ok I go it,

if you see this

you will found out:

```<code>def credentials_from_clientsecrets_and_code(filename, scope, code,
                                            message=None,
                                            redirect_uri='postmessage',
                                            http=None,
                                            cache=None,
                                            device_uri=None):
</code>```

and you realize that redirect_uri = 'postmessage' which in my case i dont have post message.

so what i do is to match that redirect_uri with authorize redirect uri that i have in google console

so for my case in my question above, i change my python code to:

```<code>credentials = client.credentials_from_clientsecrets_and_code(
                  app.config.get('GG_APP_SECRET'),
                  ['https://www.googleapis.com/auth/plus.me', 'profile', 'email'],
                  authCode, redirect_uri='https://developers.google.com/oauthplayground')
</code>```

Body:
I try to build below:

by following: this steps

however, i keep receiving redirect uri missmatch when i tried to exchange auth code (given by my mobile app) to google server - which i couldn't understand because technically there is no redirect uri required for my flow case...

here are the details:

in Android Client:

GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
        .requestScopes(new Scope(Scopes.DRIVE_APPFOLDER))
        .requestServerAuthCode(serverClientId, false)
        .build();
/**** bla.... ****/
GoogleSignInAccount acct = result.getSignInAccount();
String authCode = acct.getServerAuthCode();
/**** android app will send this authCode to my server ****/
/**** sample authCode: 4/Jny2Mxxx3x09sy4pqY3ZAwSTEz8rw2xxxxC-4VxxxxM

in my backend server:

try:
    # i receive authCode correctly from android app.
    # and use authCode to exchange to Access Token to google server as below:
    credentials = client.credentials_from_clientsecrets_and_code(
                  app.config.get('GG_APP_SECRET'),
                  ['https://www.googleapis.com/auth/plus.me', 'profile', 'email'],
                  authCode)
except Exception as e:
    log.info('>>>>> I always receive: redirect uri missmatch here: %s <<<<<', e)
    return generate_response(code=400, error=False, type='Fail', message=str(e))

this is curl from my backend server:

curl -X POST --header 'Content-Type: application/json' --header 'Accept: application/json' -d '{ \
   "authCode": "4/HP_cP_t70pgBrxxx7sjzCil7kaUHkxxxerdkMxxxrRg" \
 }' 'http://localhost:5005/api/user/register/gg'

this is my console settings:

Questions:

is the serverClientId in android client suppose to be the clientID of above image?

what is the redirect uri that i should put in google console above?

what should i set/configure for my redirect uri? or is there any specific settings that i need to do?

Body:
Ok I go it,

if you see this

you will found out:

def credentials_from_clientsecrets_and_code(filename, scope, code,
                                            message=None,
                                            redirect_uri='postmessage',
                                            http=None,
                                            cache=None,
                                            device_uri=None):

and you realize that redirect_uri = 'postmessage' which in my case i dont have post message.

so what i do is to match that redirect_uri with authorize redirect uri that i have in google console

so for my case in my question above, i change my python code to:

credentials = client.credentials_from_clientsecrets_and_code(
                  app.config.get('GG_APP_SECRET'),
                  ['https://www.googleapis.com/auth/plus.me', 'profile', 'email'],
                  authCode, redirect_uri='https://developers.google.com/oauthplayground')