问:
Switch columns on a row with dynamic data table using css grid?
I'm looking at building a data table using css grids. The idea would be that it is ready to be fully responsive. Take the following example: https://jsfiddle.net/9L46zfp7/

body {
  margin: 0;
}

.container {
  width: 100%;
}

.cssgrid {
  display: grid;
  grid-template-columns: repeat(5, 1fr);
  grid-auto-flow: dense;
}

.column {
  padding: 10px;
  border-bottom: 1px solid black;
  white-space: nowrap;
  text-overflow: ellipsis;
  overflow: hidden;
}

.column1 {
  grid-column: 1;
  background-color: wheat;
}

.column2 {
  grid-column: 2;
  background-color: palegreen;
}

.column3 {
  grid-column: 3;
  background-color: lemonchiffon;
}

.column4 {
  grid-column: 4;
  background-color: lightcyan;
}

.column5 {
  grid-column: 5;
  background-color: thistle;
}

@media screen and (max-width: 800px) {
  .cssgrid {
    grid-template-columns: repeat(4, 1fr);
  }
  .column1 {
    grid-column: 1;
    grid-row: span 2;
  }
  .column2 {
    grid-column: 2;
    border: 0;
  }
  .column3 {
    grid-column: 3;
    border: 0;
  }
  .column4 {
    grid-column: 2;
    grid-column: span 2;
  }
  .column5 {
    grid-column: 4;
    grid-row: span 2;
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">
  <div class="cssgrid">
    <!-- row -->
    <div class="column column1">0</div>
    <div class="column column2">1</div>
    <div class="column column3">2</div>
    <div class="column column4">3</div>
    <div class="column column5">4</div>
    <!-- row -->
    <div class="column column1">5</div>
    <div class="column column2">6</div>
    <div class="column column3">7</div>
    <div class="column column4">8</div>
    <div class="column column5">9</div>
  </div>
</div></code>```

Here, you'll see that when the screen is less than 800px wide, the table rows will "split up" into two rows. Now, I'd really like to switch the green with the blue columns.

Is this possible using css only, knowing that the data is dynamically generated (so I cannot reference any specific column number, the html should remain unchanged)?

Thanks in advance!

答:
You can drop the grid-column: n definitions from your code and see that it works without it (grid-auto-flow: dense helps you in achieving the layout without holes in it):

body {
  margin: 0;
}

.container {
  width: 100%;
}

.cssgrid {
  display: grid;
  grid-template-columns: 40px repeat(3, 1fr) 40px;
  grid-auto-flow: dense;
}

.column {
  padding: 10px;
  border-bottom: 1px solid black;
  white-space: nowrap;
  text-overflow: ellipsis;
  overflow: hidden;
}

.column1 {
  background-color: wheat;
}

.column2 {
  background-color: palegreen;
}

.column3 {
  background-color: lemonchiffon;
}

.column4 {
  background-color: lightcyan;
}

.column5 {
  background-color: thistle;
}

@media screen and (max-width: 800px) {
  .cssgrid {
    grid-template-columns: 25px repeat(2, 1fr) 25px;
  }
  .column1 {
    grid-row: span 2;
  }
  .column2 {
    border: 0;
  }
  .column3 {
    border: 0;
  }
  .column4 {
    grid-column: span 2;
  }
  .column5 {
    grid-row: span 2;
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">
  <div class="cssgrid">
    <!-- row -->
    <div class="column column1">0</div>
    <div class="column column2">1</div>
    <div class="column column3">2</div>
    <div class="column column4">3</div>
    <div class="column column5">4</div>
    <!-- row -->
    <div class="column column1">5</div>
    <div class="column column2">6</div>
    <div class="column column3">7</div>
    <div class="column column4">8</div>
    <div class="column column5">9</div>
  </div>
</div></code>```

Now for generalizing you can use some nth-child logic for this to work for any number of columns - see demo below:

body {
  margin: 0;
}

.container {
  width: 100%;
}

.cssgrid {
  display: grid;
  grid-template-columns: 40px repeat(3, 1fr) 40px;
  grid-auto-flow: dense;
}

.column {
  padding: 10px;
  border-bottom: 1px solid black;
  white-space: nowrap;
  text-overflow: ellipsis;
  overflow: hidden;
}

@media screen and (max-width: 800px) {
  .cssgrid {
    grid-template-columns: 25px repeat(2, 1fr) 25px;
  }
  .column:nth-child(5n - 4),
  .column:nth-child(5n) {
    grid-row: span 2;
  }
  .column:nth-child(5n - 1) {
    grid-column: span 2;
  }
}

/* presentation styles below */

.column:nth-child(5n - 4) {
  background-color: wheat;
}

.column:nth-child(5n - 3) {
  background-color: palegreen;
}

.column:nth-child(5n - 2) {
  background-color: lemonchiffon;
}

.column:nth-child(5n - 1) {
  background-color: lightcyan;
}

.column:nth-child(5n) {
  background-color: thistle;
}

@media screen and (max-width: 800px) {
  .column:nth-child(5n - 3),
  .column:nth-child(5n - 2) {
    border: 0;
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">
  <div class="cssgrid">
    <!-- row -->
    <div class="column">0</div>
    <div class="column">1</div>
    <div class="column">2</div>
    <div class="column">3</div>
    <div class="column">4</div>
    <!-- row -->
    <div class="column">5</div>
    <div class="column">6</div>
    <div class="column">7</div>
    <div class="column">8</div>
    <div class="column">9</div>
  </div>
</div></code>```

I'd really like to switch the green with the blue columns.

With the current markup you can't really exchange the rows but you can get the colspans right:

body {
  margin: 0;
}

.container {
  width: 100%;
}

.cssgrid {
  display: grid;
  grid-template-columns: 40px repeat(3, 1fr) 40px;
  grid-auto-flow: dense;
}

.column {
  padding: 10px;
  border-bottom: 1px solid black;
  white-space: nowrap;
  text-overflow: ellipsis;
  overflow: hidden;
}

@media screen and (max-width: 800px) {
  .cssgrid {
    grid-template-columns: 25px repeat(2, 1fr) 25px;
  }
  .column:nth-child(5n - 4),
  .column:nth-child(5n) {
    grid-row: span 2;
  }
  .column:nth-child(5n - 3) {
    grid-column: span 2;
  }
  .column:nth-child(5n - 2) {
    grid-column: 3;
  }

  .column:nth-child(5n - 1) {
    grid-column: 2;
  }
}

/* presentation styles below */

.column:nth-child(5n - 4) {
  background-color: wheat;
}

.column:nth-child(5n - 3) {
  background-color: palegreen;
}

.column:nth-child(5n - 2) {
  background-color: lemonchiffon;
}

.column:nth-child(5n - 1) {
  background-color: lightcyan;
}

.column:nth-child(5n) {
  background-color: thistle;
}

@media screen and (max-width: 800px) {
  .column:nth-child(5n - 3){
    border: 0;
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">
  <div class="cssgrid">
    <!-- row -->
    <div class="column">0</div>
    <div class="column">1</div>
    <div class="column">2</div>
    <div class="column">3</div>
    <div class="column">4</div>
    <!-- row -->
    <div class="column">5</div>
    <div class="column">6</div>
    <div class="column">7</div>
    <div class="column">8</div>
    <div class="column">9</div>
  </div>
</div></code>```

You can't switch the row positions unless you explicitly place into rows (which essentially defeats the purpose I guess but you'll have to do with this) - see demo below:

body {
  margin: 0;
}

.container {
  width: 100%;
}

.cssgrid {
  display: grid;
  grid-template-columns: 40px repeat(3, 1fr) 40px;
  grid-auto-flow: dense;
}

.column {
  padding: 10px;
  border-bottom: 1px solid black;
  white-space: nowrap;
  text-overflow: ellipsis;
  overflow: hidden;
}

@media screen and (max-width: 800px) {
  .cssgrid {
    grid-template-columns: 25px repeat(2, 1fr) 25px;
  }
  .column:nth-child(5n - 4),
  .column:nth-child(5n) {
    grid-row: span 2;
  }
  .column:nth-child(5n - 3) {
    grid-column: span 2;
  }
  .column:nth-child(5n - 2) {
    grid-column: 3;
  }

  .column:nth-child(5n - 1) {
    grid-column: 2;
  }
  /* explicitly placing in rows for first group */
  .column:nth-child(2) {
    grid-row: 2;
    grid-column: 2 / span 2;
  }
  /* explicitly placing in rows for second group */
  .column:nth-child(7) {
    grid-row: 4;
    grid-column: 2 / span 2;
  }
  /* and so on */
}

/* presentation styles below */

.column:nth-child(5n - 4) {
  background-color: wheat;
}

.column:nth-child(5n - 3) {
  background-color: palegreen;
}

.column:nth-child(5n - 2) {
  background-color: lemonchiffon;
}

.column:nth-child(5n - 1) {
  background-color: lightcyan;
}

.column:nth-child(5n) {
  background-color: thistle;
}

@media screen and (max-width: 800px) {
  .column:nth-child(5n - 2),
  .column:nth-child(5n - 1) {
    border: 0;
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">
  <div class="cssgrid">
    <!-- row -->
    <div class="column">0</div>
    <div class="column">1</div>
    <div class="column">2</div>
    <div class="column">3</div>
    <div class="column">4</div>
    <!-- row -->
    <div class="column">5</div>
    <div class="column">6</div>
    <div class="column">7</div>
    <div class="column">8</div>
    <div class="column">9</div>
  </div>
</div></code>```

Body:
I'm looking at building a data table using css grids. The idea would be that it is ready to be fully responsive. Take the following example: https://jsfiddle.net/9L46zfp7/

body {
  margin: 0;
}

.container {
  width: 100%;
}

.cssgrid {
  display: grid;
  grid-template-columns: repeat(5, 1fr);
  grid-auto-flow: dense;
}

.column {
  padding: 10px;
  border-bottom: 1px solid black;
  white-space: nowrap;
  text-overflow: ellipsis;
  overflow: hidden;
}

.column1 {
  grid-column: 1;
  background-color: wheat;
}

.column2 {
  grid-column: 2;
  background-color: palegreen;
}

.column3 {
  grid-column: 3;
  background-color: lemonchiffon;
}

.column4 {
  grid-column: 4;
  background-color: lightcyan;
}

.column5 {
  grid-column: 5;
  background-color: thistle;
}

@media screen and (max-width: 800px) {
  .cssgrid {
    grid-template-columns: repeat(4, 1fr);
  }
  .column1 {
    grid-column: 1;
    grid-row: span 2;
  }
  .column2 {
    grid-column: 2;
    border: 0;
  }
  .column3 {
    grid-column: 3;
    border: 0;
  }
  .column4 {
    grid-column: 2;
    grid-column: span 2;
  }
  .column5 {
    grid-column: 4;
    grid-row: span 2;
  }
}

0

1

2

3

4

5

6

7

8

9

Here, you'll see that when the screen is less than 800px wide, the table rows will "split up" into two rows. Now, I'd really like to switch the green with the blue columns.

Is this possible using css only, knowing that the data is dynamically generated (so I cannot reference any specific column number, the html should remain unchanged)?

Thanks in advance!

Body:
You can drop the grid-column: n definitions from your code and see that it works without it (grid-auto-flow: dense helps you in achieving the layout without holes in it):

body {
  margin: 0;
}

.container {
  width: 100%;
}

.cssgrid {
  display: grid;
  grid-template-columns: 40px repeat(3, 1fr) 40px;
  grid-auto-flow: dense;
}

.column {
  padding: 10px;
  border-bottom: 1px solid black;
  white-space: nowrap;
  text-overflow: ellipsis;
  overflow: hidden;
}

.column1 {
  background-color: wheat;
}

.column2 {
  background-color: palegreen;
}

.column3 {
  background-color: lemonchiffon;
}

.column4 {
  background-color: lightcyan;
}

.column5 {
  background-color: thistle;
}

@media screen and (max-width: 800px) {
  .cssgrid {
    grid-template-columns: 25px repeat(2, 1fr) 25px;
  }
  .column1 {
    grid-row: span 2;
  }
  .column2 {
    border: 0;
  }
  .column3 {
    border: 0;
  }
  .column4 {
    grid-column: span 2;
  }
  .column5 {
    grid-row: span 2;
  }
}

<div class="container">
  <div class="cssgrid">
    <!-- row -->
    <div class="column column1">0</div>
    <div class="column column2">1</div>
    <div class="column column3">2</div>
    <div class="column column4">3</div>
    <div class="column column5">4</div>
    <!-- row -->
    <div class="column column1">5</div>
    <div class="column column2">6</div>
    <div class="column column3">7</div>
    <div class="column column4">8</div>
    <div class="column column5">9</div>
  </div>
</div>

Now for generalizing you can use some nth-child logic for this to work for any number of columns - see demo below:

body {
  margin: 0;
}

.container {
  width: 100%;
}

.cssgrid {
  display: grid;
  grid-template-columns: 40px repeat(3, 1fr) 40px;
  grid-auto-flow: dense;
}

.column {
  padding: 10px;
  border-bottom: 1px solid black;
  white-space: nowrap;
  text-overflow: ellipsis;
  overflow: hidden;
}

@media screen and (max-width: 800px) {
  .cssgrid {
    grid-template-columns: 25px repeat(2, 1fr) 25px;
  }
  .column:nth-child(5n - 4),
  .column:nth-child(5n) {
    grid-row: span 2;
  }
  .column:nth-child(5n - 1) {
    grid-column: span 2;
  }
}

/* presentation styles below */

.column:nth-child(5n - 4) {
  background-color: wheat;
}

.column:nth-child(5n - 3) {
  background-color: palegreen;
}

.column:nth-child(5n - 2) {
  background-color: lemonchiffon;
}

.column:nth-child(5n - 1) {
  background-color: lightcyan;
}

.column:nth-child(5n) {
  background-color: thistle;
}

@media screen and (max-width: 800px) {
  .column:nth-child(5n - 3),
  .column:nth-child(5n - 2) {
    border: 0;
  }
}

<div class="container">
  <div class="cssgrid">
    <!-- row -->
    <div class="column">0</div>
    <div class="column">1</div>
    <div class="column">2</div>
    <div class="column">3</div>
    <div class="column">4</div>
    <!-- row -->
    <div class="column">5</div>
    <div class="column">6</div>
    <div class="column">7</div>
    <div class="column">8</div>
    <div class="column">9</div>
  </div>
</div>

I'd really like to switch the green with the blue columns.

With the current markup you can't really exchange the rows but you can get the colspans right:

body {
  margin: 0;
}

.container {
  width: 100%;
}

.cssgrid {
  display: grid;
  grid-template-columns: 40px repeat(3, 1fr) 40px;
  grid-auto-flow: dense;
}

.column {
  padding: 10px;
  border-bottom: 1px solid black;
  white-space: nowrap;
  text-overflow: ellipsis;
  overflow: hidden;
}

@media screen and (max-width: 800px) {
  .cssgrid {
    grid-template-columns: 25px repeat(2, 1fr) 25px;
  }
  .column:nth-child(5n - 4),
  .column:nth-child(5n) {
    grid-row: span 2;
  }
  .column:nth-child(5n - 3) {
    grid-column: span 2;
  }
  .column:nth-child(5n - 2) {
    grid-column: 3;
  }

  .column:nth-child(5n - 1) {
    grid-column: 2;
  }
}

/* presentation styles below */

.column:nth-child(5n - 4) {
  background-color: wheat;
}

.column:nth-child(5n - 3) {
  background-color: palegreen;
}

.column:nth-child(5n - 2) {
  background-color: lemonchiffon;
}

.column:nth-child(5n - 1) {
  background-color: lightcyan;
}

.column:nth-child(5n) {
  background-color: thistle;
}

@media screen and (max-width: 800px) {
  .column:nth-child(5n - 3){
    border: 0;
  }
}

<div class="container">
  <div class="cssgrid">
    <!-- row -->
    <div class="column">0</div>
    <div class="column">1</div>
    <div class="column">2</div>
    <div class="column">3</div>
    <div class="column">4</div>
    <!-- row -->
    <div class="column">5</div>
    <div class="column">6</div>
    <div class="column">7</div>
    <div class="column">8</div>
    <div class="column">9</div>
  </div>
</div>

You can't switch the row positions unless you explicitly place into rows (which essentially defeats the purpose I guess but you'll have to do with this) - see demo below:

body {
  margin: 0;
}

.container {
  width: 100%;
}

.cssgrid {
  display: grid;
  grid-template-columns: 40px repeat(3, 1fr) 40px;
  grid-auto-flow: dense;
}

.column {
  padding: 10px;
  border-bottom: 1px solid black;
  white-space: nowrap;
  text-overflow: ellipsis;
  overflow: hidden;
}

@media screen and (max-width: 800px) {
  .cssgrid {
    grid-template-columns: 25px repeat(2, 1fr) 25px;
  }
  .column:nth-child(5n - 4),
  .column:nth-child(5n) {
    grid-row: span 2;
  }
  .column:nth-child(5n - 3) {
    grid-column: span 2;
  }
  .column:nth-child(5n - 2) {
    grid-column: 3;
  }

  .column:nth-child(5n - 1) {
    grid-column: 2;
  }
  /* explicitly placing in rows for first group */
  .column:nth-child(2) {
    grid-row: 2;
    grid-column: 2 / span 2;
  }
  /* explicitly placing in rows for second group */
  .column:nth-child(7) {
    grid-row: 4;
    grid-column: 2 / span 2;
  }
  /* and so on */
}

/* presentation styles below */

.column:nth-child(5n - 4) {
  background-color: wheat;
}

.column:nth-child(5n - 3) {
  background-color: palegreen;
}

.column:nth-child(5n - 2) {
  background-color: lemonchiffon;
}

.column:nth-child(5n - 1) {
  background-color: lightcyan;
}

.column:nth-child(5n) {
  background-color: thistle;
}

@media screen and (max-width: 800px) {
  .column:nth-child(5n - 2),
  .column:nth-child(5n - 1) {
    border: 0;
  }
}

<div class="container">
  <div class="cssgrid">
    <!-- row -->
    <div class="column">0</div>
    <div class="column">1</div>
    <div class="column">2</div>
    <div class="column">3</div>
    <div class="column">4</div>
    <!-- row -->
    <div class="column">5</div>
    <div class="column">6</div>
    <div class="column">7</div>
    <div class="column">8</div>
    <div class="column">9</div>
  </div>
</div>


来源: stackexchange

问:
ORACLE SQL Range of hours
i have a problem, i have a table with 3 columns

```<code>- date - varchar2   - varchar2 -
| date | start_hour | end_hour |
</code>```

I need to make a validation to not overlap hour ranges.

For example:

```<code>| date  | start_hour | end_hour |
| date1 | 09:00AM    | 09:30AM  |
| date1 | 10:30AM    | 11:30AM  |
| date1 | 01:00PM    | 03:00PM  |
</code>```

Assuming the date is the same for the 3 rows.

What i need is, to no overlap these ranges

I cant insert a ranges like this

 start_hour =  08:00AM and end_hour = 09:20AM, because, a range between 09:00AM and 09:30AM already exist, so, the new range clashes with the range who exist in the table.
I tried so many querys, with not between, the end_hour i insert need to be less than the start_hour from a table.
Anyone have an idea how to do it?

答:
I assume that you have converted your time format to hh24:mi

maybe this could help:

```<code>with tab as(
select 'date1' as dat,  '09:00' as  start_hour, '09:30' as end_hour from dual union all
select 'date1' as dat,  '10:30' as  start_hour, '11:30' as end_hour from dual union all
select 'date1' as dat,  '13:00' as  start_hour, '15:00' as end_hour from dual
)
SELECT COUNT(*)
  FROM   tab
  WHERE  start_hour <= '09:10' --:new_end_hour
  AND    end_hour   >= '07:00' --:new_start_hour
  AND    dat = 'date1'
  ;
</code>```

or you can use between to check it start_hour or  end_hour ist between the values

```<code>with tab as(
select 'date1' as dat,  '09:00' as  start_hour, '09:30' as end_hour from dual union all
select 'date1' as dat,  '10:30' as  start_hour, '11:30' as end_hour from dual union all
select 'date1' as dat,  '13:00' as  start_hour, '15:00' as end_hour from dual
)
SELECT COUNT(*)
  FROM   tab
  WHERE  ('09:00' between start_hour and end_hour
  or    '09:10' between start_hour and end_hour
  )
  AND    dat = 'date1'
  ;
</code>```

db<>fiddle here

ContentLicense: CC BY-SA 4.0

Title: ORACLE SQL Range of hours

Body:
i have a problem, i have a table with 3 columns

- date - varchar2   - varchar2 -
| date | start_hour | end_hour |

I need to make a validation to not overlap hour ranges.

For example:

| date  | start_hour | end_hour |
| date1 | 09:00AM    | 09:30AM  |
| date1 | 10:30AM    | 11:30AM  |
| date1 | 01:00PM    | 03:00PM  |

Assuming the date is the same for the 3 rows.

What i need is, to no overlap these ranges

I cant insert a ranges like this

 start_hour =  08:00AM and end_hour = 09:20AM, because, a range between 09:00AM and 09:30AM already exist, so, the new range clashes with the range who exist in the table.
I tried so many querys, with not between, the end_hour i insert need to be less than the start_hour from a table.
Anyone have an idea how to do it?

Body:
I assume that you have converted your time format to hh24:mi

maybe this could help:

with tab as(
select 'date1' as dat,  '09:00' as  start_hour, '09:30' as end_hour from dual union all
select 'date1' as dat,  '10:30' as  start_hour, '11:30' as end_hour from dual union all
select 'date1' as dat,  '13:00' as  start_hour, '15:00' as end_hour from dual
)
SELECT COUNT(*)
  FROM   tab
  WHERE  start_hour <= '09:10' --:new_end_hour
  AND    end_hour   >= '07:00' --:new_start_hour
  AND    dat = 'date1'
  ;

or you can use between to check it start_hour or  end_hour ist between the values

with tab as(
select 'date1' as dat,  '09:00' as  start_hour, '09:30' as end_hour from dual union all
select 'date1' as dat,  '10:30' as  start_hour, '11:30' as end_hour from dual union all
select 'date1' as dat,  '13:00' as  start_hour, '15:00' as end_hour from dual
)
SELECT COUNT(*)
  FROM   tab
  WHERE  ('09:00' between start_hour and end_hour
  or    '09:10' between start_hour and end_hour
  )
  AND    dat = 'date1'
  ;

db<>fiddle here


问:
How to conditionally append a data frame row to one above
I have a data frame that looks like this

```<code>   ID       Date  Period Account                      Amount1 Amount2
  <chr>    <chr> <chr>  <chr>                        <chr> <chr>
1 76311099 43494 /1     P / ABC / 123456             NA    3116362
2 NA       NA    NA     C100ST                       NA    NA
3 66112599 37135 /26    S / ADR                      NA    1246880.3900000001
4 NA       NA    NA     65101599 / S0                NA    NA
5 45461599 37155 /O6    B / INR / REVERSE            NA    623440.19000000006
6 NA       NA    NA     UNDO / S0                    NA    NA
7 69876599 37134 /O3    N / ABC                   401.63   NA
8 19991099 37122 /O5    P / PDA / ASK 4265        401.65   NA
9 NA       NA    NA     AT045BT                      NA    NA
</code>```

I've been struggling to get this done but nothing I tried has worked. Basically what I want to do is if the ID value of a row is NA, I want to append the text in the Account column to the row above and then remove it.

I'm expecting the end result to look something like this:

```<code>   ID      Date  Period Account                      Amount1 Amount2
  <chr>    <chr> <chr>  <chr>                        <chr> <chr>
1 76311099 43494 /1     P / ABC / 123456 / C100ST     NA    3116362
2 66112599 37135 /26    S / ADR / 65101599 / S0       NA    1246880.3900000001
3 45461599 37155 /O6    B / INR / REVERSE / UNDO / S0 NA    623440.19000000006
4 69876599 37134 /O3    N / ABC                       401.63   NA
5 19991099 37122 /O5    P / PDA / ASK 4265 / AT045BT  401.65   NA
</code>```

As you can see, the Row with ID value 69876599 remains the same as there was no other row immediately below it with a NA value for ID.

Does anyone know a way to deal with this?

答:
For a base-R solution...

Let d = your data frame,

```<code>i <- which(is.na(d[,1]))
d[i-1,"Account"] <- paste(d[i-1,"Account"],d[i,"Account"])
d <- d[-i,]
</code>```

Body:
I have a data frame that looks like this

   ID       Date  Period Account                      Amount1 Amount2
  <chr>    <chr> <chr>  <chr>                        <chr> <chr>
1 76311099 43494 /1     P / ABC / 123456             NA    3116362
2 NA       NA    NA     C100ST                       NA    NA
3 66112599 37135 /26    S / ADR                      NA    1246880.3900000001
4 NA       NA    NA     65101599 / S0                NA    NA
5 45461599 37155 /O6    B / INR / REVERSE            NA    623440.19000000006
6 NA       NA    NA     UNDO / S0                    NA    NA
7 69876599 37134 /O3    N / ABC                   401.63   NA
8 19991099 37122 /O5    P / PDA / ASK 4265        401.65   NA
9 NA       NA    NA     AT045BT                      NA    NA

I've been struggling to get this done but nothing I tried has worked. Basically what I want to do is if the ID value of a row is NA, I want to append the text in the Account column to the row above and then remove it.

I'm expecting the end result to look something like this:

   ID      Date  Period Account                      Amount1 Amount2
  <chr>    <chr> <chr>  <chr>                        <chr> <chr>
1 76311099 43494 /1     P / ABC / 123456 / C100ST     NA    3116362
2 66112599 37135 /26    S / ADR / 65101599 / S0       NA    1246880.3900000001
3 45461599 37155 /O6    B / INR / REVERSE / UNDO / S0 NA    623440.19000000006
4 69876599 37134 /O3    N / ABC                       401.63   NA
5 19991099 37122 /O5    P / PDA / ASK 4265 / AT045BT  401.65   NA

As you can see, the Row with ID value 69876599 remains the same as there was no other row immediately below it with a NA value for ID.

Does anyone know a way to deal with this?

Body:
For a base-R solution...

Let d = your data frame,

i <- which(is.na(d[,1]))
d[i-1,"Account"] <- paste(d[i-1,"Account"],d[i,"Account"])
d <- d[-i,]


问:
How to fix a view from going off of a page when it is constrained to a card view
I have recently converted over an android project into androidx and I am having issues with trying to stop views going off of the page. My layout is as follows, a Constraint Layout that contains a Card View and a Text View. Within this Card View I have a Constraint Layout that contains the Text View. Outside of the Card View I have a Button which is constrained to the Card View.

The issue with this is that when I run the program the Card View goes off of the screen and the button moves all the way to the top even though they are all constrained properly.

I will show below the code I am using to achieve this and an image of my result on the emulator.

Here is the layout in the editor [1]: https://imgur.com/a/0FLa1IK

Here is the layout shown on the Emulator [2]: https://imgur.com/a/SsvKiOG

Any help would be greatly appreciated.

```<code><androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <androidx.cardview.widget.CardView
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:layout_marginStart="8dp"
        android:layout_marginTop="8dp"
        android:layout_marginBottom="8dp"
        app:layout_constraintBottom_toTopOf="@+id/materialButton"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent">

        <androidx.constraintlayout.widget.ConstraintLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent">

            <TextView
                android:layout_width="0dp"
                android:layout_height="0dp"
                android:layout_marginStart="16dp"
                android:layout_marginTop="16dp"
                android:layout_marginEnd="16dp"
                android:layout_marginBottom="16dp"
                android:text="Text View Test"
                app:layout_constraintBottom_toBottomOf="parent"
                app:layout_constraintEnd_toEndOf="parent"
                app:layout_constraintStart_toStartOf="parent"
                app:layout_constraintTop_toTopOf="parent" />
        </androidx.constraintlayout.widget.ConstraintLayout>

    </androidx.cardview.widget.CardView>

    <Button
        android:id="@+id/materialButton"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginStart="8dp"
        android:layout_marginEnd="8dp"
        android:layout_marginBottom="256dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>

</code>```

答:
Your layout is getting pushed because of this line:

```<code>android:layout_marginBottom="256dp"
</code>```

Different phones got different screen size, in your layout you are using fixed size on your view ("256dp") and it makes your layout non-responsive.

So what may look good on your preview may not look the same on a real phone.

If you want to place some view anywhere on your screen and keep it responsive I recommend using guidelines, something like this:

```<code><androidx.constraintlayout.widget.ConstraintLayout
  xmlns:android="http://schemas.android.com/apk/res/android"
  xmlns:app="http://schemas.android.com/apk/res-auto"
  android:layout_width="match_parent"
  android:layout_height="match_parent">

<androidx.cardview.widget.CardView
    android:id="@+id/cv_text"
    android:layout_width="0dp"
    android:layout_height="0dp"
    android:layout_margin="8dp"
    android:layout_marginStart="8dp"
    android:layout_marginLeft="8dp"
    android:layout_marginBottom="8dp"
    app:layout_constraintBottom_toTopOf="@+id/materialButton"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toBottomOf="parent"
    app:layout_constraintTop_toTopOf="parent">

    <TextView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:text="Text View Test"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</androidx.cardview.widget.CardView>

<Button
    android:id="@+id/materialButton"
    android:layout_width="0dp"
    android:layout_height="wrap_content"
    android:layout_marginStart="8dp"
    android:layout_marginEnd="8dp"
    android:layout_marginBottom="8dp"
    app:layout_constraintBottom_toTopOf="@+id/guideline13"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent" />

<androidx.constraintlayout.widget.Guideline
    android:id="@+id/guideline13"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:orientation="horizontal"
    app:layout_constraintGuide_percent=".5" />

</androidx.constraintlayout.widget.ConstraintLayout>
</code>```

And it will look like this:

Body:
I have recently converted over an android project into androidx and I am having issues with trying to stop views going off of the page. My layout is as follows, a Constraint Layout that contains a Card View and a Text View. Within this Card View I have a Constraint Layout that contains the Text View. Outside of the Card View I have a Button which is constrained to the Card View.

The issue with this is that when I run the program the Card View goes off of the screen and the button moves all the way to the top even though they are all constrained properly.

I will show below the code I am using to achieve this and an image of my result on the emulator.

Here is the layout in the editor [1]: https://imgur.com/a/0FLa1IK

Here is the layout shown on the Emulator [2]: https://imgur.com/a/SsvKiOG

Any help would be greatly appreciated.

<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <androidx.cardview.widget.CardView
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:layout_marginStart="8dp"
        android:layout_marginTop="8dp"
        android:layout_marginBottom="8dp"
        app:layout_constraintBottom_toTopOf="@+id/materialButton"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent">

        <androidx.constraintlayout.widget.ConstraintLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent">

            <TextView
                android:layout_width="0dp"
                android:layout_height="0dp"
                android:layout_marginStart="16dp"
                android:layout_marginTop="16dp"
                android:layout_marginEnd="16dp"
                android:layout_marginBottom="16dp"
                android:text="Text View Test"
                app:layout_constraintBottom_toBottomOf="parent"
                app:layout_constraintEnd_toEndOf="parent"
                app:layout_constraintStart_toStartOf="parent"
                app:layout_constraintTop_toTopOf="parent" />
        </androidx.constraintlayout.widget.ConstraintLayout>

    </androidx.cardview.widget.CardView>

    <Button
        android:id="@+id/materialButton"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginStart="8dp"
        android:layout_marginEnd="8dp"
        android:layout_marginBottom="256dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>

Body:
Your layout is getting pushed because of this line:

android:layout_marginBottom="256dp"

Different phones got different screen size, in your layout you are using fixed size on your view ("256dp") and it makes your layout non-responsive.

So what may look good on your preview may not look the same on a real phone.

If you want to place some view anywhere on your screen and keep it responsive I recommend using guidelines, something like this:

<androidx.constraintlayout.widget.ConstraintLayout
  xmlns:android="http://schemas.android.com/apk/res/android"
  xmlns:app="http://schemas.android.com/apk/res-auto"
  android:layout_width="match_parent"
  android:layout_height="match_parent">

<androidx.cardview.widget.CardView
    android:id="@+id/cv_text"
    android:layout_width="0dp"
    android:layout_height="0dp"
    android:layout_margin="8dp"
    android:layout_marginStart="8dp"
    android:layout_marginLeft="8dp"
    android:layout_marginBottom="8dp"
    app:layout_constraintBottom_toTopOf="@+id/materialButton"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toBottomOf="parent"
    app:layout_constraintTop_toTopOf="parent">

    <TextView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:text="Text View Test"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</androidx.cardview.widget.CardView>

<Button
    android:id="@+id/materialButton"
    android:layout_width="0dp"
    android:layout_height="wrap_content"
    android:layout_marginStart="8dp"
    android:layout_marginEnd="8dp"
    android:layout_marginBottom="8dp"
    app:layout_constraintBottom_toTopOf="@+id/guideline13"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent" />

<androidx.constraintlayout.widget.Guideline
    android:id="@+id/guideline13"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:orientation="horizontal"
    app:layout_constraintGuide_percent=".5" />

</androidx.constraintlayout.widget.ConstraintLayout>

And it will look like this:


问:
Convert DTS.Variables of type System.Object into a list
I have an SSIS package that executes a SQL task in order to get the names of servers I need to connect to. Then, the results of that query are stored in an variable object called "servers". I then want to run another package on each server at once, so I wanted to split out the "servers" variable. However, when I do this in a C# Script Task, I keep getting the error:

Error: 0x1 at Script Task: Exception has been thrown by the target of an invocation.

Here's the code to split out the servers variable:

Error: 0x1 at Script Task: Exception has been thrown by the target of an invocation.

```<code>public void Main()
{
    var serverlist = (string[])Dts.Variables["User::servers"].Value;

    Dts.Variables["server1"].Value = serverlist[0];
    Dts.TaskResult = (int)ScriptResults.Success;
}

</code>```

It should be a pretty simple code, but for some reason, it just does not work.

答:
Create a new package variable and call it ConnectionStringOle

Add a ForEach Loop

Type: Foreach ADO Enumerator

ADO object source variable: Select the ObjectRs.

Enumerator Mode: Rows in all the tables (ADO.NET dataset only)

In Variable Mappings, map result to the new package variable from step 1

Modify the SQL server Connection Manager to set the ConnectionString property to the ConnectionStringOle value.

From there, do whatever you need to do per loop iteration.

Note: if you are only pulling the server instance's name, then you should create another package variable that parses the instance's name into the entire ConnectionString value. You can get this by copying the existing ConnectionString's value into the variable expression.

Body:
I have an SSIS package that executes a SQL task in order to get the names of servers I need to connect to. Then, the results of that query are stored in an variable object called "servers". I then want to run another package on each server at once, so I wanted to split out the "servers" variable. However, when I do this in a C# Script Task, I keep getting the error:

Error: 0x1 at Script Task: Exception has been thrown by the target of an invocation.

Here's the code to split out the servers variable:

Error: 0x1 at Script Task: Exception has been thrown by the target of an invocation.

public void Main()
{
    var serverlist = (string[])Dts.Variables["User::servers"].Value;

    Dts.Variables["server1"].Value = serverlist[0];
    Dts.TaskResult = (int)ScriptResults.Success;
}

It should be a pretty simple code, but for some reason, it just does not work.


问:
"," separator in read.csv - R
How to define "," as the column separator (sep) in read.csv in R?
I have tried read.csv(file=x,header = FALSE,sep = "",""), which doest work correctly.

答:
sep can only be one character, but you can open your file x e.g. with readLines and exchange your "," separator e.g. with \t by using gsub.

```<code>read.table(text=gsub("\",\"", "\t", readLines("x")))
</code>```

Title: "," separator in read.csv - R

Body:
sep can only be one character, but you can open your file x e.g. with readLines and exchange your "," separator e.g. with \t by using gsub.

read.table(text=gsub("\",\"", "\t", readLines("x")))


问:
Is there a way to Debug why my executable JAR of a JavaFX-Project runs on my Computer but not on others ? (Using jdk 1.8._051)
I exportet a Jar of a JavaFX2 Project. It works fine, but when I run it on another machine there will be a
classDefNotFoundExeption: javafx.application.Application

Any hints how to tackle this Problem ?

This is my Manifest:

```<code>Class-Path: .
Main-Class: proj.view.Launcher

</code>```

I also programmed Launcher that starts a Swing GUI in case JavaFX is not found.

Here is my Launcher Class

public class Launcher {

    public static void main(String[] args) {

        try {

            Class c = javafx.application.Application.class;
            proj.main.App.main(args);

        }catch (NoClassDefFoundError e) {
            String[] t = {"Swing Backup","Application start Error"};
            MainFrame.remote(t);

        }

    }

}

```

答:
The other computers are running on a Java installation that doesn't include JavaFX. It works on your machine because you do have JavaFX installed.

To test if javafx.application.Application is available, you need to use reflection, i.e.

```<code>boolean hasJavaFX;
try {
    Class.forName("javafx.application.Application");
    hasJavaFX = true;
} catch (ClassNotFoundException e) {
    hasJavaFX = false;
}
if (hasJavaFX) {
    MainFrame.remote(new String[] {"Swing Backup","Application start Error"});
} else {
    proj.main.App.main(args);
}
</code>```

Body:
I exportet a Jar of a JavaFX2 Project. It works fine, but when I run it on another machine there will be a
classDefNotFoundExeption: javafx.application.Application

Any hints how to tackle this Problem ?

This is my Manifest:

Class-Path: .
Main-Class: proj.view.Launcher

I also programmed Launcher that starts a Swing GUI in case JavaFX is not found.

Here is my Launcher Class

public class Launcher {

    public static void main(String[] args) {

        try {

            Class c = javafx.application.Application.class;
            proj.main.App.main(args);

        }catch (NoClassDefFoundError e) {
            String[] t = {"Swing Backup","Application start Error"};
            MainFrame.remote(t);

        }

    }

}

Body:
The other computers are running on a Java installation that doesn't include JavaFX. It works on your machine because you do have JavaFX installed.

To test if javafx.application.Application is available, you need to use reflection, i.e.

boolean hasJavaFX;
try {
    Class.forName("javafx.application.Application");
    hasJavaFX = true;
} catch (ClassNotFoundException e) {
    hasJavaFX = false;
}
if (hasJavaFX) {
    MainFrame.remote(new String[] {"Swing Backup","Application start Error"});
} else {
    proj.main.App.main(args);
}


问:
Dart: cancelable post delay / future
I am new to flutter and I want to translate some text from an InputField by calling an API. However I don't want to call it on every key stroke, but instead only when the user paused typing.

On Android I would just use the Handler class with postDelay() with beforehand calling removeAllCallbacksAndMessages(null). Is there a way to do something similar on Dart?

Here is my current code:

```<code>Future<String> getTranslation(String query, Language from, Language to) async {
    // cancel here if a call to this function was less than 500 millis ago.
    return Future.delayed(const Duration(milliseconds: 500), () {
      return _translator.translate(query, from: from.code, to: to.code)
    });
  }
</code>```

Edit 1

I'm calling the code from my Bloc like so:

```<code>@override
  Stream<State> mapEventToState(Event event) async* {
    if (event is QueryChangeEvent) {
      yield TextTranslationChangeState(
          query: event.query ?? "",
          translation: await _repo.getTranslation(event.query, currentState.fromLang, currentState.toLang));
  }
</code>```

This is why I cannot call .then() on the future because I wouldn't be able to yield the new state from the block of the nested function.

Any help is appreciated!

答:
You can achieve cancelling the Future async operation by using CancelableOperation.

Here is an example (p.s I simplified your method signature for me to test it easily)

```<code>  CancelableOperation cancellableOperation;

  Future<dynamic> fromCancelable(Future<dynamic> future) async {
    cancellableOperation?.cancel();
    cancellableOperation = CancelableOperation.fromFuture(future, onCancel: () {
      print('Operation Cancelled');
    });
    return cancellableOperation.value;
  }

  Future<dynamic> getTranslation(String query, String from, String to) async {
    return Future.delayed(const Duration(milliseconds: 1000), () {
      return "Hello";
    });
  }
</code>```

On Text Changed Listener:

```<code>  onTextChanged() {
    fromCancelable(getTranslation("query", "EN", "TR")).then((value) {
      print("Then called: $value");
    });
  }
</code>```

Sample output:

```<code>I/flutter ( 7312): Operation Cancelled
I/flutter ( 7312): Operation Cancelled
I/flutter ( 7312): Operation Cancelled
I/flutter ( 7312): Operation Cancelled
I/flutter ( 7312): Then called: Hello
</code>```

Title: Dart: cancelable post delay / future

Body:
I am new to flutter and I want to translate some text from an InputField by calling an API. However I don't want to call it on every key stroke, but instead only when the user paused typing.

On Android I would just use the Handler class with postDelay() with beforehand calling removeAllCallbacksAndMessages(null). Is there a way to do something similar on Dart?

Here is my current code:

Future<String> getTranslation(String query, Language from, Language to) async {
    // cancel here if a call to this function was less than 500 millis ago.
    return Future.delayed(const Duration(milliseconds: 500), () {
      return _translator.translate(query, from: from.code, to: to.code)
    });
  }

Edit 1

I'm calling the code from my Bloc like so:

@override
  Stream<State> mapEventToState(Event event) async* {
    if (event is QueryChangeEvent) {
      yield TextTranslationChangeState(
          query: event.query ?? "",
          translation: await _repo.getTranslation(event.query, currentState.fromLang, currentState.toLang));
  }

This is why I cannot call .then() on the future because I wouldn't be able to yield the new state from the block of the nested function.

Any help is appreciated!

Body:
You can achieve cancelling the Future async operation by using CancelableOperation.

Here is an example (p.s I simplified your method signature for me to test it easily)

  CancelableOperation cancellableOperation;

  Future<dynamic> fromCancelable(Future<dynamic> future) async {
    cancellableOperation?.cancel();
    cancellableOperation = CancelableOperation.fromFuture(future, onCancel: () {
      print('Operation Cancelled');
    });
    return cancellableOperation.value;
  }

  Future<dynamic> getTranslation(String query, String from, String to) async {
    return Future.delayed(const Duration(milliseconds: 1000), () {
      return "Hello";
    });
  }

On Text Changed Listener:

  onTextChanged() {
    fromCancelable(getTranslation("query", "EN", "TR")).then((value) {
      print("Then called: $value");
    });
  }

Sample output:

I/flutter ( 7312): Operation Cancelled
I/flutter ( 7312): Operation Cancelled
I/flutter ( 7312): Operation Cancelled
I/flutter ( 7312): Operation Cancelled
I/flutter ( 7312): Then called: Hello


问:
Error 400 bad request when creating keycloak roles in Java
I try to create a Keycloak role from my Java program. I am able to create user so it's not a problem of connection to my Keycloak server but the create function for the role always give me an error 400 bad request. What is the solution to create a role from Java?

Keycloak kc = KeycloakBuilder.builder()
            .serverUrl("http://localhost:8080/auth")
            .realm("master")
            .grantType(OAuth2Constants.PASSWORD)
            .username("***")
            .password("***")
            .clientId("admin-cli")
            .resteasyClient(new ResteasyClientBuilder().connectionPoolSize(10).build())
            .build();

RoleRepresentation roleRepresentation = new RoleRepresentation();
roleRepresentation.setName(nomRole);
roleRepresentation.setClientRole(true);
kc.realm("master").roles().create(roleRepresentation);

```

error :
  Exception in thread "main" javax.ws.rs.BadRequestException: HTTP 400 Bad Request
      at org.jboss.resteasy.client.jaxrs.internal.ClientInvocation.handleErrorStatus(ClientInvocation.java:215)
      at org.jboss.resteasy.client.jaxrs.internal.proxy.extractors.DefaultEntityExtractorFactory$3.extractEntity(DefaultEntityExtractorFactory.java:50)
      at org.jboss.resteasy.client.jaxrs.internal.proxy.ClientInvoker.invokeSync(ClientInvoker.java:150)
      at org.jboss.resteasy.client.jaxrs.internal.proxy.ClientInvoker.invoke(ClientInvoker.java:112)
      at org.jboss.resteasy.client.jaxrs.internal.proxy.ClientProxy.invoke(ClientProxy.java:76)
      at com.sun.proxy.$Proxy25.create(Unknown Source)
      at Main.CreateKeycloakRole(Main.java:37)
      at Main.main(Main.java:96)

答: I upgraded to the latest jboss/keycloak image and the same code worked for me</p>

Body:
I try to create a Keycloak role from my Java program. I am able to create user so it's not a problem of connection to my Keycloak server but the create function for the role always give me an error 400 bad request. What is the solution to create a role from Java?

Keycloak kc = KeycloakBuilder.builder()
            .serverUrl("http://localhost:8080/auth")
            .realm("master")
            .grantType(OAuth2Constants.PASSWORD)
            .username("***")
            .password("***")
            .clientId("admin-cli")
            .resteasyClient(new ResteasyClientBuilder().connectionPoolSize(10).build())
            .build();

RoleRepresentation roleRepresentation = new RoleRepresentation();
roleRepresentation.setName(nomRole);
roleRepresentation.setClientRole(true);
kc.realm("master").roles().create(roleRepresentation);

error :
  Exception in thread "main" javax.ws.rs.BadRequestException: HTTP 400 Bad Request
      at org.jboss.resteasy.client.jaxrs.internal.ClientInvocation.handleErrorStatus(ClientInvocation.java:215)
      at org.jboss.resteasy.client.jaxrs.internal.proxy.extractors.DefaultEntityExtractorFactory$3.extractEntity(DefaultEntityExtractorFactory.java:50)
      at org.jboss.resteasy.client.jaxrs.internal.proxy.ClientInvoker.invokeSync(ClientInvoker.java:150)
      at org.jboss.resteasy.client.jaxrs.internal.proxy.ClientInvoker.invoke(ClientInvoker.java:112)
      at org.jboss.resteasy.client.jaxrs.internal.proxy.ClientProxy.invoke(ClientProxy.java:76)
      at com.sun.proxy.$Proxy25.create(Unknown Source)
      at Main.CreateKeycloakRole(Main.java:37)
      at Main.main(Main.java:96)


问:
How to confirm a file doesn't exist as opposed to access denied?
I use Test-Path to check existence and connectivity for a variety of files and folders in my scripts.  If I get a return value of $false, I don't have any way of knowing if the file definitely doesn't exist, or if the user account doesn't have access or connectivity to the path.

How can I check and be certain that a file does not exist, while knowing the command had sufficient access and connectivity?

I was unable to attain this answer from the following posts:

Check if a file exists or not in Windows PowerShell?

A better way to check if a path exists or not in PowerShell

I assembled the suggestion @Matt provided into a function as such:

```<code>function Get-FileType([string]$Path)
{
    try
    {
        get-item -LiteralPath $Path -ErrorAction Stop
        $exists = 'Exists'
    }
    catch [System.UnauthorizedAccessException] {$exists = 'Access Denied'}              #Inaccessible
    catch [System.Management.Automation.ItemNotFoundException]{$exists = 'Not Found'}   #Doesn't Exist
    catch [System.Management.Automation.DriveNotFoundException]{$exists = 'Not Found'}  #Doesn't Exist
    catch {$exists='Unknown'} #Unknown

    return $exists
}

Get-FileType 'C:\test data\myfile.txt'
</code>```

答:
Why not attempt the get the item and examine the error message if it fails.

```<code>$path = "\\sqlskylinevm\path\file.txt"

$file = try{
    Get-Item $path -ErrorAction Stop
} catch [System.UnauthorizedAccessException] {
    "can't get to it"
} catch [System.Management.Automation.ItemNotFoundException]{
    "does not exist"
}

if($file -eq "can't get to it"){
    Write-Warning "File exists but access is denied"
} elseif($file -eq "does not exist"){
    Write-Warning "Could not find file"
} else {
    Write-Host "Oh Happy Days!" -ForegroundColor Green
}
</code>```

$file in this case would contain a string of text with a message or the file/directory itself that you are testing against. You could also do the same thing with Test-Path ... -ErrorAction I guess it really depends what you want to do with the findings.

That code is not ideal but gives you the paths you needs. It differentiates between access denied, does not exist and does exist.

Body:
I use Test-Path to check existence and connectivity for a variety of files and folders in my scripts.  If I get a return value of $false, I don't have any way of knowing if the file definitely doesn't exist, or if the user account doesn't have access or connectivity to the path.

How can I check and be certain that a file does not exist, while knowing the command had sufficient access and connectivity?

I was unable to attain this answer from the following posts:

Check if a file exists or not in Windows PowerShell?

A better way to check if a path exists or not in PowerShell

I assembled the suggestion @Matt provided into a function as such:

function Get-FileType([string]$Path)
{
    try
    {
        get-item -LiteralPath $Path -ErrorAction Stop
        $exists = 'Exists'
    }
    catch [System.UnauthorizedAccessException] {$exists = 'Access Denied'}              #Inaccessible
    catch [System.Management.Automation.ItemNotFoundException]{$exists = 'Not Found'}   #Doesn't Exist
    catch [System.Management.Automation.DriveNotFoundException]{$exists = 'Not Found'}  #Doesn't Exist
    catch {$exists='Unknown'} #Unknown

    return $exists
}

Get-FileType 'C:\test data\myfile.txt'

Body:
Why not attempt the get the item and examine the error message if it fails.

$path = "\\sqlskylinevm\path\file.txt"

$file = try{
    Get-Item $path -ErrorAction Stop
} catch [System.UnauthorizedAccessException] {
    "can't get to it"
} catch [System.Management.Automation.ItemNotFoundException]{
    "does not exist"
}

if($file -eq "can't get to it"){
    Write-Warning "File exists but access is denied"
} elseif($file -eq "does not exist"){
    Write-Warning "Could not find file"
} else {
    Write-Host "Oh Happy Days!" -ForegroundColor Green
}

$file in this case would contain a string of text with a message or the file/directory itself that you are testing against. You could also do the same thing with Test-Path ... -ErrorAction I guess it really depends what you want to do with the findings.

That code is not ideal but gives you the paths you needs. It differentiates between access denied, does not exist and does exist.


问:
Android : How to read file in bytes?
I am trying to get file content in bytes in Android application. I have get the file in SD card now want to get the selected file in bytes. I googled but no such success. Please help

Below is the code to get files with extension. Through this i get files and show in spinner. On file selection I want to get file in bytes.

```<code>private List<String> getListOfFiles(String path) {

   File files = new File(path);

   FileFilter filter = new FileFilter() {

      private final List<String> exts = Arrays.asList("jpeg", "jpg", "png", "bmp", "gif","mp3");

      public boolean accept(File pathname) {
         String ext;
         String path = pathname.getPath();
         ext = path.substring(path.lastIndexOf(".") + 1);
         return exts.contains(ext);
      }
   };

   final File [] filesFound = files.listFiles(filter);
   List<String> list = new ArrayList<String>();
   if (filesFound != null && filesFound.length > 0) {
      for (File file : filesFound) {
         list.add(file.getName());
      }
   }
   return list;
}
</code>```

答:
If you want to use a the openFileInput method from a Context for this, you can use the following code.

This will create a BufferArrayOutputStream and append each byte as it's read from the file to it.

/**
 *

 *     Creates a InputStream for a file using the specified Context
 *     and returns the Bytes read from the file.
 *

 *
 * @param context The context to use.
 * @param file The file to read from.
 * @return The array of bytes read from the file, or null if no file was found.
 */
public static byte[] read(Context context, String file) throws IOException {
    byte[] ret = null;

    if (context != null) {
        try {
            InputStream inputStream = context.openFileInput(file);
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();

            int nextByte = inputStream.read();
            while (nextByte != -1) {
                outputStream.write(nextByte);
                nextByte = inputStream.read();
            }

            ret = outputStream.toByteArray();

        } catch (FileNotFoundException ignored) { }
    }

    return ret;
}
```

ContentLicense: CC BY-SA 3.0

Title: Android : How to read file in bytes?

Body:
I am trying to get file content in bytes in Android application. I have get the file in SD card now want to get the selected file in bytes. I googled but no such success. Please help

Below is the code to get files with extension. Through this i get files and show in spinner. On file selection I want to get file in bytes.

private List<String> getListOfFiles(String path) {

   File files = new File(path);

   FileFilter filter = new FileFilter() {

      private final List<String> exts = Arrays.asList("jpeg", "jpg", "png", "bmp", "gif","mp3");

      public boolean accept(File pathname) {
         String ext;
         String path = pathname.getPath();
         ext = path.substring(path.lastIndexOf(".") + 1);
         return exts.contains(ext);
      }
   };

   final File [] filesFound = files.listFiles(filter);
   List<String> list = new ArrayList<String>();
   if (filesFound != null && filesFound.length > 0) {
      for (File file : filesFound) {
         list.add(file.getName());
      }
   }
   return list;
}

Body:
If you want to use a the openFileInput method from a Context for this, you can use the following code.

This will create a BufferArrayOutputStream and append each byte as it's read from the file to it.

/**
 * <p>
 *     Creates a InputStream for a file using the specified Context
 *     and returns the Bytes read from the file.
 * </p>
 *
 * @param context The context to use.
 * @param file The file to read from.
 * @return The array of bytes read from the file, or null if no file was found.
 */
public static byte[] read(Context context, String file) throws IOException {
    byte[] ret = null;

    if (context != null) {
        try {
            InputStream inputStream = context.openFileInput(file);
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();

            int nextByte = inputStream.read();
            while (nextByte != -1) {
                outputStream.write(nextByte);
                nextByte = inputStream.read();
            }

            ret = outputStream.toByteArray();

        } catch (FileNotFoundException ignored) { }
    }

    return ret;
}


问:
Autoeconders Keras with Variable Inputs
I have a keras code implementing an autoencoder like that:

```<code>ENCODING_DIM = 5

# input placeholder
input_img = tf.keras.layers.Input(shape=(320,))

# this is the encoded representation of the input
encoded = tf.keras.layers.Dense(35, activation='relu')(input_img)
encoded = tf.keras.layers.Dense(20, activation='relu')(encoded)
encoded = tf.keras.layers.Dense(ENCODING_DIM, activation='relu')(encoded)

decoded = tf.keras.layers.Dense(20, activation='relu')(encoded)
decoded = tf.keras.layers.Dense(35, activation='relu')(decoded)
decoded = tf.keras.layers.Dense(320, activation='sigmoid')(decoded)

autoencoder = tf.keras.models.Model(input_img, decoded)

encoder = tf.keras.models.Model(input_img, encoded)
encoded_input = tf.keras.layers.Input(shape=(ENCODING_DIM,))

decoder_layer = autoencoder.layers[-1]
#decoded_input = tf.keras.models.Model(encoded_input,decoder_layer(encoded_input))

autoencoder.compile(optimizer='nadam', loss='binary_crossentropy')
from keras.callbacks import ModelCheckpoint
</code>```

it works perfectly.

Now I would like to have variable input dimensions (e.g. the first vector [320x1], the second [280x1], etc...)

Now I try to do that:

```<code>ENCODING_DIM = 5

# input placeholder
input_img = tf.keras.layers.Input(shape=(None,))

# this is the encoded representation of the input
encoded = tf.keras.layers.Dense(35, activation='relu')(input_img)
encoded = tf.keras.layers.Dense(20, activation='relu')(encoded)
encoded = tf.keras.layers.Dense(ENCODING_DIM, activation='relu')(encoded)

decoded = tf.keras.layers.Dense(20, activation='relu')(encoded)
decoded = tf.keras.layers.Dense(35, activation='relu')(decoded)
decoded = tf.keras.layers.Dense(320, activation='sigmoid')(decoded)

autoencoder = tf.keras.models.Model(input_img, decoded)

encoder = tf.keras.models.Model(input_img, encoded)
encoded_input = tf.keras.layers.Input(shape=(ENCODING_DIM,))

decoder_layer = autoencoder.layers[-1]
#decoded_input = tf.keras.models.Model(encoded_input,decoder_layer(encoded_input))

autoencoder.compile(optimizer='nadam', loss='binary_crossentropy')
from keras.callbacks import ModelCheckpoint
</code>```

but it returns an error like:

```<code>ValueError                                Traceback (most recent call last)
<ipython-input-24-7764c4707491> in <module>()
     14
     15 # this is the encoded representation of the input
---> 16 encoded = tf.keras.layers.Dense(35, activation='relu')(input_img)
     17 encoded = tf.keras.layers.Dense(20, activation='relu')(encoded)
     18 encoded = tf.keras.layers.Dense(ENCODING_DIM, activation='relu')(encoded)

2 frames
/usr/local/lib/python3.6/dist-packages/tensorflow/python/keras/layers/core.py in build(self, input_shape)
    935     input_shape = tensor_shape.TensorShape(input_shape)
    936     if tensor_shape.dimension_value(input_shape[-1]) is None:
--> 937       raise ValueError('The last dimension of the inputs to `Dense` '
    938                        'should be defined. Found `None`.')
    939     last_dim = tensor_shape.dimension_value(input_shape[-1])

ValueError: The last dimension of the inputs to `Dense` should be defined. Found `None`.
</code>```

How can I implement an autoencoder having different input dimensions?

答: Dense layer will create, in your case, 35 neurons where each will be connected to each input feature (out of 320). It will initialize the matrix of weight of size 35x320, for example. There is no way to initialize such a matrix when input size is not known, at least when it comes to dense layers. You will have to pad you inputs to some maximum possible input length (320?) to apply model as you define it. </p>

Title: Autoeconders Keras with Variable Inputs

Body:
I have a keras code implementing an autoencoder like that:

ENCODING_DIM = 5

# input placeholder
input_img = tf.keras.layers.Input(shape=(320,))

# this is the encoded representation of the input
encoded = tf.keras.layers.Dense(35, activation='relu')(input_img)
encoded = tf.keras.layers.Dense(20, activation='relu')(encoded)
encoded = tf.keras.layers.Dense(ENCODING_DIM, activation='relu')(encoded)

decoded = tf.keras.layers.Dense(20, activation='relu')(encoded)
decoded = tf.keras.layers.Dense(35, activation='relu')(decoded)
decoded = tf.keras.layers.Dense(320, activation='sigmoid')(decoded)

autoencoder = tf.keras.models.Model(input_img, decoded)

encoder = tf.keras.models.Model(input_img, encoded)
encoded_input = tf.keras.layers.Input(shape=(ENCODING_DIM,))

decoder_layer = autoencoder.layers[-1]
#decoded_input = tf.keras.models.Model(encoded_input,decoder_layer(encoded_input))

autoencoder.compile(optimizer='nadam', loss='binary_crossentropy')
from keras.callbacks import ModelCheckpoint

it works perfectly.

Now I would like to have variable input dimensions (e.g. the first vector [320x1], the second [280x1], etc...)

Now I try to do that:

ENCODING_DIM = 5

# input placeholder
input_img = tf.keras.layers.Input(shape=(None,))

# this is the encoded representation of the input
encoded = tf.keras.layers.Dense(35, activation='relu')(input_img)
encoded = tf.keras.layers.Dense(20, activation='relu')(encoded)
encoded = tf.keras.layers.Dense(ENCODING_DIM, activation='relu')(encoded)

decoded = tf.keras.layers.Dense(20, activation='relu')(encoded)
decoded = tf.keras.layers.Dense(35, activation='relu')(decoded)
decoded = tf.keras.layers.Dense(320, activation='sigmoid')(decoded)

autoencoder = tf.keras.models.Model(input_img, decoded)

encoder = tf.keras.models.Model(input_img, encoded)
encoded_input = tf.keras.layers.Input(shape=(ENCODING_DIM,))

decoder_layer = autoencoder.layers[-1]
#decoded_input = tf.keras.models.Model(encoded_input,decoder_layer(encoded_input))

autoencoder.compile(optimizer='nadam', loss='binary_crossentropy')
from keras.callbacks import ModelCheckpoint

but it returns an error like:

ValueError                                Traceback (most recent call last)
<ipython-input-24-7764c4707491> in <module>()
     14
     15 # this is the encoded representation of the input
---> 16 encoded = tf.keras.layers.Dense(35, activation='relu')(input_img)
     17 encoded = tf.keras.layers.Dense(20, activation='relu')(encoded)
     18 encoded = tf.keras.layers.Dense(ENCODING_DIM, activation='relu')(encoded)

2 frames
/usr/local/lib/python3.6/dist-packages/tensorflow/python/keras/layers/core.py in build(self, input_shape)
    935     input_shape = tensor_shape.TensorShape(input_shape)
    936     if tensor_shape.dimension_value(input_shape[-1]) is None:
--> 937       raise ValueError('The last dimension of the inputs to `Dense` '
    938                        'should be defined. Found `None`.')
    939     last_dim = tensor_shape.dimension_value(input_shape[-1])

ValueError: The last dimension of the inputs to `Dense` should be defined. Found `None`.

How can I implement an autoencoder having different input dimensions?


问:
Postgres / SQL count across multiple tables based on multiple tables
I have 4 tables, and the goal is a simple true/false (or count if it's easier) for whether there exists either an AccountLink or a ResourceLink based on given User.uuid and Resource.uuid.

Minimal working example

http://sqlfiddle.com/#!17/09144/1

Goal

True/false response based on User.uuid and Resource.uuid, which are unrelated.

Schema

```<code>User
- id
- uuid

Resource
- id
- account_id
- uuid

AccountLink
- id
- account_id
- user_id

ResourceLink
- id
- resource_id
- user_id
</code>```

Currently working

Gives id list instead of true/false, which can be handled in application code, but the query itself is also inefficient:

SELECT id
FROM "AccountLinks"
WHERE user_id = (SELECT id FROM "Users" WHERE uuid = ?)
  AND account_id = (SELECT account_id FROM "Resources" WHERE uuid = ?)
UNION
SELECT id
FROM "ResourceLinks"
WHERE user_id = (SELECT id FROM "Users" WHERE uuid = ?)
  AND resource_id = (SELECT id FROM "Resources" WHERE uuid = ?)
```

Is there a way to find the correct user and resource once based on their uuid, and then use those id properties to count across multiple tables?

答:
Hmmm . . . I think you want a cross join with additional information brought in:

select
  (exists (select 1
     from "AccountLinks" al
     where al.user_id = u.id and al.account_id = r.account_id
  )) as has_accountlink,
  (exists (select 1
     from "ResourceLinks" rl
     where rl.user_id = u.id and rl.resource_id = r.id
  )) as has_resourcelink
from "Users" u cross join
     "Resources" r
where u.uuid = ? and r.uuid = ?
```

Body:
I have 4 tables, and the goal is a simple true/false (or count if it's easier) for whether there exists either an AccountLink or a ResourceLink based on given User.uuid and Resource.uuid.

Minimal working example

http://sqlfiddle.com/#!17/09144/1

Goal

True/false response based on User.uuid and Resource.uuid, which are unrelated.

Schema

User
- id
- uuid

Resource
- id
- account_id
- uuid

AccountLink
- id
- account_id
- user_id

ResourceLink
- id
- resource_id
- user_id

Currently working

Gives id list instead of true/false, which can be handled in application code, but the query itself is also inefficient:

SELECT id
FROM "AccountLinks"
WHERE user_id = (SELECT id FROM "Users" WHERE uuid = ?)
  AND account_id = (SELECT account_id FROM "Resources" WHERE uuid = ?)
UNION
SELECT id
FROM "ResourceLinks"
WHERE user_id = (SELECT id FROM "Users" WHERE uuid = ?)
  AND resource_id = (SELECT id FROM "Resources" WHERE uuid = ?)

Is there a way to find the correct user and resource once based on their uuid, and then use those id properties to count across multiple tables?


问:
Handling packets received from multiple clients to multiple threads in c
when multiple clients send packets to server how can i write code to receive them on their corresponding child threads instead of receiving them on main process

i am writing c program for udp client and server using threads so if i have 4 clients connected 4 threads will be created and each thread will send some data. after receiving the data the clients will send acks but the problem is those acks should be received by the corresponding threads but

i have receivefrom function in main process to listen for new clients and i also have receivefrom function on threads to get ack packets but these ack coming from client are going to main process instead of coming to threads please help me thanks in advance

my code
server code

```<code>//created udp socket

// binded

while(1)
{
    // to receive new connections
    n=recvfrom(sock,buffer,512,0,(struct sockaddr*)&from,&length);

    // if some client sent request i will assign new thread to serve it
    pthread_create(&thread_id[str_cnt], NULL, serve,(void*)(&cli[str_cnt]));
}

function serve(args)
{

    while(1)
    {
        // sendind data to that client
        sendto(sockfd, buf, BUFSIZE, 0, (struct sockaddr *) &clientaddr,clientlen);

        //now wating for ack from the client
        sendto(sockfd, buf, BUFSIZE, 0, (struct sockaddr *) &clientaddr,clientlen);
    }
}

}
</code>```

答:
You can't have multiple threads reading from the same socket at the
  same time.

What you should do instead is either:

have a dedicated thread that receives all inbound packets, looks at the source IP/Port, and routes the data to the appropriate processing
  thread as needed.

give each processing thread its own socket that is bind()'ed to the same local IP/Port and connect()'ed to the particular source
  IP/Port it is interested in, then each thread can call recvfrom()
  independently and it will only return packets that match the source
  that the thread is expecting.

I took this from Remy Lebeau on this question.

UDP doesn't have a notion of separate connections unless you use different ports and handle them yourself, that's why they created TCP (and also for more reliable, in-order communication.)  You're already emulating reliable communication by using ACKs, so the only overhead is in-order communication (and checksums, if you don't like them either) so you might be better off using TCP.

Body:
when multiple clients send packets to server how can i write code to receive them on their corresponding child threads instead of receiving them on main process

i am writing c program for udp client and server using threads so if i have 4 clients connected 4 threads will be created and each thread will send some data. after receiving the data the clients will send acks but the problem is those acks should be received by the corresponding threads but

i have receivefrom function in main process to listen for new clients and i also have receivefrom function on threads to get ack packets but these ack coming from client are going to main process instead of coming to threads please help me thanks in advance

my code
server code

//created udp socket

// binded

while(1)
{
    // to receive new connections
    n=recvfrom(sock,buffer,512,0,(struct sockaddr*)&from,&length);

    // if some client sent request i will assign new thread to serve it
    pthread_create(&thread_id[str_cnt], NULL, serve,(void*)(&cli[str_cnt]));
}

function serve(args)
{

    while(1)
    {
        // sendind data to that client
        sendto(sockfd, buf, BUFSIZE, 0, (struct sockaddr *) &clientaddr,clientlen);

        //now wating for ack from the client
        sendto(sockfd, buf, BUFSIZE, 0, (struct sockaddr *) &clientaddr,clientlen);
    }
}

}


问:
Crashlytics found an invalid API key: null. after updated com.google.gms:google-services:4.1.0
I had this bug after updated from com.google.gms:google-services:4.0.1 to com.google.gms:google-services:4.1.0

```<code>Crashlytics found an invalid API key: null.
Check the Crashlytics plugin to make sure that the application has been added successfully!
Contact support@fabric.io for assistance.
</code>```

For Java projects, they hadn't this problem. I tried to invalidate cache and restart but not resolve.

I'm using:
Android Studio 3.3 Canary 8

```<code>dependencies {
      classpath 'com.android.tools.build:gradle:3.3.0-alpha08'

      classpath 'com.google.gms:google-services:4.1.0'
      classpath 'io.fabric.tools:gradle:1.25.4'

      classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:1.2.61"
      classpath "org.jetbrains.kotlin:kotlin-android-extensions:1.2.61"
}
</code>```

FirebaseCrashlytics version:

```<code>implementation 'com.google.firebase:firebase-core:16.0.3'
implementation 'com.crashlytics.sdk.android:crashlytics:2.9.5'
</code>```

Thanks!

答:
You need to add the meta data for the fabric in AndroidManifest.xml

```<code><meta-data
android:name="io.fabric.ApiKey"
android:value="xxx6c41xxx6ec601xxxd4xxxa2" />
</code>```

Be guided that the best way is stated below:

Add the Fabric API key to your fabric.properties: apiKey=fabric_api_key

```<code># Fabric properties file: app/fabric.properties
apiSecret=xx68f6074dxxxxxc11dxxx97c172e8ebf0
apiKey=xxxe75b4xxxx97e8cxxxx0135e9d46f5a2xxx
</code>```

Official documentation

Body:
I had this bug after updated from com.google.gms:google-services:4.0.1 to com.google.gms:google-services:4.1.0

Crashlytics found an invalid API key: null.
Check the Crashlytics plugin to make sure that the application has been added successfully!
Contact support@fabric.io for assistance.

For Java projects, they hadn't this problem. I tried to invalidate cache and restart but not resolve.

I'm using:
Android Studio 3.3 Canary 8

dependencies {
      classpath 'com.android.tools.build:gradle:3.3.0-alpha08'

      classpath 'com.google.gms:google-services:4.1.0'
      classpath 'io.fabric.tools:gradle:1.25.4'

      classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:1.2.61"
      classpath "org.jetbrains.kotlin:kotlin-android-extensions:1.2.61"
}

FirebaseCrashlytics version:

implementation 'com.google.firebase:firebase-core:16.0.3'
implementation 'com.crashlytics.sdk.android:crashlytics:2.9.5'

Thanks!

Body:
You need to add the meta data for the fabric in AndroidManifest.xml

<meta-data
android:name="io.fabric.ApiKey"
android:value="xxx6c41xxx6ec601xxxd4xxxa2" />

Be guided that the best way is stated below:

Add the Fabric API key to your fabric.properties: apiKey=fabric_api_key

# Fabric properties file: app/fabric.properties
apiSecret=xx68f6074dxxxxxc11dxxx97c172e8ebf0
apiKey=xxxe75b4xxxx97e8cxxxx0135e9d46f5a2xxx

Official documentation


问:
How to update Dynamic Resource within a Dynamic Resource?
I have a visual brush which is a group of shapes, the main colour of which is a dynamic resource itself - so the shape is for example MyShape and the Colour, MyColour which is referenced by the Shape object.

My problem is when I update the colour for this - it only happens the first time the shape is loaded (the colour needs to be set first) however as much as I change the colour it won't update the dynamic resource that uses the colour - how do I make this work?

Just need to make a dynamic resource work within another dynamic resource and have them both update when I change the colour.

I have no idea how to get this to work - I spent time creating a colour-picker for WPF only to find I cannot change the colour of this item - 1-Tier resources work where I set the brush/colour directly but not a colour within another object or 2-Tier Resource.

Edit: My problem seems to be specific to using these in a seperate Resource / Dictionary as my program needs to access this item from a class not the Window, the main example mentioned does not work when the MyColor is in a seperate Resource.

答:
Can you post an example of how you are attempting to change the color in the resource dictionary?

When I make a sample app and try to change the resource value it appears that the SolidColorBrush in the resource dictionary has been frozen so it can't be modified.  To get around this I just set the new value to a new SolidColorBrush.

OwnerDisplayName: RoguePlanetoid

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: RoguePlanetoid

OwnerDisplayName: Caleb Vear


问:
How can I change the title of a ggplot2 legend?
I was looking here but I can't figure it out.

How can I change the word "type" to something else?

答:
Just a word to the wise ... all of these options above can be overridden if you do something dumb like I just did.  Earlier in my project, I had simply turned off a legend I didn't like using the "themes" parameter within ggplot:

```<code>theme(legend.title = element_blank())
</code>```

If you do this, no matter what beautiful commands you put in to change the title -- and I tried all of those above -- they won't be overridden by your command to turn the legend off!  You have been warned!  ;{)

Body:
Just a word to the wise ... all of these options above can be overridden if you do something dumb like I just did.  Earlier in my project, I had simply turned off a legend I didn't like using the "themes" parameter within ggplot:

theme(legend.title = element_blank())

If you do this, no matter what beautiful commands you put in to change the title -- and I tried all of those above -- they won't be overridden by your command to turn the legend off!  You have been warned!  ;{)


问:
scipy fsolve fails for few values in input, and how to improve solver convergence
I am using scipy.optimize fsolve for finding roots of two equations. fsolve works well for some range of b values (0.1 to 0.6), but fails for values like 0.9 or 0.99.

I have tried moving to least_squares or minimize, but get a tuple error whilst providing initial conditions.

Including edits from below findings be self:

from scipy.optimize import fsolve
import scipy.stats as st
from numpy import *
import numpy as np

def rod(var1, var2, mu, sigma):
    return (st.lognorm.ppf(var1, s = sigma, scale = np.exp(mu), loc = sigma))/(st.lognorm.ppf(var2, s = sigma, scale = np.exp(mu), loc = sigma))
def fs_spfs(var1, mu, sigma):
    return (st.lognorm.ppf(var1, s = sigma, scale = np.exp(mu), loc = sigma))

a = 44.0
b = 0.5  #fsolve works for 0.5, 0.9, 0.99 but not for 0.95, incidentally works for 0.950001
c = 1.26

def f(x):
    y = np.zeros(2)
    y[0] = ((fs_spfs((1-b), x[0], x[1]) - a))
    y[1] = (((fs_spfs(0.9, x[0], x[1])/fs_spfs(0.1, x[0], x[1]))   - c))
    print(y)
    return y

x0 = np.array([1., 0.01])
solution = fsolve(f, x0)
print( "(x, y) = (" + str(solution[0]) + ", " + str(solution[1]) + ")")

```

<p>Results with b = 0.5</p>

<pre class="lang-py prettyprint-override"><code>b = 0.5

(x, y) = (3.7821340072441982, 0.09035467410258388)

fs_spfs((1-b), solution[0], solution[1]) # expected answer = 44.
43.99999999999982

rod(0.9, 0.1, solution[0], solution[1]) # exptected answer = 1.26
1.2599999999999958
</code>```

Results with b = 0.9

b = 0.9

(x, y) = (3.8979025451494755, 0.09033430819655046)

fs_spfs((1-b), solution[0], solution[1]) # expected answer = 44.
43.999999999989164

rod(0.9, 0.1, solution[0], solution[1]) # exptected answer = 1.26
1.2600000000001814
```

Works for b = 0.99 as well, but fails for b = 0.95. Incidentally works for b = 0.950001

答:
Following initial condition seems to be working for majority of common cases:

x0 = np.array([0.000001, 0.0000001])
```

Works for values till 0.999, still fails for 0.9999.

Body:
I am using scipy.optimize fsolve for finding roots of two equations. fsolve works well for some range of b values (0.1 to 0.6), but fails for values like 0.9 or 0.99.

I have tried moving to least_squares or minimize, but get a tuple error whilst providing initial conditions.

Including edits from below findings be self:

from scipy.optimize import fsolve
import scipy.stats as st
from numpy import *
import numpy as np

def rod(var1, var2, mu, sigma):
    return (st.lognorm.ppf(var1, s = sigma, scale = np.exp(mu), loc = sigma))/(st.lognorm.ppf(var2, s = sigma, scale = np.exp(mu), loc = sigma))
def fs_spfs(var1, mu, sigma):
    return (st.lognorm.ppf(var1, s = sigma, scale = np.exp(mu), loc = sigma))

a = 44.0
b = 0.5  #fsolve works for 0.5, 0.9, 0.99 but not for 0.95, incidentally works for 0.950001
c = 1.26

def f(x):
    y = np.zeros(2)
    y[0] = ((fs_spfs((1-b), x[0], x[1]) - a))
    y[1] = (((fs_spfs(0.9, x[0], x[1])/fs_spfs(0.1, x[0], x[1]))   - c))
    print(y)
    return y

x0 = np.array([1., 0.01])
solution = fsolve(f, x0)
print( "(x, y) = (" + str(solution[0]) + ", " + str(solution[1]) + ")")

Results with b = 0.5

b = 0.5

(x, y) = (3.7821340072441982, 0.09035467410258388)

fs_spfs((1-b), solution[0], solution[1]) # expected answer = 44.
43.99999999999982

rod(0.9, 0.1, solution[0], solution[1]) # exptected answer = 1.26
1.2599999999999958

Results with b = 0.9

b = 0.9

(x, y) = (3.8979025451494755, 0.09033430819655046)

fs_spfs((1-b), solution[0], solution[1]) # expected answer = 44.
43.999999999989164

rod(0.9, 0.1, solution[0], solution[1]) # exptected answer = 1.26
1.2600000000001814

Works for b = 0.99 as well, but fails for b = 0.95. Incidentally works for b = 0.950001

Body:
Following initial condition seems to be working for majority of common cases:

x0 = np.array([0.000001, 0.0000001])

Works for values till 0.999, still fails for 0.9999.


问:
Elasticsearch : Root mapping definition has unsupported parameters index : not_analyzed
Hi all I am trying to create schema Test.

```<code>PUT /test
{
    "mappings": {
        "field1": {
            "type": "integer"
        },
        "field2": {
            "type": "integer"
        },
        "field3": {
            "type": "string",
            "index": "not_analyzed"
        },
        "field4": {
            "type": "string",
            "analyzer": "autocomplete",
            "search_analyzer": "standard"
        }
    },
    "settings": {
        bla
        bla
        bla
    }
}
</code>```

I am getting the following error

```<code>{
    "error": {
        "root_cause": [{
            "type": "mapper_parsing_exception",
            "reason": "Root mapping definition has unsupported parameters: [index : not_analyzed] [type : string]"
        }],
        "type": "mapper_parsing_exception",
        "reason": "Failed to parse mapping [featured]: Root mapping definition has unsupported parameters:  [index : not_analyzed] [type : string]",
        "caused_by": {
            "type": "mapper_parsing_exception",
            "reason": "Root mapping definition has unsupported parameters:  [index : not_analyzed] [type : string]"
        }
    },
    "status": 400
}
</code>```

Please help me to resolve this error

答:
Check your Elastic version.

I had these problem because I was looking at the incorrect version's documentation.

Body:
Hi all I am trying to create schema Test.

PUT /test
{
    "mappings": {
        "field1": {
            "type": "integer"
        },
        "field2": {
            "type": "integer"
        },
        "field3": {
            "type": "string",
            "index": "not_analyzed"
        },
        "field4": {
            "type": "string",
            "analyzer": "autocomplete",
            "search_analyzer": "standard"
        }
    },
    "settings": {
        bla
        bla
        bla
    }
}

I am getting the following error

{
    "error": {
        "root_cause": [{
            "type": "mapper_parsing_exception",
            "reason": "Root mapping definition has unsupported parameters: [index : not_analyzed] [type : string]"
        }],
        "type": "mapper_parsing_exception",
        "reason": "Failed to parse mapping [featured]: Root mapping definition has unsupported parameters:  [index : not_analyzed] [type : string]",
        "caused_by": {
            "type": "mapper_parsing_exception",
            "reason": "Root mapping definition has unsupported parameters:  [index : not_analyzed] [type : string]"
        }
    },
    "status": 400
}

Please help me to resolve this error


问:
Why is it sometimes valid to write an include statement in a codeblock?
I amcoming from a python background, where the following is valid:

```<code>def f():
    import someLibrary
    someLibrary.libraryFunction()
</code>```

So when I needed to debug C code, I wrote, in the middle of my function:

```<code>void f(int param)
{
     int status;
     /* other code */
     #include <stdio.h>
     printf("status: %d", status);
     /* more code */
}
</code>```

And it compiled and worked as I expected. Later it was pointed out to me that this shouldn't compile, since the C pre-processor literally replaces the #include~ statement with the contents ofstdio.h`.
So why was this valid code?

答:
it was pointed out to me that this shouldn't compile, since the C pre-processor literally replaces the #include statement with the contents ofstdio.h.

The logic on that doesn't make sense. Just because the pre-processor inserts the text from the stdio.h file doesn't mean it should not compile. If there's nothing in that file that would result in a compile error, then it will compile just fine.

Furthermore, headers usually have a multiple inclusion guard in them. So if they were included already previously, any further attempts to include it have no effect. In this case, if <stdio.h> was already included previously in the file (directly or indirectly), the #include will have no effect.

With that being said, don't do that though. In C, standard headers are not supposed to be included while inside a function scope.

Body:
I amcoming from a python background, where the following is valid:

def f():
    import someLibrary
    someLibrary.libraryFunction()

So when I needed to debug C code, I wrote, in the middle of my function:

void f(int param)
{
     int status;
     /* other code */
     #include <stdio.h>
     printf("status: %d", status);
     /* more code */
}

And it compiled and worked as I expected. Later it was pointed out to me that this shouldn't compile, since the C pre-processor literally replaces the #include~ statement with the contents ofstdio.h`.
So why was this valid code?


问:
Tibco ems multiple consumers
I am very new to tibco ems and  have a question related to scenario where I have multiple consumers and one producer queue. If I am using client ackg mode, can all consumers consume different messages in parallel ? Consumers are on different machines and I want to set up tibco ems in a way so that all consumers can work on different messages concurrently. Also, if any of the consumers fails to send acknowledgement, how redelivery will happen?</p>

答: Yes, if you use client ack mode you can have different consumers work on different messages. When messages aren't acknowledged and the client connection is terminated, the message will be released back into the queue (and the redelivery count will be incremented). In your client code, you might want to check if the redelivery count is higher than 0 and have some logic to make sure you don't handle messages twice (if that is a concern).</p>

Title: Tibco ems multiple consumers


问:
FormatCondition.Modify results in Run-time error '1004' Application-defined or object-defined error
I have vba code that sets up a worksheet, One of the features is conditional formatting of column "Y". When I try to change Formula1 of the FormatCondition object, I get the Run-time '1004'.

The  Excel Template to be used by Golf Courses to aid in scoring of games played by large groups of players. I use highlighting of cell fill to call attention to significant values - in this case - to the top three players in the "Total Game". Three FormatCondition objects exist in the FormatConditions collection of the range "Y8:Y127". I have written some code that partially enumerates the existing FormatCondition objects, so I know they are there and contain what is expected. I created these through the normal Excel GUI - not vba.

```<code>For k = 1 To 3
    WST.Range("$Y$8:$Y$127").FormatConditions(k).Modify xlExpression, ,
      Replace(strScore, "#", k, 1, 1)
Next k
</code>```

The problem occurs with k = 1.

The Replace function call results in:

```<code>=VLOOKUP(A8,$A$7:$AY$127,51,FALSE)=1
</code>```

I am trying to modify Formula1 of the FormatCondition object which starts out containing :

```<code>=VLOOKUP(A8,$AA$7:$AY$127,25,FALSE)=3
</code>```

I tried the following from the debugger:

```<code> ? Replace(strScore,"#",k,1,1)
 =VLOOKUP(A8,$A$7:$AY$127,51,FALSE)=1
 ? WST.Range("$Y$8:$Y$127").FormatConditions(k).Formula1
 =VLOOKUP(A8,$AA$7:$AY$127,25,FALSE)=3

x=WST.Range("$Y$8:$Y$127").FormatConditions(k).Modify(xlExpression,,"=VLOOKUP(A8,$A$7:$AY$127,51,FALSE)=1","")
</code>```

I tried activating the WST sheet but same results.

All tries result in Run-time error '1004'

答:
Sorry for bugging folks on this forum. I can get around the problem. The FormatCondition object fails because the worksheet is protected. But the worksheet is protected using:

```<code> `wks.Protect Password:=gPassword, UserInterfaceOnly:=True`
</code>```

which should allow vba to modify conditional formatting but prevent mods via the user interface. This works for most things in Excel, but clearly not for the FormatCondition object.

Body:
I have vba code that sets up a worksheet, One of the features is conditional formatting of column "Y". When I try to change Formula1 of the FormatCondition object, I get the Run-time '1004'.

The  Excel Template to be used by Golf Courses to aid in scoring of games played by large groups of players. I use highlighting of cell fill to call attention to significant values - in this case - to the top three players in the "Total Game". Three FormatCondition objects exist in the FormatConditions collection of the range "Y8:Y127". I have written some code that partially enumerates the existing FormatCondition objects, so I know they are there and contain what is expected. I created these through the normal Excel GUI - not vba.

For k = 1 To 3
    WST.Range("$Y$8:$Y$127").FormatConditions(k).Modify xlExpression, ,
      Replace(strScore, "#", k, 1, 1)
Next k

The problem occurs with k = 1.

The Replace function call results in:

=VLOOKUP(A8,$A$7:$AY$127,51,FALSE)=1

I am trying to modify Formula1 of the FormatCondition object which starts out containing :

=VLOOKUP(A8,$AA$7:$AY$127,25,FALSE)=3

I tried the following from the debugger:

 ? Replace(strScore,"#",k,1,1)
 =VLOOKUP(A8,$A$7:$AY$127,51,FALSE)=1
 ? WST.Range("$Y$8:$Y$127").FormatConditions(k).Formula1
 =VLOOKUP(A8,$AA$7:$AY$127,25,FALSE)=3

x=WST.Range("$Y$8:$Y$127").FormatConditions(k).Modify(xlExpression,,"=VLOOKUP(A8,$A$7:$AY$127,51,FALSE)=1","")

I tried activating the WST sheet but same results.

All tries result in Run-time error '1004'

Body:
Sorry for bugging folks on this forum. I can get around the problem. The FormatCondition object fails because the worksheet is protected. But the worksheet is protected using:

 `wks.Protect Password:=gPassword, UserInterfaceOnly:=True`

which should allow vba to modify conditional formatting but prevent mods via the user interface. This works for most things in Excel, but clearly not for the FormatCondition object.


问:
3DES Key Size Matter in C#.Net

Below Code is Working Fine in c#.NET

```<code>byte[] key = Encoding.ASCII.GetByte("012345678901234567890123"); //24characters
byte[] plainText = Encoding.ASCII.GetBytes("lasaa");
TripleDES des = TripleDES.Create();
des.Key = key;
des.Mode = CipherMode.CBC;
ICryptoTransform ic = des.CreateEncryptor();
byte[] enc = ic.TransformFinalBlock(plainText, 0, plainText.Length);
MessageBox.Show(UTF8Encoding.UTF8.GetString(enc));
</code>```

My questions regarding above are...

How can I specify KeySize? if i use des.KeySize= 128 or 192 or 256 it gives

Specified key is not a valid size for this algorithm

If I change character length in key by adding more (ex:40 chars). It gives error

Specified key is not a valid size for this algorithm

I want to know why is this happen?

答:
A 3DES key has length 128 or 192 bits. Note that, internally, the algorithm will use only 112 (respectively 168) bits out of those 128 (respectively 192) bits; however, the key itself, as encoded into bytes, stored and exchanged, must have length 16 or 24 bytes. Trying to set a key which does not have one of those two lengths triggers an error, which you observe when you try to use a 40-byte key.

You should not try to set the "key size": you already decide that when you set the key. When you set the TripleDES.Key property, the TripleDES class sees that you give it a 24-byte key, and thus will set itself the KeySize property to 192.

(The output of 3DES encryption is binary, not UTF-8 encoding of a string. Chances are that your final UTF8Encoding.UTF8.GetString(enc) will protest.)

Title: 3DES Key Size Matter in C#.Net

Body:
Below Code is Working Fine in c#.NET

byte[] key = Encoding.ASCII.GetByte("012345678901234567890123"); //24characters
byte[] plainText = Encoding.ASCII.GetBytes("lasaa");
TripleDES des = TripleDES.Create();
des.Key = key;
des.Mode = CipherMode.CBC;
ICryptoTransform ic = des.CreateEncryptor();
byte[] enc = ic.TransformFinalBlock(plainText, 0, plainText.Length);
MessageBox.Show(UTF8Encoding.UTF8.GetString(enc));

My questions regarding above are...

How can I specify KeySize? if i use des.KeySize= 128 or 192 or 256 it gives

Specified key is not a valid size for this algorithm

If I change character length in key by adding more (ex:40 chars). It gives error

Specified key is not a valid size for this algorithm

I want to know why is this happen?


问:
Why cant we change the color of badge class in bootstrap 4 using css?
The class for badge in Bootstrap v4.3.1 is

```<code>.badge {
   display: inline-block;
   padding: 0.25em 0.4em;
   font-size: 75%;
   font-weight: 700;
   line-height: 1;
   text-align: center;
   white-space: nowrap;
   vertical-align: baseline;
   border-radius: 0.25rem;
   transition: color 0.15s ease-in-out, background-color 0.15s ease-in-out,
   border-color 0.15s ease-in-out, box-shadow 0.15s ease-in-out;
}
</code>```

and to change its color we can add the following class

```<code>.badge-success {
   color: #fff;
   background-color: #28a745;
}
</code>```

Logic would say, if I wanted to make my own color I could make a new class in my css file like such

```<code>.badge-mine {
   color: #212529;
   background-color: #808080;
}
</code>```

and it should work when this works...

```<code><span class="badge badge-success">test</span>
</code>```

then this should work too, but it does not work, even though they appear the same.

```<code><span class="badge badge-mine">test</span>
</code>```

I have checked many answers, but no one seems to answer why we cannot do it like this. Although, I am no expert in CSS I understand that the last command overwrites the previous one i.e. this should overwrite

```<code>color: #212529;
background-color: #808080;
</code>```

this

```<code>color: #fff;
background-color: #28a745;
</code>```

but for some reason it is not happening here.

Can some bootstrap 4 expert shed some light on why the badge-mine does not work even though it looks almost exactly like badge-success?

Thanks

答:
It should work as intended what you did. But if your two badges

```<code><span class="badge badge-success">test</span>
<span class="badge badge-mine">test</span>
</code>```

looks the same the problem is somewhere else, your badge can't have the same style of .badge-success if it doesn't have it as class.
Anyway css class priority works principally on how much specific are them.
For example

```<code>.badge.badge-success {
   background-color: red;
}
</code>```

overrides

```<code>.badge-success {
   background-color: green
}
</code>```

You can override this behaviour adding !important to css params, like

```<code>background-color: red!important;
</code>```

Body:
The class for badge in Bootstrap v4.3.1 is

.badge {
   display: inline-block;
   padding: 0.25em 0.4em;
   font-size: 75%;
   font-weight: 700;
   line-height: 1;
   text-align: center;
   white-space: nowrap;
   vertical-align: baseline;
   border-radius: 0.25rem;
   transition: color 0.15s ease-in-out, background-color 0.15s ease-in-out,
   border-color 0.15s ease-in-out, box-shadow 0.15s ease-in-out;
}

and to change its color we can add the following class

.badge-success {
   color: #fff;
   background-color: #28a745;
}

Logic would say, if I wanted to make my own color I could make a new class in my css file like such

.badge-mine {
   color: #212529;
   background-color: #808080;
}

and it should work when this works...

test

then this should work too, but it does not work, even though they appear the same.

test

I have checked many answers, but no one seems to answer why we cannot do it like this. Although, I am no expert in CSS I understand that the last command overwrites the previous one i.e. this should overwrite

color: #212529;
background-color: #808080;

this

color: #fff;
background-color: #28a745;

but for some reason it is not happening here.

Can some bootstrap 4 expert shed some light on why the badge-mine does not work even though it looks almost exactly like badge-success?

Thanks

Body:
It should work as intended what you did. But if your two badges

<span class="badge badge-success">test</span>
<span class="badge badge-mine">test</span>

looks the same the problem is somewhere else, your badge can't have the same style of .badge-success if it doesn't have it as class.
Anyway css class priority works principally on how much specific are them.
For example

.badge.badge-success {
   background-color: red;
}

overrides

.badge-success {
   background-color: green
}

You can override this behaviour adding !important to css params, like

background-color: red!important;