问:
how to find collegue Id in table
i have one table as Employee that have two column Id and Branch. i have to find its collegue Id except his own id from table without using subquery.

```<code>Id      Branch
==============
1       Delhi
2       Mumbai
3       Delhi
4       Delhi
5       Mumbai
6       Mumbai
</code>```

if i enter e.g. 3 then my answer has to be 1 and 4.

答:
use self join

```<code>  select t2.id from table_name t1
  join table_name t2 on t1.Branch=t2.Branch
  where t1.id=3 and t2.id!=3
</code>```

for data preparation easily i used CTE version below with result

```<code> with cte as
(

select 1 as id, 'Delhi' as b
union all
select 2,    'Mumbai'
union all
select 3    ,  'Delhi'
union all
select 4  ,     'Delhi'

) select t2.id from cte t1 join cte t2 on t1.b=t2.b
  where t1.id=3 and t2.id!=3
</code>```

demo link

here is the output

```<code>id
1
4
</code>```

Title: how to find collegue Id in table

Body:
i have one table as Employee that have two column Id and Branch. i have to find its collegue Id except his own id from table without using subquery.

Id      Branch
==============
1       Delhi
2       Mumbai
3       Delhi
4       Delhi
5       Mumbai
6       Mumbai

if i enter e.g. 3 then my answer has to be 1 and 4.

Body:
use self join

  select t2.id from table_name t1
  join table_name t2 on t1.Branch=t2.Branch
  where t1.id=3 and t2.id!=3

for data preparation easily i used CTE version below with result

 with cte as
(

select 1 as id, 'Delhi' as b
union all
select 2,    'Mumbai'
union all
select 3    ,  'Delhi'
union all
select 4  ,     'Delhi'

) select t2.id from cte t1 join cte t2 on t1.b=t2.b
  where t1.id=3 and t2.id!=3

demo link

here is the output

id
1
4


来源: stackexchange

问:
Is there a way to simulate a click on an alert in JavaScript?
I have a page with an iframe whose source page is in a separate domain. From time to time, the source page generates an alert. When it does so, it stops what it is doing until the user clicks OK to the alert.

What I would like to do is programmatically click OK on this alert so the source page can get back to being useful. Is this possible?

答:
What happens if you override alert with a no-op in your code?

e.g.

```<code><script>
// uncomment next line to swallow alerts
//  function alert(nope) { return; }
<script>
<script>
  $(document).ready(function() { alert("Hello, world!"); });
</script>
</code>```

With the line commented out, alert appears.  With line commented in, alert does not appear.

OwnerDisplayName: moffdub

ContentLicense: CC BY-SA 2.5

Body:
What happens if you override alert with a no-op in your code?

e.g.

<script>
// uncomment next line to swallow alerts
//  function alert(nope) { return; }
<script>
<script>
  $(document).ready(function() { alert("Hello, world!"); });
</script>

With the line commented out, alert appears.  With line commented in, alert does not appear.

OwnerDisplayName: tlholaday

LastEditorDisplayName: tlholaday


问:
Effective stdin reading c programming
can anyone help me optimalize code for reading standard input. Here it is what I have now:</p>

```<code>unsigned char *msg;
size_t msgBytes = 0;
size_t inputMsgBuffLen = 1024;
if ( (msg = (unsigned char *) malloc(sizeof(unsigned char) * inputMsgBuffLen) ) == NULL ) {
    quitErr("Couldn't allocate memmory!", EXIT_FAILURE);
}
for (int c; (c = getchar()) != EOF; msgBytes++) {
    if (msgBytes >= (inputMsgBuffLen)) {
        inputMsgBuffLen <<= 1;
        if ( ( msg = (unsigned char *)realloc(msg, sizeof(unsigned char) * inputMsgBuffLen) ) == NULL) {
            free(msg);
            quitErr("Couldn't allocate more memmory!", EXIT_FAILURE);
        }
    }
    msg[msgBytes] = (unsigned char)c;
}
</code>```

答:
Why do you want to "optimalize" the code?

Did you time it?

Did you find it was too slow?

Are you ready to time the new versions?

Do you realize timing run time of code is dependent of many many factors (like current processor load, number of active users, disk activity, ..., ...)

The best optimization you can do, is start with a very large value for malloc (and possibly realloc down after all data has been read).

```<code>size_t inputMsgBuffLen = 400000000; /* approx 400 mega */
</code>```

ContentLicense: CC BY-SA 3.0

Title: Effective stdin reading c programming

Body:
can anyone help me optimalize code for reading standard input. Here it is what I have now:

unsigned char *msg;
size_t msgBytes = 0;
size_t inputMsgBuffLen = 1024;
if ( (msg = (unsigned char *) malloc(sizeof(unsigned char) * inputMsgBuffLen) ) == NULL ) {
    quitErr("Couldn't allocate memmory!", EXIT_FAILURE);
}
for (int c; (c = getchar()) != EOF; msgBytes++) {
    if (msgBytes >= (inputMsgBuffLen)) {
        inputMsgBuffLen <<= 1;
        if ( ( msg = (unsigned char *)realloc(msg, sizeof(unsigned char) * inputMsgBuffLen) ) == NULL) {
            free(msg);
            quitErr("Couldn't allocate more memmory!", EXIT_FAILURE);
        }
    }
    msg[msgBytes] = (unsigned char)c;
}

Body:
Why do you want to "optimalize" the code?

Did you time it?

Did you find it was too slow?

Are you ready to time the new versions?

Do you realize timing run time of code is dependent of many many factors (like current processor load, number of active users, disk activity, ..., ...)

The best optimization you can do, is start with a very large value for malloc (and possibly realloc down after all data has been read).

size_t inputMsgBuffLen = 400000000; /* approx 400 mega */


问:
How to get a transaction history by specific transaction ID(txhash) in Corda
To get state I can use Vault, but what about transactions? How I can get them, for example, by txHash? Is it possible to do this by vaultService.queryBy(criteria) ?

Since internalVerifiedTransactionsSnapshot method is deprecated now, any ways to retrieve a specific transaction by using txhash as of Corda 4?

答:
Inside of the node you can call:

```<code>serviceHub.validatedTransactions.getTransaction(hash)
</code>```

Via rpc I think you can do this:

```<code>proxy.stateMachineRecordedTransactionMappingSnapshot().map { it.transactionId }.first { it == hash }
</code>```

But a better solution would be to create a flow that takes in a hash, calls the first snippet and returns the transaction.

ContentLicense: CC BY-SA 4.0

Body:
Inside of the node you can call:

serviceHub.validatedTransactions.getTransaction(hash)

Via rpc I think you can do this:

proxy.stateMachineRecordedTransactionMappingSnapshot().map { it.transactionId }.first { it == hash }

But a better solution would be to create a flow that takes in a hash, calls the first snippet and returns the transaction.


问:
Hide the outside element on click of parent div
This is my HTML code:

```<code><html>
<head>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
 <body>
     <div class="product details product-item-details">
     <div class="swatch-option text" >Large</div>
       <div class="price-box price-final_price">
           <span class="price-container price-final_price tax weee">
            <span class="price-label" style="display:
           inline;">From</span>100</span>

          </div>
     </div>

   <div class="product details product-item-details">
     <div class="swatch-option text" >Large</div>
     <div class="price-box price-final_price">
          <span class="price-container price-final_price tax weee">
            <span class="price-label" style="display: inline;">From</span>200</span>

        </div>
    </div>

    <div class="product details product-item-details">
     <div class="swatch-option text" >Large</div>
     <div class="price-box price-final_price">
          <span class="price-container price-final_price tax weee">
            <span class="price-label" style="display: inline;">From</span>300</span>

          </div>
  </div>
 <script>
  $(document).ready(function($){
     $('.product-item-details .swatch-option').live("click",function(){
        $(this).next('.price-final_price .price-container .price-label').hide();

    });
  });
  <script>

 </body>
</head>
</html>
</code>```

I need to hide "From" label of the span element "price-label" when a particular div is clicked.

The above jQuery code is not working for me,

Any help would be greatly appreciated. Thanks

答:
please try this code:

<!DOCTYPE html>

Large

         From100

Large

         From200

Large

         From300

```

Body:
This is my HTML code:

Large

            From100

Large

            From200

Large

            From300

Body:
please try this code:

<!DOCTYPE html>
<html>
<head>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
  <script>
      $(document).ready(function(){
         $('.product-item-details .swatch-option').click(function(){

           $(this).next().find('.price-label').hide();
         });
      });
   </script>
  </head>
 <body>
   <div class="product details product-item-details">
      <div class="swatch-option text" >Large</div>
      <div class="price-box price-final_price">
         <span class="price-container price-final_price tax weee">
         <span class="price-label" style="display: inline;">From</span>100</span>
      </div>
   </div>

   <div class="product details product-item-details">
     <div class="swatch-option text" >Large</div>
     <div class="price-box price-final_price">
         <span class="price-container price-final_price tax weee">
         <span class="price-label" style="display: inline;">From</span>200</span>
      </div>
   </div>

   <div class="product details product-item-details">
      <div class="swatch-option text" >Large</div>
      <div class="price-box price-final_price">
         <span class="price-container price-final_price tax weee">
         <span class="price-label" style="display: inline;">From</span>300</span>
      </div>
   </div>

 </body>
</head>
</html>


问:
Element out from container box that already fix
I have a bunch of image that will show random quantity. I try to make every line with 2 images. But it doesn't want to split to 2 each line. but. 1 line 1 image. I already set the container to desire max width I will use and the max size each image. in  code i set max container i will use to 1024px. and each image 512px. i think it should not have problem. i already check with inspect. no padding and margin already. if i set it a bit low example to 509.5px. it will split to 2.

Here's the code:

var caption = document.getElementsByClassName('caption');

for (var i = 0; i < caption.length; i++) {
  caption[i].innerHTML = "";
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>ul {
  display: inline;
  margin: 0;
  padding: 0;
  list-style-type: none;
}

li {
  display: inline;
}

.banner figure {
  display: inline;
  margin: 0;
}

.banner figure .caption {
  display: inline;
}</code>```

banner

banner

banner

banner

banner

banner

banner

```

答:
You can use css grid if you want columns and rows

ul {
    display: grid;
    grid-template-columns:50% 50%;
    margin: 0;
    padding: 0;
    list-style-type: none;
}
 .banner figure{
    margin: 0;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div style="width: 1024px">
<section id="banner">
<ul>
<li class="banner"><figure><img src="assets/img/banner.jpg" width="512px" height="50px"><figcaption class="caption">banner</figcaption></figure></li>
<li class="banner"><figure><img src="assets/img/banner.jpg" width="512px" height="50px"><figcaption class="caption">banner</figcaption></figure></li>
<li class="banner"><figure><img src="assets/img/banner.jpg" width="512px" height="50px"><figcaption class="caption">banner</figcaption></figure></li>
<li class="banner"><figure><img src="assets/img/banner.jpg" width="512px" height="50px"><figcaption class="caption">banner</figcaption></figure></li>
<li class="banner"><figure><img src="assets/img/banner.jpg" width="512px" height="50px"><figcaption class="caption">banner</figcaption></figure></li>
<li class="banner"><figure><img src="assets/img/banner.jpg" width="512px" height="50px"><figcaption class="caption">banner</figcaption></figure></li>
<li class="banner"><figure><img src="assets/img/banner.jpg" width="512px" height="50px"><figcaption class="caption">banner</figcaption></figure></li>
</ul>
</section>
</div></code>```

check this out for more information about css grid https://css-tricks.com/snippets/css/complete-guide-grid/

Body:
I have a bunch of image that will show random quantity. I try to make every line with 2 images. But it doesn't want to split to 2 each line. but. 1 line 1 image. I already set the container to desire max width I will use and the max size each image. in  code i set max container i will use to 1024px. and each image 512px. i think it should not have problem. i already check with inspect. no padding and margin already. if i set it a bit low example to 509.5px. it will split to 2.

Here's the code:

var caption = document.getElementsByClassName('caption');

for (var i = 0; i < caption.length; i++) {
  caption[i].innerHTML = "";
}

ul {
  display: inline;
  margin: 0;
  padding: 0;
  list-style-type: none;
}

li {
  display: inline;
}

.banner figure {
  display: inline;
  margin: 0;
}

.banner figure .caption {
  display: inline;
}

banner

banner

banner

banner

banner

banner

banner

Body:
You can use css grid if you want columns and rows

ul {
    display: grid;
    grid-template-columns:50% 50%;
    margin: 0;
    padding: 0;
    list-style-type: none;
}
 .banner figure{
    margin: 0;
}

<div style="width: 1024px">
<section id="banner">
<ul>
<li class="banner"><a href="https://www.google.com"><figure><img src="assets/img/banner.jpg" width="512px" height="50px"><figcaption class="caption">banner</figcaption></figure></a></li>
<li class="banner"><a href="https://www.google.com"><figure><img src="assets/img/banner.jpg" width="512px" height="50px"><figcaption class="caption">banner</figcaption></figure></a></li>
<li class="banner"><a href="https://www.google.com"><figure><img src="assets/img/banner.jpg" width="512px" height="50px"><figcaption class="caption">banner</figcaption></figure></a></li>
<li class="banner"><a href="https://www.google.com"><figure><img src="assets/img/banner.jpg" width="512px" height="50px"><figcaption class="caption">banner</figcaption></figure></a></li>
<li class="banner"><a href="https://www.google.com"><figure><img src="assets/img/banner.jpg" width="512px" height="50px"><figcaption class="caption">banner</figcaption></figure></a></li>
<li class="banner"><a href="https://www.google.com"><figure><img src="assets/img/banner.jpg" width="512px" height="50px"><figcaption class="caption">banner</figcaption></figure></a></li>
<li class="banner"><a href="https://www.google.com"><figure><img src="assets/img/banner.jpg" width="512px" height="50px"><figcaption class="caption">banner</figcaption></figure></a></li>
</ul>
</section>
</div>

check this out for more information about css grid https://css-tricks.com/snippets/css/complete-guide-grid/


问:
Is it safe to replace a self object by another object of the same type in a method?
I would like to replace an object instance by another instance inside a method like this:

```<code>class A:
    def method1(self):
        self = func(self)
</code>```

The object is retrieved from a database.

答:
In many cases, a good way to achieve what you want is to call __init__ again. For example:

```<code>class MyList(list):
    def trim(self,n):
        self.__init__(self[:-n])

x = MyList([1,2,3,4])
x.trim(2)
assert type(x) == MyList
assert x == [1,2]
</code>```

Note that this comes with a few assumptions such as the all that you want to change about the object being set in __init__. Also beware that this could cause problems with inheriting classes that redefine __init__ in an incompatible manner.

Body:
I would like to replace an object instance by another instance inside a method like this:

class A:
    def method1(self):
        self = func(self)

The object is retrieved from a database.

Body:
In many cases, a good way to achieve what you want is to call __init__ again. For example:

class MyList(list):
    def trim(self,n):
        self.__init__(self[:-n])

x = MyList([1,2,3,4])
x.trim(2)
assert type(x) == MyList
assert x == [1,2]

Note that this comes with a few assumptions such as the all that you want to change about the object being set in __init__. Also beware that this could cause problems with inheriting classes that redefine __init__ in an incompatible manner.


问:
^ and $ expressed in fundamental operations in regular expressions
I've read a book where it states that all fundamental operations in regular expressions are concatatenation, or(|), closure(*) and parenthesis to override default precedence. Every other operation is just a shortcut for one or more fundamental operations.

For example, (AB)+ shortcut is expanded to (AB)(AB)* and (AB)? to (ε | AB) where ε is empty string. First of all, I looked up ASCII table and I am not sure which charcode is designated to empty string. Is it ASCII 0?

I'd like to figure out how to express the shortcuts ^ and $ as in ^AB or AB$ expression in the fundamental operations, but I am not sure how to do this. Can you help me out how this is expressed in fundamentals?

答:
^AB can be expressed as (εAB) ie an empty string followed by AB and AB$ can be expressed as (ABε) that's AB followed by an empty string.

The empty string is actually defined as '', that's a string of 0 length, so has no value in the ASCII table. However the C programming language terminates all strings with the ASCII NULL character, although this is not counted in the length of the string it still must be accounted for when allocating memory.

EDIT
As @melpomene pointed out in their comment εAB is equivalent to AB which makes the above invalid. Having talked to a work college I'm no longer sure how to do this or even if it's possible. Hopefully someone can come up with an answer.


问:
Generate sql insert script from excel worksheet
I have a large excel worksheet that I want to add to my database.

Can I generate an SQL insert script from this excel worksheet?

答:
I have a reliable way to generate SQL inserts batly,and you can modify partial parameters in processing.It helps me a lot in my work, for example, copy one hundreds data to database with incompatible structure and fields count.
 IntellIJ DataGrip , the powerful tool i use.
DG can batly receive data from WPS office or MS Excel by column or line.
after copying, DG can export data as SQL inserts.


问:
How to get HH:MM:SS difference using milliseconds in javascript?
I have two times like one is 145:02:31 and another one is 01:00:00 and I want to calculate the difference between these two times like 144:02:31 but right now I am getting 13:02:31 which is wrong.

Please help me thank you.

答:
It's a little crude with the formatting but works just the way you need.

function format_ms(time_ms) {
  let hours = 0;
  let minutes = 0;
  let seconds = 0;

  hours = parseInt(time_ms / 3600000).toString();

  time_ms %= 3600000;

  minutes = parseInt(time_ms / 60000).toString();

  time_ms %= 60000;

  seconds = parseInt(time_ms / 1000).toString();

  return hours + ":" + minutes.padStart(2, '0') + ":" + seconds.padStart(2, '0');
}

let start = moment.duration('145:02:31');
let end = moment.duration('1:00:00');
let delta_ms = start - end; // in ms

console.log(format_ms(delta_ms));```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js"></script></code>```

Body:
It's a little crude with the formatting but works just the way you need.

function format_ms(time_ms) {
  let hours = 0;
  let minutes = 0;
  let seconds = 0;

  hours = parseInt(time_ms / 3600000).toString();

  time_ms %= 3600000;

  minutes = parseInt(time_ms / 60000).toString();

  time_ms %= 60000;

  seconds = parseInt(time_ms / 1000).toString();

  return hours + ":" + minutes.padStart(2, '0') + ":" + seconds.padStart(2, '0');
}

let start = moment.duration('145:02:31');
let end = moment.duration('1:00:00');
let delta_ms = start - end; // in ms

console.log(format_ms(delta_ms));

<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js"></script>


问:
Python Altair - Setting Minimum Bar Height for Interactive Graphs
I am currently generating an interactive stacked-bar graph, where individual stacks of the bar graph can be clicked on to update other graphics.

The issue I am running into is a problem of scale.  Sometimes, I will have a dataset where 1 bar has a reading of 25,000, and another will have a reading of 1.

It becomes near impossible to see, let alone click, that entry of 1, when the scale goes up so high due to another reading.

Is it possible to set a "minimum" height for any bar piece? I know this is likely difficult or weird due to Y-axis scaling then.

Thanks!

答:
You can use strokeWidth to draw the edge:

```<code>import altair as alt

import pandas as pd
df = pd.DataFrame(dict(x=["a", "b"], y=[1, 1000]))
select = alt.selection(type="single", fields=["x"], empty="none")
alt.Chart(df).mark_bar(strokeWidth=5).encode(
    y="x",
    x="y",
    fill=alt.condition(select, alt.value("red"), alt.value("blue")),
    stroke=alt.condition(select, alt.value("red"), alt.value("blue")),
).add_selection(select)
</code>```

if you don't want to show the stroke, you can set strokeOpacity=0.001.

```<code>import altair as alt

import pandas as pd
df = pd.DataFrame(dict(x=["a", "b"], y=[1, 1000]))
select = alt.selection(type="single", fields=["x"], empty="none")
alt.Chart(df).mark_bar(strokeWidth=5, stroke="red", strokeOpacity=0.001).encode(
    y="x",
    x="y",
    fill=alt.condition(select, alt.value("red"), alt.value("blue")),
).add_selection(select).interactive()
</code>```

Body:
You can use strokeWidth to draw the edge:

import altair as alt

import pandas as pd
df = pd.DataFrame(dict(x=["a", "b"], y=[1, 1000]))
select = alt.selection(type="single", fields=["x"], empty="none")
alt.Chart(df).mark_bar(strokeWidth=5).encode(
    y="x",
    x="y",
    fill=alt.condition(select, alt.value("red"), alt.value("blue")),
    stroke=alt.condition(select, alt.value("red"), alt.value("blue")),
).add_selection(select)

if you don't want to show the stroke, you can set strokeOpacity=0.001.

import altair as alt

import pandas as pd
df = pd.DataFrame(dict(x=["a", "b"], y=[1, 1000]))
select = alt.selection(type="single", fields=["x"], empty="none")
alt.Chart(df).mark_bar(strokeWidth=5, stroke="red", strokeOpacity=0.001).encode(
    y="x",
    x="y",
    fill=alt.condition(select, alt.value("red"), alt.value("blue")),
).add_selection(select).interactive()


问:
Double mapping JSON to list
I have a problem with showing data from JSON.

My JSON data looks like this:

```<code>data1 = [
    {
        id:'1',
        name: 'one',
        on: [
            {
                id:'1.1',
                type: 'Anna',
            },
            {
                id:'1.2',
                type: 'John',
            },
        ],

    },
    {
        id:'2',
        name: 'two',
        on: [
            {
                id:'1.1',
                type: 'John',
            },
            {
                id:'1.2',
                type: 'Anna',
            },
        ],

    },
]
</code>```

I'm getting a JSON from local API by axios. This way works great in other tables. With this JSON I've try do this this way:

```<code>getData = () => {
    axios
      .get("Localhost", { params : {token : this.state.token }})
      .then(response =>
        response.data.map(data1 => ({
          id: `${data1.id}`,
          name: `${data1.name}`,
          onid: `${data1.on.id}`,
          ontype: `${data1.on.type}`,
        }))
      )
      .then(data1 => {
        this.setState({ data1 });
      })
  }
</code>```

and then in render i try to map it:

```<code><ol>
    {data1.map(user => {
      const { id, name } = user;
      return (
        <li key={id}>
          {name}
          {data1.on.map(user2 => {
            const { onid, ontype } = user2;
            return <li key={onid}> {ontype}</li>;
          })}
        </li>
      );
    })}
  </ol>
</code>```

but the map for data1.on doesn't work

I expect that data will appear like this:

One

Anna

John

Two

John

Anna

How should I do that?

答:
I think you just need to rework your map. Try something like this:

```<code>  <ol>
    {this.state.data1.map(item => {
      return (
        <li>
          {item.name.toUpperCase()}
          <ol>
            {item.on.map(person => {
              return <li>{person.type}</li>;
            })}
          </ol>
        </li>
      );
    })}
  </ol>
);
</code>```

Here is the sandbox: https://codesandbox.io/s/gallant-ellis-76bdv

Title: Double mapping JSON to list

Body:
I have a problem with showing data from JSON.

My JSON data looks like this:

data1 = [
    {
        id:'1',
        name: 'one',
        on: [
            {
                id:'1.1',
                type: 'Anna',
            },
            {
                id:'1.2',
                type: 'John',
            },
        ],

    },
    {
        id:'2',
        name: 'two',
        on: [
            {
                id:'1.1',
                type: 'John',
            },
            {
                id:'1.2',
                type: 'Anna',
            },
        ],

    },
]

I'm getting a JSON from local API by axios. This way works great in other tables. With this JSON I've try do this this way:

getData = () => {
    axios
      .get("Localhost", { params : {token : this.state.token }})
      .then(response =>
        response.data.map(data1 => ({
          id: `${data1.id}`,
          name: `${data1.name}`,
          onid: `${data1.on.id}`,
          ontype: `${data1.on.type}`,
        }))
      )
      .then(data1 => {
        this.setState({ data1 });
      })
  }

and then in render i try to map it:

    {data1.map(user => {
      const { id, name } = user;
      return (

          {name}
          {data1.on.map(user2 => {
            const { onid, ontype } = user2;
            return
 {ontype}
;
          })}

      );
    })}

but the map for data1.on doesn't work

I expect that data will appear like this:

One

Anna

John

Two

John

Anna

How should I do that?

Body:
I think you just need to rework your map. Try something like this:

  <ol>
    {this.state.data1.map(item => {
      return (
        <li>
          {item.name.toUpperCase()}
          <ol>
            {item.on.map(person => {
              return <li>{person.type}</li>;
            })}
          </ol>
        </li>
      );
    })}
  </ol>
);

Here is the sandbox: https://codesandbox.io/s/gallant-ellis-76bdv


问:
Can't make
 text aligned to top in grid layout
I've created a simple CSS grid layout of two columns and h2 elements are aligned properly at the top, but P elements are aligned vertically to the middle.

I've tried adding vertical-align: top and vertical-align: text-top, nothing changed.

#prosolcolumns {
  padding: 40px !important;
  display: grid !important;
  grid-gap: 40px !important;
  grid-template-columns: repeat(auto-fit, minmax(150px, 1fr)) !important;
  grid-template-rows: auto !important;
  background: #ffffff !important;
  max-width: 90% !important;
  min-width: 50% !important;
  box-sizing: border-box;
  /* не поддерживается в CSS2 */
  margin-left: auto !important;
  margin-right: auto !important;
}

#prosolcolumns>div,
#prosolcolumns>noindex>div {
  display: grid;
  vertical-align: top !important;
  width: auto !important;
  padding: 40px !important;
  box-sizing: border-box;
  /* не поддерживается в CSS2 */
}

#prosolcolumns p {
  padding: 0px 0px 0px 0px !important;
  margin-left: 0px !important;
  text-align: justify;
}

#prosolcolumns h2 {
  margin-left: 0px !important;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="prosolcolumns">
  <div>
    <h2>Problem</h2>
    <p>
      Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quisque feugiat sodales quam, vitae auctor ligula consequat ut. Phasellus quis mollis lectus. Aenean aliquet enim in suscipit rutrum. Praesent quis pellentesque orci, vel auctor lorem. Sed tortor
      ligula, porttitor quis lorem vitae, vehicula consectetur metus. Phasellus accumsan lectus in turpis suscipit blandit. Aenean ornare, nulla id tempus semper, lectus augue lobortis nulla, aliquam gravida risus mauris at diam. Donec in maximus nisl.
      Nullam luctus metus ut lectus commodo, a tincidunt ex ultrices. Phasellus in sollicitudin justo. Cras faucibus et diam quis facilisis. Nam ac lectus sem. Duis sit amet est nec felis malesuada semper quis pretium arcu. Sed laoreet mattis nisl, non
      tempor quam porttitor et. Nulla non ante sit amet ex blandit tincidunt nec sit amet lorem. Nam vitae lacus pretium, porta leo id, maximus enim. Vestibulum vehicula nunc vel enim euismod, ac convallis sem iaculis. Lorem ipsum dolor sit amet, consectetur
      adipiscing elit. Phasellus sit amet sem sapien. Sed vel turpis eget nunc facilisis maximus fermentum vel tellus.
    </p>
  </div>
  <div>
    <h2>Solution</h2>
    <p>
      Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quisque feugiat sodales quam, vitae auctor ligula consequat ut. Phasellus quis mollis lectus. Aenean aliquet enim in suscipit rutrum. Praesent quis pellentesque orci, vel auctor lorem. Sed tortor
      ligula, porttitor quis lorem vitae, vehicula consectetur metus. Phasellus accumsan lectus in turpis suscipit blandit. Aenean ornare, nulla id tempus semper, lectus augue lobortis nulla, aliquam gravida risus mauris at diam. Donec in maximus nisl.
      Nullam luctus metus ut lectus commodo, a tincidunt ex ultrices.
    </p>
  </div>
</div></code>```

答:
Add the following property:</p>

```<code>#prosolcolumns > div{
    grid-template-rows: 40px auto;
}
</code>```

Title: Can't make <p> text aligned to top in grid layout

Body:
I've created a simple CSS grid layout of two columns and h2 elements are aligned properly at the top, but P elements are aligned vertically to the middle.

I've tried adding vertical-align: top and vertical-align: text-top, nothing changed.

#prosolcolumns {
  padding: 40px !important;
  display: grid !important;
  grid-gap: 40px !important;
  grid-template-columns: repeat(auto-fit, minmax(150px, 1fr)) !important;
  grid-template-rows: auto !important;
  background: #ffffff !important;
  max-width: 90% !important;
  min-width: 50% !important;
  box-sizing: border-box;
  /* не поддерживается в CSS2 */
  margin-left: auto !important;
  margin-right: auto !important;
}

#prosolcolumns>div,
#prosolcolumns>noindex>div {
  display: grid;
  vertical-align: top !important;
  width: auto !important;
  padding: 40px !important;
  box-sizing: border-box;
  /* не поддерживается в CSS2 */
}

#prosolcolumns p {
  padding: 0px 0px 0px 0px !important;
  margin-left: 0px !important;
  text-align: justify;
}

#prosolcolumns h2 {
  margin-left: 0px !important;
}

Problem

      Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quisque feugiat sodales quam, vitae auctor ligula consequat ut. Phasellus quis mollis lectus. Aenean aliquet enim in suscipit rutrum. Praesent quis pellentesque orci, vel auctor lorem. Sed tortor
      ligula, porttitor quis lorem vitae, vehicula consectetur metus. Phasellus accumsan lectus in turpis suscipit blandit. Aenean ornare, nulla id tempus semper, lectus augue lobortis nulla, aliquam gravida risus mauris at diam. Donec in maximus nisl.
      Nullam luctus metus ut lectus commodo, a tincidunt ex ultrices. Phasellus in sollicitudin justo. Cras faucibus et diam quis facilisis. Nam ac lectus sem. Duis sit amet est nec felis malesuada semper quis pretium arcu. Sed laoreet mattis nisl, non
      tempor quam porttitor et. Nulla non ante sit amet ex blandit tincidunt nec sit amet lorem. Nam vitae lacus pretium, porta leo id, maximus enim. Vestibulum vehicula nunc vel enim euismod, ac convallis sem iaculis. Lorem ipsum dolor sit amet, consectetur
      adipiscing elit. Phasellus sit amet sem sapien. Sed vel turpis eget nunc facilisis maximus fermentum vel tellus.

Solution

      Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quisque feugiat sodales quam, vitae auctor ligula consequat ut. Phasellus quis mollis lectus. Aenean aliquet enim in suscipit rutrum. Praesent quis pellentesque orci, vel auctor lorem. Sed tortor
      ligula, porttitor quis lorem vitae, vehicula consectetur metus. Phasellus accumsan lectus in turpis suscipit blandit. Aenean ornare, nulla id tempus semper, lectus augue lobortis nulla, aliquam gravida risus mauris at diam. Donec in maximus nisl.
      Nullam luctus metus ut lectus commodo, a tincidunt ex ultrices.

Body:
Add the following property:

#prosolcolumns > div{
    grid-template-rows: 40px auto;
}


问:
How can i use multiple implements?
I'm making App with Android Studio.

I have a

```<code>public class MainActivity extends Activity implements View.OnClickListener, OnCheckedChangeListener
</code>```

And I need to add "AppCompatActivity" to the MainActivity.

I have searched on the Internet and I found only one can be used for extends.

So I Changed to

```<code>public class MainActivity extends Activity implements View.OnClickListener, OnCheckedChangeListener, AppCompatActivity
</code>```

This and AppCompatActivity has an error that "Interface expected here".

How can I solve this problem?

答:
The AppCompatActivity is a class not an interface  so you can't use implements keyword  to inherit the AppCompatActivity

You need to use extends keyword to inherit the AppCompatActivity class

Use this

```<code>public class MainActivity extends AppCompatActivity implements View.OnClickListener, OnCheckedChangeListener
</code>```

instead of

```<code>public class MainActivity extends Activity implements View.OnClickListener, OnCheckedChangeListener, AppCompatActivity
</code>```

Title: How can i use multiple implements?

Body:
I'm making App with Android Studio.

I have a

public class MainActivity extends Activity implements View.OnClickListener, OnCheckedChangeListener

And I need to add "AppCompatActivity" to the MainActivity.

I have searched on the Internet and I found only one can be used for extends.

So I Changed to

public class MainActivity extends Activity implements View.OnClickListener, OnCheckedChangeListener, AppCompatActivity

This and AppCompatActivity has an error that "Interface expected here".

How can I solve this problem?

Body:
The AppCompatActivity is a class not an interface  so you can't use implements keyword  to inherit the AppCompatActivity

You need to use extends keyword to inherit the AppCompatActivity class

Use this

public class MainActivity extends AppCompatActivity implements View.OnClickListener, OnCheckedChangeListener

instead of

public class MainActivity extends Activity implements View.OnClickListener, OnCheckedChangeListener, AppCompatActivity


问:
How do you turn off the multi touch capibility of the viewcontroller?
right now, the multi touch events causing the app to crash. I need to turn off the multi touch of capibility of the viewcontroller.</p>

Body: viewController.view.multipleTouchEnabled=NO;


问:
May Spring @Bean methods return instance fields?
The following Spring bean declaration appears to run and behave "as expected":

@Configuration
public class AppConfig {

    private final Foo foo;

    public AppConfig() {
        foo = new Foo();
    }

    @Bean
    public Foo foo() {
        return foo;
    }
}
```

<p>where "as expected" means "nothing is <em>obviously</em> wrong".</p>

<p>Supposing that <code>Foo</code> has some complex lifecycle (e.g. manages external resources with <code>AutoCloseable</code>), is that a valid and sensible declaration of <code>foo()</code>? All of the examples I can find, official and not, indicate that the <code>foo</code> instance should be instantiated inside <code>foo()</code>, not stored in and retrieved from a field. However, I can find no definitive information in any documentation that this should or should not be safe.</p>

<p>The most relevant documentation I can find is about the Spring IoC bean lifecycle, for instance https://docs.spring.io/spring/docs/5.1.0.RELEASE/spring-framework-reference/core.html#beans-factory-scopes. Reading between the lines, a <code>singleton</code> or <code>application</code> scoped bean, say, would be effectively valid because by the time it <em>ceases</em> to be valid the application is no longer alive. Since <code>singleton</code> is the default scope, the declaration above becomes implicitly valid.</p>

<p>Even with the appropriate scoping, suppose you introduce an alternative, profile-specific declaration</p>

```@Bean("foo")
@Profile("!test")
public Foo realFoo() {
    return this.foo;
}

@Bean("foo")
@Profile("test")
public Foo testFoo() {
    return new TestFoo();
}
```

Will this.foo now always be instantiated, even when activating the test profile? If so, does Spring still manage realFoo()'s value even though that bean is supposed to be inactive?

This question is not a duplicate of Spring @Bean at method returning already created bean, which begs the question, but that question may correctly identify the answer.

答:
You will lose benefits of what Spring IoC have to offer if you store it in the field and may even lead to unexpected behavior with certains scopes.

This will work if scope is singleton or application as it will only invoke foo() only once. But if the scope is changed to protoptype (creating a new instance everytime). Then it could cause unexpected behavior. Because you store foo in a field, so it will still behave as singleton, because it always points to the same instance.

If you initiate classes in your constructor it will always initiate, even if the profile is not active. Spring can not (and shouldn't) detect where instances are initiated. Spring IoC will not invoke the method if the profile isn't active. Along with the explanation above it will be safer to initiate instances in the method itself.

Body:
The following Spring bean declaration appears to run and behave "as expected":

@Configuration
public class AppConfig {

    private final Foo foo;

    public AppConfig() {
        foo = new Foo();
    }

    @Bean
    public Foo foo() {
        return foo;
    }
}

where "as expected" means "nothing is obviously wrong".

Supposing that Foo has some complex lifecycle (e.g. manages external resources with AutoCloseable), is that a valid and sensible declaration of foo()? All of the examples I can find, official and not, indicate that the foo instance should be instantiated inside foo(), not stored in and retrieved from a field. However, I can find no definitive information in any documentation that this should or should not be safe.

The most relevant documentation I can find is about the Spring IoC bean lifecycle, for instance https://docs.spring.io/spring/docs/5.1.0.RELEASE/spring-framework-reference/core.html#beans-factory-scopes. Reading between the lines, a singleton or application scoped bean, say, would be effectively valid because by the time it ceases to be valid the application is no longer alive. Since singleton is the default scope, the declaration above becomes implicitly valid.

Even with the appropriate scoping, suppose you introduce an alternative, profile-specific declaration

@Bean("foo")
@Profile("!test")
public Foo realFoo() {
    return this.foo;
}

@Bean("foo")
@Profile("test")
public Foo testFoo() {
    return new TestFoo();
}

Will this.foo now always be instantiated, even when activating the test profile? If so, does Spring still manage realFoo()'s value even though that bean is supposed to be inactive?

This question is not a duplicate of Spring @Bean at method returning already created bean, which begs the question, but that question may correctly identify the answer.


问:
is it possible to tile each row diffrent times by the given vector
With tensorflow, I have this tensors of rows like

```<code>[
   [0, 1, 2],
   [1, 2, 3],
   [4, 5, 6]
]
</code>```

and I have a list by which I want repeat above rows,

```<code>[ 3, 2, 1 ]
</code>```

As a result, I want

```<code>[
   [0, 1, 2],
   [0, 1, 2],
   [0, 1, 2],
   [1, 2, 3],
   [1, 2, 3],
   [4, 5, 6]
]
</code>```

which means
I want [0, 1, 2] three times,
[1, 2, 3] twice,
[4, 5, 6] just once by following the [3, 2, 1] (which is my second argument.)

This is not a problem, if it is handled as a procedure.

But I have no clue with tensorflow ops.

Suggested 'duplicated' question has a point.
The answer's idea was inspiring as well.
But I think there exist some needs to generalize the case and merge and carve the scattered solutions into one.
Let me add some solutions I have found.

答:
This is a good answer.

Tensorflow numpy repeat

I found another clue from tensorflow contrib tree

https://github.com/tensorflow/tensorflow/blob/59ecde3ecfc83aeb8ec0682e4e39bf0a234bbef8/tensorflow/contrib/training/python/training/resample.py#L32

which repeat a list of range([0,...,n]) of scalars to its own times.
0 to 0 times
1 to 1 times
2 to 2 times
...
n to n times

which looks too limited to use with itself.

But the while_loop of control_flow_ops looks very helpful.

```<code>with ops.name_scope(name, 'repeat_range', [counts]) as scope:
    counts = ops.convert_to_tensor(counts, name='counts')

    def cond(unused_output, i):
      return i < size

    def body(output, i):
      value = array_ops.fill(counts[i:i+1], i)
      return (output.write(i, value), i + 1)

    size = array_ops.shape(counts)[0]
    init_output_array = tensor_array_ops.TensorArray(
        dtype=dtypes.int32, size=size, infer_shape=False)
    output_array, num_writes = control_flow_ops.while_loop(
        cond, body, loop_vars=[init_output_array, 0])

    return control_flow_ops.cond(
        num_writes > 0,
        output_array.concat,
        lambda: array_ops.zeros(shape=[0], dtype=dtypes.int32),
        name=scope)
</code>```

So I exchange array_ops.fill in the body with

```<code>   tile_repeats = tf.concat([[counts[i]], tf.ones([tf.rank(rows) - 1],
          dtype=tf.int32)], axis=0)
   value = tf.tile(tf.expand_dims(rows[i], 0), tile_repeats)
</code>```

And it workd.

Body:
With tensorflow, I have this tensors of rows like

[
   [0, 1, 2],
   [1, 2, 3],
   [4, 5, 6]
]

and I have a list by which I want repeat above rows,

[ 3, 2, 1 ]

As a result, I want

[
   [0, 1, 2],
   [0, 1, 2],
   [0, 1, 2],
   [1, 2, 3],
   [1, 2, 3],
   [4, 5, 6]
]

which means
I want [0, 1, 2] three times,
[1, 2, 3] twice,
[4, 5, 6] just once by following the [3, 2, 1] (which is my second argument.)

This is not a problem, if it is handled as a procedure.

But I have no clue with tensorflow ops.

Suggested 'duplicated' question has a point.
The answer's idea was inspiring as well.
But I think there exist some needs to generalize the case and merge and carve the scattered solutions into one.
Let me add some solutions I have found.

Body:
This is a good answer.

Tensorflow numpy repeat

I found another clue from tensorflow contrib tree

https://github.com/tensorflow/tensorflow/blob/59ecde3ecfc83aeb8ec0682e4e39bf0a234bbef8/tensorflow/contrib/training/python/training/resample.py#L32

which repeat a list of range([0,...,n]) of scalars to its own times.
0 to 0 times
1 to 1 times
2 to 2 times
...
n to n times

which looks too limited to use with itself.

But the while_loop of control_flow_ops looks very helpful.

with ops.name_scope(name, 'repeat_range', [counts]) as scope:
    counts = ops.convert_to_tensor(counts, name='counts')

    def cond(unused_output, i):
      return i < size

    def body(output, i):
      value = array_ops.fill(counts[i:i+1], i)
      return (output.write(i, value), i + 1)

    size = array_ops.shape(counts)[0]
    init_output_array = tensor_array_ops.TensorArray(
        dtype=dtypes.int32, size=size, infer_shape=False)
    output_array, num_writes = control_flow_ops.while_loop(
        cond, body, loop_vars=[init_output_array, 0])

    return control_flow_ops.cond(
        num_writes > 0,
        output_array.concat,
        lambda: array_ops.zeros(shape=[0], dtype=dtypes.int32),
        name=scope)

So I exchange array_ops.fill in the body with

   tile_repeats = tf.concat([[counts[i]], tf.ones([tf.rank(rows) - 1],
          dtype=tf.int32)], axis=0)
   value = tf.tile(tf.expand_dims(rows[i], 0), tile_repeats)

And it workd.


问:
Laravel keeps reloading and nothing comes up
After I type php artisan serve in my terminal, laravel development server start : http://127.0.0.1:8000

But when I do reload in my browser, it keeps loading and doesn't show any error

And again this happens to all my project I have.

I don't know what's going on

答: I had the same problem and I solved it with php artisan config:cache and then restart your server with php artisan serve


问:
Python not creating csv file after parsing - using selenium and beautifulsoup
My code works in two parts

Opens browser with selenium and adds in the details to get results from a page

Parse the html of the results page and write that to a csv file.

Problem
The second part works only if I download the page and manually add the local url (on my computer). If I add the first part of the code, selenium opens the browser but no csv file is exported.

Things I've used to write this -
Ubuntu Mate 18.04
Pycharm editor
Firefox Browser

I have printed every level of the code and got the right output. However, output stops after the for loop.

```<code>from bs4 import BeautifulSoup as soup
from urllib.request import urlopen as uReq
import pandas as pd
import csv
import os
from selenium import webdriver
from selenium.webdriver.common.keys import Keys

os.environ["PATH"] += os.pathsep + r'/home/pierre/PycharmProjects/scraping/venv'
browser = webdriver.Firefox()
browser.get('http://karresults.nic.in/indexPUC_2019.asp')

reg = browser.find_element_by_id('reg')
reg.send_keys('738286')

sub = browser.find_element_by_class_name('btn-default')

sub.click()

url = browser.current_url

my_url = url

uClient = uReq(my_url)
page_html = uClient.read()
uClient.close()
page_soup = soup(page_html, "html.parser")

results = []

for record in page_soup.findAll('tr'):
    for data in record.findAll('td'):
        results = results + [data.text.replace(u'\xa0', u'').strip()]

        print(results)

        with open('myfile.csv', 'w') as f:
            for item in results:
                f.write(item + ',')

</code>```

No errors on Pycharm console

答:
There is no need to re-request for updated URL, you have to wait for a couple of seconds using a time module.

```<code>from bs4 import BeautifulSoup
from selenium import webdriver
import time

os.environ["PATH"] += os.pathsep + r'/home/pierre/PycharmProjects/scraping/venv'
browser = webdriver.Firefox()
browser.get('http://karresults.nic.in/indexPUC_2019.asp')

reg = browser.find_element_by_id('reg')
reg.send_keys('738286')

sub = browser.find_element_by_class_name('btn-default')

sub.click()

time.sleep(3)

soup = BeautifulSoup(browser.page_source, 'lxml')
results = []
for record in soup.find_all('tr'):
    for data in record.find_all('td'):
        results = results + [data.text.replace(u'\xa0', u'').strip()]
        with open('myfile.csv', 'w') as f:
            for item in results:
                f.write(item + ',')
</code>```

csv file O/P:

```<code>Name,ANIKET ANIL BALEKUNDRI,Reg. No.,738286,ENGLISH,76,,76P,HINDI,76,,76P,Part A - TOTAL,152,PHYSICS,44,30,74P,CHEMISTRY,46,30,76P,MATHEMATICS,73,,73P,BIOLOGY,55,29,84P,Part B - TOTAL,307,GRAND TOTAL MARKS,459,FINAL RESULT,First Class,
</code>```

Body:
My code works in two parts

Opens browser with selenium and adds in the details to get results from a page

Parse the html of the results page and write that to a csv file.

Problem
The second part works only if I download the page and manually add the local url (on my computer). If I add the first part of the code, selenium opens the browser but no csv file is exported.

Things I've used to write this -
Ubuntu Mate 18.04
Pycharm editor
Firefox Browser

I have printed every level of the code and got the right output. However, output stops after the for loop.

from bs4 import BeautifulSoup as soup
from urllib.request import urlopen as uReq
import pandas as pd
import csv
import os
from selenium import webdriver
from selenium.webdriver.common.keys import Keys

os.environ["PATH"] += os.pathsep + r'/home/pierre/PycharmProjects/scraping/venv'
browser = webdriver.Firefox()
browser.get('http://karresults.nic.in/indexPUC_2019.asp')

reg = browser.find_element_by_id('reg')
reg.send_keys('738286')

sub = browser.find_element_by_class_name('btn-default')

sub.click()

url = browser.current_url

my_url = url

uClient = uReq(my_url)
page_html = uClient.read()
uClient.close()
page_soup = soup(page_html, "html.parser")

results = []

for record in page_soup.findAll('tr'):
    for data in record.findAll('td'):
        results = results + [data.text.replace(u'\xa0', u'').strip()]

        print(results)

        with open('myfile.csv', 'w') as f:
            for item in results:
                f.write(item + ',')

No errors on Pycharm console

Body:
There is no need to re-request for updated URL, you have to wait for a couple of seconds using a time module.

from bs4 import BeautifulSoup
from selenium import webdriver
import time

os.environ["PATH"] += os.pathsep + r'/home/pierre/PycharmProjects/scraping/venv'
browser = webdriver.Firefox()
browser.get('http://karresults.nic.in/indexPUC_2019.asp')

reg = browser.find_element_by_id('reg')
reg.send_keys('738286')

sub = browser.find_element_by_class_name('btn-default')

sub.click()

time.sleep(3)

soup = BeautifulSoup(browser.page_source, 'lxml')
results = []
for record in soup.find_all('tr'):
    for data in record.find_all('td'):
        results = results + [data.text.replace(u'\xa0', u'').strip()]
        with open('myfile.csv', 'w') as f:
            for item in results:
                f.write(item + ',')

csv file O/P:

Name,ANIKET ANIL BALEKUNDRI,Reg. No.,738286,ENGLISH,76,,76P,HINDI,76,,76P,Part A - TOTAL,152,PHYSICS,44,30,74P,CHEMISTRY,46,30,76P,MATHEMATICS,73,,73P,BIOLOGY,55,29,84P,Part B - TOTAL,307,GRAND TOTAL MARKS,459,FINAL RESULT,First Class,


问:
Android response from script problem
I am using HttpClient using POST method to send a string to a script. The script works fine, it just checks to see whether the table exists in a db. If the table exists "1" is echo'd back.

In the following code everything works fine

```<code>HttpClient client = new DefaultHttpClient();
                    HttpPost post = new HttpPost("//remote//script.php");

                    List<NameValuePair> pairs = new ArrayList<NameValuePair>();
                    pairs.add(new BasicNameValuePair("tblname", concatenated));
                    try
                    {
                        post.setEntity(new UrlEncodedFormEntity(pairs));
                    }
                    catch (UnsupportedEncodingException e)
                    {
                        e.printStackTrace();
                    }
                    try
                    {
                        HttpResponse response = client.execute(post);
                        entity = response.getEntity();
                        res = EntityUtils.toString(entity); //this is now the echo back from the script, "1" means tbl already exists exists

                    }
                    catch (ClientProtocolException e)
                    {
                        e.printStackTrace();
                    }
                    catch (IOException e)
                    {
                        e.printStackTrace();
                    }

                    Toast msg1 = Toast.makeText(main.this, res, Toast.LENGTH_LONG);
                    msg1.setGravity(Gravity.CENTER, msg1.getXOffset() / 2, msg1.getYOffset() / 2);
                    msg1.show();
                    SavePreferences("prefs", concatenated);
                    //fire the authed intent
                    startauthedactivity();
                    }
</code>```

If the table supplied to the script exists 1 is displayed in the toast at the end, if it doesnt exists then the toast is empty, this is correct behavior.

When I apply an -if- to the response it always calls the true condition , even if the table exists. In the following code if the table exists then res should = 1 and the condition is not true so the else block should fire but it never does. However, weirdly, if i pass a table which exists to the script then the toast does actually display a 1...

```<code>if(res != "1")
                {

                Toast msg1 = Toast.makeText(main.this, res, Toast.LENGTH_LONG);
                msg1.setGravity(Gravity.CENTER, msg1.getXOffset() / 2, msg1.getYOffset() / 2);
                msg1.show();
                SavePreferences("prefs", concatenated);
                //fire the authed intent
                startauthedactivity();
                }
                else
                {
                    //do nothing
                }
</code>```

答:
change

```<code>if(res != "1")
</code>```

to

```<code>if(res.equals("1"))
</code>```

Why?

== compares the reference of the object (it's position in the memory). equals compares the contents of the string.

Title: Android response from script problem

Body:
I am using HttpClient using POST method to send a string to a script. The script works fine, it just checks to see whether the table exists in a db. If the table exists "1" is echo'd back.

In the following code everything works fine

HttpClient client = new DefaultHttpClient();
                    HttpPost post = new HttpPost("//remote//script.php");

                    List<NameValuePair> pairs = new ArrayList<NameValuePair>();
                    pairs.add(new BasicNameValuePair("tblname", concatenated));
                    try
                    {
                        post.setEntity(new UrlEncodedFormEntity(pairs));
                    }
                    catch (UnsupportedEncodingException e)
                    {
                        e.printStackTrace();
                    }
                    try
                    {
                        HttpResponse response = client.execute(post);
                        entity = response.getEntity();
                        res = EntityUtils.toString(entity); //this is now the echo back from the script, "1" means tbl already exists exists

                    }
                    catch (ClientProtocolException e)
                    {
                        e.printStackTrace();
                    }
                    catch (IOException e)
                    {
                        e.printStackTrace();
                    }

                    Toast msg1 = Toast.makeText(main.this, res, Toast.LENGTH_LONG);
                    msg1.setGravity(Gravity.CENTER, msg1.getXOffset() / 2, msg1.getYOffset() / 2);
                    msg1.show();
                    SavePreferences("prefs", concatenated);
                    //fire the authed intent
                    startauthedactivity();
                    }

If the table supplied to the script exists 1 is displayed in the toast at the end, if it doesnt exists then the toast is empty, this is correct behavior.

When I apply an -if- to the response it always calls the true condition , even if the table exists. In the following code if the table exists then res should = 1 and the condition is not true so the else block should fire but it never does. However, weirdly, if i pass a table which exists to the script then the toast does actually display a 1...

if(res != "1")
                {

                Toast msg1 = Toast.makeText(main.this, res, Toast.LENGTH_LONG);
                msg1.setGravity(Gravity.CENTER, msg1.getXOffset() / 2, msg1.getYOffset() / 2);
                msg1.show();
                SavePreferences("prefs", concatenated);
                //fire the authed intent
                startauthedactivity();
                }
                else
                {
                    //do nothing
                }

Body:
change

if(res != "1")

to

if(res.equals("1"))

Why?

== compares the reference of the object (it's position in the memory). equals compares the contents of the string.


问:
Why does the App engine (python3 - standard environment) generate aborted connections when connecting to a cloud sql -2nd Gen Mysql instance?
I'm currently developing a project with python 3.7, Django 2.1, Mysql as database.

I'm deploying it in google cloud app engine standard environment and for the database I'm using a cloud SQL - MySql 2nd gen instance.

The application works well, however when I analyze the logs I see these errors:

"aborted connection - Got an error reading communication packets"

In this case the connection is being closed by my app (django).If I configure my app to have persistent connections and I put wait_timeout (i.e 60) in the config of the cloud sql, the error is:

"aborted connection - Got timeout reading communication packets".

I just determined that it's not a problem with sql cloud, or with the configuration of my application, but that it's an app engine problem. I came to this conclusion in the following way:

if I connect to the sql cloud instance through Mysql workbench, no connection is aborted

Similarly if I run my application on a local server, but connecting to cloud sql (through the cloud_sql_proxy), no error is generated and everything works perfect.

So my conclusion is that it is a problem of how the app engine connects to the cloud sql instance.

Why does this happen? How could it be solved?

答:
I believe this is because requests from App Engine applications to Cloud SQL are subject to the following time and connection limits:

For apps running in the App Engine standard environment, all database requests must finish within the HTTP request timer, around 60 seconds. For apps running in the flexible environment, all database requests must finish within 60 minutes.

Offline requests like cron tasks have a time limit of 10 minutes.

Requests to Cloud SQL have limitations based on the scaling type of the App Engine module and how long an instance can remain in memory (residence).

Each App Engine instance running in a standard environment cannot have more than 60 concurrent connections to a Cloud SQL instance. For applications written in Java 8 or Go 1.8, the limit is 100.

Connection Issues: If you see errors containing "Aborted connection nnnn to db:", it usually indicates that your application is not terminating connections properly. It could also be caused by network issues. This error does not mean that there are problems with your Cloud SQL instance.


问:
Why is iOS Safari (and iOS Chrome) displaying background-image's differently to every other browser?
I am in the middle of putting together a really basic site, where the header has an image that is "fixed" (CSS) for a "paralax"-ish effect.
However, on iOS devices, this background image renders out strangely, showing a very zoomed in version of the image when compared to literally every other browser/mobile device.

I have tried playing with all of the background-* properties, but I can't get any of them to work correctly for the life of me! I don't know if there's a -webkit-background-*I should be looking for, but in theory my implementation is fairly simple/standard!

Styles:

#header {
    padding: 3em 0;
    text-align: center;
    width: calc(100% + 10em);
    margin: 0 -5em;
    height: 500px;
    position: relative;
    z-index: 2;
    overflow: hidden;
}

#header .content {
    position: relative;
    top: 50%;
    -webkit-transform: translateY(-50%);
    transform: translateY(-50%);
    z-index: 2;
}

#header .content .logo {
    display: block;
    margin: 0 auto 1.5em;
    max-width: 75px;
    z-index: 2;
    position: relative;
}

#header p {
    font-size: 1.25em;
    letter-spacing: -.025em;
    margin: 0 0 2em;
    position: relative;
    z-index: 2;
}

#header:after {
    content: "";
    background-image: url(/static/media/16fcfe6…/will-stocks-profile.322ff34c.jpeg);
    opacity: .35;
    top: 0;
    left: 0;
    bottom: 0;
    right: 0;
    position: absolute;
    z-index: 0;
    background-attachment: fixed;
    background-position: 100% 33%;
    background-repeat: no-repeat;
    background-size: cover;
    -webkit-filter: blur(3px);
    filter: blur(3px);
}
```

<p>The HTML markup for the element in question:</p>

<pre class="lang-html prettyprint-override"><code><header id="header">
  <div class="content">
    <img src="/assets/images/Logo.png" class="logo" alt="Logo">
    <p>Tech reviewer, IT professional & avid blogger.</p>
  </div>
</header>
</code>```

Visiting the site (currently in a "test status) on any other mobile device/tablet (or even using Chrome DevTools devices) and the image displays exactly as intended. But visit it on an iOS device and you'll see that there's just a small section of the image visible (rotate to landscape and you'll see a little more) - it looks like the image becomes zoomed?

答:
I have now included a media query, which resolve the image sizing issue by using background-attachment: scroll; instead of fixed - however doing this removes the "parallax" effect on mobile devices (which I understand can be considered expensive):

#header:after {
  content: "";
  background-image: url(./../images/will-stocks-profile.jpeg);
  opacity: 0.35;
  top: 0;
  left: 0;
  bottom: 0;
  right: 0;
  position: absolute;
  z-index: 0;
  background-position: 100% 33%;
  background-repeat: no-repeat;
  background-size: cover;
  filter: blur(3px);
}

@media screen and (max-width: 999px) {
  #header:after {
    background-attachment: scroll;
  }
}

@media screen and (min-width: 1000px) {
  #header:after {
    background-attachment: fixed;
  }
}
```

In theory, it should be a simple job to build out a little Javascript snippet to keep an image pinned to the top, however I don't know how this will work with a background-image on an :after pseudo... And surely a JS scroll event listener is going to be more expensive than using CSS?

Body:
I am in the middle of putting together a really basic site, where the header has an image that is "fixed" (CSS) for a "paralax"-ish effect.
However, on iOS devices, this background image renders out strangely, showing a very zoomed in version of the image when compared to literally every other browser/mobile device.

I have tried playing with all of the background-* properties, but I can't get any of them to work correctly for the life of me! I don't know if there's a -webkit-background-*I should be looking for, but in theory my implementation is fairly simple/standard!

Styles:

#header {
    padding: 3em 0;
    text-align: center;
    width: calc(100% + 10em);
    margin: 0 -5em;
    height: 500px;
    position: relative;
    z-index: 2;
    overflow: hidden;
}

#header .content {
    position: relative;
    top: 50%;
    -webkit-transform: translateY(-50%);
    transform: translateY(-50%);
    z-index: 2;
}

#header .content .logo {
    display: block;
    margin: 0 auto 1.5em;
    max-width: 75px;
    z-index: 2;
    position: relative;
}

#header p {
    font-size: 1.25em;
    letter-spacing: -.025em;
    margin: 0 0 2em;
    position: relative;
    z-index: 2;
}

#header:after {
    content: "";
    background-image: url(/static/media/16fcfe6…/will-stocks-profile.322ff34c.jpeg);
    opacity: .35;
    top: 0;
    left: 0;
    bottom: 0;
    right: 0;
    position: absolute;
    z-index: 0;
    background-attachment: fixed;
    background-position: 100% 33%;
    background-repeat: no-repeat;
    background-size: cover;
    -webkit-filter: blur(3px);
    filter: blur(3px);
}

The HTML markup for the element in question:

Tech reviewer, IT professional & avid blogger.

Visiting the site (currently in a "test status) on any other mobile device/tablet (or even using Chrome DevTools devices) and the image displays exactly as intended. But visit it on an iOS device and you'll see that there's just a small section of the image visible (rotate to landscape and you'll see a little more) - it looks like the image becomes zoomed?

Body:
I have now included a media query, which resolve the image sizing issue by using background-attachment: scroll; instead of fixed - however doing this removes the "parallax" effect on mobile devices (which I understand can be considered expensive):

#header:after {
  content: "";
  background-image: url(./../images/will-stocks-profile.jpeg);
  opacity: 0.35;
  top: 0;
  left: 0;
  bottom: 0;
  right: 0;
  position: absolute;
  z-index: 0;
  background-position: 100% 33%;
  background-repeat: no-repeat;
  background-size: cover;
  filter: blur(3px);
}

@media screen and (max-width: 999px) {
  #header:after {
    background-attachment: scroll;
  }
}

@media screen and (min-width: 1000px) {
  #header:after {
    background-attachment: fixed;
  }
}

In theory, it should be a simple job to build out a little Javascript snippet to keep an image pinned to the top, however I don't know how this will work with a background-image on an :after pseudo... And surely a JS scroll event listener is going to be more expensive than using CSS?


答:
In Java you have to use equals() to compare strings

```<code>if("1".equals(res)) {...
</code>```

Note that you should use "1".equals(res) instead of res.equals("1").

If res is null, the first one will work, since equals handles null arguments.
The second will get a NullPointerException because res is null :)

Title: Android response from script problem

Body:
In Java you have to use equals() to compare strings

if("1".equals(res)) {...

Note that you should use "1".equals(res) instead of res.equals("1").

If res is null, the first one will work, since equals handles null arguments.
The second will get a NullPointerException because res is null :)


问:
How to parseInt captured block in regex
I want to increase digit right after '#'.
My function:

let test = `#2*345+#1-#2-3+#1`;
console.log(test.replace(/#([0-9])/g, `#${'$1' + 1}`)); //#21*345+#11-#21-3
console.log(test.replace(/#([0-9])/g, `#${parseInt('$1') + 1}`)); //#NaN*345+#NaN-#NaN-3

//but my expect result is "#3*345+#2-#3-3"```

Hope your help!

答:
The group substitution occurs after the template literal is evaluated. Use a replacer function instead:

let test = `#2*345+#1-#2-3+#1`;
console.log(test.replace(/#([0-9])/g, (_, num) => `#${parseInt(num) + 1}`));```

Title: How to parseInt captured block in regex

Body:
I want to increase digit right after '#'.
My function:

let test = `#2*345+#1-#2-3+#1`;
console.log(test.replace(/#([0-9])/g, `#${'$1' + 1}`)); //#21*345+#11-#21-3
console.log(test.replace(/#([0-9])/g, `#${parseInt('$1') + 1}`)); //#NaN*345+#NaN-#NaN-3

//but my expect result is "#3*345+#2-#3-3"

Hope your help!


问:
How to create customize popup using absolute layout?
Is there a way to use absolute layout as a customize pop-up? I am trying to create a customize popup. Is this possible?</p>

```<code><StackLayout HorizontalOptions="FillAndExpand" VerticalOptions="FillAndExpand" BackgroundColor="Yellow">
    //Elements here
</StackLayout>
<AbsoluteLayout StyleClass="dialogbox" HorizontalOptions="FillAndExpand" VerticalOptions="FillAndExpand">
   //Popup here
</AbsoluteLayout>
</code>```

答:
You can achieve that with AbsoluteLayout and add a fade animation. Here is running GIF.

There is code.

```<code>      <StackLayout>

    <Button
        x:Name="btn"
        Text="click"
        />

    <ContentView x:Name="popupLoginView" BackgroundColor="#C0808080" Padding="10, 0" IsVisible="false" AbsoluteLayout.LayoutBounds="0, 0, 1, 1" AbsoluteLayout.LayoutFlags="All">
        <AbsoluteLayout  VerticalOptions="Center" HorizontalOptions="Center">
            <StackLayout Orientation="Vertical" HeightRequest="200" WidthRequest="300" BackgroundColor="White">
                <Entry Margin="20,20,20,10" Placeholder="Enter Username"></Entry>
                <Entry Margin="20,0,20,0" Placeholder="Enter Password"></Entry>
                <Button Margin="20,0,20,0" Text="Login"></Button>

            </StackLayout>
        </AbsoluteLayout>
    </ContentView>
</StackLayout>
</code>```

In xamarin forms, you can add fade animation to view. There is animation code.

```<code> public partial class MainPage : ContentPage
{
    public MainPage()
    {
        InitializeComponent();
      btn.Clicked += Btn_Clicked;
    }

    private async void Btn_Clicked(object sender, EventArgs e)
    {

        if (popupLoginView.IsVisible==true)
        {
            btn.IsEnabled = false;
              await popupLoginView.FadeTo(0,2000);
            await Task.Delay(2000);
            popupLoginView.Opacity = 0;
            popupLoginView.IsVisible = false;

            btn.IsEnabled = true;
            return;

        }
        if (popupLoginView.IsVisible == false)
        {

            if (popupLoginView.Opacity==1)
            {
                popupLoginView.Opacity = 0;
            }

            popupLoginView.IsVisible = true;
            btn.IsEnabled = false;
            await popupLoginView.FadeTo(1, 2000);
              await Task.Delay(2000);
            btn.IsEnabled = true;
            popupLoginView.Opacity = 1;
            return;

        }

    }
}
</code>```

There is article about fade animation.
https://learn.microsoft.com/en-us/xamarin/xamarin-forms/user-interface/animation/simple#fading

If you want to achieve it with Rg.Plugins.Popup and add the animation, you can refer to this article, it will add some animations.

https://www.c-sharpcorner.com/article/learn-about-xamarin-forms-animation-with-popuppage/

Body:
Is there a way to use absolute layout as a customize pop-up? I am trying to create a customize popup. Is this possible?

<StackLayout HorizontalOptions="FillAndExpand" VerticalOptions="FillAndExpand" BackgroundColor="Yellow">
    //Elements here
</StackLayout>
<AbsoluteLayout StyleClass="dialogbox" HorizontalOptions="FillAndExpand" VerticalOptions="FillAndExpand">
   //Popup here
</AbsoluteLayout>

Body:
You can achieve that with AbsoluteLayout and add a fade animation. Here is running GIF.

There is code.

      <StackLayout>

    <Button
        x:Name="btn"
        Text="click"
        />

    <ContentView x:Name="popupLoginView" BackgroundColor="#C0808080" Padding="10, 0" IsVisible="false" AbsoluteLayout.LayoutBounds="0, 0, 1, 1" AbsoluteLayout.LayoutFlags="All">
        <AbsoluteLayout  VerticalOptions="Center" HorizontalOptions="Center">
            <StackLayout Orientation="Vertical" HeightRequest="200" WidthRequest="300" BackgroundColor="White">
                <Entry Margin="20,20,20,10" Placeholder="Enter Username"></Entry>
                <Entry Margin="20,0,20,0" Placeholder="Enter Password"></Entry>
                <Button Margin="20,0,20,0" Text="Login"></Button>

            </StackLayout>
        </AbsoluteLayout>
    </ContentView>
</StackLayout>

In xamarin forms, you can add fade animation to view. There is animation code.

 public partial class MainPage : ContentPage
{
    public MainPage()
    {
        InitializeComponent();
      btn.Clicked += Btn_Clicked;
    }

    private async void Btn_Clicked(object sender, EventArgs e)
    {

        if (popupLoginView.IsVisible==true)
        {
            btn.IsEnabled = false;
              await popupLoginView.FadeTo(0,2000);
            await Task.Delay(2000);
            popupLoginView.Opacity = 0;
            popupLoginView.IsVisible = false;

            btn.IsEnabled = true;
            return;

        }
        if (popupLoginView.IsVisible == false)
        {

            if (popupLoginView.Opacity==1)
            {
                popupLoginView.Opacity = 0;
            }

            popupLoginView.IsVisible = true;
            btn.IsEnabled = false;
            await popupLoginView.FadeTo(1, 2000);
              await Task.Delay(2000);
            btn.IsEnabled = true;
            popupLoginView.Opacity = 1;
            return;

        }

    }
}

There is article about fade animation.
https://learn.microsoft.com/en-us/xamarin/xamarin-forms/user-interface/animation/simple#fading

If you want to achieve it with Rg.Plugins.Popup and add the animation, you can refer to this article, it will add some animations.

https://www.c-sharpcorner.com/article/learn-about-xamarin-forms-animation-with-popuppage/


问:
Angular: ERROR Error: No component factory found
I have created two components in the same ts file as below. Was referring the example code from https://material.angular.io/components/dialog/examples and it uses the same approach.

```<code>import { Component, OnInit, Inject } from '@angular/core';
import { MatDialogModule, MatDialog, MAT_DIALOG_DATA, MatDialogRef } from '@angular/material/dialog';

@Component({
  selector: 'app-srapi',
  templateUrl: './srapi.component.html',
  styleUrls: ['./srapi.component.scss']
})
export class SrapiComponent {

  constructor(private dialog: MatDialog) { }

  onCreate(): void {
    const dialogRef = this.dialog.open(SrapiTFLFormComponent);
  }
}

@Component({
  selector: 'app-srapi-tfl-form',
  templateUrl: './srapi-tfl-form.html'
})
export class SrapiTFLFormComponent{

  constructor(public dialogRef: MatDialogRef<SrapiTFLFormComponent>) {}
}
</code>```

Also declared and imported both of these in app.module.ts

```<code>import { SrapiComponent, SrapiTFLFormComponent } from './srapi/srapi.component';

@NgModule({
  declarations: [
    AppComponent,
    LoginComponent,
    HeaderComponent,
    FooterComponent,
    RegisterComponent,
    EdcUserFormComponent,
    SidebarComponent,
    EdcMasterDataComponent,
    SrapiComponent,
    SrapiTFLFormComponent
  ],
  imports: [
    BrowserModule,
.
.
</code>```

but it gives an error when it opens the dialog.

ERROR Error: No component factory found for SrapiTFLFormComponent. Did you add it to @NgModule.entryComponents?
          at noComponentFactoryError (core.js:15705)

答:
In app.module.ts add SrapiTFLFormComponent in EntryComponent arrays:

as you using this component to be opened as Dialog then you have to add  it in EntryComponents array:

An entry component is any component that Angular loads imperatively, (which means you’re not referencing it in the template), by type. You specify an entry component by bootstrapping it in an NgModule, or including it in a routing definition

Like:

```<code>entryComponents: [ SrapiTFLFormComponent ]
</code>```

Body:
I have created two components in the same ts file as below. Was referring the example code from https://material.angular.io/components/dialog/examples and it uses the same approach.

import { Component, OnInit, Inject } from '@angular/core';
import { MatDialogModule, MatDialog, MAT_DIALOG_DATA, MatDialogRef } from '@angular/material/dialog';

@Component({
  selector: 'app-srapi',
  templateUrl: './srapi.component.html',
  styleUrls: ['./srapi.component.scss']
})
export class SrapiComponent {

  constructor(private dialog: MatDialog) { }

  onCreate(): void {
    const dialogRef = this.dialog.open(SrapiTFLFormComponent);
  }
}

@Component({
  selector: 'app-srapi-tfl-form',
  templateUrl: './srapi-tfl-form.html'
})
export class SrapiTFLFormComponent{

  constructor(public dialogRef: MatDialogRef<SrapiTFLFormComponent>) {}
}

Also declared and imported both of these in app.module.ts

import { SrapiComponent, SrapiTFLFormComponent } from './srapi/srapi.component';

@NgModule({
  declarations: [
    AppComponent,
    LoginComponent,
    HeaderComponent,
    FooterComponent,
    RegisterComponent,
    EdcUserFormComponent,
    SidebarComponent,
    EdcMasterDataComponent,
    SrapiComponent,
    SrapiTFLFormComponent
  ],
  imports: [
    BrowserModule,
.
.

but it gives an error when it opens the dialog.

ERROR Error: No component factory found for SrapiTFLFormComponent. Did you add it to @NgModule.entryComponents?
          at noComponentFactoryError (core.js:15705)

Body:
In app.module.ts add SrapiTFLFormComponent in EntryComponent arrays:

as you using this component to be opened as Dialog then you have to add  it in EntryComponents array:

An entry component is any component that Angular loads imperatively, (which means you’re not referencing it in the template), by type. You specify an entry component by bootstrapping it in an NgModule, or including it in a routing definition

Like:

entryComponents: [ SrapiTFLFormComponent ]


答:
You can use callback function of replace

let test = `#2*345+#1-#2-3+#1`;

let op = test.replace(/#([0-9])/g, (match,g1)=>`#${parseInt(g1) + 1}`);

console.log(op)```

Title: How to parseInt captured block in regex


问:
How to add values together from a database in windows form application
I'm trying to add all of a students course values together to get the average. The values are saved into a database but when I try add the values together and insert them into a text box it inserts both values into the text box instead of adding the values together.</p>

```<code>            string output = "";
            output += (dr["Course 1"].ToString());
            output += (dr["Course 2"].ToString());
            txtbxaverage.Text = output;

        }
</code>```

答:
As mentioned in the comments, using '+' with strings concatenates them, i.e. "Foo" + "Bar" will give you "FooBar". In your case what you need to do depends on the type that's stored in the dr[] array. If the array stores integers, you can simply add them directly, like so:

```<code>string output = "";
int sum = dr["Course 1"] + dr["Course 2"];
output = sum.ToString();
</code>```

If the array stores floats or doubles it's the same, except you'd have to declare sum as the appropriate type.

If the array stores strings, you need to parse them before doing your sums, like this:

```<code>string output = "";
int sum = 0;
int value1, value2;
int.TryParse(dr["Course 1"], out value1);
int.TryParse(dr["Course 2"], out value2);
sum = value1 + value2;
output = sum.ToString();
</code>```

Body:
I'm trying to add all of a students course values together to get the average. The values are saved into a database but when I try add the values together and insert them into a text box it inserts both values into the text box instead of adding the values together.

            string output = "";
            output += (dr["Course 1"].ToString());
            output += (dr["Course 2"].ToString());
            txtbxaverage.Text = output;

        }

Body:
As mentioned in the comments, using '+' with strings concatenates them, i.e. "Foo" + "Bar" will give you "FooBar". In your case what you need to do depends on the type that's stored in the dr[] array. If the array stores integers, you can simply add them directly, like so:

string output = "";
int sum = dr["Course 1"] + dr["Course 2"];
output = sum.ToString();

If the array stores floats or doubles it's the same, except you'd have to declare sum as the appropriate type.

If the array stores strings, you need to parse them before doing your sums, like this:

string output = "";
int sum = 0;
int value1, value2;
int.TryParse(dr["Course 1"], out value1);
int.TryParse(dr["Course 2"], out value2);
sum = value1 + value2;
output = sum.ToString();


问:
Can I use GetDataRow() on a view if the view's datasource is IQueryable?
I am implementing drag and drop functionality in a form and I'm running into a situation where I need to GetDataRow, but the view has been bound to an IQueryable, as such:

```<code>    private void stackOverFlow()
    {
        Func<int, IQueryable> query = i =>
                                      from p in _data.PERSON
                                      where p.FavoriteNumber == i
                                      select p;

        gc1.DataSource = query(17);

        var row = ((GridView) gc1.DefaultView).GetDataRow(0);
    }
</code>```

The row is always null due to the nature of the binding... Any help would be highly appreciated.

Thanks

答:
This should work:

```<code>gc1.DataSource = query(17).ToList();
</code>```

Check this answer.

Body:
I am implementing drag and drop functionality in a form and I'm running into a situation where I need to GetDataRow, but the view has been bound to an IQueryable, as such:

    private void stackOverFlow()
    {
        Func<int, IQueryable> query = i =>
                                      from p in _data.PERSON
                                      where p.FavoriteNumber == i
                                      select p;

        gc1.DataSource = query(17);

        var row = ((GridView) gc1.DefaultView).GetDataRow(0);
    }

The row is always null due to the nature of the binding... Any help would be highly appreciated.

Thanks

Body:
This should work:

gc1.DataSource = query(17).ToList();

Check this answer.


问:
Serve static html files with gorilla mux
I'm trying to serve different HTML files depending on the route. The router works fine for "/" and it serves the index.html. However when going to any other route like "/download", it also renders the index.html, even tho the file that is to be served is called share.html.

What am I doing wrong here?

```<code>    package main

import (
    "net/http"
    "github.com/gorilla/mux"
    "log"
    "path"
    "fmt"
)

// main func
func main() {
    routes()
}

// routes
func routes() {
    // init router
    r := mux.NewRouter()
    // index route
    r.HandleFunc("/", home)
    r.HandleFunc("/share", share)
    r.HandleFunc("/download", download)

    // start server on port 1337
    log.Fatal(http.ListenAndServe(":1337", r))
}

// serves index file
func home(w http.ResponseWriter, r*http.Request) {
    p := path.Dir("./public/views/index.html")
    // set header
    w.Header().Set("Content-type", "text/html")
    http.ServeFile(w, r, p)
}

// get shared files
func share(w http.ResponseWriter, r *http.Request) {
    switch r.Method {
    case "POST":
        if err := r.ParseForm(); err != nil {
            fmt.Fprint(w, "ParseForm() err: %v", err)
            return
        }
        log.Println(r.FormValue("name"))
        http.Redirect(w, r, "/download", http.StatusMovedPermanently)
    }
}

func download(w http.ResponseWriter, r *http.Request) {
    p := path.Dir("./public/views/share.html")
    // set header
    w.Header().Set("Content-type", "text/html")
    http.ServeFile(w, r, p)
}
</code>```

答:
I believe you might be looking for "PathPrefix"</p>

```<code>func routes() {
    // init router
    r := mux.NewRouter()
    r.PathPrefix("/").Handler(http.FileServer(http.Dir("./public/views/")))
}
</code>```

Body:
I'm trying to serve different HTML files depending on the route. The router works fine for "/" and it serves the index.html. However when going to any other route like "/download", it also renders the index.html, even tho the file that is to be served is called share.html.

What am I doing wrong here?

    package main

import (
    "net/http"
    "github.com/gorilla/mux"
    "log"
    "path"
    "fmt"
)

// main func
func main() {
    routes()
}

// routes
func routes() {
    // init router
    r := mux.NewRouter()
    // index route
    r.HandleFunc("/", home)
    r.HandleFunc("/share", share)
    r.HandleFunc("/download", download)

    // start server on port 1337
    log.Fatal(http.ListenAndServe(":1337", r))
}

// serves index file
func home(w http.ResponseWriter, r*http.Request) {
    p := path.Dir("./public/views/index.html")
    // set header
    w.Header().Set("Content-type", "text/html")
    http.ServeFile(w, r, p)
}

// get shared files
func share(w http.ResponseWriter, r *http.Request) {
    switch r.Method {
    case "POST":
        if err := r.ParseForm(); err != nil {
            fmt.Fprint(w, "ParseForm() err: %v", err)
            return
        }
        log.Println(r.FormValue("name"))
        http.Redirect(w, r, "/download", http.StatusMovedPermanently)
    }
}

func download(w http.ResponseWriter, r *http.Request) {
    p := path.Dir("./public/views/share.html")
    // set header
    w.Header().Set("Content-type", "text/html")
    http.ServeFile(w, r, p)
}

Body:
I believe you might be looking for "PathPrefix"

func routes() {
    // init router
    r := mux.NewRouter()
    r.PathPrefix("/").Handler(http.FileServer(http.Dir("./public/views/")))
}


答:
in your app.module.ts add below code :

```<code>import { SrapiComponent, SrapiTFLFormComponent } from './srapi/srapi.component';

@NgModule({
  declarations: [
    AppComponent,
    LoginComponent,
    HeaderComponent,
    FooterComponent,
    RegisterComponent,
    EdcUserFormComponent,
    SidebarComponent,
    EdcMasterDataComponent,
    SrapiComponent,
    SrapiTFLFormComponent
  ],
  imports: [
    BrowserModule,
.
.
],
entryComponents: [
   SrapiTFLFormComponent
]
</code>```

Title: Angular: ERROR Error: No component factory found

Body:
in your app.module.ts add below code :

import { SrapiComponent, SrapiTFLFormComponent } from './srapi/srapi.component';

@NgModule({
  declarations: [
    AppComponent,
    LoginComponent,
    HeaderComponent,
    FooterComponent,
    RegisterComponent,
    EdcUserFormComponent,
    SidebarComponent,
    EdcMasterDataComponent,
    SrapiComponent,
    SrapiTFLFormComponent
  ],
  imports: [
    BrowserModule,
.
.
],
entryComponents: [
   SrapiTFLFormComponent
]


问:
How to solve 'Permission denied' error in IE/Edge when using ckeditor autocomplete plugin in Angular with ng2-ckeditor
I need to use the autocomplete CKEditor plugin in Angular. I'm using ng2-ckeditor for using CKEditor with Angular, Angular 6 and a custom local distribution of CKEditor 4.10 with the plugins I need (including autocomplete and textMatch).
When the # character is inputed, a list of items should show for the autocomplete.

This is the html fragment for the ckeditor component

<ckeditor #myCKEditor formControlName="ckeditorControl" [config]="ckeditorConfig"
  debounce="500" (ready)="loadAutocomplete($event)">
</ckeditor>
```

<p>And here is the relevant typescript code</p>

<pre class="lang-js prettyprint-override"><code>import { CKEditorComponent } from 'ng2-ckeditor';
[...]
declare var CKEDITOR: any;
[...]
export class PlantillesAddComponent {
  @ViewChild('myCKEditor') myCKEditor: CKEditorComponent;
  model = MODEL; //List of elements that autocomplete should show
  ckeditorConfig = CKEDITORCONFIG ; // {extraPlugins: 'autocomplete,textmatch', [...]}
  [...]
  loadAutocomplete(event) {
    const config = {
      textTestCallback: this.textTestCallback,
      dataCallback: this.dataCallback,
      outputTemplate: '{value}'
    };
    const editor = event.editor;
    try {
      // This doesn't work in IE/EDGE
      new CKEDITOR.plugins.autocomplete(editor, config);
    } catch (e) {
      console.error('ERROR IN IE/EDGE');
      console.error(e); //'Permission denied error'
    }
  }

  textTestCallback = (range) => {
    if (!range.collapsed) {
      return null;
    }
    return CKEDITOR.plugins.textMatch.match(range, this.matchCallback);
  }

  matchCallback = (text, offset) => {
    const left = text.slice(0, offset),
      match = left.match(/#{1}/);
    if (!match) {
      return null;
    }
    return { start: match.index, end: offset };
  }

  dataCallback = (matchInfo, callback) => {
    const data = this.model.filter(function (item) {
      if (item.name.toLowerCase().indexOf(matchInfo.query.substring(1).toLowerCase()) === 0) {
        if (item.value == null) {
          item.value = '${' + item.name + '}';
        }
        return true;
      }
    });
    callback(data);
  }

}
</code>```

In firefox and chrome, when the # is introduced in editor, the list of selectable elements is correctly shown; but in IE and Edge this doesn't work.
Checking the javascript console, it seems the error comes from this line:
new CKEDITOR.plugins.autocomplete(editor, config);, in which a 'Permission denied' error is thrown for both IE and EDGE explorers.

答:
According to it's Readme, it seems that adding the divarea plugin solves many issues with ng2-ckeditor.

For adding this new plugin, I used the CKEditor builder, so I also updated to the last actual version of CKEDitor 4.x (specifically 4.11.4).

Now the autocomplete works in both IE and Edge, but I'm not absolutely sure about if the solution was the version upgrade or the addition of the divarea plugin.

Body:
I need to use the autocomplete CKEditor plugin in Angular. I'm using ng2-ckeditor for using CKEditor with Angular, Angular 6 and a custom local distribution of CKEditor 4.10 with the plugins I need (including autocomplete and textMatch).
When the # character is inputed, a list of items should show for the autocomplete.

This is the html fragment for the ckeditor component

<ckeditor #myCKEditor formControlName="ckeditorControl" [config]="ckeditorConfig"
  debounce="500" (ready)="loadAutocomplete($event)">
</ckeditor>

And here is the relevant typescript code

import { CKEditorComponent } from 'ng2-ckeditor';
[...]
declare var CKEDITOR: any;
[...]
export class PlantillesAddComponent {
  @ViewChild('myCKEditor') myCKEditor: CKEditorComponent;
  model = MODEL; //List of elements that autocomplete should show
  ckeditorConfig = CKEDITORCONFIG ; // {extraPlugins: 'autocomplete,textmatch', [...]}
  [...]
  loadAutocomplete(event) {
    const config = {
      textTestCallback: this.textTestCallback,
      dataCallback: this.dataCallback,
      outputTemplate: '{value}'
    };
    const editor = event.editor;
    try {
      // This doesn't work in IE/EDGE
      new CKEDITOR.plugins.autocomplete(editor, config);
    } catch (e) {
      console.error('ERROR IN IE/EDGE');
      console.error(e); //'Permission denied error'
    }
  }

  textTestCallback = (range) => {
    if (!range.collapsed) {
      return null;
    }
    return CKEDITOR.plugins.textMatch.match(range, this.matchCallback);
  }

  matchCallback = (text, offset) => {
    const left = text.slice(0, offset),
      match = left.match(/#{1}/);
    if (!match) {
      return null;
    }
    return { start: match.index, end: offset };
  }

  dataCallback = (matchInfo, callback) => {
    const data = this.model.filter(function (item) {
      if (item.name.toLowerCase().indexOf(matchInfo.query.substring(1).toLowerCase()) === 0) {
        if (item.value == null) {
          item.value = '${' + item.name + '}';
        }
        return true;
      }
    });
    callback(data);
  }

}

In firefox and chrome, when the # is introduced in editor, the list of selectable elements is correctly shown; but in IE and Edge this doesn't work.
Checking the javascript console, it seems the error comes from this line:
new CKEDITOR.plugins.autocomplete(editor, config);, in which a 'Permission denied' error is thrown for both IE and EDGE explorers.


问:
Upgrade angular CLI to 8
I have encountered the following errors when updating the version of Angular Cli to 8.

```<code>Could not find module "@angular-devkit/build-angular" from "C:\\Users\\AGT\\Desktop\\central8\\client".
Error: Could not find module "@angular-devkit/build-angular" from "C:\\Users\\AGT\\Desktop\\central8\\client".
    at Object.resolve (C:\Users\AGT\AppData\Roaming\npm\node_modules\@angular\cli\node_modules\@angular-devkit\core\node\resolve.js:151:11)
    at WorkspaceNodeModulesArchitectHost.resolveBuilder (C:\Users\AGT\AppData\Roaming\npm\node_modules\@angular\cli\node_modules\@angular-devkit\architect\node\node-modules-architect-host.js:31:40)
    at ServeCommand.initialize (C:\Users\AGT\AppData\Roaming\npm\node_modules\@angular\cli\models\architect-command.js:135:55)
    at process._tickCallback (internal/process/next_tick.js:68:7)
    at Function.Module.runMain (internal/modules/cjs/loader.js:757:11)
    at startup (internal/bootstrap/node.js:283:19)
    at bootstrapNodeJSCore (internal/bootstrap/node.js:622:3)
</code>```

答:
```<code>npm uninstall -g @angular/cli
npm cache verify
npm install -g @angular/cli@latest
</code>```

Then in your Local project package:

```<code>rm -rf node_modules dist
npm install --save-dev @angular/cli@latest
npm i
ng update --all --force
npm install --save-dev @angular-devkit/build-angular
</code>```

Your app has now been upgrade to the latest version

Title: Upgrade angular CLI to 8

Body:
I have encountered the following errors when updating the version of Angular Cli to 8.

Could not find module "@angular-devkit/build-angular" from "C:\\Users\\AGT\\Desktop\\central8\\client".
Error: Could not find module "@angular-devkit/build-angular" from "C:\\Users\\AGT\\Desktop\\central8\\client".
    at Object.resolve (C:\Users\AGT\AppData\Roaming\npm\node_modules\@angular\cli\node_modules\@angular-devkit\core\node\resolve.js:151:11)
    at WorkspaceNodeModulesArchitectHost.resolveBuilder (C:\Users\AGT\AppData\Roaming\npm\node_modules\@angular\cli\node_modules\@angular-devkit\architect\node\node-modules-architect-host.js:31:40)
    at ServeCommand.initialize (C:\Users\AGT\AppData\Roaming\npm\node_modules\@angular\cli\models\architect-command.js:135:55)
    at process._tickCallback (internal/process/next_tick.js:68:7)
    at Function.Module.runMain (internal/modules/cjs/loader.js:757:11)
    at startup (internal/bootstrap/node.js:283:19)
    at bootstrapNodeJSCore (internal/bootstrap/node.js:622:3)

Body:
npm uninstall -g @angular/cli
npm cache verify
npm install -g @angular/cli@latest

Then in your Local project package:

rm -rf node_modules dist
npm install --save-dev @angular/cli@latest
npm i
ng update --all --force
npm install --save-dev @angular-devkit/build-angular

Your app has now been upgrade to the latest version


问:
Save BLOB to doc
I'm trying to save oracle blob to file with extension .doc,
but getting error: Type mismatch on line oFile.Write "blob content"

Tried to change method, but no luck

```<code> BlobToFile
    WriteFromBinary
    WriteFromUnsizedBinary
    WriteFromText
    WriteFromUnsizedText
</code>```

My code:

```<code>Private Sub cmdOpenWord_Click()

 oraFile.Connect = Name & "/" & code
 oraFile.DatabaseName = OraDatabase.DatabaseName
 oraFile.RecordSource = SQL
 oraFile.Refresh
 If oraFile.Recordset.RecordCount > 0 Then
     Dim oFile As Object
     Set oFile = fso.CreateTextFile("C:\vba.doc", True, True)
     oFile.Write oraFile.Recordset(1).Value
     oFile.Close
     Set oFile = Nothing
 Else
     No_object.Visible = True
 End If
 End Sub
</code>```

In watch object is oracleblob type

```<code>Watch :: oraFile.Recordset(1).Value :: Variant/Object/IOraBlob :         frmDelete.cmdOpenWord_Click
</code>```

If I try to rewrite I getting another error, looks like visual basic language not suported in visual basic.

```<code>Sub BlobToFile(ByVal dr As IDataReader, ByVal fieldIndex As Integer, ByVal filename As String)
Const CHUNK_SIZE As Integer = 200
Dim buffer(CHUNK_SIZE - 1) As Byte
Set stream = CreateObject("Scripting.FileSystemObject")
Dim index As Long
index = 0
Try
    Do
        ' Get the next chunk, exit if no more bytes.
        Dim length As Integer
        length = CInt(dr.GetBytes(fieldIndex, index, buffer, 0, CHUNK_SIZE))
        If length = 0 Then Exit Do
        ' Write to file and increment index in field data.
        stream.Write (buffer, 0, length)
        index = index + length
    Loop
Finally
    stream.Close
    End
End Sub
</code>```

Error message: Compile error: User defined type not defined

答:
Try ADODB.Stream

```<code>Dim stm As New ADODB.Stream
With stm
    .Open
    .Type = adTypeBinary
    .Write oraFile.Recordset(1)
    .SaveToFile "D:\vba.doc", adSaveCreateOverWrite
End With
stm.Close
Set stm = Nothing
</code>```

and try to save in another folder or drive sometimes windows does not allowed save on system drive.

Title: Save BLOB to doc

Body:
I'm trying to save oracle blob to file with extension .doc,
but getting error: Type mismatch on line oFile.Write "blob content"

Tried to change method, but no luck

 BlobToFile
    WriteFromBinary
    WriteFromUnsizedBinary
    WriteFromText
    WriteFromUnsizedText

My code:

Private Sub cmdOpenWord_Click()

 oraFile.Connect = Name & "/" & code
 oraFile.DatabaseName = OraDatabase.DatabaseName
 oraFile.RecordSource = SQL
 oraFile.Refresh
 If oraFile.Recordset.RecordCount > 0 Then
     Dim oFile As Object
     Set oFile = fso.CreateTextFile("C:\vba.doc", True, True)
     oFile.Write oraFile.Recordset(1).Value
     oFile.Close
     Set oFile = Nothing
 Else
     No_object.Visible = True
 End If
 End Sub

In watch object is oracleblob type

Watch :: oraFile.Recordset(1).Value :: Variant/Object/IOraBlob :         frmDelete.cmdOpenWord_Click

If I try to rewrite I getting another error, looks like visual basic language not suported in visual basic.

Sub BlobToFile(ByVal dr As IDataReader, ByVal fieldIndex As Integer, ByVal filename As String)
Const CHUNK_SIZE As Integer = 200
Dim buffer(CHUNK_SIZE - 1) As Byte
Set stream = CreateObject("Scripting.FileSystemObject")
Dim index As Long
index = 0
Try
    Do
        ' Get the next chunk, exit if no more bytes.
        Dim length As Integer
        length = CInt(dr.GetBytes(fieldIndex, index, buffer, 0, CHUNK_SIZE))
        If length = 0 Then Exit Do
        ' Write to file and increment index in field data.
        stream.Write (buffer, 0, length)
        index = index + length
    Loop
Finally
    stream.Close
    End
End Sub

Error message: Compile error: User defined type not defined

Body:
Try ADODB.Stream

Dim stm As New ADODB.Stream
With stm
    .Open
    .Type = adTypeBinary
    .Write oraFile.Recordset(1)
    .SaveToFile "D:\vba.doc", adSaveCreateOverWrite
End With
stm.Close
Set stm = Nothing

and try to save in another folder or drive sometimes windows does not allowed save on system drive.


问:
Return statement in for loops within an function in python
I know that my return statement is in wrong place, but can't figure out how to fix it.

Here is my code:

```<code>def show_Number(limit):
   for number in range(limit):
       if number % 2 == 0:
           print(f"{number} even")

       else:
           number % 2 != 0
           print(f"{number} odd")
   return number

</code>```

I expect the output of this function to be:

```<code>0 even
1 odd
2 even
3 odd
4 even
</code>```

but the actual output is:

```<code>0 even
1 odd
2 even
3 odd
4 even
4
</code>```

答:
You do not need a return statement there, also this number % 2 != 0, does nothing in the else block:

```<code>def show_Number(limit):
   for number in range(limit):
       if number % 2 == 0:
           print(f"{number} even")
       else:
           print(f"{number} odd")
</code>```

Body:
I know that my return statement is in wrong place, but can't figure out how to fix it.

Here is my code:

def show_Number(limit):
   for number in range(limit):
       if number % 2 == 0:
           print(f"{number} even")

       else:
           number % 2 != 0
           print(f"{number} odd")
   return number

I expect the output of this function to be:

0 even
1 odd
2 even
3 odd
4 even

but the actual output is:

0 even
1 odd
2 even
3 odd
4 even
4

Body:
You do not need a return statement there, also this number % 2 != 0, does nothing in the else block:

def show_Number(limit):
   for number in range(limit):
       if number % 2 == 0:
           print(f"{number} even")
       else:
           print(f"{number} odd")