问:
How to force maven update?
I imported my already working project on another computer and it started to download dependencies.

Apparently my internet connection crashed and now I get the following:

```<code>    >Build errors for comics; org.apache.maven.lifecycle.LifecycleExecutionException:
    Failed to execute goal on project comicsTest: Could not resolve dependencies for project comicsTest:comicsTest:war:0.0.1-SNAPSHOT:
    The following artifacts could not be resolved:
    org.springframework:spring-context:jar:3.0.5.RELEASE,
    org.hibernate:hibernate-entitymanager:jar:3.6.0.Final,
    org.hibernate:hibernate-core:jar:3.6.0.Final,
    org.hibernate:hibernate-commons-annotations:jar:3.2.0.Final,
    org.aspectj:aspectjweaver:jar:1.6.8,
    commons-lang:commons-lang:jar:2.5,

    >mysql:mysql-connector-java:jar:5.1.13: Failure to transfer org.springframework:spring-context:jar:3.0.5.RELEASE from http://repo1.maven.org/maven2 was cached in the local repository, resolution will not be reattempted until the update interval of central has elapsed or updates are forced.

    >Original error: Could not transfer artifact org.springframework:spring-context:jar:3.0.5.RELEASE from central (http://repo1.maven.org/maven2): No response received after 60000
</code>```

How do I force maven to update?

答:
Just in case someone wants only update project's snapshot dependencies and doesn't want to install artifact:

```<code>mvn dependency:resolve -U
</code>```

Don't forget to reimport dependencies in your IDE. In IDEA you need to right click on pom file and choose Maven -> Reimport

Title: How to force maven update?

Body:
I imported my already working project on another computer and it started to download dependencies.

Apparently my internet connection crashed and now I get the following:

    >Build errors for comics; org.apache.maven.lifecycle.LifecycleExecutionException:
    Failed to execute goal on project comicsTest: Could not resolve dependencies for project comicsTest:comicsTest:war:0.0.1-SNAPSHOT:
    The following artifacts could not be resolved:
    org.springframework:spring-context:jar:3.0.5.RELEASE,
    org.hibernate:hibernate-entitymanager:jar:3.6.0.Final,
    org.hibernate:hibernate-core:jar:3.6.0.Final,
    org.hibernate:hibernate-commons-annotations:jar:3.2.0.Final,
    org.aspectj:aspectjweaver:jar:1.6.8,
    commons-lang:commons-lang:jar:2.5,

    >mysql:mysql-connector-java:jar:5.1.13: Failure to transfer org.springframework:spring-context:jar:3.0.5.RELEASE from http://repo1.maven.org/maven2 was cached in the local repository, resolution will not be reattempted until the update interval of central has elapsed or updates are forced.

    >Original error: Could not transfer artifact org.springframework:spring-context:jar:3.0.5.RELEASE from central (http://repo1.maven.org/maven2): No response received after 60000

How do I force maven to update?

Body:
Just in case someone wants only update project's snapshot dependencies and doesn't want to install artifact:

mvn dependency:resolve -U

Don't forget to reimport dependencies in your IDE. In IDEA you need to right click on pom file and choose Maven -> Reimport


来源: stackexchange

问:
IE11 + jQuery 1.8.3: dynamically added textarea with placeholder has text set to placeholder
This is very likely a bug, but I'm reporting it here for reference and for the slight chance of someone being able to propose a workaround.

IE 11 supports the placeholder attribute natively on textarea elements. That's great. But adding a new textarea with a placeholder to the DOM, it automatically puts the placeholder text into the textarea's field, too!

Here's the repro: http://jsfiddle.net/wE577/1/

答:
We are using jquery version 1.10.1 but still facing the issue,

```<code><textarea placeholder='Max 250 characters'>Max 250 characters</textarea>
</code>```

For this we emptied the value of textarea while clicking (or calling), like this

```<code>$('#textareaID textarea').val('');
</code>```

ContentLicense: CC BY-SA 3.0

Body:
We are using jquery version 1.10.1 but still facing the issue,

<textarea placeholder='Max 250 characters'>Max 250 characters</textarea>

For this we emptied the value of textarea while clicking (or calling), like this

$('#textareaID textarea').val('');


问:
Bypassing the AJAX Same-Origin Policy - A particular case
While I was trying to refresh page contents dynamically using Ajax/JQuery, I have learned about the S-O-P issue and restrictions, however I was wondering if there could be a way to solve my little problem.

To make it easier to understand I will first explain the workflow.

I do receive web pages via email, that is HTML emails. The web pages contain HTML forms in such a way, once the form is complete it is sent to the proper web server (php) to store data.

I mostly use Outlook 2007 as my email client (don't say anything here, I know!!!), but for some security restrictions, IFRAMES are disabled when "opening" the email. I have circumvented this problem using a VBA script that copies the whole page content, saves it on the filesystem as a stand-alone web page and loads into the browser (Firefox).

Once the page is loaded into the browser, the address bar shows a local/filesystem URL, such as

```<code>file:///C:/Users/Bob/Desktop/outlookpage.htm
</code>```

Till here no problem, works fine; now the problem:

I wished to dynamic update page contents using Ajax, using jQuery.load, however that's where the S-O-P comes in. The PHP page being loaded to dynamically update the web page is seen as running on another domain, thus being blocked.

I was wondering how to circumvent this.

答: That's not going to work because in order to bypass the same origin policy, you would need to use a proxy on the same domain, which will then communicate to the page that's handling the data on a different domain.  There's no way to generate a proxy script on another user's computer (or at least, there SHOULDN'T BE A WAY).  I would either just post the form normally, which will open the user's default browser, or provide a link to an online form in the email.  The link should be provided anyway, in case their email client doesn't support HTML email.   </p>

ContentLicense: CC BY-SA 2.5

Body:
While I was trying to refresh page contents dynamically using Ajax/JQuery, I have learned about the S-O-P issue and restrictions, however I was wondering if there could be a way to solve my little problem.

To make it easier to understand I will first explain the workflow.

I do receive web pages via email, that is HTML emails. The web pages contain HTML forms in such a way, once the form is complete it is sent to the proper web server (php) to store data.

I mostly use Outlook 2007 as my email client (don't say anything here, I know!!!), but for some security restrictions, IFRAMES are disabled when "opening" the email. I have circumvented this problem using a VBA script that copies the whole page content, saves it on the filesystem as a stand-alone web page and loads into the browser (Firefox).

Once the page is loaded into the browser, the address bar shows a local/filesystem URL, such as

file:///C:/Users/Bob/Desktop/outlookpage.htm

Till here no problem, works fine; now the problem:

I wished to dynamic update page contents using Ajax, using jQuery.load, however that's where the S-O-P comes in. The PHP page being loaded to dynamically update the web page is seen as running on another domain, thus being blocked.

I was wondering how to circumvent this.


问:
split div into 2 columns doesn't work
Can you please help me, it took me so much time trying to fixe this problem.
i have 2 slider and i need to split each slide into 2 colums. The problem is that the second column which is float: right doesn't show in both sliders .
Here is a code pen that shows the problem codepen
thank you

Here is my structure:

    .Dash_map_wrapSlider {
 position: absolute;
 overflow: hidden;
 height: 100%;
 width: calc(100% - 3rem);
 bottom: calc(-80% + 10rem);
 left: 3rem;
 background: #fff;
 border: 1px solid;
 transition: 0.5s;
 z-index: 1;}

    .Dash_map_wrapSlider:hover{
 bottom: 0rem;
 transition: 0.5s;}

    .Dash_map_wrapSlider:hover{
 bottom: 0rem;
 transition: 0.5s;}

    .Dash_map_wrapSliderchoise {
 background: #3E474F;
 box-shadow: 0 .5em 1em #111;
 position: absolute;
 left: 0;
 bottom: 0;
 z-index: 900;
 width: 100%;
 height: 2rem;
 line-height: 2rem;
 text-align: center;
 vertical-align: middle;}

    .Dash_map_sumSlide {
 height: 100%;
 width: 100%;
 position: absolute;
 top: 0;
 left: 100%;
 z-index: 10;
 background-color: #fff;
 transition: left 0s .75s;}

    .clsDashMap_sumSlideInput {
 display: none;
 height: 11rem;}

    .clsDashMap_sumSlideTitle {
 position : absolute;
 top:0;
 width: 100%;
 height: 2rem;
 left: inherit;
 color: #fff;
 background-color: #73b9ff;
 text-align: center;
 font-weight: bold;
 font-size: 1.20rem;}

    .clsDashMap_sumSlideContentBoxTitle {
 font-weight: bold;
 color: #666;}

    .clsDashMap_sumSlideSiteContentSummary {
 position : absolute;
 top: 2rem;
 width: 100%;
 height: 16rem;
 color: #000000;
 background-color: aliceblue;
 text-align: center;}

    .clsDashMap_sumSlideContent {
 position: absolute;
 top: 20rem;
 margin: auto;
 width: 100%;
 color: #000000;}

    [id^="Dash"]:checked + .Dash_map_sumSlide {
 left: 0;
 z-index: 100;
 transition: left .65s ease-out;}

    .Dash_map_wrapSliderchoise label {
 color: #fff;
 cursor: pointer;
 display: inline-block;
 line-height: 2rem;
 font-size: 0.75rem;
 font-weight: bold;
 padding: 0 1em;}

    .clsDashMap_sumSlideContentBox {
 margin: auto;
 float: left;
    padding: 10px;
    text-align: center;}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="Dash_map_wrapSlider">
    <div style="border: 1px solid red;width: 100%;">
     <input id="Dash_map_sumSlideSite" class="clsDashMap_sumSlideInput" type="radio" name="slides" checked>
     <div class="Dash_map_sumSlide slide_Site " style="float: left;width: 50%;border: 2px solid yellow;">
      <div class="clsDashMap_sumSlideTitle">SITE</div>
      <div class="clsDashMap_sumSlideSiteContentSummary">
       <div class="clsDashMap_sumSlideContentBox">
        <div class="clsDashMap_sumSlideContentBoxTitle">Etat</div>
        <div class="green led">OK</div>
        <div class="red led">KO</div>
       </div>
       <div class="clsDashMap_sumSlideContentBox">
        <div class="clsDashMap_sumSlideContentBoxTitle">AlarmesSite</div>
        <canvas id="pieChartAlm" ></canvas>
       </div>
       <div class="clsDashMap_sumSlideContentBox">
        <div class="clsDashMap_sumSlideContentBoxTitle">TicketsSite</div>
        <canvas id="pieChartTkt" ></canvas>
       </div>
      </div>
      <div class="clsDashMap_sumSlideContent">put here content</div>
     </div>

     <div class="Dash_map_sumSlide slide_Alarme" style="float: right;width: 50%; border: 2px solid green;">
      <div class="clsDashMap_sumSlideTitle" >ALARME</div>
      <div class="clsDashMap_sumSlideSiteContentSummary">
       <div class="clsDashMap_sumSlideContentBox">
        <div class="clsDashMap_sumSlideContentBoxTitle">Etat</div>
        <div class="green led">OK</div>
        <div class="red led">KO</div>
       </div>
       <div class="clsDashMap_sumSlideContentBox">
        <div class="clsDashMap_sumSlideContentBoxTitle">ALARME1Alm</div>
        <canvas id="pieChartAlm" ></canvas>
       </div>
       <div class="clsDashMap_sumSlideContentBox">
        <div class="clsDashMap_sumSlideContentBoxTitle">Tickets1Alm</div>
        <canvas id="pieChartTkt" ></canvas>
       </div>
      </div>
      <div class="clsDashMap_sumSlideContent">put here content</div>
     </div>
    </div>

    <div style="border: 1px solid red;">
     <input id="Dash_map_sumSlideAlarme" class="clsDashMap_sumSlideInput" type="radio" name="slides" checked>
     <div class="Dash_map_sumSlide slide_Site " style="width: 50%;border: 2px solid black;">
      <div class="clsDashMap_sumSlideTitle">TECHNICIEN</div>
      <div class="clsDashMap_sumSlideSiteContentSummary">
       <div class="clsDashMap_sumSlideContentBox">
        <div class="clsDashMap_sumSlideContentBoxTitle">Etat</div>
        <div class="green led">OK</div>
        <div class="red led">KO</div>
       </div>
       <div class="clsDashMap_sumSlideContentBox">
        <div class="clsDashMap_sumSlideContentBoxTitle">Alarmes2Tech</div>
       </div>
       <div class="clsDashMap_sumSlideContentBox">
        <div class="clsDashMap_sumSlideContentBoxTitle">Tickets2Tech</div>
       </div>
      </div>
      <div class="clsDashMap_sumSlideContent">put here content</div>
     </div>
      <div class="Dash_map_sumSlide slide_Alarme" style="width: 50%; float: right;border: 2px solid darkturquoise;">
      <div class="clsDashMap_sumSlideTitle" style="position: initial;">ACTION</div>
      <div class="clsDashMap_sumSlideSiteContentSummary">
       <div class="clsDashMap_sumSlideContentBox">
        <div class="clsDashMap_sumSlideContentBoxTitle">Etat</div>
        <div class="green led">OK</div>
        <div class="red led">KO</div>
       </div>
       <div class="clsDashMap_sumSlideContentBox">
        <div class="clsDashMap_sumSlideContentBoxTitle">alarme3Act</div>
       </div>
       <div class="clsDashMap_sumSlideContentBox">
        <div class="clsDashMap_sumSlideContentBoxTitle">Tickets3Act</div>
       </div>
      </div>
      <div class="clsDashMap_sumSlideContent">put here content</div>
     </div>
    </div></code>```

答: Have you tried out Bootstrap Grid? I think it is just what you need.</p>

Title: split div into 2 columns doesn't work

Body:
Can you please help me, it took me so much time trying to fixe this problem.
i have 2 slider and i need to split each slide into 2 colums. The problem is that the second column which is float: right doesn't show in both sliders .
Here is a code pen that shows the problem codepen
thank you

Here is my structure:

    .Dash_map_wrapSlider {
 position: absolute;
 overflow: hidden;
 height: 100%;
 width: calc(100% - 3rem);
 bottom: calc(-80% + 10rem);
 left: 3rem;
 background: #fff;
 border: 1px solid;
 transition: 0.5s;
 z-index: 1;}

    .Dash_map_wrapSlider:hover{
 bottom: 0rem;
 transition: 0.5s;}

    .Dash_map_wrapSlider:hover{
 bottom: 0rem;
 transition: 0.5s;}

    .Dash_map_wrapSliderchoise {
 background: #3E474F;
 box-shadow: 0 .5em 1em #111;
 position: absolute;
 left: 0;
 bottom: 0;
 z-index: 900;
 width: 100%;
 height: 2rem;
 line-height: 2rem;
 text-align: center;
 vertical-align: middle;}

    .Dash_map_sumSlide {
 height: 100%;
 width: 100%;
 position: absolute;
 top: 0;
 left: 100%;
 z-index: 10;
 background-color: #fff;
 transition: left 0s .75s;}

    .clsDashMap_sumSlideInput {
 display: none;
 height: 11rem;}

    .clsDashMap_sumSlideTitle {
 position : absolute;
 top:0;
 width: 100%;
 height: 2rem;
 left: inherit;
 color: #fff;
 background-color: #73b9ff;
 text-align: center;
 font-weight: bold;
 font-size: 1.20rem;}

    .clsDashMap_sumSlideContentBoxTitle {
 font-weight: bold;
 color: #666;}

    .clsDashMap_sumSlideSiteContentSummary {
 position : absolute;
 top: 2rem;
 width: 100%;
 height: 16rem;
 color: #000000;
 background-color: aliceblue;
 text-align: center;}

    .clsDashMap_sumSlideContent {
 position: absolute;
 top: 20rem;
 margin: auto;
 width: 100%;
 color: #000000;}

    [id^="Dash"]:checked + .Dash_map_sumSlide {
 left: 0;
 z-index: 100;
 transition: left .65s ease-out;}

    .Dash_map_wrapSliderchoise label {
 color: #fff;
 cursor: pointer;
 display: inline-block;
 line-height: 2rem;
 font-size: 0.75rem;
 font-weight: bold;
 padding: 0 1em;}

    .clsDashMap_sumSlideContentBox {
 margin: auto;
 float: left;
    padding: 10px;
    text-align: center;}

     <input id="Dash_map_sumSlideSite" class="clsDashMap_sumSlideInput" type="radio" name="slides" checked>

SITE

Etat

OK

KO

AlarmesSite

        <canvas id="pieChartAlm" ></canvas>

TicketsSite

        <canvas id="pieChartTkt" ></canvas>

put here content

ALARME

Etat

OK

KO

ALARME1Alm

        <canvas id="pieChartAlm" ></canvas>

Tickets1Alm

        <canvas id="pieChartTkt" ></canvas>

put here content

     <input id="Dash_map_sumSlideAlarme" class="clsDashMap_sumSlideInput" type="radio" name="slides" checked>

TECHNICIEN

Etat

OK

KO

Alarmes2Tech

Tickets2Tech

put here content

ACTION

Etat

OK

KO

alarme3Act

Tickets3Act

put here content


问:
Access SQL appears to be treating date as dd/mm/yyyy?
I have a table in MS Access which holds staff details (tblStaff):

```<code>| Employee Number |  Employee Name |  Dept     |
------------------------------------------------
|     205147      |   Joe Bloggs   |  IT       |
|     205442      |   John Doe     |  Accounts |
</code>```

I refresh this table with new data weekly and if any records have changed (e.g. changed dept) then they are archived in another table (tblArchiveStaff) along with the dates that that record was valid from and to.

```<code>| Employee Number |  Employee Name |  Dept     | DateFrom | DateTo   |
----------------------------------------------------------------------
|     205147      |   Joe Bloggs   |  HR       | 03/01/16 | 01/06/17 |
</code>```

I am trying to write a query that will select records from either of these tables based on which ones were valid for a given date

We can assume that records in tblStaff are valid from the dateTo + 1 of the last entry for that employee in tblArchiveStaff, or from 03 Jan 16 if they have no archived records.

So far I have come up with the below query into which I have hardcoded the date condition of #07/01/2017#:

```<code>SELECT [Employee Number], [Dept], DateFrom, DateTo
FROM

     (
      SELECT ts.[Employee Number], ts.[Dept], nz(ta2.DateTo,#01/02/16#)+1 AS DateFrom, date() AS DateTo
      FROM tblStaff ts LEFT JOIN tblArchiveStaff ta2 ON ts.[Employee Number] = ta2.[Employee Number]

      UNION ALL

      SELECT ta.[Employee Number], ta.[Dept], ta.DateFrom, ta.DateTo
      FROM tblArchiveStaff ta

     ) AS tblUnion

WHERE #07/01/2017# BETWEEN DateFrom AND DateTo;
</code>```

As I understand it the above query should return records valid on July 1st 2017 which would be both records in tblStaff, it is however returning the record in tblArchiveStaff. It is almost like it is treating the date condition as 7 January which would mean it is formatted dd/mm/yyyy which I thought was impossible.

Can anyone explain this please?

答:
That is because you don't play by the rules. Always handle dates as date values, not strings, not numbers, no exceptions.

So, when you use Nz and even add 1, the union query cannot figure out the datatype, thus it falls back to return the result as text. Then DateFrom becomes Text while DateTo is Date which makes filtering a wild guess.

*Edit - I have also amended the first part of the union query to ensure the current record follows on from the most recent archived record)

Correct as this:

```<code>SELECT
    tblUnion.[Employee Number],
    tblUnion.[Dept],
    tblUnion.DateFrom,
    tblUnion.DateTo
FROM
    (SELECT
        ts.[Employee Number],
        ts.[Dept],
        DateAdd("d", 1, Nz(ta2.MaxDateTo, #01/02/16#)) AS DateFrom,
        Date() AS DateTo
    FROM
        tblStaff ts
    LEFT JOIN
       (SELECT
        [Employee Number],
        max(DateTo) AS MaxDateTo
    FROM
        tblArchiveStaff
    GROUP BY
       [Employee Number]) ta2
        ON ts.[Employee Number] = ta2.[Employee Number]

    UNION ALL

    SELECT
        ta.[Employee Number],
        ta.[Dept],
        ta.DateFrom,
        ta.DateTo
    FROM
        tblArchiveStaff ta) AS tblUnion
WHERE
    #7/1/2017# Between [DateFrom] And [DateTo];
</code>```

and you will get the desired output:

```<code>Employee Number Dept      DateFrom  DateTo
205147          IT        2017-01-07    2017-07-05
205442          Accounts  2016-01-03    2017-07-05
</code>```

Body:
I have a table in MS Access which holds staff details (tblStaff):

| Employee Number |  Employee Name |  Dept     |
------------------------------------------------
|     205147      |   Joe Bloggs   |  IT       |
|     205442      |   John Doe     |  Accounts |

I refresh this table with new data weekly and if any records have changed (e.g. changed dept) then they are archived in another table (tblArchiveStaff) along with the dates that that record was valid from and to.

| Employee Number |  Employee Name |  Dept     | DateFrom | DateTo   |
----------------------------------------------------------------------
|     205147      |   Joe Bloggs   |  HR       | 03/01/16 | 01/06/17 |

I am trying to write a query that will select records from either of these tables based on which ones were valid for a given date

We can assume that records in tblStaff are valid from the dateTo + 1 of the last entry for that employee in tblArchiveStaff, or from 03 Jan 16 if they have no archived records.

So far I have come up with the below query into which I have hardcoded the date condition of #07/01/2017#:

SELECT [Employee Number], [Dept], DateFrom, DateTo
FROM

     (
      SELECT ts.[Employee Number], ts.[Dept], nz(ta2.DateTo,#01/02/16#)+1 AS DateFrom, date() AS DateTo
      FROM tblStaff ts LEFT JOIN tblArchiveStaff ta2 ON ts.[Employee Number] = ta2.[Employee Number]

      UNION ALL

      SELECT ta.[Employee Number], ta.[Dept], ta.DateFrom, ta.DateTo
      FROM tblArchiveStaff ta

     ) AS tblUnion

WHERE #07/01/2017# BETWEEN DateFrom AND DateTo;

As I understand it the above query should return records valid on July 1st 2017 which would be both records in tblStaff, it is however returning the record in tblArchiveStaff. It is almost like it is treating the date condition as 7 January which would mean it is formatted dd/mm/yyyy which I thought was impossible.

Can anyone explain this please?

Body:
That is because you don't play by the rules. Always handle dates as date values, not strings, not numbers, no exceptions.

So, when you use Nz and even add 1, the union query cannot figure out the datatype, thus it falls back to return the result as text. Then DateFrom becomes Text while DateTo is Date which makes filtering a wild guess.

*Edit - I have also amended the first part of the union query to ensure the current record follows on from the most recent archived record)

Correct as this:

SELECT
    tblUnion.[Employee Number],
    tblUnion.[Dept],
    tblUnion.DateFrom,
    tblUnion.DateTo
FROM
    (SELECT
        ts.[Employee Number],
        ts.[Dept],
        DateAdd("d", 1, Nz(ta2.MaxDateTo, #01/02/16#)) AS DateFrom,
        Date() AS DateTo
    FROM
        tblStaff ts
    LEFT JOIN
       (SELECT
        [Employee Number],
        max(DateTo) AS MaxDateTo
    FROM
        tblArchiveStaff
    GROUP BY
       [Employee Number]) ta2
        ON ts.[Employee Number] = ta2.[Employee Number]

    UNION ALL

    SELECT
        ta.[Employee Number],
        ta.[Dept],
        ta.DateFrom,
        ta.DateTo
    FROM
        tblArchiveStaff ta) AS tblUnion
WHERE
    #7/1/2017# Between [DateFrom] And [DateTo];

and you will get the desired output:

Employee Number Dept      DateFrom  DateTo
205147          IT        2017-01-07    2017-07-05
205442          Accounts  2016-01-03    2017-07-05


问:
Images now shown in WordPress Media Library
I've added 3 subfolders in the wp-content/uploads/2017 folder, but when i try to access them in the admin dashboard, they're not displayed. Why ?</p>

答: Its not accessed due to file permissions.Change the folder permission to 755 or 777.</p>


问:
Get Class Type of inherited object?
In C#, how can I get the inherited Class Type of an object where the object is an inherited object instead of the Type of the instantiated object?

Here is some code:

```<code>public class ClassA
{
    public virtual void GetClassType()
    {
        var type = this.GetType();
        Console.WriteLine(type.Name);
    }
}
public class ClassB : ClassA
{
    public override void GetClassType()
    {
        base.GetClassType();
        var type = this.GetType();
        Console.WriteLine(type.Name);
    }
}
public class ClassC : ClassB
{
    public override void GetClassType()
    {
        base.GetClassType();
        var type = this.GetType();
        Console.WriteLine(type.Name);
    }
}

private void GetClassType()
{
    var objectA = new ClassC();
    objectA.GetClassType();
}
</code>```

The GetClassType method outputs the following to the console:

ClassC
  ClassC
  ClassC

Is it possible to get the Type of the Class, instead of the Type of the object such that the following is the console output?

ClassA
  ClassB
  ClassC

答:
If you have something like this

```<code>class A {}

class B : A {}
</code>```

You can do this:

```<code>var b = new B();
var baseType = b.GetType().BaseType;
</code>```

Title: Get Class Type of inherited object?

Body:
In C#, how can I get the inherited Class Type of an object where the object is an inherited object instead of the Type of the instantiated object?

Here is some code:

public class ClassA
{
    public virtual void GetClassType()
    {
        var type = this.GetType();
        Console.WriteLine(type.Name);
    }
}
public class ClassB : ClassA
{
    public override void GetClassType()
    {
        base.GetClassType();
        var type = this.GetType();
        Console.WriteLine(type.Name);
    }
}
public class ClassC : ClassB
{
    public override void GetClassType()
    {
        base.GetClassType();
        var type = this.GetType();
        Console.WriteLine(type.Name);
    }
}

private void GetClassType()
{
    var objectA = new ClassC();
    objectA.GetClassType();
}

The GetClassType method outputs the following to the console:

ClassC
  ClassC
  ClassC

Is it possible to get the Type of the Class, instead of the Type of the object such that the following is the console output?

ClassA
  ClassB
  ClassC

Body:
If you have something like this

class A {}

class B : A {}

You can do this:

var b = new B();
var baseType = b.GetType().BaseType;


问:
custom post types link hierarchy
I have to independet custom post types:

course

lesson

So one course can have many lesson and one lesson can be used in many courses. It is a m:n relation.

Now I've content that should be only visible on the lesson page, if it is viewed from a specific course.

Actually the link structure is like that:

Go to course: example.org/my-first-course

I see all lessons, that related to this course

Click on a lesson. Link structure is: example.org/great-lesson

My problem at this stage is, that I don't know from which course the lesson i called.

One thing I can do is to attach the course id as a get parameter to the link:
example.org/great-lesson/?course_id=123

But I would like to have a link structure more like that:
example.org/my-first-course/great-lesson

How can I do this?

.:: UPDATE: SOLUTION ::.

Here is my solution, maybe it'll help someone.

If you use "add_rewrite_rule", don't forget to change the slug (slug-custom-post-type) for your custom post type and the query var (cpt-query-var) of it.

I've tried to use index.php?name=$matches[1], but it will redirect to the custom post type and all other information in the URL will be lost. So it is important to use the custom post type query var instead.

To access the 'course' you have to use the get_query_var function:
echo get_query_var('course', '');

```<code>function my_rewrite_rules() {
  add_rewrite_rule( '^slug-custom-post-type/([^/]*)/?', 'index.php?cpt-query-var=$matches[1]&course=$matches[2]', 'top' );
}

add_action('init', 'my_rewrite_rules');

function my_query_vars($qvars) {
  $qvars[] = 'course';
  return $qvars;
}

add_filter( 'query_vars', 'my_query_vars' );
</code>```

答:
I think you should use,

```<code>example.org/great-lesson/my-first-course
</code>```

instead of using

```<code>example.org/my-first-course/great-lesson
</code>```

as the great-lesson will be static here and the id or slug is dynamic which shows detailed course/lesson.

And to add custom rewrite rule you can use,

```<code>function custom_rewrite_basic() {
  add_rewrite_rule('^great_lesson/(.*)', 'index.php?page_id=$matches[1]', 'top');
}
add_action('init', 'custom_rewrite_basic');
</code>```

Then get the slug from url and write code according to it. Read more about add_custom_rule

Title: custom post types link hierarchy

Body:
I have to independet custom post types:

course

lesson

So one course can have many lesson and one lesson can be used in many courses. It is a m:n relation.

Now I've content that should be only visible on the lesson page, if it is viewed from a specific course.

Actually the link structure is like that:

Go to course: example.org/my-first-course

I see all lessons, that related to this course

Click on a lesson. Link structure is: example.org/great-lesson

My problem at this stage is, that I don't know from which course the lesson i called.

One thing I can do is to attach the course id as a get parameter to the link:
example.org/great-lesson/?course_id=123

But I would like to have a link structure more like that:
example.org/my-first-course/great-lesson

How can I do this?

.:: UPDATE: SOLUTION ::.

Here is my solution, maybe it'll help someone.

If you use "add_rewrite_rule", don't forget to change the slug (slug-custom-post-type) for your custom post type and the query var (cpt-query-var) of it.

I've tried to use index.php?name=$matches[1], but it will redirect to the custom post type and all other information in the URL will be lost. So it is important to use the custom post type query var instead.

To access the 'course' you have to use the get_query_var function:
echo get_query_var('course', '');

function my_rewrite_rules() {
  add_rewrite_rule( '^slug-custom-post-type/([^/]*)/?', 'index.php?cpt-query-var=$matches[1]&course=$matches[2]', 'top' );
}

add_action('init', 'my_rewrite_rules');

function my_query_vars($qvars) {
  $qvars[] = 'course';
  return $qvars;
}

add_filter( 'query_vars', 'my_query_vars' );

Body:
I think you should use,

example.org/great-lesson/my-first-course

instead of using

example.org/my-first-course/great-lesson

as the great-lesson will be static here and the id or slug is dynamic which shows detailed course/lesson.

And to add custom rewrite rule you can use,

function custom_rewrite_basic() {
  add_rewrite_rule('^great_lesson/(.*)', 'index.php?page_id=$matches[1]', 'top');
}
add_action('init', 'custom_rewrite_basic');

Then get the slug from url and write code according to it. Read more about add_custom_rule


问:
Frequent concurrent method calls in Java data-logger
I'm implementing a Java Data-logger which reads, at precise intervals of time, some datas from different production machines. To avoid having one call blocking the following ones, I was thinking of making a new thread for every call to the parser class.

However, this would require the creation of many threads, and then to stop them, every 10 seconds (which is my reading interval). A non-concurrent approach would cause me to have many delays when the parser gets an exception (due to the possible timeouts of the IoT devices i'm using) making the next calls to be delayed.

```<code>while(!error){

//JDBC connections and other calls here
//Queryresult is a ResultSet that returns all the machine addresses needing to be read

    while(queryresult.next()){
                        //Parser.ParseSpeedV is the method I need to call concurrently
                        Double v = Parser.ParseSpeedV(..Params..);
                        Double s = v*queryresult.getDouble("const");
                        st = conn.createStatement();
                        st.executeUpdate("INSERT INTO ...");
                    }
st.close();
Thread.sleep(10000);
}
</code>```

What is the best way to achieve a concurrent method calls (to the method ParseSpeedV) without having the overhead caused by thousands of thread starting every day?

答:
Your situation is the perfect use case for a Thread Pool.  This part of Java's library that's built on top of simple Threads and allows you to create a fixed-sized pool of threads and reuse them over and over:

```<code>ExecutorService executor = Executors.newFixedThreadPool(5);
</code>```

Any time you want to do some work you add it to the executor

```<code>executor.execute(new Runnable() {
    @Override
    public void run() {
        // Do some work
    }
});
</code>```

If you call execute more than 5 times, the extra runnables are held in a queue until there's room.

Now, if you need to receive information from these runnning tasks, you need to write a class that implements Runnable and accepts some kind of object that wishes to have the information that your runnable has:

```<code>public class Worker implements Runnable {
   Consumer consumer;

   public Worker(Consumer consumer) {
       this.consumer = consumer;
   }

   @Override public void run() {
       // Do work
       value = // get value
       consumer.put(value);
   }
}
</code>```

Now all you have to do is define a Consumer class that operates on the value (has that put() method, or whatever) and create your Workers like this:

```<code>Consumer consumer = new Consumer();
Worker worker = new Worker(myConsumer);
executor.execute(worker);
</code>```

Body:
I'm implementing a Java Data-logger which reads, at precise intervals of time, some datas from different production machines. To avoid having one call blocking the following ones, I was thinking of making a new thread for every call to the parser class.

However, this would require the creation of many threads, and then to stop them, every 10 seconds (which is my reading interval). A non-concurrent approach would cause me to have many delays when the parser gets an exception (due to the possible timeouts of the IoT devices i'm using) making the next calls to be delayed.

while(!error){

//JDBC connections and other calls here
//Queryresult is a ResultSet that returns all the machine addresses needing to be read

    while(queryresult.next()){
                        //Parser.ParseSpeedV is the method I need to call concurrently
                        Double v = Parser.ParseSpeedV(..Params..);
                        Double s = v*queryresult.getDouble("const");
                        st = conn.createStatement();
                        st.executeUpdate("INSERT INTO ...");
                    }
st.close();
Thread.sleep(10000);
}

What is the best way to achieve a concurrent method calls (to the method ParseSpeedV) without having the overhead caused by thousands of thread starting every day?

Body:
Your situation is the perfect use case for a Thread Pool.  This part of Java's library that's built on top of simple Threads and allows you to create a fixed-sized pool of threads and reuse them over and over:

ExecutorService executor = Executors.newFixedThreadPool(5);

Any time you want to do some work you add it to the executor

executor.execute(new Runnable() {
    @Override
    public void run() {
        // Do some work
    }
});

If you call execute more than 5 times, the extra runnables are held in a queue until there's room.

Now, if you need to receive information from these runnning tasks, you need to write a class that implements Runnable and accepts some kind of object that wishes to have the information that your runnable has:

public class Worker implements Runnable {
   Consumer consumer;

   public Worker(Consumer consumer) {
       this.consumer = consumer;
   }

   @Override public void run() {
       // Do work
       value = // get value
       consumer.put(value);
   }
}

Now all you have to do is define a Consumer class that operates on the value (has that put() method, or whatever) and create your Workers like this:

Consumer consumer = new Consumer();
Worker worker = new Worker(myConsumer);
executor.execute(worker);


问:
shared_pointer unexpected behaviour
There is piece of code:

A.cpp

```<code>class MySomeClass: public SomeClass
{
   public:
   void specificMethod();
}

class A
{
    public:
    A::A();

    std::shared_ptr< B > m_bObject;
    std::shared_ptr< MySomeClass > m_argument;
}

A::A()
{
    m_argument= std::make_shared< MySomeClass >();
    m_bObject = std::make_shared< B >( m_argument);
}
</code>```

B.cpp

```<code>B::B(const std::shared_ptr< SomeClass >& smartOne):m_smartOne(smartOne)
{}

B::someMethod()
{
    m_smartOne->specificMethod();
}
</code>```

B.h

```<code>class B
{
public:
    B(const std::shared_ptr< SomeClass >& smarOne);
    void someMethod();

private:
    const std::shared_ptr< SomeClass >& m_smartOne;
};
</code>```

Problem is when I call m_bObject->someMethod() there is a core dump because m_smartOne is not a MySomeClass but SomeClass.

Why? Is it scope problem, ownership problem, other?

I've recieved code of B class and can't change it.

答:
When std::make_shared(m_argument) constructs the B object, it will create a temporary shared_ptr<SomeClass> object from m_argument, which is of the type shared_ptr<MySomeClass>. A reference to that temporary is passed to B's constructor, which stores a reference that immediately became dangling as the temporary object is destroyed after the constructor call completes.

The result of using a dangling reference is, of course, undefined behavior. Anything can happen.

If you can't touch B, then the best you can do is probably to have A store a shared_ptr<SomeClass> member so that no temporary is created. But even then A will effectively store a reference into itself, which means that the default copy/move constructors and assignment operators will all do the wrong thing. That's a giant can of worms.

Title: shared_pointer unexpected behaviour

Body:
There is piece of code:

A.cpp

class MySomeClass: public SomeClass
{
   public:
   void specificMethod();
}

class A
{
    public:
    A::A();

    std::shared_ptr m_bObject;
    std::shared_ptr< MySomeClass > m_argument;
}

A::A()
{
    m_argument= std::make_shared< MySomeClass >();
    m_bObject = std::make_shared( m_argument);
}

B.cpp

B::B(const std::shared_ptr< SomeClass >& smartOne):m_smartOne(smartOne)
{}

B::someMethod()
{
    m_smartOne->specificMethod();
}

B.h

class B
{
public:
    B(const std::shared_ptr< SomeClass >& smarOne);
    void someMethod();

private:
    const std::shared_ptr< SomeClass >& m_smartOne;
};

Problem is when I call m_bObject->someMethod() there is a core dump because m_smartOne is not a MySomeClass but SomeClass.

Why? Is it scope problem, ownership problem, other?

I've recieved code of B class and can't change it.

Body:
When std::make_shared<B>(m_argument) constructs the B object, it will create a temporary shared_ptr<SomeClass> object from m_argument, which is of the type shared_ptr<MySomeClass>. A reference to that temporary is passed to B's constructor, which stores a reference that immediately became dangling as the temporary object is destroyed after the constructor call completes.

The result of using a dangling reference is, of course, undefined behavior. Anything can happen.

If you can't touch B, then the best you can do is probably to have A store a shared_ptr<SomeClass> member so that no temporary is created. But even then A will effectively store a reference into itself, which means that the default copy/move constructors and assignment operators will all do the wrong thing. That's a giant can of worms.


问:
How to implement a global click handler without conflicting with already defined events
I would like to bind a click event to all the elements inside a web page without getting conflicted with the events which are already defined. I' trying to use the following code to define the global click event. </p>

```<code>$("body").click(function (event) {
}
</code>```

<p>I'm using this click event to figure out if it's a page redirect and to save that data into the html5 history object. What is the best way to implement such a logic in an already defined system? </p>

答:
```<code><input type="button" onclick="buttonClick()" value = 'hey' />

<script>
$("body").click(function(){
    alert("hey body");
});
$("body").click(function(){
    alert("hey body 2");
});

function buttonClick(){
    alert("hey button");
}
</script>
</code>```

Check this simple test.

Click on body will trigger "hey body" and "hey body 2".

Clicking on the button will trigger "Hey button" "Hey body" and "Hey body2". The events are simply added on top of each other and every linked event get triggered.

Body:
I would like to bind a click event to all the elements inside a web page without getting conflicted with the events which are already defined. I' trying to use the following code to define the global click event.

$("body").click(function (event) {
}

I'm using this click event to figure out if it's a page redirect and to save that data into the html5 history object. What is the best way to implement such a logic in an already defined system?

Body:
<input type="button" onclick="buttonClick()" value = 'hey' />

<script>
$("body").click(function(){
    alert("hey body");
});
$("body").click(function(){
    alert("hey body 2");
});

function buttonClick(){
    alert("hey button");
}
</script>

Check this simple test.

Click on body will trigger "hey body" and "hey body 2".

Clicking on the button will trigger "Hey button" "Hey body" and "Hey body2". The events are simply added on top of each other and every linked event get triggered.


问:
Using both term and match query on same text field?
I have an index with a text field.

```<code>"state": {
  "type": "text"
}
</code>```

Now suppose there are two data.

```<code>"state": "vail"
and
"state": "eagle vail"
</code>```

For one of my requirements,

 - I need to do a term level query, such that if I type "vail", the search results should only return states with "vail" and not "eagle vail".

But another requirement for different search on the same index,

 - I need to do a match query for full text search, such that if I type "vail", "eagle vail" should display as well.

So my question is, how do I do both term level and full text search in this field, as for doing a term level query, I would have to set it as "keyword" type such that it wont be analyzed.

答:
You can use "multi-field" feature to achieve this. Here is a mapping:

```<code>{
    "mappings": {
        "my_type": {
            "properties": {
                "state": {
                    "type": "text",
                    "fields": {
                        "raw": {
                            "type": "keyword"
                        }
                    }
                }
            }
        }
    }
}
</code>```

In this case state will act as text field (tokenized) whereas state.raw will be keyword (single-token). When indexing a document you should only set state. state.raw will be created automatically.

Body:
I have an index with a text field.

"state": {
  "type": "text"
}

Now suppose there are two data.

"state": "vail"
and
"state": "eagle vail"

For one of my requirements,

 - I need to do a term level query, such that if I type "vail", the search results should only return states with "vail" and not "eagle vail".

But another requirement for different search on the same index,

 - I need to do a match query for full text search, such that if I type "vail", "eagle vail" should display as well.

So my question is, how do I do both term level and full text search in this field, as for doing a term level query, I would have to set it as "keyword" type such that it wont be analyzed.

Body:
You can use "multi-field" feature to achieve this. Here is a mapping:

{
    "mappings": {
        "my_type": {
            "properties": {
                "state": {
                    "type": "text",
                    "fields": {
                        "raw": {
                            "type": "keyword"
                        }
                    }
                }
            }
        }
    }
}

In this case state will act as text field (tokenized) whereas state.raw will be keyword (single-token). When indexing a document you should only set state. state.raw will be created automatically.


问:
Angular 2 Dropdown Options Default Value
In Angular 1 I could select the default option for a drop down box using the following:

```<code><select
    data-ng-model="carSelection"
    data-ng-options = "x.make for x in cars" data-ng-selected="$first">
</select>
</code>```

In Angular 2 I have:

```<code><select class="form-control" [(ngModel)]="selectedWorkout" (ngModelChange)="updateWorkout($event)">
    <option *ngFor="#workout of workouts">{{workout.name}}</option>
</select>
</code>```

How could I select a default option given my option data is:

[{name: 'arm'}, {name: 'back'}, {name:'leg'}] and my value I to default on on is back?

答:
Struggled a bit with this one, but ended up with the following solution... maybe it will help someone.

HTML template:

```<code><select (change)="onValueChanged($event.target)">
    <option *ngFor="let option of uifOptions" [value]="option.value" [selected]="option == uifSelected ? true : false">{{option.text}}</option>
</select>
</code>```

Component:

```<code>import { Component, Input, Output, EventEmitter, OnInit } from '@angular/core';
export class UifDropdownComponent implements OnInit {
    @Input() uifOptions: {value: string, text: string}[];
    @Input() uifSelectedValue: string = '';
    @Output() uifSelectedValueChange:EventEmitter<string> = new EventEmitter<string>();
    uifSelected: {value: string, text: string} = {'value':'', 'text':''};

    constructor() { }

    onValueChanged(target: HTMLSelectElement):void {
        this.uifSelectedValue = target.value;
        this.uifSelectedValueChange.emit(this.uifSelectedValue);
    }

    ngOnInit() {
        this.uifSelected = this.uifOptions.filter(o => o.value ==
        this.uifSelectedValue)[0];
    }
}
</code>```

Body:
In Angular 1 I could select the default option for a drop down box using the following:

<select
    data-ng-model="carSelection"
    data-ng-options = "x.make for x in cars" data-ng-selected="$first">
</select>

In Angular 2 I have:

<select class="form-control" [(ngModel)]="selectedWorkout" (ngModelChange)="updateWorkout($event)">
    <option *ngFor="#workout of workouts">{{workout.name}}</option>
</select>

How could I select a default option given my option data is:

[{name: 'arm'}, {name: 'back'}, {name:'leg'}] and my value I to default on on is back?

Body:
Struggled a bit with this one, but ended up with the following solution... maybe it will help someone.

HTML template:

<select (change)="onValueChanged($event.target)">
    <option *ngFor="let option of uifOptions" [value]="option.value" [selected]="option == uifSelected ? true : false">{{option.text}}</option>
</select>

Component:

import { Component, Input, Output, EventEmitter, OnInit } from '@angular/core';
export class UifDropdownComponent implements OnInit {
    @Input() uifOptions: {value: string, text: string}[];
    @Input() uifSelectedValue: string = '';
    @Output() uifSelectedValueChange:EventEmitter<string> = new EventEmitter<string>();
    uifSelected: {value: string, text: string} = {'value':'', 'text':''};

    constructor() { }

    onValueChanged(target: HTMLSelectElement):void {
        this.uifSelectedValue = target.value;
        this.uifSelectedValueChange.emit(this.uifSelectedValue);
    }

    ngOnInit() {
        this.uifSelected = this.uifOptions.filter(o => o.value ==
        this.uifSelectedValue)[0];
    }
}


问:
Standard App Engine project wrongly deployed as flexible
I have had a few python apps running on App Engine standard environment for a few years, the last successful deployment being April 7, 2017.  Today when trying to deploy an update using this command:

```<code>    gcloud.cmd app deploy --project <redacted-project-id> -v 5 --promote --quiet
</code>```

I'm receiving the following error:

```<code>    Updated property [core/project].
    Services to deploy:

    descriptor:      [D:\Projects\appengine\app.yaml]
    source:          [D:\Projects\appengine]
    target project:  [<redacted-project-id>]
    target service:  [default]
    target version:  [5]
    target url:      [https://<redacted-project-id>.appspot.com]

    If this is your first deployment, this may take a while...failed.
    WARNING: We couldn't validate that your project is ready to deploy to App Engine Flexible Environment. If deployment fails, please check the following message and try again:
    Server responded with code [400]:
      Bad Request Unexpected HTTP status 400.
      Failed Project Preparation (app_id='s~<redacted-project-id>'). Out of retries.  Last error: Temporary error occurred while verifying project: TEMPORARY_ERROR: Operation does not satisfy the following requirements: billing-enabled {Billing must be enabled for activation of service '' in project '<redacted-project-id>' to proceed., https://console.developers.google.com/project/<redacted-project-id>/settings}
    com.google.api.management.server.common.exceptions.ServiceManagementNonRetriableStorageException: Operation does not satisfy the following requirements: billing-enabled {Billing must be enabled for activation of service '' in project '<redacted-project-id>' to proceed., https://console.developers.google.com/project/<redacted-project-id>/settings}
    Beginning deployment of service [default]...
    Building and pushing image for service [default]
    Some files were skipped. Pass `--verbosity=info` to see which ones.
    You may also view the gcloud log file, found at
    [C:\Users\Brian\AppData\Roaming\gcloud\logs\2017.07.04\22.44.12.404000.log].
    ERROR: (gcloud.app.deploy) You do not have permission to access project [<redacted-project-id>] (or it may not exist): The caller does not have permission
</code>```

I enabled billing for this project and it attempted to create a docker as if I wanted to use the flexible environment.

```<code>    Updated property [core/project].
    Services to deploy:

    descriptor:      [D:\Projects\appengine\app.yaml]
    source:          [D:\Projects\appengine]
    target project:  [<redacted-project-id>]
    target service:  [default]
    target version:  [5]
    target url:      [https://<redacted-project-id>.appspot.com]

    If this is your first deployment, this may take a while...done.

    Beginning deployment of service [default]...
    Building and pushing image for service [default]
    Some files were skipped. Pass `--verbosity=info` to see which ones.
    You may also view the gcloud log file, found at
    [C:\Users\Brian\AppData\Roaming\gcloud\logs\2017.07.04\22.56.43.574000.log].
    Started cloud build [818a94e7-584a-46a2-be15-bdb304b38fd3].
    To see logs in the Cloud Console: https://console.cloud.google.com/gcr/builds/818a94e7-584a-46a2-be15-bdb304b38fd3?project=<redacted-project-id>
    ----------------------------- REMOTE BUILD OUTPUT ------------------------------
    starting build "818a94e7-584a-46a2-be15-bdb304b38fd3"

    FETCHSOURCE
    Fetching storage object: gs://staging.<redacted-project-id>.appspot.com/us.gcr.io/<redacted-project-id>/appengine/default.5:latest#1499201946081566
    Copying gs://staging.<redacted-project-id>.appspot.com/us.gcr.io/<redacted-project-id>/appengine/default.5:latest#1499201946081566...
    | [1 files][ 79.1 MiB/ 79.1 MiB]
    Operation completed over 1 objects/79.1 MiB.
    BUILD
    Already have image (with digest): gcr.io/cloud-builders/docker
    Sending build context to Docker daemon  184.6MB
    Step 1/2 : FROM gcr.io/google-appengine/php:latest
    latest: Pulling from google-appengine/php
    Digest: sha256:eeafc3e85abe6fb29b39fd87c73342527e2fdefc6ec173d55c60378e36b51fab
    Status: Downloaded newer image for gcr.io/google-appengine/php:latest
    # Executing 3 build triggers...
    Step 1/1 : COPY . $APP_DIR
    Step 1/1 : RUN chown -R www-data.www-data $APP_DIR

    Command killed by keyboard interrupt
</code>```

Why it was creating a PHP docker for a Python project is a mystery.  Is this a bug or is it a misconfiguration on my end due to recent gcloud component updates?

My app.yaml file as requested:

```<code>    runtime: python27
    api_version: 1
    threadsafe: yes

    default_expiration: "7d 0h"

    handlers:
    - url: /robots.txt
      static_files: static/robots.txt
      upload: static/robots.txt

    - url: /fonts/(.*\.otf)
      static_files: static/fonts/\1
      upload: static/fonts/(.*\.otf)
      mime_type: application/x-font-otf

    - url: /fonts/(.*\.ttf)
      static_files: static/fonts/\1
      upload: static/fonts/(.*\.ttf)
      mime_type: application/x-font-ttf

    - url: /fonts/(.*\.eot)
      static_files: static/fonts/\1
      upload: static/fonts/(.*\.eot)
      mime_type: application/vnd.ms-fontobject

    - url: /fonts/(.*\.svg)
      static_files: static/fonts/\1
      upload: static/fonts/(.*\.svg)
      mime_type: image/svg+xml

    - url: /fonts/(.*\.woff)
      static_files: static/fonts/\1
      upload: static/fonts/(.*\.woff)
      mime_type: application/font-woff

    - url: /fonts/(.*\.woff2)
      static_files: static/fonts/\1
      upload: static/fonts/(.*\.woff2)
      mime_type: application/font-woff2

    - url: /BingSiteAuth.xml
      static_files: static/BingSiteAuth.xml
      upload: static/BingSiteAuth.xml

    - url: /favicon.ico
      static_files: static/img/favicon.ico
      upload: static/img/favicon.ico

    - url: /(.*\.txt)
      static_files: static/verification/\1
      upload: static/verification/(.*\.txt)

    - url: /static
      static_dir: static

    - url: /tasks/.*
      script: main.app
      login: admin

    - url: /cron/.*
      script: main.app
      login: admin

    - url: /.*
      script: main.app

    error_handlers:
    - error_code: over_quota
      file: static/over_quota.html

    libraries:
    - name: webapp2
      version: latest
    - name: jinja2
      version: latest
    - name: lxml
      version: latest
    - name: numpy
      version: "1.6.1"
    - name: pycrypto
      version: latest
</code>```

Possible solution: This appears to be a bug caused by deploying with gcloud.cmd.  I am able to deploy one app using appcfg.py like this:

```<code>    python.exe -u "C:\Program Files (x86)\Google\Cloud SDK\google-cloud-sdk\platform\google_appengine\appcfg.py" --oauth2_credential_file=C:\Users\Brian\.appcfg_oauth2 --application=<redacted-project-id> --version=5 update appengine
</code>```

It worked on one app, the other app is failing with a similar error as above, "Bad Request Unexpected HTTP status 400".

答: I discovered the solution, it was on my end.  The above errors are caused because my deploy script was providing the wrong path to my codebase when calling gcloud app deploy.  It was executing one directory above the codebase, which results in the above errors.  Hope that helps someone else.

Body:
I have had a few python apps running on App Engine standard environment for a few years, the last successful deployment being April 7, 2017.  Today when trying to deploy an update using this command:

    gcloud.cmd app deploy --project <redacted-project-id> -v 5 --promote --quiet

I'm receiving the following error:

    Updated property [core/project].
    Services to deploy:

    descriptor:      [D:\Projects\appengine\app.yaml]
    source:          [D:\Projects\appengine]
    target project:  [<redacted-project-id>]
    target service:  [default]
    target version:  [5]
    target url:      [https://<redacted-project-id>.appspot.com]

    If this is your first deployment, this may take a while...failed.
    WARNING: We couldn't validate that your project is ready to deploy to App Engine Flexible Environment. If deployment fails, please check the following message and try again:
    Server responded with code [400]:
      Bad Request Unexpected HTTP status 400.
      Failed Project Preparation (app_id='s~<redacted-project-id>'). Out of retries.  Last error: Temporary error occurred while verifying project: TEMPORARY_ERROR: Operation does not satisfy the following requirements: billing-enabled {Billing must be enabled for activation of service '' in project '<redacted-project-id>' to proceed., https://console.developers.google.com/project/<redacted-project-id>/settings}
    com.google.api.management.server.common.exceptions.ServiceManagementNonRetriableStorageException: Operation does not satisfy the following requirements: billing-enabled {Billing must be enabled for activation of service '' in project '<redacted-project-id>' to proceed., https://console.developers.google.com/project/<redacted-project-id>/settings}
    Beginning deployment of service [default]...
    Building and pushing image for service [default]
    Some files were skipped. Pass `--verbosity=info` to see which ones.
    You may also view the gcloud log file, found at
    [C:\Users\Brian\AppData\Roaming\gcloud\logs\2017.07.04\22.44.12.404000.log].
    ERROR: (gcloud.app.deploy) You do not have permission to access project [<redacted-project-id>] (or it may not exist): The caller does not have permission

I enabled billing for this project and it attempted to create a docker as if I wanted to use the flexible environment.

    Updated property [core/project].
    Services to deploy:

    descriptor:      [D:\Projects\appengine\app.yaml]
    source:          [D:\Projects\appengine]
    target project:  [<redacted-project-id>]
    target service:  [default]
    target version:  [5]
    target url:      [https://<redacted-project-id>.appspot.com]

    If this is your first deployment, this may take a while...done.

    Beginning deployment of service [default]...
    Building and pushing image for service [default]
    Some files were skipped. Pass `--verbosity=info` to see which ones.
    You may also view the gcloud log file, found at
    [C:\Users\Brian\AppData\Roaming\gcloud\logs\2017.07.04\22.56.43.574000.log].
    Started cloud build [818a94e7-584a-46a2-be15-bdb304b38fd3].
    To see logs in the Cloud Console: https://console.cloud.google.com/gcr/builds/818a94e7-584a-46a2-be15-bdb304b38fd3?project=<redacted-project-id>
    ----------------------------- REMOTE BUILD OUTPUT ------------------------------
    starting build "818a94e7-584a-46a2-be15-bdb304b38fd3"

    FETCHSOURCE
    Fetching storage object: gs://staging.<redacted-project-id>.appspot.com/us.gcr.io/<redacted-project-id>/appengine/default.5:latest#1499201946081566
    Copying gs://staging.<redacted-project-id>.appspot.com/us.gcr.io/<redacted-project-id>/appengine/default.5:latest#1499201946081566...
    | [1 files][ 79.1 MiB/ 79.1 MiB]
    Operation completed over 1 objects/79.1 MiB.
    BUILD
    Already have image (with digest): gcr.io/cloud-builders/docker
    Sending build context to Docker daemon  184.6MB
    Step 1/2 : FROM gcr.io/google-appengine/php:latest
    latest: Pulling from google-appengine/php
    Digest: sha256:eeafc3e85abe6fb29b39fd87c73342527e2fdefc6ec173d55c60378e36b51fab
    Status: Downloaded newer image for gcr.io/google-appengine/php:latest
    # Executing 3 build triggers...
    Step 1/1 : COPY . $APP_DIR
    Step 1/1 : RUN chown -R www-data.www-data $APP_DIR

    Command killed by keyboard interrupt

Why it was creating a PHP docker for a Python project is a mystery.  Is this a bug or is it a misconfiguration on my end due to recent gcloud component updates?

My app.yaml file as requested:

    runtime: python27
    api_version: 1
    threadsafe: yes

    default_expiration: "7d 0h"

    handlers:
    - url: /robots.txt
      static_files: static/robots.txt
      upload: static/robots.txt

    - url: /fonts/(.*\.otf)
      static_files: static/fonts/\1
      upload: static/fonts/(.*\.otf)
      mime_type: application/x-font-otf

    - url: /fonts/(.*\.ttf)
      static_files: static/fonts/\1
      upload: static/fonts/(.*\.ttf)
      mime_type: application/x-font-ttf

    - url: /fonts/(.*\.eot)
      static_files: static/fonts/\1
      upload: static/fonts/(.*\.eot)
      mime_type: application/vnd.ms-fontobject

    - url: /fonts/(.*\.svg)
      static_files: static/fonts/\1
      upload: static/fonts/(.*\.svg)
      mime_type: image/svg+xml

    - url: /fonts/(.*\.woff)
      static_files: static/fonts/\1
      upload: static/fonts/(.*\.woff)
      mime_type: application/font-woff

    - url: /fonts/(.*\.woff2)
      static_files: static/fonts/\1
      upload: static/fonts/(.*\.woff2)
      mime_type: application/font-woff2

    - url: /BingSiteAuth.xml
      static_files: static/BingSiteAuth.xml
      upload: static/BingSiteAuth.xml

    - url: /favicon.ico
      static_files: static/img/favicon.ico
      upload: static/img/favicon.ico

    - url: /(.*\.txt)
      static_files: static/verification/\1
      upload: static/verification/(.*\.txt)

    - url: /static
      static_dir: static

    - url: /tasks/.*
      script: main.app
      login: admin

    - url: /cron/.*
      script: main.app
      login: admin

    - url: /.*
      script: main.app

    error_handlers:
    - error_code: over_quota
      file: static/over_quota.html

    libraries:
    - name: webapp2
      version: latest
    - name: jinja2
      version: latest
    - name: lxml
      version: latest
    - name: numpy
      version: "1.6.1"
    - name: pycrypto
      version: latest

Possible solution: This appears to be a bug caused by deploying with gcloud.cmd.  I am able to deploy one app using appcfg.py like this:

    python.exe -u "C:\Program Files (x86)\Google\Cloud SDK\google-cloud-sdk\platform\google_appengine\appcfg.py" --oauth2_credential_file=C:\Users\Brian\.appcfg_oauth2 --application=<redacted-project-id> --version=5 update appengine

It worked on one app, the other app is failing with a similar error as above, "Bad Request Unexpected HTTP status 400".


问:
Socket.IO infinite loop on connection
Socket.IO make an infinte loop on connection !
It's weird and never happen until now. I don't know what's wrong. I try to rebuild the package, I copy some code from an older source and the same result...

```<code>io.on('connection', function(socket){
  console.log('someone connected << infinite loop');
});
</code>```

It's a basic ExpressJS server with http on top.

```<code>const
port        = process.env.PORT || 3200,
app         = require('express')(),
express     = require('express'),
mysql       = require('mysql'),
bodyParser  = require('body-parser'),
path        = require('path'),
methodOverride = require('method-override'),
http        = require('http').Server(app),
io          = require('socket.io')(http);
</code>```

Client-Side

```<code>var socket = io();
</code>```

答: The problem was at the client-side, I don't load the latest version of socket.io like on the server-side. In my package.json I have 2.0.3 and at the client-side was 1.2.0.. For everyone who have this problem</p>

Title: Socket.IO infinite loop on connection

Body:
Socket.IO make an infinte loop on connection !
It's weird and never happen until now. I don't know what's wrong. I try to rebuild the package, I copy some code from an older source and the same result...

io.on('connection', function(socket){
  console.log('someone connected << infinite loop');
});

It's a basic ExpressJS server with http on top.

const
port        = process.env.PORT || 3200,
app         = require('express')(),
express     = require('express'),
mysql       = require('mysql'),
bodyParser  = require('body-parser'),
path        = require('path'),
methodOverride = require('method-override'),
http        = require('http').Server(app),
io          = require('socket.io')(http);

Client-Side

var socket = io();


问:
PL/SQL use a value declared for setting a sequence start
I'm new in PL/SQL in Oracle and what I've tried so far doesn't work

I want to get the max(id) of my table... And then create a SEQUENCE which starts with this maxID+1

```<code>DECLARE maxId NUMBER;

BEGIN
  SELECT max(id)+1 INTO maxId FROM TABLE;
  CREATE SEQUENCE "DB"."SEQ_TABLE"  MINVALUE 1 MAXVALUE 999999 INCREMENT BY 1 START WITH maxId CACHE 20 NOORDER NOCYCLE;
END;
/
</code>```

But I can't use CREATE here ...

How can I achieve this ?

答:
You can try this :</p>

```<code> DECLARE
       maxId   NUMBER;
       v_sql   VARCHAR2 (200);
    BEGIN
       SELECT MAX (employee_id) + 1
         INTO maxId
         FROM employee;

         v_sql:= 'CREATE SEQUENCE SEQ_TABLE START WITH '|| maxId ||' INCREMENT BY 1 MINVALUE 1 MAXVALUE 999999 NOORDER  NOCYCLE';
        EXECUTE IMMEDIATE v_sql ;
    END;
    /
</code>```

Body:
I'm new in PL/SQL in Oracle and what I've tried so far doesn't work

I want to get the max(id) of my table... And then create a SEQUENCE which starts with this maxID+1

DECLARE maxId NUMBER;

BEGIN
  SELECT max(id)+1 INTO maxId FROM TABLE;
  CREATE SEQUENCE "DB"."SEQ_TABLE"  MINVALUE 1 MAXVALUE 999999 INCREMENT BY 1 START WITH maxId CACHE 20 NOORDER NOCYCLE;
END;
/

But I can't use CREATE here ...

How can I achieve this ?

Body:
You can try this :

 DECLARE
       maxId   NUMBER;
       v_sql   VARCHAR2 (200);
    BEGIN
       SELECT MAX (employee_id) + 1
         INTO maxId
         FROM employee;

         v_sql:= 'CREATE SEQUENCE SEQ_TABLE START WITH '|| maxId ||' INCREMENT BY 1 MINVALUE 1 MAXVALUE 999999 NOORDER  NOCYCLE';
        EXECUTE IMMEDIATE v_sql ;
    END;
    /


问:
How would I capture a "double-click" on a touch-screen device with JavaFX?
I'm working on an application that will be released both for desktop and for mobile devices with touch screens. There is a feature which will require the user to double-click (for desktop).

How do I capture a "double-click" on a touch-screen device? Is that even possible?

答:
I think you found a solution by now.

But this is how I did it,

I used the MousePressed event with the condition MouseEvent.getClickCount() == 2.


问:
com.jcraft.jsch.JSchException: connection is closed by foreign host when i use jsch to connect my ftp server
i want to start a Sftp server by embedding it in my java code .
when i start the Sftp server and then start the client , the exception throws .

my server code

```<code>public class EmbeddedSftpServer  {
    public static  final String SERVER_BASE_DIR = System.getProperty("user.dir") + File.separator + "src";
  //  public static  final String SERVER_KEYSTORE = SERVER_BASE_DIR + File.separator + "resources" + File.separator + "ftpserver.jks";
    public static  final String SERVER_KEYSTORE= "C:\\Users\\y73wang\\IdeaProjects\\SFTPServer\\src\\main\\resources\\ftpserver.jks";
    //public static  final String SERVER_USERS = SERVER_BASE_DIR + File.separator + "resources" + File.separator + "users.properties";
    public static  final String SERVER_USERS ="C:\\Users\\y73wang\\IdeaProjects\\SFTPServer\\src\\main\\resources\\users.properties";
    //public static  final String USER_HOME_DIR = SERVER_BASE_DIR + File.separator + "SftpHomeDir" ;
    public static  final String USER_HOME_DIR = "D:\\TEST";
    public static  final String SAMPLE_FILE = "test.txt";
    public static  final String ADMIN = "admin";
    public static  final String PASSWORD = "password";
    public static  final int DEFAULT_PORT =8009;
    private final FtpServer server;

    public static EmbeddedSftpServer createDefaultServer() throws Exception {
        return  new EmbeddedSftpServer(DEFAULT_PORT,ADMIN,PASSWORD,true);
    }
    public EmbeddedSftpServer( int port, String username, String password, boolean implicitSsl ) throws Exception {
        this.server = createServer( port, username, password, implicitSsl );
    }

    private FtpServer createServer( int port, String username, String password, boolean implicitSsl ) throws FtpException {
        ListenerFactory factory = new ListenerFactory();
        factory.setPort( port );
        if ( implicitSsl ) {
            SslConfigurationFactory ssl = new SslConfigurationFactory();
            ssl.setKeystoreFile( new File( SERVER_KEYSTORE ) );
            ssl.setKeystorePassword( PASSWORD );
            // set the SSL configuration for the listener
            factory.setSslConfiguration( ssl.createSslConfiguration() );
            factory.setImplicitSsl( true );
        }

        FtpServerFactory serverFactory = new FtpServerFactory();
        // replace the default listener
        serverFactory.addListener( "default", factory.createListener() );

        PropertiesUserManagerFactory userManagerFactory = new PropertiesUserManagerFactory();

        userManagerFactory.setFile( new File( SERVER_USERS ) );
        UserManager userManager = userManagerFactory.createUserManager();
        if ( !userManager.doesExist( username ) ) {
            BaseUser user = new BaseUser();
            user.setName( username );
            user.setPassword( password );
            user.setEnabled( true );
            user.setHomeDirectory( USER_HOME_DIR );
            user.setAuthorities( Collections.<Authority>singletonList( new WritePermission() ) );
            userManager.save( user );
        }

        serverFactory.setUserManager( userManager );
        return serverFactory.createServer();
    }
    public void start() throws FtpException {
        server.start();
    }
    public void stop(){
        if (server != null){
            server.stop();
        }
    }
   public static  void main(String[] args) throws Exception {
       EmbeddedSftpServer sftpServer = new EmbeddedSftpServer(DEFAULT_PORT,"admin","admin",true);
       sftpServer.start();
   }
}
</code>```

user.properties:

```<code># Password is "admin"
ftpserver.user.admin.userpassword=21232F297A57A5A743894A0E4A801FC3
ftpserver.user.admin.homedirectory=D:/test
ftpserver.user.admin.enableflag=true
ftpserver.user.admin.writepermission=true
ftpserver.user.admin.maxloginnumber=10
ftpserver.user.admin.maxloginperip=10
ftpserver.user.admin.idletime=0
ftpserver.user.admin.uploadrate=0
ftpserver.user.admin.downloadrate=0

ftpserver.user.anonymous.userpassword=
ftpserver.user.anonymous.homedirectory=D:/test
ftpserver.user.anonymous.enableflag=true
ftpserver.user.anonymous.writepermission=false
ftpserver.user.anonymous.maxloginnumber=20
ftpserver.user.anonymous.maxloginperip=2
ftpserver.user.anonymous.idletime=300
ftpserver.user.anonymous.uploadrate=4800
ftpserver.user.anonymous.downloadrate=4800
</code>```

the Client code :

```<code>public class JschClient {
public void sendFile(String filename) throws JSchException, SftpException, FileNotFoundException {
    int Port =22;
    String sftphost = "127.0.0.1";
    String userName = "admin";
    String password = "admin";
    String HomeDir = "D:\\test";
    Session session =null;
    Channel channel =null;
    ChannelSftp channelSftp = null;
    JSch jSch = new JSch();
    session =jSch.getSession(userName,sftphost,8009);
    java.util.Properties config = new java.util.Properties();
    config.put("StrictHostKeyChecking","no");
    config.put("PreferredAuthentications", "password");
    session.setConfig(config);
    session.setPassword(password);
    session.connect(60000);
    channel = session.openChannel("sftp");
    channel.connect();
    channelSftp = (ChannelSftp) channel;
    ((ChannelSftp) channel).cd(HomeDir);
    File f = new File(filename);
    channelSftp.put(new FileInputStream(f),f.getName());
    channelSftp.exit();
    System.out.println("sftp Channel exited.");
    channel.disconnect();
    System.out.println("Channel disconnected.");
    session.disconnect();
    System.out.println("Host Session disconnected.");
}
public static void main(String[]agrs) throws FileNotFoundException, JSchException, SftpException {
    JschClient jschClient = new JschClient();
    jschClient.sendFile("D:\\file1.txt");
}
</code>```

error log:

```<code>Exception in thread "main" com.jcraft.jsch.JSchException: connection is closed by foreign host
at com.jcraft.jsch.Session.connect(Session.java:269)
at client.JschClient.sendFile(JschClient.java:29)
at client.JschClient.main(JschClient.java:45)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:144)
</code>```

is there any wrong in my code ?

答:
May be i am very late to answer your question but still if anyone needs how to connect with SFTP using jsch library.

You can use below method

```<code>   static Session session = null;
    static Channel channel = null;

public Session sftpConnection(final String value, final String sftpUser, final String sftpHost, final int sftpPort,
        final String sftpPass) {
        System.out.println("preparing the host information for sftp.");
        try {
            JSch jsch = new JSch();
            this.session = jsch.getSession(sftpUser, sftpHost, sftpPort);
            if (value.equals("puttyServer")) {
                this.session.setProxy(new ProxySOCKS5("proxy need to add", Integer.parseInt("portnumber need to add")));
            }
            this.session.setPassword(sftpPass);
            java.util.Properties config = new java.util.Properties();
            config.put("StrictHostKeyChecking", "no");
            this.session.setConfig(config);
            this.session.connect();
            return this.session;
        } catch (Exception ex) {
            ex.printStackTrace();
            sftpConnection(value, sftpUser, sftpHost, sftpPort, sftpPass);
        }
        return null;
    }
</code>```

Body:
i want to start a Sftp server by embedding it in my java code .
when i start the Sftp server and then start the client , the exception throws .

my server code

public class EmbeddedSftpServer  {
    public static  final String SERVER_BASE_DIR = System.getProperty("user.dir") + File.separator + "src";
  //  public static  final String SERVER_KEYSTORE = SERVER_BASE_DIR + File.separator + "resources" + File.separator + "ftpserver.jks";
    public static  final String SERVER_KEYSTORE= "C:\\Users\\y73wang\\IdeaProjects\\SFTPServer\\src\\main\\resources\\ftpserver.jks";
    //public static  final String SERVER_USERS = SERVER_BASE_DIR + File.separator + "resources" + File.separator + "users.properties";
    public static  final String SERVER_USERS ="C:\\Users\\y73wang\\IdeaProjects\\SFTPServer\\src\\main\\resources\\users.properties";
    //public static  final String USER_HOME_DIR = SERVER_BASE_DIR + File.separator + "SftpHomeDir" ;
    public static  final String USER_HOME_DIR = "D:\\TEST";
    public static  final String SAMPLE_FILE = "test.txt";
    public static  final String ADMIN = "admin";
    public static  final String PASSWORD = "password";
    public static  final int DEFAULT_PORT =8009;
    private final FtpServer server;

    public static EmbeddedSftpServer createDefaultServer() throws Exception {
        return  new EmbeddedSftpServer(DEFAULT_PORT,ADMIN,PASSWORD,true);
    }
    public EmbeddedSftpServer( int port, String username, String password, boolean implicitSsl ) throws Exception {
        this.server = createServer( port, username, password, implicitSsl );
    }

    private FtpServer createServer( int port, String username, String password, boolean implicitSsl ) throws FtpException {
        ListenerFactory factory = new ListenerFactory();
        factory.setPort( port );
        if ( implicitSsl ) {
            SslConfigurationFactory ssl = new SslConfigurationFactory();
            ssl.setKeystoreFile( new File( SERVER_KEYSTORE ) );
            ssl.setKeystorePassword( PASSWORD );
            // set the SSL configuration for the listener
            factory.setSslConfiguration( ssl.createSslConfiguration() );
            factory.setImplicitSsl( true );
        }

        FtpServerFactory serverFactory = new FtpServerFactory();
        // replace the default listener
        serverFactory.addListener( "default", factory.createListener() );

        PropertiesUserManagerFactory userManagerFactory = new PropertiesUserManagerFactory();

        userManagerFactory.setFile( new File( SERVER_USERS ) );
        UserManager userManager = userManagerFactory.createUserManager();
        if ( !userManager.doesExist( username ) ) {
            BaseUser user = new BaseUser();
            user.setName( username );
            user.setPassword( password );
            user.setEnabled( true );
            user.setHomeDirectory( USER_HOME_DIR );
            user.setAuthorities( Collections.<Authority>singletonList( new WritePermission() ) );
            userManager.save( user );
        }

        serverFactory.setUserManager( userManager );
        return serverFactory.createServer();
    }
    public void start() throws FtpException {
        server.start();
    }
    public void stop(){
        if (server != null){
            server.stop();
        }
    }
   public static  void main(String[] args) throws Exception {
       EmbeddedSftpServer sftpServer = new EmbeddedSftpServer(DEFAULT_PORT,"admin","admin",true);
       sftpServer.start();
   }
}

user.properties:

# Password is "admin"
ftpserver.user.admin.userpassword=21232F297A57A5A743894A0E4A801FC3
ftpserver.user.admin.homedirectory=D:/test
ftpserver.user.admin.enableflag=true
ftpserver.user.admin.writepermission=true
ftpserver.user.admin.maxloginnumber=10
ftpserver.user.admin.maxloginperip=10
ftpserver.user.admin.idletime=0
ftpserver.user.admin.uploadrate=0
ftpserver.user.admin.downloadrate=0

ftpserver.user.anonymous.userpassword=
ftpserver.user.anonymous.homedirectory=D:/test
ftpserver.user.anonymous.enableflag=true
ftpserver.user.anonymous.writepermission=false
ftpserver.user.anonymous.maxloginnumber=20
ftpserver.user.anonymous.maxloginperip=2
ftpserver.user.anonymous.idletime=300
ftpserver.user.anonymous.uploadrate=4800
ftpserver.user.anonymous.downloadrate=4800

the Client code :

public class JschClient {
public void sendFile(String filename) throws JSchException, SftpException, FileNotFoundException {
    int Port =22;
    String sftphost = "127.0.0.1";
    String userName = "admin";
    String password = "admin";
    String HomeDir = "D:\\test";
    Session session =null;
    Channel channel =null;
    ChannelSftp channelSftp = null;
    JSch jSch = new JSch();
    session =jSch.getSession(userName,sftphost,8009);
    java.util.Properties config = new java.util.Properties();
    config.put("StrictHostKeyChecking","no");
    config.put("PreferredAuthentications", "password");
    session.setConfig(config);
    session.setPassword(password);
    session.connect(60000);
    channel = session.openChannel("sftp");
    channel.connect();
    channelSftp = (ChannelSftp) channel;
    ((ChannelSftp) channel).cd(HomeDir);
    File f = new File(filename);
    channelSftp.put(new FileInputStream(f),f.getName());
    channelSftp.exit();
    System.out.println("sftp Channel exited.");
    channel.disconnect();
    System.out.println("Channel disconnected.");
    session.disconnect();
    System.out.println("Host Session disconnected.");
}
public static void main(String[]agrs) throws FileNotFoundException, JSchException, SftpException {
    JschClient jschClient = new JschClient();
    jschClient.sendFile("D:\\file1.txt");
}

error log:

Exception in thread "main" com.jcraft.jsch.JSchException: connection is closed by foreign host
at com.jcraft.jsch.Session.connect(Session.java:269)
at client.JschClient.sendFile(JschClient.java:29)
at client.JschClient.main(JschClient.java:45)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:144)

is there any wrong in my code ?

Body:
May be i am very late to answer your question but still if anyone needs how to connect with SFTP using jsch library.

You can use below method

   static Session session = null;
    static Channel channel = null;

public Session sftpConnection(final String value, final String sftpUser, final String sftpHost, final int sftpPort,
        final String sftpPass) {
        System.out.println("preparing the host information for sftp.");
        try {
            JSch jsch = new JSch();
            this.session = jsch.getSession(sftpUser, sftpHost, sftpPort);
            if (value.equals("puttyServer")) {
                this.session.setProxy(new ProxySOCKS5("proxy need to add", Integer.parseInt("portnumber need to add")));
            }
            this.session.setPassword(sftpPass);
            java.util.Properties config = new java.util.Properties();
            config.put("StrictHostKeyChecking", "no");
            this.session.setConfig(config);
            this.session.connect();
            return this.session;
        } catch (Exception ex) {
            ex.printStackTrace();
            sftpConnection(value, sftpUser, sftpHost, sftpPort, sftpPass);
        }
        return null;
    }


问:
Convert a file to a UTF-8 file in Node.js
I'm new to JavaScript and Node.js. So, I have a JSON file and I want to encode this file to a UTF-8 JSON file. How is it possible with Node.js?

The source JSON file is generated by another framework and contains maybe BOMs, but I need a UTF-8 JSON file without BOMs to handle it.

答:
```<code>var fs = require('fs');
const detectCharacterEncoding = require('detect-character-encoding'); //npm install detect-character-encoding
var buffer = fs.readFileSync('filename.txt');
var originalEncoding = detectCharacterEncoding(buffer);
var file = fs.readFileSync('filename.txt', originalEncoding.encoding);
fs.writeFileSync('filename.txt', file, 'UTF-8');
</code>```

How does this work?

When fs reads in a file, it converts it from the encoding of the file to the format that JS uses.

After that, when fs writes the file, it converts the string stored by JS to UTF-8 and writes it to file.

Body:
var fs = require('fs');
const detectCharacterEncoding = require('detect-character-encoding'); //npm install detect-character-encoding
var buffer = fs.readFileSync('filename.txt');
var originalEncoding = detectCharacterEncoding(buffer);
var file = fs.readFileSync('filename.txt', originalEncoding.encoding);
fs.writeFileSync('filename.txt', file, 'UTF-8');

How does this work?

When fs reads in a file, it converts it from the encoding of the file to the format that JS uses.

After that, when fs writes the file, it converts the string stored by JS to UTF-8 and writes it to file.


问:
How can I get useful error messages in PHP?
Quite often I will try and run a PHP script and just get a blank screen back. No error message; just an empty screen. The cause might have been a simple syntax error (wrong bracket, missing semicolon), or a failed function call, or something else entirely.

It is very difficult to figure out what went wrong. I end up commenting out code, entering "echo" statements everywhere, etc. trying to narrow down the problem. But there surely must be a better way, right?

Is there a way to get PHP to produce a useful error message, like Java does?

答:
For those who use nginx and have a white screen even for file with <?php echo 123;. In my case I didn't have this required option for PHP in nginx config file:

```<code>fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
</code>```

This option wasn't in fastcgi_params file, so PHP didn't work and there wasn't any errors in logs.

ContentLicense: CC BY-SA 4.0

Body:
For those who use nginx and have a white screen even for file with <?php echo 123;. In my case I didn't have this required option for PHP in nginx config file:

fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;

This option wasn't in fastcgi_params file, so PHP didn't work and there wasn't any errors in logs.


问:
flex:1, display:flex on the same element?
I cannot find reliable information online or in caniuse website.

Is it 'legal' and well supported to use display: flex on a flexbox item? I mean:

```<code>.parent{
   display: flex;
}

.child{
   flex:1;
   display: flex;
}
</code>```

And do you maybe know of any browser support chart?

答:
It's not a matter of "support".

display:flex makes an element a "flex-parent".

flex: 1 applies only to "flex-children".

It's entirely "legal" because the two properties don't apply for the same reasons and aren't specifically related.

For information on nested flexboxes, you can refer to the W3.org Specification*

* Thanks to LGSon

Body:
I cannot find reliable information online or in caniuse website.

Is it 'legal' and well supported to use display: flex on a flexbox item? I mean:

.parent{
   display: flex;
}

.child{
   flex:1;
   display: flex;
}

And do you maybe know of any browser support chart?


问:
Android: application crashes on Picture.createFromStream()
My app displays a series of pictures.  For memory reasons, I want to serialize these pictures when they are not in use.  The serialization seems to work (doesn't throw exceptions or crash), but the application crashes on my Picture.createFromStream() call.  I can't find anything informative in the LogCat output, nor does the failed call throw a Throwable.  Any advice?</p>

```<code>12-20 10:48:37.121: WARN/InputManagerService(53): Window already focused, ignoring focus gain of: com.android.internal.view.IInputMethodClient$Stub$Proxy@438abe88
12-20 10:48:37.132: DEBUG/dalvikvm(53): threadid=17: bogus mon 1+0>0; adjusting
12-20 10:48:50.901: DEBUG/dalvikvm(238): GC freed 15257 objects / 1725344 bytes in 99ms
12-20 10:50:26.912: DEBUG/dalvikvm(238): GC freed 29 objects / 1200 bytes in 56ms
12-20 10:51:03.661: INFO/DEBUG(28): *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** ***
12-20 10:51:03.661: INFO/DEBUG(28): Build fingerprint: 'generic/sdk/generic/:1.6/Donut/20842:eng/test-keys'
12-20 10:51:03.661: INFO/DEBUG(28): pid: 238, tid: 238  >>> com. <<<
12-20 10:51:03.661: INFO/DEBUG(28): signal 11 (SIGSEGV), fault addr 00000004
12-20 10:51:03.661: INFO/DEBUG(28):  r0 00000004  r1 00000000  r2 00000004  r3 00299b98
12-20 10:51:03.661: INFO/DEBUG(28):  r4 00000000  r5 00000000  r6 00000001  r7 00299b00
12-20 10:51:03.661: INFO/DEBUG(28):  r8 00299ac0  r9 00000000  10 66616374  fp 00299b60
12-20 10:51:03.661: INFO/DEBUG(28):  ip ac1285f4  sp bef065f0  lr ac06fc10  pc afb04408  cpsr 60000010
12-20 10:51:03.771: INFO/DEBUG(28):          #00  pc 00004408  /system/lib/libcutils.so
12-20 10:51:03.771: INFO/DEBUG(28):          #01  lr ac06fc10  /system/lib/libsgl.so
12-20 10:51:03.771: INFO/DEBUG(28): stack:
12-20 10:51:03.781: INFO/DEBUG(28):     bef065b0  00299b00  [heap]
12-20 10:51:03.781: INFO/DEBUG(28):     bef065b4  ac07b4f8  /system/lib/libsgl.so
12-20 10:51:03.781: INFO/DEBUG(28):     bef065b8  00000000
12-20 10:51:03.781: INFO/DEBUG(28):     bef065bc  00616374
12-20 10:51:03.781: INFO/DEBUG(28):     bef065c0  00299b78  [heap]
12-20 10:51:03.781: INFO/DEBUG(28):     bef065c4  ac038f48  /system/lib/libsgl.so
12-20 10:51:03.781: INFO/DEBUG(28):     bef065c8  00299ac0  [heap]
12-20 10:51:03.781: INFO/DEBUG(28):     bef065cc  00000001
12-20 10:51:03.781: INFO/DEBUG(28):     bef065d0  00299b60  [heap]
12-20 10:51:03.781: INFO/DEBUG(28):     bef065d4  00299b78  [heap]
12-20 10:51:03.791: INFO/DEBUG(28):     bef065d8  00000000
12-20 10:51:03.791: INFO/DEBUG(28):     bef065dc  00000001
12-20 10:51:03.791: INFO/DEBUG(28):     bef065e0  00299b00  [heap]
12-20 10:51:03.791: INFO/DEBUG(28):     bef065e4  00299b78  [heap]
12-20 10:51:03.791: INFO/DEBUG(28):     bef065e8  df002777
12-20 10:51:03.791: INFO/DEBUG(28):     bef065ec  e3a070ad
12-20 10:51:03.791: INFO/DEBUG(28): #00 bef065f0  00000000
12-20 10:51:03.791: INFO/DEBUG(28):     bef065f4  ac06fc10  /system/lib/libsgl.so
12-20 10:51:03.791: INFO/DEBUG(28):     bef065f8  bef06647  [stack]
12-20 10:51:03.791: INFO/DEBUG(28):     bef065fc  00000001
12-20 10:51:03.801: INFO/DEBUG(28):     bef06600  00000070
12-20 10:51:03.801: INFO/DEBUG(28):     bef06604  afe0ea00  /system/lib/libc.so
12-20 10:51:03.801: INFO/DEBUG(28):     bef06608  00299b00  [heap]
12-20 10:51:03.801: INFO/DEBUG(28):     bef0660c  afe0ed94  /system/lib/libc.so
12-20 10:51:03.801: INFO/DEBUG(28):     bef06610  00299b00  [heap]
12-20 10:51:03.801: INFO/DEBUG(28):     bef06614  000001b4
12-20 10:51:03.801: INFO/DEBUG(28):     bef06618  000000dc
12-20 10:51:03.801: INFO/DEBUG(28):     bef0661c  00002bcc
12-20 10:51:03.801: INFO/DEBUG(28):     bef06620  bef06670  [stack]
12-20 10:51:03.811: INFO/DEBUG(28):     bef06624  afe0b70f  /system/lib/libc.so
12-20 10:51:03.811: INFO/DEBUG(28):     bef06628  afe39dd4  /system/lib/libc.so
12-20 10:51:03.811: INFO/DEBUG(28):     bef0662c  00299b00  [heap]
12-20 10:51:03.811: INFO/DEBUG(28):     bef06630  00299ae0  [heap]
12-20 10:51:03.811: INFO/DEBUG(28):     bef06634  00299ac0  [heap]
12-20 10:51:04.661: DEBUG/Zygote(30): Process 238 terminated by signal (11)
12-20 10:51:04.671: INFO/ActivityManager(53): Process com. (pid 238) has died.
12-20 10:51:04.691: INFO/WindowManager(53): WIN DEATH: Window{43899ae8
12-20 10:51:04.701: INFO/WindowManager(53): WINDOW DIED during motion dispatch:
12-20 10:51:04.761: WARN/UsageStats(53): Unexpected resume of com.android.launcher while already resumed in
12-20 10:51:04.791: WARN/WindowManager(53): Requested window android.os.BinderProxy@437913d8 does not exist
12-20 10:51:04.791: WARN/WindowManager(53): java.lang.RuntimeException
12-20 10:51:04.791: WARN/WindowManager(53):     at com.android.server.WindowManagerService.windowForClientLocked(WindowManagerService.java:7767)
12-20 10:51:04.791: WARN/WindowManager(53):     at com.android.server.WindowManagerService.windowForClientLocked(WindowManagerService.java:7759)
12-20 10:51:04.791: WARN/WindowManager(53):     at com.android.server.WindowManagerService.removeWindow(WindowManagerService.java:1359)
12-20 10:51:04.791: WARN/WindowManager(53):     at com.android.server.WindowManagerService.dispatchPointer(WindowManagerService.java:4078)
12-20 10:51:04.791: WARN/WindowManager(53):     at com.android.server.WindowManagerService.access$1200(WindowManagerService.java:127)
12-20 10:51:04.791: WARN/WindowManager(53):     at com.android.server.WindowManagerService$InputDispatcherThread.process(WindowManagerService.java:5356)
12-20 10:51:04.791: WARN/WindowManager(53):     at com.android.server.WindowManagerService$InputDispatcherThread.run(WindowManagerService.java:5264)
12-20 10:51:04.832: WARN/InputManagerService(53): Got RemoteException sending setActive(false) notification to pid 238 uid 10023
</code>```

答:
That is a crash in native code, and therefore qualifies as a platform bug. Very similar stacktraces appear in bug reports 7468 and 2535.

Am afraid you will have to find a workaround fairly blindly. For starters, how many times do you draw to the Canvas between beginRecording() and endRecording()? How big is a typical serialized file?

Body:
My app displays a series of pictures.  For memory reasons, I want to serialize these pictures when they are not in use.  The serialization seems to work (doesn't throw exceptions or crash), but the application crashes on my Picture.createFromStream() call.  I can't find anything informative in the LogCat output, nor does the failed call throw a Throwable.  Any advice?

12-20 10:48:37.121: WARN/InputManagerService(53): Window already focused, ignoring focus gain of: com.android.internal.view.IInputMethodClient$Stub$Proxy@438abe88
12-20 10:48:37.132: DEBUG/dalvikvm(53): threadid=17: bogus mon 1+0>0; adjusting
12-20 10:48:50.901: DEBUG/dalvikvm(238): GC freed 15257 objects / 1725344 bytes in 99ms
12-20 10:50:26.912: DEBUG/dalvikvm(238): GC freed 29 objects / 1200 bytes in 56ms
12-20 10:51:03.661: INFO/DEBUG(28): *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** ***
12-20 10:51:03.661: INFO/DEBUG(28): Build fingerprint: 'generic/sdk/generic/:1.6/Donut/20842:eng/test-keys'
12-20 10:51:03.661: INFO/DEBUG(28): pid: 238, tid: 238  >>> com. <<<
12-20 10:51:03.661: INFO/DEBUG(28): signal 11 (SIGSEGV), fault addr 00000004
12-20 10:51:03.661: INFO/DEBUG(28):  r0 00000004  r1 00000000  r2 00000004  r3 00299b98
12-20 10:51:03.661: INFO/DEBUG(28):  r4 00000000  r5 00000000  r6 00000001  r7 00299b00
12-20 10:51:03.661: INFO/DEBUG(28):  r8 00299ac0  r9 00000000  10 66616374  fp 00299b60
12-20 10:51:03.661: INFO/DEBUG(28):  ip ac1285f4  sp bef065f0  lr ac06fc10  pc afb04408  cpsr 60000010
12-20 10:51:03.771: INFO/DEBUG(28):          #00  pc 00004408  /system/lib/libcutils.so
12-20 10:51:03.771: INFO/DEBUG(28):          #01  lr ac06fc10  /system/lib/libsgl.so
12-20 10:51:03.771: INFO/DEBUG(28): stack:
12-20 10:51:03.781: INFO/DEBUG(28):     bef065b0  00299b00  [heap]
12-20 10:51:03.781: INFO/DEBUG(28):     bef065b4  ac07b4f8  /system/lib/libsgl.so
12-20 10:51:03.781: INFO/DEBUG(28):     bef065b8  00000000
12-20 10:51:03.781: INFO/DEBUG(28):     bef065bc  00616374
12-20 10:51:03.781: INFO/DEBUG(28):     bef065c0  00299b78  [heap]
12-20 10:51:03.781: INFO/DEBUG(28):     bef065c4  ac038f48  /system/lib/libsgl.so
12-20 10:51:03.781: INFO/DEBUG(28):     bef065c8  00299ac0  [heap]
12-20 10:51:03.781: INFO/DEBUG(28):     bef065cc  00000001
12-20 10:51:03.781: INFO/DEBUG(28):     bef065d0  00299b60  [heap]
12-20 10:51:03.781: INFO/DEBUG(28):     bef065d4  00299b78  [heap]
12-20 10:51:03.791: INFO/DEBUG(28):     bef065d8  00000000
12-20 10:51:03.791: INFO/DEBUG(28):     bef065dc  00000001
12-20 10:51:03.791: INFO/DEBUG(28):     bef065e0  00299b00  [heap]
12-20 10:51:03.791: INFO/DEBUG(28):     bef065e4  00299b78  [heap]
12-20 10:51:03.791: INFO/DEBUG(28):     bef065e8  df002777
12-20 10:51:03.791: INFO/DEBUG(28):     bef065ec  e3a070ad
12-20 10:51:03.791: INFO/DEBUG(28): #00 bef065f0  00000000
12-20 10:51:03.791: INFO/DEBUG(28):     bef065f4  ac06fc10  /system/lib/libsgl.so
12-20 10:51:03.791: INFO/DEBUG(28):     bef065f8  bef06647  [stack]
12-20 10:51:03.791: INFO/DEBUG(28):     bef065fc  00000001
12-20 10:51:03.801: INFO/DEBUG(28):     bef06600  00000070
12-20 10:51:03.801: INFO/DEBUG(28):     bef06604  afe0ea00  /system/lib/libc.so
12-20 10:51:03.801: INFO/DEBUG(28):     bef06608  00299b00  [heap]
12-20 10:51:03.801: INFO/DEBUG(28):     bef0660c  afe0ed94  /system/lib/libc.so
12-20 10:51:03.801: INFO/DEBUG(28):     bef06610  00299b00  [heap]
12-20 10:51:03.801: INFO/DEBUG(28):     bef06614  000001b4
12-20 10:51:03.801: INFO/DEBUG(28):     bef06618  000000dc
12-20 10:51:03.801: INFO/DEBUG(28):     bef0661c  00002bcc
12-20 10:51:03.801: INFO/DEBUG(28):     bef06620  bef06670  [stack]
12-20 10:51:03.811: INFO/DEBUG(28):     bef06624  afe0b70f  /system/lib/libc.so
12-20 10:51:03.811: INFO/DEBUG(28):     bef06628  afe39dd4  /system/lib/libc.so
12-20 10:51:03.811: INFO/DEBUG(28):     bef0662c  00299b00  [heap]
12-20 10:51:03.811: INFO/DEBUG(28):     bef06630  00299ae0  [heap]
12-20 10:51:03.811: INFO/DEBUG(28):     bef06634  00299ac0  [heap]
12-20 10:51:04.661: DEBUG/Zygote(30): Process 238 terminated by signal (11)
12-20 10:51:04.671: INFO/ActivityManager(53): Process com. (pid 238) has died.
12-20 10:51:04.691: INFO/WindowManager(53): WIN DEATH: Window{43899ae8
12-20 10:51:04.701: INFO/WindowManager(53): WINDOW DIED during motion dispatch:
12-20 10:51:04.761: WARN/UsageStats(53): Unexpected resume of com.android.launcher while already resumed in
12-20 10:51:04.791: WARN/WindowManager(53): Requested window android.os.BinderProxy@437913d8 does not exist
12-20 10:51:04.791: WARN/WindowManager(53): java.lang.RuntimeException
12-20 10:51:04.791: WARN/WindowManager(53):     at com.android.server.WindowManagerService.windowForClientLocked(WindowManagerService.java:7767)
12-20 10:51:04.791: WARN/WindowManager(53):     at com.android.server.WindowManagerService.windowForClientLocked(WindowManagerService.java:7759)
12-20 10:51:04.791: WARN/WindowManager(53):     at com.android.server.WindowManagerService.removeWindow(WindowManagerService.java:1359)
12-20 10:51:04.791: WARN/WindowManager(53):     at com.android.server.WindowManagerService.dispatchPointer(WindowManagerService.java:4078)
12-20 10:51:04.791: WARN/WindowManager(53):     at com.android.server.WindowManagerService.access$1200(WindowManagerService.java:127)
12-20 10:51:04.791: WARN/WindowManager(53):     at com.android.server.WindowManagerService$InputDispatcherThread.process(WindowManagerService.java:5356)
12-20 10:51:04.791: WARN/WindowManager(53):     at com.android.server.WindowManagerService$InputDispatcherThread.run(WindowManagerService.java:5264)
12-20 10:51:04.832: WARN/InputManagerService(53): Got RemoteException sending setActive(false) notification to pid 238 uid 10023


问:
Pass month name dynamically in AWK (GNU) with control statement
Hi I'm trying out below command to match month and day (of 6 days ago, which is Jun 29) to search a directory using AWK, but the result is always '0' instead it is supposed to be around 1800.

```<code>ls -ltr /test/output|awk  -v month="$(date --date="6 days ago" +"\"%b\"")", -v day="$(date --date="6 days ago" +%d)"  '$6 ==month && $7==day {print $9}'|wc -l
</code>```

tried this also

```<code>ls -ltr /test/output|awk  -v month="$(date --date="6 days ago" +%b)", -v day="$(date --date="6 days ago" +%d)"  '$6 ==month && $7==day {print $9}'|wc -l
</code>```

but it is working if I hardcode Month

```<code>ls -ltr /test/output|awk  -v month="$(date --date="6 days ago" +"\"%b\"")", -v day="$(date --date="6 days ago" +%d)"  '$6 =="Jun" && $7==day {print $9}'|wc -l
</code>```

Please suggest what I'm missing in the code?

答:
You have quotation marks in your month variable and so use:

```<code>date --date="6 days ago" +\%b
</code>```

Alternatively, in awk, refer to the month with:

```<code>gensub("\"","","g",month)
</code>```

I've notices that you also have a comma between the two variable assignments (-v) which needs to be removed. The complete solution is:

```<code>ls -ltr /test/output|awk  -v month="$(date --date="6 days ago" +\%b)" -v day="$(date --date="6 days ago" +%d)"  '$6 ==month && $7==day {print $9}'|wc -l
</code>```

Body:
Hi I'm trying out below command to match month and day (of 6 days ago, which is Jun 29) to search a directory using AWK, but the result is always '0' instead it is supposed to be around 1800.

ls -ltr /test/output|awk  -v month="$(date --date="6 days ago" +"\"%b\"")", -v day="$(date --date="6 days ago" +%d)"  '$6 ==month && $7==day {print $9}'|wc -l

tried this also

ls -ltr /test/output|awk  -v month="$(date --date="6 days ago" +%b)", -v day="$(date --date="6 days ago" +%d)"  '$6 ==month && $7==day {print $9}'|wc -l

but it is working if I hardcode Month

ls -ltr /test/output|awk  -v month="$(date --date="6 days ago" +"\"%b\"")", -v day="$(date --date="6 days ago" +%d)"  '$6 =="Jun" && $7==day {print $9}'|wc -l

Please suggest what I'm missing in the code?

Body:
You have quotation marks in your month variable and so use:

date --date="6 days ago" +\%b

Alternatively, in awk, refer to the month with:

gensub("\"","","g",month)

I've notices that you also have a comma between the two variable assignments (-v) which needs to be removed. The complete solution is:

ls -ltr /test/output|awk  -v month="$(date --date="6 days ago" +\%b)" -v day="$(date --date="6 days ago" +%d)"  '$6 ==month && $7==day {print $9}'|wc -l