问:
Unable to drop existing master table in sql developer
I was using yeasterday many times Data Pump in Sql Developer Wizard to export and import data. After each export/import a new master table appeared under the "+" button in sql developer(view->dba).
I wanted to drop all this tables(about 10 tables) and I was successfull for all cases, except 2 of them. When I'm writing sql code: drop table x, it shows me error that this tables doesn't exists. It was working fine for every others tables..
When i run query select * from dba_tables where table_name='x' the table is there. I'm writing drop statement as system user.

```<code>  select *
      from dba_tables
     where table_name in ('moj_dump_job'
                        , 'moj_job_data_pump');

OWNER                          TABLE_NAME
------------------------------ ------------------------------
SYSTEM                         moj_dump_job
SYSTEM                         moj_job_data_pump

drop table moj_dump_job;

Error starting at line : 1 in command -
drop table moj_dump_job
Error report -
ORA-00942: table or view does not exist
00942. 00000 -  "table or view does not exist"
*Cause:
*Action:
</code>```

I tired to drop this jobs, but it doesnt't work:

```<code>select owner_name, job_name
  from DBA_DATAPUMP_JOBS;

OWNER_NAME                     JOB_NAME
------------------------------ ------------------------------
SYSTEM                         moj_job_data_pump
SYSTEM                         moj_dump_job

BEGIN
  dbms_scheduler.drop_job(job_name => 'moj_dump_job');
END;

Error starting at line : 13 in command -
BEGIN
  dbms_scheduler.drop_job(job_name => 'moj_dump_job');
END;
Error report -
ORA-27475: "SYSTEM.MOJ_DUMP_JOB" must be a job
ORA-06512: at "SYS.DBMS_ISCHED", line 213
ORA-06512: at "SYS.DBMS_SCHEDULER", line 657
ORA-06512: at line 2
27475. 00000 -  "unknown %s \"%s\".\"%s\""
*Cause:    The specified object did not exist, privileges were not granted,
           or the object was of the wrong type.
*Action:   Specify an object of the correct type on which you have privileges.
</code>```

Do you have any idea what can I do? Using schema name before table name doesn't help.
Best regards, Darek

答:
Thank's for your help. It work's.

```<code>drop table "moj_dump_job"
drop table "moj_job_data_pump";

Table "moj_dump_job" dropped.
Table "moj_job_data_pump" dropped.
</code>```

Now

```<code> select *
   from dba_tables
  where table_name in ('moj_dump_job'
                     , 'moj_job_data_pump');

select owner_name, job_name
  from DBA_DATAPUMP_JOBS;
</code>```

Both statements doesn't return any rows. That's perfect, but the 2 tables are still visible under view ->dba ->data pump -> export jobs. How to drop them from the tree?

Body:
I was using yeasterday many times Data Pump in Sql Developer Wizard to export and import data. After each export/import a new master table appeared under the "+" button in sql developer(view->dba).
I wanted to drop all this tables(about 10 tables) and I was successfull for all cases, except 2 of them. When I'm writing sql code: drop table x, it shows me error that this tables doesn't exists. It was working fine for every others tables..
When i run query select * from dba_tables where table_name='x' the table is there. I'm writing drop statement as system user.

  select *
      from dba_tables
     where table_name in ('moj_dump_job'
                        , 'moj_job_data_pump');

OWNER                          TABLE_NAME
------------------------------ ------------------------------
SYSTEM                         moj_dump_job
SYSTEM                         moj_job_data_pump

drop table moj_dump_job;

Error starting at line : 1 in command -
drop table moj_dump_job
Error report -
ORA-00942: table or view does not exist
00942. 00000 -  "table or view does not exist"
*Cause:
*Action:

I tired to drop this jobs, but it doesnt't work:

select owner_name, job_name
  from DBA_DATAPUMP_JOBS;

OWNER_NAME                     JOB_NAME
------------------------------ ------------------------------
SYSTEM                         moj_job_data_pump
SYSTEM                         moj_dump_job

BEGIN
  dbms_scheduler.drop_job(job_name => 'moj_dump_job');
END;

Error starting at line : 13 in command -
BEGIN
  dbms_scheduler.drop_job(job_name => 'moj_dump_job');
END;
Error report -
ORA-27475: "SYSTEM.MOJ_DUMP_JOB" must be a job
ORA-06512: at "SYS.DBMS_ISCHED", line 213
ORA-06512: at "SYS.DBMS_SCHEDULER", line 657
ORA-06512: at line 2
27475. 00000 -  "unknown %s \"%s\".\"%s\""
*Cause:    The specified object did not exist, privileges were not granted,
           or the object was of the wrong type.
*Action:   Specify an object of the correct type on which you have privileges.

Do you have any idea what can I do? Using schema name before table name doesn't help.
Best regards, Darek

Body:
Thank's for your help. It work's.

drop table "moj_dump_job"
drop table "moj_job_data_pump";

Table "moj_dump_job" dropped.
Table "moj_job_data_pump" dropped.

Now

 select *
   from dba_tables
  where table_name in ('moj_dump_job'
                     , 'moj_job_data_pump');

select owner_name, job_name
  from DBA_DATAPUMP_JOBS;

Both statements doesn't return any rows. That's perfect, but the 2 tables are still visible under view ->dba ->data pump -> export jobs. How to drop them from the tree?


来源: stackexchange

问:
Identifying if a string ONLY has specific text
I have a column with a string that sometimes has one name, two, names or several names separated by semi-colons. I want to identify if a row matches all the specified names, but not if a row contains only some of the specified names.

SME

Row 1 - John;Ralph;Susan;Joe

Row 2 - Ralph

Row 3 - Susan;Ralph;Robert;Margaret

Row 4 - Ralph;Susan

```<code>df1['SME'] = df1.SMES.str.ONLY contains('Ralph', na=False, case=True)
df2['SME'] = df1.SMES.str.ONLY contains('Ralph;Susan', na=False, case=True)
</code>```

Expecting df1

Row 1 - False

Row 2 - True

Row 3 - False

Row 4 - False

Expecting df2

Row 1 - False

Row 2 - False

Row 3 - False

Row 4 - True

答:
I found an online python editor: https://www.onlinegdb.com/online_python_compiler

```<code>Row1 = "John;Ralph;Susan;Joe"
Row2 = "Ralph"
Row3 = "Susan;Ralph;Robert;Margaret"
Row4 = "Ralph;Susan"

Find1 = "Ralph"
Find2 = "Ralph;Susan"
Find3 = "Susan;Ralph"

def ContainsAllOf(Row,Find):
    Result = 'False'
    Rows = Row.split(';')
    Finds = Find.split(';')
    if len(Rows) == len(Finds):
        difference = [r for r in Rows if r not in Finds]
        if len(difference) == 0:
            Result = 'True'
    print(Row + '\n' + Find + '\n' + Result + '\n')

ContainsAllOf(Row1,Find1)
ContainsAllOf(Row2,Find1)
ContainsAllOf(Row3,Find1)
ContainsAllOf(Row4,Find1)

ContainsAllOf(Row1,Find2)
ContainsAllOf(Row2,Find2)
ContainsAllOf(Row3,Find2)
ContainsAllOf(Row4,Find2)

ContainsAllOf(Row1,Find3)
ContainsAllOf(Row2,Find3)
ContainsAllOf(Row3,Find3)
ContainsAllOf(Row4,Find3)
</code>```

Here's the output:

```<code>John;Ralph;Susan;Joe
Ralph
False

Ralph
Ralph
True

Susan;Ralph;Robert;Margaret
Ralph
False

Ralph;Susan
Ralph
False

John;Ralph;Susan;Joe
Ralph;Susan
False

Ralph
Ralph;Susan
False

Susan;Ralph;Robert;Margaret
Ralph;Susan
False

Ralph;Susan
Ralph;Susan
True

John;Ralph;Susan;Joe
Susan;Ralph
False

Ralph
Susan;Ralph
False

Susan;Ralph;Robert;Margaret
Susan;Ralph
False

Ralph;Susan
Susan;Ralph
True
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have a column with a string that sometimes has one name, two, names or several names separated by semi-colons. I want to identify if a row matches all the specified names, but not if a row contains only some of the specified names.

SME

Row 1 - John;Ralph;Susan;Joe

Row 2 - Ralph

Row 3 - Susan;Ralph;Robert;Margaret

Row 4 - Ralph;Susan

df1['SME'] = df1.SMES.str.ONLY contains('Ralph', na=False, case=True)
df2['SME'] = df1.SMES.str.ONLY contains('Ralph;Susan', na=False, case=True)

Expecting df1

Row 1 - False

Row 2 - True

Row 3 - False

Row 4 - False

Expecting df2

Row 1 - False

Row 2 - False

Row 3 - False

Row 4 - True

Body:
I found an online python editor: https://www.onlinegdb.com/online_python_compiler

Row1 = "John;Ralph;Susan;Joe"
Row2 = "Ralph"
Row3 = "Susan;Ralph;Robert;Margaret"
Row4 = "Ralph;Susan"

Find1 = "Ralph"
Find2 = "Ralph;Susan"
Find3 = "Susan;Ralph"

def ContainsAllOf(Row,Find):
    Result = 'False'
    Rows = Row.split(';')
    Finds = Find.split(';')
    if len(Rows) == len(Finds):
        difference = [r for r in Rows if r not in Finds]
        if len(difference) == 0:
            Result = 'True'
    print(Row + '\n' + Find + '\n' + Result + '\n')

ContainsAllOf(Row1,Find1)
ContainsAllOf(Row2,Find1)
ContainsAllOf(Row3,Find1)
ContainsAllOf(Row4,Find1)

ContainsAllOf(Row1,Find2)
ContainsAllOf(Row2,Find2)
ContainsAllOf(Row3,Find2)
ContainsAllOf(Row4,Find2)

ContainsAllOf(Row1,Find3)
ContainsAllOf(Row2,Find3)
ContainsAllOf(Row3,Find3)
ContainsAllOf(Row4,Find3)

Here's the output:

John;Ralph;Susan;Joe
Ralph
False

Ralph
Ralph
True

Susan;Ralph;Robert;Margaret
Ralph
False

Ralph;Susan
Ralph
False

John;Ralph;Susan;Joe
Ralph;Susan
False

Ralph
Ralph;Susan
False

Susan;Ralph;Robert;Margaret
Ralph;Susan
False

Ralph;Susan
Ralph;Susan
True

John;Ralph;Susan;Joe
Susan;Ralph
False

Ralph
Susan;Ralph
False

Susan;Ralph;Robert;Margaret
Susan;Ralph
False

Ralph;Susan
Susan;Ralph
True


问:
How do I make the CSS grid at center of the page
I tried to move the grid at center of the page, I dont know why it doesn't work

I looked a lot of example, I see people using this:
justify-content: center;

Even if I tried it and it doesn't work.

Here's my code

ul {
  list-style-type: none;
  background-color: silver;
  padding: 10px;
  text-align: center;
  margin: none;
}

p {
  text-align: center;
  padding: none;
}

li {
  display: inline;
  padding: 10px;
}

a {
  color: yellow;
}

.testing {
  padding: 150px;
  display: grid;
  grid-template-columns: 1fr 1fr 1fr;
  grid-gap: 10px;
  /* next comment was fixed to meet syntax in a plain style sheet */
  justify-content: center;
  /* its not moving to the center of the page*/
}

.testing div {
  width: 225px;
  height: 225px;
  background-color: blue;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><ul>

  <li>href=" ">Home</a ></li>
   <li>href="#news">News</a ></li>
   <li>href="#contact">Contact</a ></li>

</ul>

     <p>hellow world</p >

 <div class = "testing">
<div></div></code>```

答: The grid is centered, you just gave it 3 equal columns but only one child element, so the div is showing in the left-most column of the grid.  If you change the CSS to grid-template-columns: 1fr or define a template area in the center it will display as you expected, but having only one column begs the question of why you are using a grid layout to begin with.  What kind of layout are you trying to build? Maybe a flexbox solution would better fit your needs?

Body:
I tried to move the grid at center of the page, I dont know why it doesn't work

I looked a lot of example, I see people using this:
justify-content: center;

Even if I tried it and it doesn't work.

Here's my code

ul {
  list-style-type: none;
  background-color: silver;
  padding: 10px;
  text-align: center;
  margin: none;
}

p {
  text-align: center;
  padding: none;
}

li {
  display: inline;
  padding: 10px;
}

a {
  color: yellow;
}

.testing {
  padding: 150px;
  display: grid;
  grid-template-columns: 1fr 1fr 1fr;
  grid-gap: 10px;
  /* next comment was fixed to meet syntax in a plain style sheet */
  justify-content: center;
  /* its not moving to the center of the page*/
}

.testing div {
  width: 225px;
  height: 225px;
  background-color: blue;
}

Home

News

Contact

hellow world


问:
How to easily compare local and remote files via SFTP
I would like to compare local and remote files via sftp or other method, dreamweaver has the option of doing this in your favorite merge editor (i like winmerge), but I am not using dw at this juncture. Are there any other decent (windows7) programs out there that do synchronize and compare nicely?</p>

答:
Beyond Compare does (using our SFTP components BTW), but the way is not quite obvious -- you need to enter the URL in the form of "sftp://username@host.tld/path/to/directory/" as a directory to compare. I have yet to find how to store this string in some reusable way in Beyond Compare. </p>

<p>Upd: Forgot to mention that Beyond Compare handles regular FTP and FTP-over-TLS as well. </p>

ContentLicense: CC BY-SA 3.0

Body:
Beyond Compare does (using our SFTP components BTW), but the way is not quite obvious -- you need to enter the URL in the form of "sftp://username@host.tld/path/to/directory/" as a directory to compare. I have yet to find how to store this string in some reusable way in Beyond Compare.

Upd: Forgot to mention that Beyond Compare handles regular FTP and FTP-over-TLS as well.


问:
How can I fix this problem? It annoying me long time
The window never show up clearly and complete. The Picture is below

Screen Show for Visual Studio

答: Fixed, Changed my monitor dpi from 300 to 150</p>


问:
Iterating over matrixes in a list stopped in numpy
I would like to iterate over a matrix of matrixes (indeed, sounds weird),

```<code>import numpy as np

ar = np.array

A = ar([[[1,2,3],[4,5,6],[7,8,9]],[[11,12,13],[14,15,16],[17,18,19]], [[1,2,3],[4,5,6],[7,8,9]], [[20,21,22],[23,24,25],[26,27,28]]])

B = np.copy(A)
C = np.copy(A)

im = np.array([A,B,C])
</code>```

in order to receive the matrix which stores the values of (x,y) position in subsequent matrixes. For example, in [1, 2, 3], on the postion of 1, that means: A[0,0,0], there will appear only ones in the next matrixes. Thus I will receive an array in the new matrix (considering also A[0,0,1] and A[0,0,2]):

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

Therefore for the first array of A:

```<code>[[[1  1  1] [2  2  2] [3  3  3]]
[[4  4  4] [5  5  5] [6  6  6]]
[[7  7  7] [8  8  8] [9  9  9]]]
</code>```

I have created this function:

```<code>def loop_ar(arr):
    matrix, v, c, s = arr.shape
    new = np.zeros((v,c,s,matrix)) #The columns in the last array of new represent the subsequent arrays
    for x in range(v):
        for y in range(c):
            for s in range(s):
                for ma in range(matrix):
                    new[x,y,s,ma] = arr[ma, x, y, s]
    return new
</code>```

However, the output indicates, that the matrix stops iterating after few turns:

```<code>[[[[1. 1. 1.]
   [2. 2. 2.]
   [3. 3. 3.]]

  [[4. 4. 4.]
   [5. 5. 5.]
   [0. 0. 0.]]

  [[7. 7. 7.]
   [0. 0. 0.]
   [0. 0. 0.]]]

 [[[0. 0. 0.]
   [0. 0. 0.]
   [0. 0. 0.]]

  [[0. 0. 0.]
   [0. 0. 0.]
   [0. 0. 0.]]

  [[0. 0. 0.]
   [0. 0. 0.]
   [0. 0. 0.]]]

   ...
</code>```

When I tested this function on the list of lists, it worked. What has happened in this case? How can I fix it? It os only a simple case to illustrate my expectations; however, I would like to know the solution to a more complex problem, when B and C are not the copies of A. How can I force then the loop to iterate?

The B and C in the more complex case should have the same shape as A, howeb=ver they will differ in the last array. As in A we have:

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

in B we would have for example on the same position:

```<code>[23  34  56]
</code>```

and in C:

```<code>[54  43  32]
</code>```

Therefore the new matrix will include the array:

```<code>[[1  23  54]  [2  34  43]  [3  56  32]]
</code>```

I have completed this task (I hope so) with converting a list to an array, because loop_arr worked for lists. However, it is a roundabaout. I want the solution and the explanation of the interruption in looping.

Here I present random data for the more complex question:

```<code>A = ar([[[1,2,3],[4,5,6],[7,8,9]],[[11,12,13],[14,15,16],[17,18,19]],[[20,21,22],[23,24,25],[26,27,28]]])

B = ar([[[23,34,56], [56, 78, 90], [12, 34, 32]], [[74,75,65], [25,57,76], [90,24,35]]])

C = ar([[[13,31,53], [54,96,69], [78, 90, 99]], [[35,64,66], [13,35,53], [37,73,61]], [[62, 87,97], [80,35,62], [75,76,67]]]
</code>```

The new matrix would look like:

```<code>[[[[1  23  13]  [2  34  31]  [3  56  53]]
[[4  56  54]  [5  78  96] [6  90  69]]
[[7  12  78]  [8  34  90]  [9  32  99]]]
      ...so on, so on, so on...
                                     ]]]]
</code>```

Body:
I would like to iterate over a matrix of matrixes (indeed, sounds weird),

import numpy as np

ar = np.array

A = ar([[[1,2,3],[4,5,6],[7,8,9]],[[11,12,13],[14,15,16],[17,18,19]], [[1,2,3],[4,5,6],[7,8,9]], [[20,21,22],[23,24,25],[26,27,28]]])

B = np.copy(A)
C = np.copy(A)

im = np.array([A,B,C])

in order to receive the matrix which stores the values of (x,y) position in subsequent matrixes. For example, in [1, 2, 3], on the postion of 1, that means: A[0,0,0], there will appear only ones in the next matrixes. Thus I will receive an array in the new matrix (considering also A[0,0,1] and A[0,0,2]):

[[1  1  1] [2  2  2] [3  3  3]]

Therefore for the first array of A:

[[[1  1  1] [2  2  2] [3  3  3]]
[[4  4  4] [5  5  5] [6  6  6]]
[[7  7  7] [8  8  8] [9  9  9]]]

I have created this function:

def loop_ar(arr):
    matrix, v, c, s = arr.shape
    new = np.zeros((v,c,s,matrix)) #The columns in the last array of new represent the subsequent arrays
    for x in range(v):
        for y in range(c):
            for s in range(s):
                for ma in range(matrix):
                    new[x,y,s,ma] = arr[ma, x, y, s]
    return new

However, the output indicates, that the matrix stops iterating after few turns:

[[[[1. 1. 1.]
   [2. 2. 2.]
   [3. 3. 3.]]

  [[4. 4. 4.]
   [5. 5. 5.]
   [0. 0. 0.]]

  [[7. 7. 7.]
   [0. 0. 0.]
   [0. 0. 0.]]]

 [[[0. 0. 0.]
   [0. 0. 0.]
   [0. 0. 0.]]

  [[0. 0. 0.]
   [0. 0. 0.]
   [0. 0. 0.]]

  [[0. 0. 0.]
   [0. 0. 0.]
   [0. 0. 0.]]]

   ...

When I tested this function on the list of lists, it worked. What has happened in this case? How can I fix it? It os only a simple case to illustrate my expectations; however, I would like to know the solution to a more complex problem, when B and C are not the copies of A. How can I force then the loop to iterate?

The B and C in the more complex case should have the same shape as A, howeb=ver they will differ in the last array. As in A we have:

[1  2  3]

in B we would have for example on the same position:

[23  34  56]

and in C:

[54  43  32]

Therefore the new matrix will include the array:

[[1  23  54]  [2  34  43]  [3  56  32]]

I have completed this task (I hope so) with converting a list to an array, because loop_arr worked for lists. However, it is a roundabaout. I want the solution and the explanation of the interruption in looping.

Here I present random data for the more complex question:

A = ar([[[1,2,3],[4,5,6],[7,8,9]],[[11,12,13],[14,15,16],[17,18,19]],[[20,21,22],[23,24,25],[26,27,28]]])

B = ar([[[23,34,56], [56, 78, 90], [12, 34, 32]], [[74,75,65], [25,57,76], [90,24,35]]])

C = ar([[[13,31,53], [54,96,69], [78, 90, 99]], [[35,64,66], [13,35,53], [37,73,61]], [[62, 87,97], [80,35,62], [75,76,67]]]

The new matrix would look like:

[[[[1  23  13]  [2  34  31]  [3  56  53]]
[[4  56  54]  [5  78  96] [6  90  69]]
[[7  12  78]  [8  34  90]  [9  32  99]]]
      ...so on, so on, so on...
                                     ]]]]

Body:
numpy is already vectorized. You can do a kronecker product:

 np.kron(a,np.ones(3)).reshape(np.r_[a.shape,3])

array([[[[ 1.,  1.,  1.],
         [ 2.,  2.,  2.],
         [ 3.,  3.,  3.]],

        [[ 4.,  4.,  4.],
         [ 5.,  5.,  5.],
         [ 6.,  6.,  6.]],

        [[ 7.,  7.,  7.],
         [ 8.,  8.,  8.],
         [ 9.,  9.,  9.]]],

       [[[11., 11., 11.],
         [12., 12., 12.],
         [13., 13., 13.]],

        : : : :
        : : : :


答:
Just change padding: 150px; to padding: 50%;, on .testing ('testing' class).

This should work.

Best regards,

Brhaka

Title: How do I make the CSS grid at center of the page


问:
How to find neighboring records in the SQL table in terms of month and year?
Please help me to optimize my SQL query.

I have a table with the fields: date, commodity_id, exp_month_id, exp_year, price, where the first 4 fields are the primary key. The months are designated with the alphabet-ordered letters: e.g. F (for Jan), G (for Feb.), H (for March), etc. Thus the letter of more distant from Jan. month will be larger than the letter of the less distant month (F < G < H < ...). Some commodity_ids have all 12 months in the table, some only 5 or 3, which are constant for all years.

I need to calculate the difference between prices (gradient) of the neighboring records in terms of exp_month_id, exp_year. As the first step, I want to define for every couple (exp_month_id, exp_year) the valid couple (next_month_id, next_year). The main problem here, that if the current exp_month_id is the last in the year, then next_year = exp_year + 1 and next_month_id should be the first one in the year.

I have written the following query to do the job:

WITH trading_months AS (
    SELECT DISTINCT commodity_id,
                    exp_month_id
      FROM futures
     ORDER BY exp_month_id
)
SELECT DISTINCT f.commodity_id,
                f.exp_month_id,
                f.exp_year,
                (
                WITH [temp] AS (
                        SELECT exp_month_id
                          FROM trading_months
                         WHERE commodity_id = f.commodity_id
                    )
                    SELECT exp_month_id
                      FROM [temp]
                     WHERE exp_month_id > f.exp_month_id
                    UNION ALL
                    SELECT exp_month_id
                      FROM [temp]
                     LIMIT 1
                )
                AS next_month_id,
                (
                    SELECT CASE WHEN EXISTS (
                                   SELECT commodity_id,
                                          exp_month_id
                                     FROM trading_months
                                    WHERE commodity_id = f.commodity_id AND
                                          exp_month_id > f.exp_month_id
                                    LIMIT 1
                               )
                           THEN f.exp_year ELSE f.exp_year + 1 END
                )
                AS next_year
  FROM futures AS f
```

This query serves as a base for a dynamic table (view) which is subsequently used for calculating the gradient. However, the execution of this query takes more than one second and thus the whole process takes minutes. I wonder if you could help me optimizing the query.

答:
Thanks to the hint of @Shawn to use window functions I could rewrite the query in much shorter form:

CREATE VIEW "futures_nextmonths_win" AS
WITH trading_months AS (
    SELECT DISTINCT commodity_id,
                    exp_month_id,
                    exp_year
    FROM futures)
SELECT commodity_id,
       exp_month_id,
       exp_year,
       lead(exp_month_id) OVER w AS next_month_id,
       lead(exp_year) OVER w AS next_year
FROM trading_months
WINDOW w AS (PARTITION BY commodity_id ORDER BY exp_year, exp_month_id);
```

which is also slightly faster then the original one.

Body:
Please help me to optimize my SQL query.

I have a table with the fields: date, commodity_id, exp_month_id, exp_year, price, where the first 4 fields are the primary key. The months are designated with the alphabet-ordered letters: e.g. F (for Jan), G (for Feb.), H (for March), etc. Thus the letter of more distant from Jan. month will be larger than the letter of the less distant month (F < G < H < ...). Some commodity_ids have all 12 months in the table, some only 5 or 3, which are constant for all years.

I need to calculate the difference between prices (gradient) of the neighboring records in terms of exp_month_id, exp_year. As the first step, I want to define for every couple (exp_month_id, exp_year) the valid couple (next_month_id, next_year). The main problem here, that if the current exp_month_id is the last in the year, then next_year = exp_year + 1 and next_month_id should be the first one in the year.

I have written the following query to do the job:

WITH trading_months AS (
    SELECT DISTINCT commodity_id,
                    exp_month_id
      FROM futures
     ORDER BY exp_month_id
)
SELECT DISTINCT f.commodity_id,
                f.exp_month_id,
                f.exp_year,
                (
                WITH [temp] AS (
                        SELECT exp_month_id
                          FROM trading_months
                         WHERE commodity_id = f.commodity_id
                    )
                    SELECT exp_month_id
                      FROM [temp]
                     WHERE exp_month_id > f.exp_month_id
                    UNION ALL
                    SELECT exp_month_id
                      FROM [temp]
                     LIMIT 1
                )
                AS next_month_id,
                (
                    SELECT CASE WHEN EXISTS (
                                   SELECT commodity_id,
                                          exp_month_id
                                     FROM trading_months
                                    WHERE commodity_id = f.commodity_id AND
                                          exp_month_id > f.exp_month_id
                                    LIMIT 1
                               )
                           THEN f.exp_year ELSE f.exp_year + 1 END
                )
                AS next_year
  FROM futures AS f

This query serves as a base for a dynamic table (view) which is subsequently used for calculating the gradient. However, the execution of this query takes more than one second and thus the whole process takes minutes. I wonder if you could help me optimizing the query.

Body:
Thanks to the hint of @Shawn to use window functions I could rewrite the query in much shorter form:

CREATE VIEW "futures_nextmonths_win" AS
WITH trading_months AS (
    SELECT DISTINCT commodity_id,
                    exp_month_id,
                    exp_year
    FROM futures)
SELECT commodity_id,
       exp_month_id,
       exp_year,
       lead(exp_month_id) OVER w AS next_month_id,
       lead(exp_year) OVER w AS next_year
FROM trading_months
WINDOW w AS (PARTITION BY commodity_id ORDER BY exp_year, exp_month_id);

which is also slightly faster then the original one.


问:
Finite difference in Haskell, or how to disable potential optimizations
I'd like to implement the following naive (first order) finite differencing function:

```<code>finite_difference :: Fractional a => a -> (a -> a) -> a -> a
finite_difference h f x = ((f $ x + h) - (f x)) / h
</code>```

As you may know, there is a subtle problem: one has to make sure that (x + h) and x differ by an exactly representable number. Otherwise, the result has a huge error, leveraged by the fact that (f $ x + h) - (f x) involves catastrophic cancellation (and one has to carefully choose h, but that is not my problem here).

In C or C++, the problem can be solved like this:

```<code>volatile double temp = x + h;
h = temp - x;
</code>```

and the volatile modifier disables any optimization pertaining to the variable temp, so we are assured that a "clever" compiler will not optimize away those two lines.

I don't know enough Haskell yet to know how to solve this. I'm afraid that

```<code>let temp = x + h
    hh = temp - x
in ((f $ x + hh) - (f x)) / h
</code>```

will get optimized away by Haskell (or the backend it uses). How do I get the equivalent of volatile here (if possible without sacrificing laziness)? I don't mind GHC specific answers.

答:
I have two solutions and a suggestion:

First solution: You can guarantee that this won't be optimized out with two helper functions and the NOINLINE pragma:

```<code>norm1 x h = x+h
{-# NOINLINE norm1 #-}

norm2 x tmp = tmp-x
{-# NOINLINE norm2 #-}

normh x h = norm2 x (norm1 x h)
</code>```

This will work, but will introduce a small cost.

Second solution: Write the normalization function in C using volatile and call it through the FFI.  The performance penalty will be minimal.

Now for the suggestion: Currently the math isn't optimized out, so it will work properly at present.  You're afraid it will break in a future compiler.  I think this is unlikely, but not so unlikely that I wouldn't want to guard against it also.  So write some unit tests that cover the cases in question.  Then if it does break in the future (for any reason), you'll know exactly why.

Body:
I'd like to implement the following naive (first order) finite differencing function:

finite_difference :: Fractional a => a -> (a -> a) -> a -> a
finite_difference h f x = ((f $ x + h) - (f x)) / h

As you may know, there is a subtle problem: one has to make sure that (x + h) and x differ by an exactly representable number. Otherwise, the result has a huge error, leveraged by the fact that (f $ x + h) - (f x) involves catastrophic cancellation (and one has to carefully choose h, but that is not my problem here).

In C or C++, the problem can be solved like this:

volatile double temp = x + h;
h = temp - x;

and the volatile modifier disables any optimization pertaining to the variable temp, so we are assured that a "clever" compiler will not optimize away those two lines.

I don't know enough Haskell yet to know how to solve this. I'm afraid that

let temp = x + h
    hh = temp - x
in ((f $ x + hh) - (f x)) / h

will get optimized away by Haskell (or the backend it uses). How do I get the equivalent of volatile here (if possible without sacrificing laziness)? I don't mind GHC specific answers.

Body:
I have two solutions and a suggestion:

First solution: You can guarantee that this won't be optimized out with two helper functions and the NOINLINE pragma:

norm1 x h = x+h
{-# NOINLINE norm1 #-}

norm2 x tmp = tmp-x
{-# NOINLINE norm2 #-}

normh x h = norm2 x (norm1 x h)

This will work, but will introduce a small cost.

Second solution: Write the normalization function in C using volatile and call it through the FFI.  The performance penalty will be minimal.

Now for the suggestion: Currently the math isn't optimized out, so it will work properly at present.  You're afraid it will break in a future compiler.  I think this is unlikely, but not so unlikely that I wouldn't want to guard against it also.  So write some unit tests that cover the cases in question.  Then if it does break in the future (for any reason), you'll know exactly why.


问:
what is the es6 fat arrow equivalent to a es5 function declaration
With ES5 I can declare either a function declaration or expression, depending on what I need.

```<code>function es5FunctionDeclaration() {
  return 'I am an es5 function declaration';
}

var es5FunctionExpression = function() {
  return 'I am an es5 function expression';
}
</code>```

With the ES6 fat arrow, it is common to create a function expression like this...

```<code>const es6FunctionExpression = () => {
  return 'I am an es6 function expression';
}
</code>```

But I haven't find a way to do a function declaration with a fat arrow, perhaps it is not possible.

```<code>// es6FunctionDeclarationWithFatArrow ??
</code>```

答:
First of all hoisting is not a good/useful phenomena and function declarations are hoisted with value. The problem of not throwing error even declaring a variable twice is also due to hoisting.

ES6 was designed to remove all those problems. So there was no point to have the same function declaration again added as a new feature to cause problems again.

The is same like why in ES6 let and const can't be redeclared or how we could make let and const like var

Body:
With ES5 I can declare either a function declaration or expression, depending on what I need.

function es5FunctionDeclaration() {
  return 'I am an es5 function declaration';
}

var es5FunctionExpression = function() {
  return 'I am an es5 function expression';
}

With the ES6 fat arrow, it is common to create a function expression like this...

const es6FunctionExpression = () => {
  return 'I am an es6 function expression';
}

But I haven't find a way to do a function declaration with a fat arrow, perhaps it is not possible.

// es6FunctionDeclarationWithFatArrow ??


问:
I am trying to implement flames game in python.Not able to remove all matching character?
```<code>def flames(l,l1):
    for i in l:
        if i in l1:
            l.remove(str(i))
            l1.remove(str(i))
n1=input("Enter first name:")
n2=input("Enter Second name:")
l=list(n1)
l1=list(n2)
flames(l,l1)
print(l)
print(l1)
</code>```

I didn't completed my code entirely.But i am done with removing matched character.But the problem is its removing only first matched character.It's not removing remaining match characters.What is the problem in my code?

答:
You might find it easier to use a dict instead of a list to keep track of the letters left in each name. For instance, if the name is "Billy", the dict would be: {"b":1, "i":1, "l":2, "y":1}. In this way you can easily remove all instances of the letter because they're all stored in the same location.

Easiest way to create the dictionaries for each name would be dictionary comprehension:

```<code>n1 = input("Enter first name: ").lower()
d1 = { char:n1.count(char) for char in n1 }
</code>```

Of course, the order of these letters doesn't matter and will likely appear in a different order. Also notice that the "B" in "Billy" becomes "b" in the dictionary. This might be a matter of preference for purposes of this game, but generally you would want to convert all characters to lowercase so upper and lower case letters are not treated as distinct.

There's one more thing to consider when using a dict rather than a list to store the characters: you can't modify the dictionary as you're iterating over it, you'll get a RuntimeError. So as you're iterating through d1 (the characters in the first name) and deleting the matching characters in d2, you'll have to remember the matched characters so you can delete them from d1 later.

```<code>d1ToDel = []
for k in d1:
    if k in d2:
        del d2[k]
        d1ToDel.append(k)
for k in d1ToDel:
    del d1[k]
</code>```

After that, you just have to sum up the values remaining in each dictionary, which will give you the remaining number of characters after removing all matches. And then do a little modulo arithmetic to figure out which of the "Flames" characters the pair will land on.

Body:
def flames(l,l1):
    for i in l:
        if i in l1:
            l.remove(str(i))
            l1.remove(str(i))
n1=input("Enter first name:")
n2=input("Enter Second name:")
l=list(n1)
l1=list(n2)
flames(l,l1)
print(l)
print(l1)

I didn't completed my code entirely.But i am done with removing matched character.But the problem is its removing only first matched character.It's not removing remaining match characters.What is the problem in my code?

Body:
You might find it easier to use a dict instead of a list to keep track of the letters left in each name. For instance, if the name is "Billy", the dict would be: {"b":1, "i":1, "l":2, "y":1}. In this way you can easily remove all instances of the letter because they're all stored in the same location.

Easiest way to create the dictionaries for each name would be dictionary comprehension:

n1 = input("Enter first name: ").lower()
d1 = { char:n1.count(char) for char in n1 }

Of course, the order of these letters doesn't matter and will likely appear in a different order. Also notice that the "B" in "Billy" becomes "b" in the dictionary. This might be a matter of preference for purposes of this game, but generally you would want to convert all characters to lowercase so upper and lower case letters are not treated as distinct.

There's one more thing to consider when using a dict rather than a list to store the characters: you can't modify the dictionary as you're iterating over it, you'll get a RuntimeError. So as you're iterating through d1 (the characters in the first name) and deleting the matching characters in d2, you'll have to remember the matched characters so you can delete them from d1 later.

d1ToDel = []
for k in d1:
    if k in d2:
        del d2[k]
        d1ToDel.append(k)
for k in d1ToDel:
    del d1[k]

After that, you just have to sum up the values remaining in each dictionary, which will give you the remaining number of characters after removing all matches. And then do a little modulo arithmetic to figure out which of the "Flames" characters the pair will land on.


问:
Errors: Data path ".builders['app-shell']" should have required property 'class'
I am getting this error while running my application. Here are the details of my application.

```<code>Angular CLI: 7.3.3
Node: 10.15.1
Angular: 7.2.7
@angular-devkit/architect -0.13.3
@angular-devkit/build-angular- 0.800.1
@angular-devkit/build-optimizer - 0.800.1
@angular-devkit/build-webpack - 0.800.1
@angular-devkit/core -7.3.3
@angular-devkit/schematics -7.3.3
@angular/cli -7.3.3
@ngtools/webpack -8.0.1
@schematics/angular -7.3.3
@schematics/update 0.13.3
rxjs 6.3.3
typescript 3.2.4
webpack 4.30.0
</code>```

I have already tried cache clean.

答:
This happened to me when I installed Angular 8, there are some incompatibilities I couldn't solve. I had to downgrade because I went down the rabbit hole juggling around with every version until I found one that worked.

First, TypeScript was outdated, the default installation added a reference to TypeScript 3.1.6 and it requires 3.4 or greater.

npm install typescript@">=3.4 <3.5"

Second, using the devkit 0.800.1 or 0.800.1 always ended up in incompatibilities. I tried many combinations but I am not sure it's fully compatible yet, specially because I am using one bootstrap a bit older and I cannot upgrade yet.

Finally I tried to downgrade (go to package.json and find the devDependencies) until one of them worked.

@angular-devkit/build-angular": "0.13.4"

I am sure your problem is dependencies versions but I cannot tell you which one. Give it a try downgrading.

Body:
I am getting this error while running my application. Here are the details of my application.

Angular CLI: 7.3.3
Node: 10.15.1
Angular: 7.2.7
@angular-devkit/architect -0.13.3
@angular-devkit/build-angular- 0.800.1
@angular-devkit/build-optimizer - 0.800.1
@angular-devkit/build-webpack - 0.800.1
@angular-devkit/core -7.3.3
@angular-devkit/schematics -7.3.3
@angular/cli -7.3.3
@ngtools/webpack -8.0.1
@schematics/angular -7.3.3
@schematics/update 0.13.3
rxjs 6.3.3
typescript 3.2.4
webpack 4.30.0

I have already tried cache clean.


问:
How to check for change in array while change is via javascript
I want to know if there is a simple, clean way to listen for an array change in an array in Javascript.

I was attempting to use jQuery's change function but soon realized that it only works when the change is made in the HTML. I need to check if a change is made in Javascript, not HTML.

答:
simple

Proxys can get quite messy when used for heavier lifting, and are limited when it comes to detecting adding or removing fields from objects, but they should work well for your use case. (mdn)

let array = new Proxy([], {
  set: (obj, prop, value) => {
    obj[prop] = value;
    if (prop === 'length')
      console.log(`array length changed to ${value}`);
    else
      console.log(`set index ${prop} to ${value}`);
    return true;
  }
});

array[5] = 3;
array.push(1);
array[0] = 10;
console.log(array);```


问:
JavaScript querySelector versions of Jquery
I am trying to move away from JQuery.

I have a div called 'clientProfiles'

```<code><div class="paperlist" data-role='listview' data-inset='true' data-split-icon='delete' id='clientProfiles'></div>
</code>```

my application will fill the 'div' with buttons like so.

```<code>function getClientHtml(device) {

                var html = "";
                html += '<div data-name="' + device.Name + '" data-id="' + device.Id + '"data-app="' + device.AppName + '" style="border-radius: 2px; border: 1px solid rgba(0,0,0,0.158)" class="clientProfile listItem">';
                html += '<img style="float-left; width:3%;" src="' + deviceNameImage(device.Name) + '"/>';
                html += '<div class="listItemBody">';
                html += '<h3 class="listItemBodyText">' + device.Name + ' - ' + device.AppName + '</h3>';
                html += '</div>';
                html += '<i class="md-icon btnDeleteProfile" data-index="0">close</i>';
                html += '</div>';
                html += '<br />';
                return html;
            };
</code>```

The html after a button has been added by a user looks like this:

```<code><div class="paperlist" data-role="listview" data-inset="true" data-split-icon="delete" id="clientProfiles">
<div data-name="Xbox One" data-id="mcX7xXZksA1fJooKY2SRS5soNbFgM4lQurFx3bxr2s" data-app="Theater" style="border-radius: 2px; border: 1px solid rgba(0,0,0,0.158)" class="clientProfile listItem">
<img style="float-left; width:3%;" src="../images/devices/xboxone.png"><div class="listItemBody"><h3 class="listItemBodyText">XBLAHBLAHNAME</h3>
</div>
<i class="md-icon btnDeleteProfile" data-index="0">close</i>
</div>
<br>
</div>
</code>```

These dynamically created buttons can be removed from the page by clicking an icon  inside the main button labeled with a with a class called '.btnDeleteProfile'.

When I wanted to add a click event to my 'btnDeleteProfile' in JQuery I could use this:

```<code> $('#clientProfiles', page).on('click', '.btnDeleteProfile', function () {});
</code>```

But now that I am not using JQuery, I'm having an issue targeting the '.btnDeleteProfile'.

document.querySelector('.btnDeleteProfile').addEventListener('click', function() {});

However MDN says that querySelector will only find the first instance of this, and there could very well be a ton of these buttons created all with different profile info attached.

the query Selector can't find the 'btnDeleteProfile'.

The error I am experiencing is 'can't add click event to null.

答:
You can use:

Event.target: The target property of the Event interface is a reference to the object that dispatched the event.

The snippet:

function getClientHtml(device) {

    var html = "";
    html += '
';
    html += '';
    html += '
';
    html += '
' + device.Name + ' - ' + device.AppName + '
';
    html += '
';
    html += 'close';
    html += '
';
    html += '
';
    return html;
}

 var clientProfiles = document.querySelector('#clientProfiles');

clientProfiles.innerHTML += getClientHtml({Name: 'Xbox One', id: "mcX7xXZksA1fJooKY2SRS5soNbFgM4lQurFx3bxr2s", AppName: 'Theater'});
clientProfiles.addEventListener('click', function(e) {
    if (e.target.classList.contains('btnDeleteProfile')) {
        e.target.closest('div').remove();
        console.log('Do it');
    }
})```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="paperlist" data-role="listview" data-inset="true" data-split-icon="delete" id="clientProfiles">
    <div data-name="Xbox One" data-id="mcX7xXZksA1fJooKY2SRS5soNbFgM4lQurFx3bxr2s" data-app="Theater" style="border-radius: 2px; border: 1px solid rgba(0,0,0,0.158)" class="clientProfile listItem">
        <img style="float-left; width:3%;" src="../images/devices/xboxone.png"><div class="listItemBody"><h3 class="listItemBodyText">XBLAHBLAHNAME</h3>
    </div>
        <i class="md-icon btnDeleteProfile" data-index="0">close</i>
    </div>
    <br>
</div></code>```

Body:
I am trying to move away from JQuery.

I have a div called 'clientProfiles'

my application will fill the 'div' with buttons like so.

function getClientHtml(device) {

                var html = "";
                html += '
';
                html += '';
                html += '
';
                html += '
' + device.Name + ' - ' + device.AppName + '
';
                html += '
';
                html += 'close';
                html += '
';
                html += '
';
                return html;
            };

The html after a button has been added by a user looks like this:

XBLAHBLAHNAME

close

These dynamically created buttons can be removed from the page by clicking an icon  inside the main button labeled with a with a class called '.btnDeleteProfile'.

When I wanted to add a click event to my 'btnDeleteProfile' in JQuery I could use this:

 $('#clientProfiles', page).on('click', '.btnDeleteProfile', function () {});

But now that I am not using JQuery, I'm having an issue targeting the '.btnDeleteProfile'.

document.querySelector('.btnDeleteProfile').addEventListener('click', function() {});

However MDN says that querySelector will only find the first instance of this, and there could very well be a ton of these buttons created all with different profile info attached.

the query Selector can't find the 'btnDeleteProfile'.

The error I am experiencing is 'can't add click event to null.

Body:
You can use:

Event.target: The target property of the Event interface is a reference to the object that dispatched the event.

The snippet:

function getClientHtml(device) {

    var html = "";
    html += '<div data-name="' + device.Name + '" data-id="' + device.Id + '"data-app="' + device.AppName + '" style="border-radius: 2px; border: 1px solid rgba(0,0,0,0.158)" class="clientProfile listItem">';
    html += '<img style="float-left; width:3%;" src="../images/devices/xboxone.png"/>';
    html += '<div class="listItemBody">';
    html += '<h3 class="listItemBodyText">' + device.Name + ' - ' + device.AppName + '</h3>';
    html += '</div>';
    html += '<i class="md-icon btnDeleteProfile" data-index="0">close</i>';
    html += '</div>';
    html += '<br />';
    return html;
}

 var clientProfiles = document.querySelector('#clientProfiles');

clientProfiles.innerHTML += getClientHtml({Name: 'Xbox One', id: "mcX7xXZksA1fJooKY2SRS5soNbFgM4lQurFx3bxr2s", AppName: 'Theater'});
clientProfiles.addEventListener('click', function(e) {
    if (e.target.classList.contains('btnDeleteProfile')) {
        e.target.closest('div').remove();
        console.log('Do it');
    }
})

<div class="paperlist" data-role="listview" data-inset="true" data-split-icon="delete" id="clientProfiles">
    <div data-name="Xbox One" data-id="mcX7xXZksA1fJooKY2SRS5soNbFgM4lQurFx3bxr2s" data-app="Theater" style="border-radius: 2px; border: 1px solid rgba(0,0,0,0.158)" class="clientProfile listItem">
        <img style="float-left; width:3%;" src="../images/devices/xboxone.png"><div class="listItemBody"><h3 class="listItemBodyText">XBLAHBLAHNAME</h3>
    </div>
        <i class="md-icon btnDeleteProfile" data-index="0">close</i>
    </div>
    <br>
</div>


答:
This code uses array_reduce() to iterate over the initial array and merge the individual components.  As you can see though some aren't arrays - so I use is_array($element)?$element:[$element] which if is isn't an array, it makes it an array...

```<code>$invoice_numbers = array_reduce($invoice_numbers, function ($list, $element) {
    return array_merge($list, is_array($element)?$element:[$element]);
}, []);

return $response->withJson(array_unique($invoice_numbers, SORT_REGULAR));
</code>```

Title: array_unique() not working - mixed with nonArray

Body:
I am having some trouble with removing duplicates from an Array. This is my code:

$invoice_numbers = array_unique($invoice_numbers, SORT_REGULAR);
return $response->withJson($invoice_numbers);

$invoice_numbers:

 {
    "0": [
    "8250",
    "8436",
    "8584",
    "8708",
    "8838",
    "9076",
    "9125",
    "9186"
    ],
    "1": [
    "8250",
    "8436",
    "8584",
    "8708",
    "8838",
    "9076",
    "9125",
    "9186",
    "9895"
    ],
    "3": [
    "9758",
    "9799",
    "10168",
    "10227",
    "10465",
    "10517",
    "10655",
    "10729",
    "10758"
    ],
    "4": [
    "9798",
    "10226",
    "10516"
    ],
    "5": [
    "10926",
    "11246",
    "11591",
    "11790",
    "11791",
    "11802",
    "11803"
    ],
    "6": [
    "10897",
    "11002",
    "11142",
    "11277",
    "11279",
    "11345",
    "11458",
    "11478",
    "11492",
    "11498",
    "11501",
    "11526",
    "11676",
    "11761",
    "11780",
    "11781",
    "11833",
    "11946",
    "12031",
    "12048",
    "12119"
    ],
    "7": "12201",
    "8": [
    "11214",
    "11502",
    "11538",
    "11677",
    "11834",
    "12120"
    ],
    "9": "11643"
    }

Now i know that this does not work with multidimensional array. But i also tried this: (Note that key nr.9 is not an array then it throws an error)

$invoice_numbers = array_unique(call_user_func_array('array_merge', $invoice_numbers), SORT_REGULAR);
return $response->withJson($invoice_numbers);

Can someone help me with creating a unique value in array? Thanks

This is the error: Warning:  array_merge(): Argument #8 is not an
  array

And result is "null"

Body:
This code uses array_reduce() to iterate over the initial array and merge the individual components.  As you can see though some aren't arrays - so I use is_array($element)?$element:[$element] which if is isn't an array, it makes it an array...

$invoice_numbers = array_reduce($invoice_numbers, function ($list, $element) {
    return array_merge($list, is_array($element)?$element:[$element]);
}, []);

return $response->withJson(array_unique($invoice_numbers, SORT_REGULAR));


问:
Make string into arraylist with individual characters Java
I have a String called new_alpha which contains only characters (no whitespace). How do I split it so that each character is a different element in a new ArrayList?

答:
```<code>int len=new_alpha.length();
ArrayList<Character> arr=new ArrayList<Character>();
for(int i=0;i<len;i++)
{ arr.add(new_alpha.charAt(i));
}
</code>```

Your all character of String convert into ArrayList;

Body:
int len=new_alpha.length();
ArrayList<Character> arr=new ArrayList<Character>();
for(int i=0;i<len;i++)
{ arr.add(new_alpha.charAt(i));
}

Your all character of String convert into ArrayList;


问:
How to give different bg color to each  created using php function?
I've a table showing 7 days of week created using php function. How can i give different background color to each day in the table. I'm new to this, any and all help would be great.

```<code><?php
for($prev_days = 0 ; $prev_days<7;$prev_days++) {
    $curr_date = date('Y-m-d', strtotime(-$prev_days.' days'));
    $dayOfWeek = date("l",strtotime(strval($curr_date)));
    /*echo $dayOfWeek;*/
?>
    <td title="click here to see the files">
        <label>
            <a onclick="document.getElementById('id01').style.display='block'" class="clr">
                <?php echo substr(strval($dayOfWeek),0,3); ?>
            </a>
        </label>
    </td>
<?php
    }
?>

.CSSTableGenerator tr:first-child td{
background:-o-linear-gradient(bottom, #005fbf 5%, #003f7f 100%);
background:-webkit-gradient( linear, left top, left bottom, color-stop(0.05, #005fbf), color-stop(1, #003f7f) );
background:-moz-linear-gradient( center top, #005fbf 5%, #003f7f 100% );
filter:progid:DXImageTransform.Microsoft.gradient(startColorstr="#005fbf", endColorstr="#003f7f");  background: -o-linear-gradient(top,#005fbf,003f7f);
background-color:#005fbf;
}
</code>```

This is the table created
: https://i.stack.imgur.com/nLnxP.png

答:
CSS only solution. Put a class on the tr parent of the td's and then use a number from 1 to 7 to add bg color on each.

```<code>.someclass td:nth-child(1) {
  background:blue
}
.someclass td:nth-child(2) {
  background:red
}
....
.someclass td:nth-child(7) {
  background:green
}

<tr class="someclass">
<?php for($prev_days = 0 ; $prev_days<7;$prev_days++) {$curr_date = date('Y-m-d', strtotime(-$prev_days.' days'));$dayOfWeek = date("l",strtotime(strval($curr_date)));
/*echo $dayOfWeek;*/?>
<td title="click here to see the files"><label><a onclick="document.getElementById('id01').style.display='block'" class="clr"><?php echo substr(strval($dayOfWeek),0,3); ?></a></label></td>
<?php}?>
</tr>
</code>```

Edit: after looking again at your image second solution I had is not good.

Title: How to give different bg color to each <td> created using php function?

Body:
I've a table showing 7 days of week created using php function. How can i give different background color to each day in the table. I'm new to this, any and all help would be great.

<?php
for($prev_days = 0 ; $prev_days<7;$prev_days++) {
    $curr_date = date('Y-m-d', strtotime(-$prev_days.' days'));
    $dayOfWeek = date("l",strtotime(strval($curr_date)));
    /*echo $dayOfWeek;*/
?>

                <?php echo substr(strval($dayOfWeek),0,3); ?>

<?php
    }
?>

.CSSTableGenerator tr:first-child td{
background:-o-linear-gradient(bottom, #005fbf 5%, #003f7f 100%);
background:-webkit-gradient( linear, left top, left bottom, color-stop(0.05, #005fbf), color-stop(1, #003f7f) );
background:-moz-linear-gradient( center top, #005fbf 5%, #003f7f 100% );
filter:progid:DXImageTransform.Microsoft.gradient(startColorstr="#005fbf", endColorstr="#003f7f");  background: -o-linear-gradient(top,#005fbf,003f7f);
background-color:#005fbf;
}

This is the table created
: https://i.stack.imgur.com/nLnxP.png

Body:
CSS only solution. Put a class on the tr parent of the td's and then use a number from 1 to 7 to add bg color on each.

.someclass td:nth-child(1) {
  background:blue
}
.someclass td:nth-child(2) {
  background:red
}
....
.someclass td:nth-child(7) {
  background:green
}

<tr class="someclass">
<?php for($prev_days = 0 ; $prev_days<7;$prev_days++) {$curr_date = date('Y-m-d', strtotime(-$prev_days.' days'));$dayOfWeek = date("l",strtotime(strval($curr_date)));
/*echo $dayOfWeek;*/?>
<td title="click here to see the files"><label><a onclick="document.getElementById('id01').style.display='block'" class="clr"><?php echo substr(strval($dayOfWeek),0,3); ?></a></label></td>
<?php}?>
</tr>

Edit: after looking again at your image second solution I had is not good.


问:
Media Player Requirements in Android
I am developing a media player application in Android. Its a bit of a lengthy explanation, but please go through it & suggest a solution

The application has a first screen that displays a list of radio stations. When the user clicks on any of these radio stations, the application goes to the second screen that displays the play, pause & stop controls. The activity in the second screen also initiates a service that prepares the Media Player & starts playing the media. Now I have two requirements

I want to show a progress status while the media has not started playing. It should be shown on top of the second screen & should disappear once the media has started playing. How do I do that? Is something is to be done in the Activity that started the service or in the Service itself?

Now when the media is playing, I want to go back to the first screen by pressing the back button(or may be exit the application). But the music should keep on playing unless I select some other radio station form the first screen(new music will start), or come back to the application from the notification panel & then stop the music.

Can someone suggest the best way to do this? Are there any sample codes available to achieve this?

Thanks

答:
To show a status dialog, look into ProgressDialog called from your UI activity. To cause a service to continue playing, you need to use startService rather than bindService.

Service lifecycle reference

Title: Media Player Requirements in Android


问:
Render a DetailsList component with all items preselected
I want to render a DetailsList with all items in that list preselected. I pass a Selection prop to the DetailsList, but calling setAllSelected() on the Selection from the component's constructor won't render all items as selected.

Though, calling setAllSelected() from an event handler would select all items as expected.

I have tried to call setAllSelected() from componentDidMount(), but without success.

I suppose items must be internally created  (wrt the DetailsList component) before the Selection can select them, but I have no idea how to force this.

I have added a CodePen.

答:
You need to set the items on the selection first like so:

```<code>this._selection.setItems(this.state.items, false)
</code>```

I adjusted your codepen here to demo this. Hope this helps.

Body:
You need to set the items on the selection first like so:

this._selection.setItems(this.state.items, false)

I adjusted your codepen here to demo this. Hope this helps.


问:
How to exclude all the test files except two using maven?
I like to do have something like bellow which will exclude all test cases except two of the test files?

```<code><plugin>
      <groupId>org.apache.maven.plugins</groupId>
      <artifactId>maven-surefire-plugin</artifactId>
      <version>2.12.4</version>
      <configuration>
        <excludes>
            <exclude>**/*Test.java</exclude>
        </excludes>
        <includes>
            <include>path/to/Some1Test.java</include>
            <include>path/to/Some2Test.java</include>
        </includes>
      </configuration>
    </plugin>
</code>```

Critical fact in here, the test files that I do not want to exclude, also has the same naming pattern as the files I want to exclude. Thanks in advance.

答:
excludes wins on includes for the surefire plugin configuration (not documented but works in this way).   And it makes sense, since excludes should be seen as the exceptional case and includes as the general case : you geneally want to include all but .....

But here you want to exactly the reverse.

So don't mix both elements because with your actual conf :

```<code>  <configuration>
    <excludes>
        <exclude>**/*Test.java</exclude>
    </excludes>
    <includes>
        <include>path/to/Some1Test.java</include>
        <include>path/to/Some2Test.java</include>
    </includes>
  </configuration>
</code>```

you exclude all sinceexcludes excludes all here(<exclude>**/*Test.java</exclude>) and that excludes win on includes.

All you need is to define includes only to make only these tests executed :

```<code>  <configuration>
    <includes>
        <include>path/to/Some1Test.java</include>
        <include>path/to/Some2Test.java</include>
    </includes>
  </configuration>
</code>```

Body:
I like to do have something like bellow which will exclude all test cases except two of the test files?

<plugin>
      <groupId>org.apache.maven.plugins</groupId>
      <artifactId>maven-surefire-plugin</artifactId>
      <version>2.12.4</version>
      <configuration>
        <excludes>
            <exclude>**/*Test.java</exclude>
        </excludes>
        <includes>
            <include>path/to/Some1Test.java</include>
            <include>path/to/Some2Test.java</include>
        </includes>
      </configuration>
    </plugin>

Critical fact in here, the test files that I do not want to exclude, also has the same naming pattern as the files I want to exclude. Thanks in advance.

Body:
excludes wins on includes for the surefire plugin configuration (not documented but works in this way).   And it makes sense, since excludes should be seen as the exceptional case and includes as the general case : you geneally want to include all but .....

But here you want to exactly the reverse.

So don't mix both elements because with your actual conf :

  <configuration>
    <excludes>
        <exclude>**/*Test.java</exclude>
    </excludes>
    <includes>
        <include>path/to/Some1Test.java</include>
        <include>path/to/Some2Test.java</include>
    </includes>
  </configuration>

you exclude all sinceexcludes excludes all here(<exclude>**/*Test.java</exclude>) and that excludes win on includes.

All you need is to define includes only to make only these tests executed :

  <configuration>
    <includes>
        <include>path/to/Some1Test.java</include>
        <include>path/to/Some2Test.java</include>
    </includes>
  </configuration>


问:
Calculate height of div based off width & maintain proportion
I am looking for a pure CSS solution to what I have here done using jQuery to help.

Basically I have 3 divs that spread evenly in width in a container. They maintain a 3/4 ration with the height being calculated off of the width. Furthermore, each div has a background image that stays proportional and some text that is centered horizontally and vertically.

$(document).ready(function() {
  function setw() {
    var footdivwidth = $('footer div').width();
    var footdivheight = footdivwidth * .75;
    $('footer div').css({
      'height': footdivheight + 'px'
    });
    $('footer div span').html('w: ' + footdivwidth + '
h: ' + footdivheight);
  }
  setw();
  $(window).resize(function() {
    setw();
  })
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>FOOTER {
  max-width: 1000px;
  margin: 0 auto;
  background-color: rgba(0, 0, 0, 0.171);
  display: flex;
  flex-wrap: wrap;
  justify-content: space-between;
}

FOOTER DIV {
  background-image: url('https://learnwebdesign.online/img/bg.jpg');
  background-position: center;
  background-size: cover;
  background-repeat: no-repeat;
  flex: 1;
  text-align: center;
  display: flex;
  align-items: center;
  justify-content: center;
}

FOOTER DIV SPAN {
  display: inline-block;
  text-align: center;
  background-color: rgba(165, 165, 165, 0.282);
  padding: 7px 15px;
  border-radius: 3px;
  color: #FFFFFF;
  text-transform: uppercase;
  font-weight: bold;
  letter-spacing: 2px;
  font-size: 21px;
}</code>```

left photo

center photo

right photo and more text

```
</div>
</div>
</p>

<p>Here is a pen showing what I have.
https://codepen.io/nom3d/pen/arGpBV</p>

<p>Here is a gif showing the effect when resized. Note the background image staying proportional and text staying centered.
<img src="https://i.stack.imgur.com/OyB78.gif" alt="3 box resize with proportions kept"></p>

<p>Also wondering if it's not possible with just CSS, how to do this with <strong>plain javascript</strong>, would I need to add id's to my divs?</p>

<p>Update: here is a plain javaScript function to handle this task</p>

```function setHeight(el,val){
    var box = document.querySelectorAll(el);
    var i;
    for(i = 0;i < box.length;i++){
        var width = box[i].offsetWidth;
        var height = width * val;
        box[i].style.height = height + 'px';
    }
}
// set your element to target and the ratio value
setHeight('footer div',.75);
window.onresize = function(event) {
    setHeight('footer div',.75);
};
```

答:
A quick pure CSS solution would involve to add to FOOTER DIV

```<code>  max-width: 333px;
  width: calc(100vw/3);
  height: calc(100vw*0.75/3);
  max-height: calc(333px*0.75);
</code>```

and add to FOOTER

```<code>  width: 100vw;
</code>```

// Javascript is only used in order to check the width/height ratio in console live.
$(document).ready(function() {

  $(window).resize(function() {
    console.log('width: ' + $('footer div').width() + ', height: ' + $('footer div').height());
  });

});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>FOOTER {
  max-width: 1000px;
  width: 100vw;
  margin: 0 auto;
  background-color: rgba(0, 0, 0, 0.171);
  display: flex;
  flex-wrap: wrap;
  /*justify-content: space-between;*/
}

FOOTER DIV {
  background-image: url('https://learnwebdesign.online/img/bg.jpg');
  background-position: center;
  background-size: cover;
  background-repeat: no-repeat;
  flex: 1;
  text-align: center;
  display: flex;
  align-items: center;
  justify-content: center;
  max-width: 333px;
  width: calc(100vw/3);
  height: calc(100vw*0.75/3);
  max-height: calc(333px*0.75);
}

FOOTER DIV SPAN {
  display: inline-block;
  text-align: center;
  background-color: rgba(165, 165, 165, 0.282);
  padding: 7px 15px;
  border-radius: 3px;
  color: #FFFFFF;
  text-transform: uppercase;
  font-weight: bold;
  letter-spacing: 2px;
  font-size: 21px;
}</code>```

left photo

center photo

right photo and more text

```

Body:
I am looking for a pure CSS solution to what I have here done using jQuery to help.

Basically I have 3 divs that spread evenly in width in a container. They maintain a 3/4 ration with the height being calculated off of the width. Furthermore, each div has a background image that stays proportional and some text that is centered horizontally and vertically.

$(document).ready(function() {
  function setw() {
    var footdivwidth = $('footer div').width();
    var footdivheight = footdivwidth * .75;
    $('footer div').css({
      'height': footdivheight + 'px'
    });
    $('footer div span').html('w: ' + footdivwidth + '
h: ' + footdivheight);
  }
  setw();
  $(window).resize(function() {
    setw();
  })
});

FOOTER {
  max-width: 1000px;
  margin: 0 auto;
  background-color: rgba(0, 0, 0, 0.171);
  display: flex;
  flex-wrap: wrap;
  justify-content: space-between;
}

FOOTER DIV {
  background-image: url('https://learnwebdesign.online/img/bg.jpg');
  background-position: center;
  background-size: cover;
  background-repeat: no-repeat;
  flex: 1;
  text-align: center;
  display: flex;
  align-items: center;
  justify-content: center;
}

FOOTER DIV SPAN {
  display: inline-block;
  text-align: center;
  background-color: rgba(165, 165, 165, 0.282);
  padding: 7px 15px;
  border-radius: 3px;
  color: #FFFFFF;
  text-transform: uppercase;
  font-weight: bold;
  letter-spacing: 2px;
  font-size: 21px;
}

left photo

center photo

right photo and more text

Here is a pen showing what I have.
https://codepen.io/nom3d/pen/arGpBV

Here is a gif showing the effect when resized. Note the background image staying proportional and text staying centered.

Also wondering if it's not possible with just CSS, how to do this with plain javascript, would I need to add id's to my divs?

Update: here is a plain javaScript function to handle this task

function setHeight(el,val){
    var box = document.querySelectorAll(el);
    var i;
    for(i = 0;i < box.length;i++){
        var width = box[i].offsetWidth;
        var height = width * val;
        box[i].style.height = height + 'px';
    }
}
// set your element to target and the ratio value
setHeight('footer div',.75);
window.onresize = function(event) {
    setHeight('footer div',.75);
};

Body:
A quick pure CSS solution would involve to add to FOOTER DIV

  max-width: 333px;
  width: calc(100vw/3);
  height: calc(100vw*0.75/3);
  max-height: calc(333px*0.75);

and add to FOOTER

  width: 100vw;

// Javascript is only used in order to check the width/height ratio in console live.
$(document).ready(function() {

  $(window).resize(function() {
    console.log('width: ' + $('footer div').width() + ', height: ' + $('footer div').height());
  });

});

FOOTER {
  max-width: 1000px;
  width: 100vw;
  margin: 0 auto;
  background-color: rgba(0, 0, 0, 0.171);
  display: flex;
  flex-wrap: wrap;
  /*justify-content: space-between;*/
}

FOOTER DIV {
  background-image: url('https://learnwebdesign.online/img/bg.jpg');
  background-position: center;
  background-size: cover;
  background-repeat: no-repeat;
  flex: 1;
  text-align: center;
  display: flex;
  align-items: center;
  justify-content: center;
  max-width: 333px;
  width: calc(100vw/3);
  height: calc(100vw*0.75/3);
  max-height: calc(333px*0.75);
}

FOOTER DIV SPAN {
  display: inline-block;
  text-align: center;
  background-color: rgba(165, 165, 165, 0.282);
  padding: 7px 15px;
  border-radius: 3px;
  color: #FFFFFF;
  text-transform: uppercase;
  font-weight: bold;
  letter-spacing: 2px;
  font-size: 21px;
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<footer>
  <div><span>left photo</span></div>
  <div><span>center photo</span></div>
  <div><span>right photo and more text</span></div>
</footer>


问:
Print specific lines using sed
Im trying to print only lines that do not start with a letter from the file "main"

Ive tried sed -n '/^[a-z]/ /!w' main
and it gives me "w': event not found"

答:
```<code>grep -v '^[a-z]' main
</code>```

will do it.

Title: Print specific lines using sed

Body:
grep -v '^[a-z]' main

will do it.


问:
Why doesn't this radial-gradient complete the circle?
I'm trying to use a radial gradient to create a border within circle elements that are radio buttons. The basic CSS is shown below. I cannot figure out why the red gradient does not circle the entire circumference of the circles.

As the white color-stop approaches 100%, gaps appear in the red at the top, right, left, and bottom.

Why does this happen, and how would I fix it while still using a radial gradient?

.container {
  background: #ddd;
  width: 400px;
  height: 200px;
  padding: 20px;
}

.radio {
  display: inline-block;
  background: white;
  border-radius: 50%;
  border: 2px solid transparent;
  width: 20px;
  height: 20px;
  margin-right: 20px;
}

.radio1 { background: radial-gradient(circle closest-side, white 75%, red 100%); }
.radio2 { background: radial-gradient(circle closest-side, white 90%, red 100%); }
.radio3 { background: radial-gradient(circle closest-side, white 95%, red 100%); }
.radio4 { background: radial-gradient(circle closest-side, white 99%, red 100%); }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">
  <div class="radio"></div>
  <div class="radio radio1"></div>
  <div class="radio radio2"></div>
  <div class="radio radio3"></div>
  <div class="radio radio4"></div>
</div></code>```

Also on JSFiddle: https://jsfiddle.net/zvgcs80f/

答:
Your percentage will be converted to pixel relatively to the width/height of your element. In your case, your element is small thus 99% and 100% will most likely be converted to the same value or very close values and you will have subpixel rendring issue.

Instead you can rely on calc() where you can easily define the thickness as a pixel value independently of the element size.

You need to also adjust background-origin and make it border-box so that you draw the gradient considering the border area and you will have a perfect circle.

.container {
  background: #ddd;
  width: 400px;
  height: 200px;
  padding: 20px;
}

.radio {
  display: inline-block;
  background: white;
  border-radius: 50%;
  border: 2px solid transparent;
  width: 20px;
  height: 20px;
  margin-right: 20px;
  background-origin:border-box;
}

.radio1 { background-image: radial-gradient(circle closest-side, white calc(100% - 1px), red 100%); }
.radio2 { background-image: radial-gradient(circle closest-side, white calc(100% - 2px), red 100%); }
.radio3 { background-image: radial-gradient(circle closest-side, white calc(100% - 3px), red 100%); }
.radio4 { background-image: radial-gradient(circle closest-side, white calc(100% - 4px), red 100%); }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">
  <div class="radio"></div>
  <div class="radio radio1"></div>
  <div class="radio radio2"></div>
  <div class="radio radio3"></div>
  <div class="radio radio4"></div>
</div></code>```

Here is an example with big values of border to better illustrate the issue related to background-origin

.container {
  background: #ddd;
  width: 400px;
  height: 200px;
  padding: 20px;
}

.radio {
  display: inline-block;
  background: white;
  border-radius: 50%;
  border: 20px solid rgba(0,0,0,0.2);
  width: 50px;
  height: 50px;
  margin-right: 20px;
 background-image: radial-gradient(circle closest-side, white calc(100% - 4px), red 100%); }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">
  <div class="radio radio4"></div>
</div></code>```

The background is drawn on the padding box then it's getting repeated over all the area (border box).

If you disable the repeat you will have this:

.container {
  background: #ddd;
  width: 400px;
  height: 200px;
  padding: 20px;
}

.radio {
  display: inline-block;
  background: white;
  border-radius: 50%;
  border: 20px solid rgba(0,0,0,0.2);
  width: 50px;
  height: 50px;
  margin-right: 20px;
 background-image: radial-gradient(circle closest-side, white calc(100% - 4px), red 100%);
  background-repeat:no-repeat;
 }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">
  <div class="radio"></div>
</div></code>```

Here is if we repeat only on the X axis

.container {
  background: #ddd;
  width: 400px;
  height: 200px;
  padding: 20px;
}

.radio {
  display: inline-block;
  background: white;
  border-radius: 50%;
  border: 20px solid rgba(0,0,0,0.2);
  width: 50px;
  height: 50px;
  margin-right: 20px;
 background-image: radial-gradient(circle closest-side, white calc(100% - 4px), red 100%);
  background-repeat:repeat-x;
 }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">
  <div class="radio"></div>
</div></code>```

And here is what is happening when using 100% for both colors which is similar to your situation and you will better understand why you have coloration only on the corners.

.container {
  background: #ddd;
  padding: 20px;
}

.radio {
  display: inline-block;
  background: white;
  border-radius: 50%;
  border: 20px solid rgba(0, 0, 0, 0.2);
  width: 50px;
  height: 50px;
  margin-right: 20px;
  background-image: radial-gradient(circle closest-side, white 100%, red 100%);
}

.one {
  background-repeat: no-repeat;
}

.two {
  background-repeat: repeat;
}

.three {
  border-width: 5px;
}
.four {
  width:20px;
  height:20px;
  border-width: 2px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">
  <div class="radio one"></div>
  <div class="radio two"></div>
  <div class="radio three"></div>
  <div class="radio four"></div>
</div></code>```

And if we change the origin it's fine:

.container {
  background: #ddd;
  width: 400px;
  height: 200px;
  padding: 20px;
}

.radio {
  display: inline-block;
  background: white;
  border-radius: 50%;
  border: 20px solid rgba(0,0,0,0.2);
  width: 50px;
  height: 50px;
  margin-right: 20px;
 background-image: radial-gradient(circle closest-side, white calc(100% - 4px), red 100%);
  background-origin:border-box;
 }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">
  <div class="radio"></div>
</div></code>```

Body:
I'm trying to use a radial gradient to create a border within circle elements that are radio buttons. The basic CSS is shown below. I cannot figure out why the red gradient does not circle the entire circumference of the circles.

As the white color-stop approaches 100%, gaps appear in the red at the top, right, left, and bottom.

Why does this happen, and how would I fix it while still using a radial gradient?

.container {
  background: #ddd;
  width: 400px;
  height: 200px;
  padding: 20px;
}

.radio {
  display: inline-block;
  background: white;
  border-radius: 50%;
  border: 2px solid transparent;
  width: 20px;
  height: 20px;
  margin-right: 20px;
}

.radio1 { background: radial-gradient(circle closest-side, white 75%, red 100%); }
.radio2 { background: radial-gradient(circle closest-side, white 90%, red 100%); }
.radio3 { background: radial-gradient(circle closest-side, white 95%, red 100%); }
.radio4 { background: radial-gradient(circle closest-side, white 99%, red 100%); }

Also on JSFiddle: https://jsfiddle.net/zvgcs80f/

Body:
Your percentage will be converted to pixel relatively to the width/height of your element. In your case, your element is small thus 99% and 100% will most likely be converted to the same value or very close values and you will have subpixel rendring issue.

Instead you can rely on calc() where you can easily define the thickness as a pixel value independently of the element size.

You need to also adjust background-origin and make it border-box so that you draw the gradient considering the border area and you will have a perfect circle.

.container {
  background: #ddd;
  width: 400px;
  height: 200px;
  padding: 20px;
}

.radio {
  display: inline-block;
  background: white;
  border-radius: 50%;
  border: 2px solid transparent;
  width: 20px;
  height: 20px;
  margin-right: 20px;
  background-origin:border-box;
}

.radio1 { background-image: radial-gradient(circle closest-side, white calc(100% - 1px), red 100%); }
.radio2 { background-image: radial-gradient(circle closest-side, white calc(100% - 2px), red 100%); }
.radio3 { background-image: radial-gradient(circle closest-side, white calc(100% - 3px), red 100%); }
.radio4 { background-image: radial-gradient(circle closest-side, white calc(100% - 4px), red 100%); }

<div class="container">
  <div class="radio"></div>
  <div class="radio radio1"></div>
  <div class="radio radio2"></div>
  <div class="radio radio3"></div>
  <div class="radio radio4"></div>
</div>

Here is an example with big values of border to better illustrate the issue related to background-origin

.container {
  background: #ddd;
  width: 400px;
  height: 200px;
  padding: 20px;
}

.radio {
  display: inline-block;
  background: white;
  border-radius: 50%;
  border: 20px solid rgba(0,0,0,0.2);
  width: 50px;
  height: 50px;
  margin-right: 20px;
 background-image: radial-gradient(circle closest-side, white calc(100% - 4px), red 100%); }

<div class="container">
  <div class="radio radio4"></div>
</div>

The background is drawn on the padding box then it's getting repeated over all the area (border box).

If you disable the repeat you will have this:

.container {
  background: #ddd;
  width: 400px;
  height: 200px;
  padding: 20px;
}

.radio {
  display: inline-block;
  background: white;
  border-radius: 50%;
  border: 20px solid rgba(0,0,0,0.2);
  width: 50px;
  height: 50px;
  margin-right: 20px;
 background-image: radial-gradient(circle closest-side, white calc(100% - 4px), red 100%);
  background-repeat:no-repeat;
 }

<div class="container">
  <div class="radio"></div>
</div>

Here is if we repeat only on the X axis

.container {
  background: #ddd;
  width: 400px;
  height: 200px;
  padding: 20px;
}

.radio {
  display: inline-block;
  background: white;
  border-radius: 50%;
  border: 20px solid rgba(0,0,0,0.2);
  width: 50px;
  height: 50px;
  margin-right: 20px;
 background-image: radial-gradient(circle closest-side, white calc(100% - 4px), red 100%);
  background-repeat:repeat-x;
 }

<div class="container">
  <div class="radio"></div>
</div>

And here is what is happening when using 100% for both colors which is similar to your situation and you will better understand why you have coloration only on the corners.

.container {
  background: #ddd;
  padding: 20px;
}

.radio {
  display: inline-block;
  background: white;
  border-radius: 50%;
  border: 20px solid rgba(0, 0, 0, 0.2);
  width: 50px;
  height: 50px;
  margin-right: 20px;
  background-image: radial-gradient(circle closest-side, white 100%, red 100%);
}

.one {
  background-repeat: no-repeat;
}

.two {
  background-repeat: repeat;
}

.three {
  border-width: 5px;
}
.four {
  width:20px;
  height:20px;
  border-width: 2px;
}

<div class="container">
  <div class="radio one"></div>
  <div class="radio two"></div>
  <div class="radio three"></div>
  <div class="radio four"></div>
</div>

And if we change the origin it's fine:

.container {
  background: #ddd;
  width: 400px;
  height: 200px;
  padding: 20px;
}

.radio {
  display: inline-block;
  background: white;
  border-radius: 50%;
  border: 20px solid rgba(0,0,0,0.2);
  width: 50px;
  height: 50px;
  margin-right: 20px;
 background-image: radial-gradient(circle closest-side, white calc(100% - 4px), red 100%);
  background-origin:border-box;
 }

<div class="container">
  <div class="radio"></div>
</div>


问:
Laravel non-recursive toArray()
Attempting to do both hasMany() and hasOne() relationships between the two tables as I've done before.

I have an Account model which has both users() (one-to-many) and a superUser() (one-to-one), both of which are stored in the built-in User model.  As with normal one-to-many relationships, the "many" table (users) stores the relationship to the "one", but for the one-to-one relationship, I'm storing the association in the accounts table.

Accounts:

/* model */
public function superUser()
{
    return $this->hasOne(User::class, 'id', 'superuser_id');
}

public function users()
{
    return $this->hasMany(User::class);
}

/* migration */
public function up()
{
    Schema::create('accounts', function (Blueprint $table) {
        $table->bigIncrements('id');
        $table->bigInteger('superuser_id')->unsigned();
        $table->string('name');
        $table->timestamps();

        $table->foreign('superuser_id')
            ->references('id')
            ->on('users')
            ->onDelete('cascade');
    });
}
```

<p>Users</p>

<pre class="lang-php prettyprint-override"><code>/* model */
public function account()
{
    return $this->belongsTo(Account::class);
}

/* migration */
public function up()
{
    Schema::create('users', function (Blueprint $table) {
        $table->bigIncrements('id');
        $table->bigInteger('account_id')->unsigned()->index()->nullable();
        $table->string('name');
        $table->string('email')->unique();
        $table->timestamp('email_verified_at')->nullable();
        $table->string('password');
        $table->rememberToken();
        $table->timestamps();
    });
}
</code>```

Testing the relationships

Create a user:

>>> $user = factory(App\User::class)->create()
=> App\User {#3014
     name: "Rose Grant II",
     email: "ernser.thomas@example.com",
     email_verified_at: "2019-05-31 15:38:32",
     updated_at: "2019-05-31 15:38:32",
     created_at: "2019-05-31 15:38:32",
     id: 23,
   }
```

<p>Create an account with <code>$user</code> as superuser:</p>

<pre class="lang-php prettyprint-override"><code>>>> $account = factory(App\Account::class)->create(['superuser_id' => $user]);
=> App\Account {#3024
     name: "Kuhic-Price",
     superuser_id: 23,
     updated_at: "2019-05-31 15:39:11",
     created_at: "2019-05-31 15:39:11",
     id: 17,
   }
>>> $account->superUser
=> App\User {#3011
     id: 23,
     account_id: null,
     name: "Rose Grant II",
     email: "ernser.thomas@example.com",
     email_verified_at: "2019-05-31 15:38:32",
     api_token: null,
     created_at: "2019-05-31 15:38:32",
     updated_at: "2019-05-31 15:38:32",
   }
</code>```

account_id is null because we haven't yet associated $user to the Account:

>>> $account->superUser->account()->associate($account)->save()
=> true
>>> $account->superUser
=> App\User {#3011
     id: 23,
     account_id: 17,
     name: "Rose Grant II",
     email: "ernser.thomas@example.com",
     email_verified_at: "2019-05-31 15:38:32",
     api_token: null,
     created_at: "2019-05-31 15:38:32",
     updated_at: "2019-05-31 15:43:55",
     account: App\Account {#3024
       name: "Kuhic-Price",
       superuser_id: 23,
       updated_at: "2019-05-31 15:39:11",
       created_at: "2019-05-31 15:39:11",
       id: 17,
       superUser: App\User {#3011},
     },
   }
```

<p>But once we do this, it hangs:</p>

<pre class="lang-php prettyprint-override"><code>>>> $account->toArray()
^C
</code>```

I'm thinking that this is due to each model pointing towards the other: the superuser of the Account loads the User which loads the Account ad infinitum.  Is this a bug in toArray() or simply normal behavior that I have to watch out for?  Or am I doing it wrong?

答:
In the Laravel codebase, toArray() is a convenience function merging the results of attributesToArray() and relationsToArray() into a single merged array:

```<code>public function toArray()
{
    return array_merge($this->attributesToArray(), $this->relationsToArray());
}
</code>```

As I suspected, relationsToArray() calls toArray() on every arrayable relationship, causing the infinite recursion:

```<code>public function relationsToArray()
{
    $attributes = [];

    foreach ($this->getArrayableRelations() as $key => $value) {
        // If the values implements the Arrayable interface we can just call this
        // toArray method on the instances which will convert both models and
        // collections to their proper array form and we'll set the values.
        if ($value instanceof Arrayable) {
            $relation = $value->toArray();   // <-- here's the recursive call
        }

    ...
</code>```

If all that is needed is the attributes (as in my case), calling attributesToArray() on the model is a good workaround:

>>> $account->attributesToArray()
=> [
     "name" => "Kuhic-Price",
     "superuser_id" => 23,
     "updated_at" => "2019-05-31 15:39:11",
     "created_at" => "2019-05-31 15:39:11",
     "id" => 17,
   ]
```

EDIT: Also this behavior is by design, as the documentation explicitly states recursion:

This method is recursive, so all attributes and all relations (including the relations of relations) will be converted to arrays (emphasis mine)

Title: Laravel non-recursive toArray()

Body:
Attempting to do both hasMany() and hasOne() relationships between the two tables as I've done before.

I have an Account model which has both users() (one-to-many) and a superUser() (one-to-one), both of which are stored in the built-in User model.  As with normal one-to-many relationships, the "many" table (users) stores the relationship to the "one", but for the one-to-one relationship, I'm storing the association in the accounts table.

Accounts:

/* model */
public function superUser()
{
    return $this->hasOne(User::class, 'id', 'superuser_id');
}

public function users()
{
    return $this->hasMany(User::class);
}

/* migration */
public function up()
{
    Schema::create('accounts', function (Blueprint $table) {
        $table->bigIncrements('id');
        $table->bigInteger('superuser_id')->unsigned();
        $table->string('name');
        $table->timestamps();

        $table->foreign('superuser_id')
            ->references('id')
            ->on('users')
            ->onDelete('cascade');
    });
}

Users

/* model */
public function account()
{
    return $this->belongsTo(Account::class);
}

/* migration */
public function up()
{
    Schema::create('users', function (Blueprint $table) {
        $table->bigIncrements('id');
        $table->bigInteger('account_id')->unsigned()->index()->nullable();
        $table->string('name');
        $table->string('email')->unique();
        $table->timestamp('email_verified_at')->nullable();
        $table->string('password');
        $table->rememberToken();
        $table->timestamps();
    });
}

Testing the relationships

Create a user:

>>> $user = factory(App\User::class)->create()
=> App\User {#3014
     name: "Rose Grant II",
     email: "ernser.thomas@example.com",
     email_verified_at: "2019-05-31 15:38:32",
     updated_at: "2019-05-31 15:38:32",
     created_at: "2019-05-31 15:38:32",
     id: 23,
   }

Create an account with $user as superuser:

>>> $account = factory(App\Account::class)->create(['superuser_id' => $user]);
=> App\Account {#3024
     name: "Kuhic-Price",
     superuser_id: 23,
     updated_at: "2019-05-31 15:39:11",
     created_at: "2019-05-31 15:39:11",
     id: 17,
   }
>>> $account->superUser
=> App\User {#3011
     id: 23,
     account_id: null,
     name: "Rose Grant II",
     email: "ernser.thomas@example.com",
     email_verified_at: "2019-05-31 15:38:32",
     api_token: null,
     created_at: "2019-05-31 15:38:32",
     updated_at: "2019-05-31 15:38:32",
   }

account_id is null because we haven't yet associated $user to the Account:

>>> $account->superUser->account()->associate($account)->save()
=> true
>>> $account->superUser
=> App\User {#3011
     id: 23,
     account_id: 17,
     name: "Rose Grant II",
     email: "ernser.thomas@example.com",
     email_verified_at: "2019-05-31 15:38:32",
     api_token: null,
     created_at: "2019-05-31 15:38:32",
     updated_at: "2019-05-31 15:43:55",
     account: App\Account {#3024
       name: "Kuhic-Price",
       superuser_id: 23,
       updated_at: "2019-05-31 15:39:11",
       created_at: "2019-05-31 15:39:11",
       id: 17,
       superUser: App\User {#3011},
     },
   }

But once we do this, it hangs:

>>> $account->toArray()
^C

I'm thinking that this is due to each model pointing towards the other: the superuser of the Account loads the User which loads the Account ad infinitum.  Is this a bug in toArray() or simply normal behavior that I have to watch out for?  Or am I doing it wrong?

Body:
In the Laravel codebase, toArray() is a convenience function merging the results of attributesToArray() and relationsToArray() into a single merged array:

public function toArray()
{
    return array_merge($this->attributesToArray(), $this->relationsToArray());
}

As I suspected, relationsToArray() calls toArray() on every arrayable relationship, causing the infinite recursion:

public function relationsToArray()
{
    $attributes = [];

    foreach ($this->getArrayableRelations() as $key => $value) {
        // If the values implements the Arrayable interface we can just call this
        // toArray method on the instances which will convert both models and
        // collections to their proper array form and we'll set the values.
        if ($value instanceof Arrayable) {
            $relation = $value->toArray();   // <-- here's the recursive call
        }

    ...

If all that is needed is the attributes (as in my case), calling attributesToArray() on the model is a good workaround:

>>> $account->attributesToArray()
=> [
     "name" => "Kuhic-Price",
     "superuser_id" => 23,
     "updated_at" => "2019-05-31 15:39:11",
     "created_at" => "2019-05-31 15:39:11",
     "id" => 17,
   ]

EDIT: Also this behavior is by design, as the documentation explicitly states recursion:

This method is recursive, so all attributes and all relations (including the relations of relations) will be converted to arrays (emphasis mine)


问:
targetSdkVersion vs. minSdkVersion: configChanges
I want to avoid Activity restarts when screen orientation changes. In older sdk versions it was done by configChanges="orientation" (in the manifest). In newer versions screenSize was added.

My minSdk is 8, the targetSdk is 17 and I find myself in a weird situation: I cannot put screenSize into configChanges (because of the minSdk) but my phone (4.1) will then destroy any activity on orientation change (because of the targetSdk).

Is there any way out? Can I somehow prevent this destruction without having to target an outdated Sdk (but still keeping it as an option in the minSdk)?

答:
You may leave your android:minSdkVersion and android:targetSdkVersion as you currently have them (8 and 17 in your example).

In order to be able to put screenSize into configChanges, change this line

target=android-someapinumber

in the project.properties file. Choose someapinumber as the android version where screenSize first appeared (e.g., API 13).

Although you asked for a specific "screenSize" problem, this solution applies to all similar situations where you want to support older devices, but at the same time you must use newer features. In this particular case, "screenSize" will be ignored by older devices that do not know this property, so you don't have to worry about backward compatibility. In other cases, you may have to add conditions in your source code like shown below to ensure in runtime that your app will not use features that are not available in a given (older) android version.

```<code>if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP)
{
    // Code that uses features available in LOLLIPOP and newer
    // versions of android, while the app also runs on older versions
    // and supports them because of android:minSdkVersion.
}
</code>```

Body:
You may leave your android:minSdkVersion and android:targetSdkVersion as you currently have them (8 and 17 in your example).

In order to be able to put screenSize into configChanges, change this line

target=android-someapinumber

in the project.properties file. Choose someapinumber as the android version where screenSize first appeared (e.g., API 13).

Although you asked for a specific "screenSize" problem, this solution applies to all similar situations where you want to support older devices, but at the same time you must use newer features. In this particular case, "screenSize" will be ignored by older devices that do not know this property, so you don't have to worry about backward compatibility. In other cases, you may have to add conditions in your source code like shown below to ensure in runtime that your app will not use features that are not available in a given (older) android version.

if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP)
{
    // Code that uses features available in LOLLIPOP and newer
    // versions of android, while the app also runs on older versions
    // and supports them because of android:minSdkVersion.
}


问:
How can I delete rows from a database table where the ID isn't found in a tuple/list
Say I have a tuple of IDs:

```<code>ids = (1,2,3,4,5)
</code>```

Using python, I want to delete every row from a database table (called schedule) that doesn't contain one of these IDs.

This is what I've tried:

```<code>delete_stmt = "DELETE from schedule WHERE ID NOT IN %s"
...
cursor.execute(delete_stmt, ids)
</code>```

I've excluded the unnecessary code like connecting to the database, but I am connected properly.

I get an error message saying:

```<code>You have an error in your SQL syntax...
</code>```

How can I fix my code to delete rows from the schedule table that aren't found in the ids tuple?

答:
IN is a MySql Function, try it with ()</p>

```<code>delete_stmt = "DELETE from schedule WHERE ID NOT IN (%s)"
</code>```

Body:
Say I have a tuple of IDs:

ids = (1,2,3,4,5)

Using python, I want to delete every row from a database table (called schedule) that doesn't contain one of these IDs.

This is what I've tried:

delete_stmt = "DELETE from schedule WHERE ID NOT IN %s"
...
cursor.execute(delete_stmt, ids)

I've excluded the unnecessary code like connecting to the database, but I am connected properly.

I get an error message saying:

You have an error in your SQL syntax...

How can I fix my code to delete rows from the schedule table that aren't found in the ids tuple?

Body:
IN is a MySql Function, try it with ()

delete_stmt = "DELETE from schedule WHERE ID NOT IN (%s)"