问:
Same results are getting updated in all rows by using where clause in SQL Server
I'm running a stored procedure inside a foreach loop in c#. After completion, all the rows of a column are getting updated with the top most value. Below is the stored procedure:

```<code>ALTER PROCEDURE [dbo].[getservername8]
    @number varchar(255)
AS
    DECLARE @server_name varchar(500)

    SELECT @server_name = short_description
    FROM [Event_alerts].[dbo].[event_alerts]

    DECLARE @s AS varchar(50)

    SELECT @s = SUBSTRING(@server_name, CHARINDEX('-', @server_name) + 15, 50)

    UPDATE event_alerts
    SET server_name = @s
    WHERE number = @number
</code>```

This is the C# code:

```<code>using (SqlCommand command2 = new SqlCommand("getservername8", conn))
{
    command2.CommandType = CommandType.StoredProcedure;

    command2.Parameters.AddWithValue("@number",number);
    command2.Parameters["@number"].Direction = ParameterDirection.Input;

    command2.ExecuteNonQuery();
}
</code>```

Any help would be much appreciated

答:
The culprit is because you are getting the same value of @server_name for each call. So   @s si also same for all. that is why you are inserting the same value in the column

```<code>select  @server_name = short_description from [Event_alerts].[dbo].[event_alerts]
declare @s as varchar(50)
select @s= SUBSTRING(@server_name, CHARINDEX('-', @server_name) + 15, 50)
</code>```

Body:
I'm running a stored procedure inside a foreach loop in c#. After completion, all the rows of a column are getting updated with the top most value. Below is the stored procedure:

ALTER PROCEDURE [dbo].[getservername8]
    @number varchar(255)
AS
    DECLARE @server_name varchar(500)

    SELECT @server_name = short_description
    FROM [Event_alerts].[dbo].[event_alerts]

    DECLARE @s AS varchar(50)

    SELECT @s = SUBSTRING(@server_name, CHARINDEX('-', @server_name) + 15, 50)

    UPDATE event_alerts
    SET server_name = @s
    WHERE number = @number

This is the C# code:

using (SqlCommand command2 = new SqlCommand("getservername8", conn))
{
    command2.CommandType = CommandType.StoredProcedure;

    command2.Parameters.AddWithValue("@number",number);
    command2.Parameters["@number"].Direction = ParameterDirection.Input;

    command2.ExecuteNonQuery();
}

Any help would be much appreciated

Body:
The culprit is because you are getting the same value of @server_name for each call. So   @s si also same for all. that is why you are inserting the same value in the column

select  @server_name = short_description from [Event_alerts].[dbo].[event_alerts]
declare @s as varchar(50)
select @s= SUBSTRING(@server_name, CHARINDEX('-', @server_name) + 15, 50)


来源: stackexchange

问:
How to replace missing entries of a column in one data frame with entries from other data frame in python?
There are two data frames df1 and df2. Two columns in df1 are A and B. There are missing values in B. For the missing values in B in df1, there are entries in df2 and its columns are A and B (The records in df2 are the ones which are missing in B of df1 only). I want to replace the missing values of B in df1 with corresponding entry of B from df2.

EDIT :

```<code>df1 = pd.DataFrame({'A': [1,2,3,4,5,6,7,8], 'b': [101,123,np.nan,678,np.nan,672,np.nan,786], 'C': ['ABC', 'DER', 'ERC','DFE','HJI','JKL','SDH',np.Nan]})

df2 = pd.DataFrame({'A': [3,7], 'B': [563,785]})
</code>```

Desired O/P:

```<code>op = pd.DataFrame({'A': [1,2,3,4,5,6,7,8], 'b': [101,123,563,678,np.nan,672,785,786], 'C': ['ABC', 'DER', 'ERC','DFE','HJI','JKL','SDH',np.Nan]})
</code>```

答:
Use, pd.merge to left merge the dataframes df1 & df2 on column A, then using Series.fillna fill the missing values in column b from the values in column B:

```<code>df = pd.merge(df1, df2, on='A', how='left')
df['b'] = df['b'].fillna(df.pop('B'))
</code>```

Result:

```<code># print(df)
   A      b    C
0  1  101.0  ABC
1  2  123.0  DER
2  3  563.0  ERC
3  4  678.0  DFE
4  5    NaN  HJI
5  6  672.0  JKL
6  7  785.0  SDH
7  8  786.0  NaN
</code>```

ContentLicense: CC BY-SA 4.0

Body:
There are two data frames df1 and df2. Two columns in df1 are A and B. There are missing values in B. For the missing values in B in df1, there are entries in df2 and its columns are A and B (The records in df2 are the ones which are missing in B of df1 only). I want to replace the missing values of B in df1 with corresponding entry of B from df2.

EDIT :

df1 = pd.DataFrame({'A': [1,2,3,4,5,6,7,8], 'b': [101,123,np.nan,678,np.nan,672,np.nan,786], 'C': ['ABC', 'DER', 'ERC','DFE','HJI','JKL','SDH',np.Nan]})

df2 = pd.DataFrame({'A': [3,7], 'B': [563,785]})

Desired O/P:

op = pd.DataFrame({'A': [1,2,3,4,5,6,7,8], 'b': [101,123,563,678,np.nan,672,785,786], 'C': ['ABC', 'DER', 'ERC','DFE','HJI','JKL','SDH',np.Nan]})

Body:
Use, pd.merge to left merge the dataframes df1 & df2 on column A, then using Series.fillna fill the missing values in column b from the values in column B:

df = pd.merge(df1, df2, on='A', how='left')
df['b'] = df['b'].fillna(df.pop('B'))

Result:

# print(df)
   A      b    C
0  1  101.0  ABC
1  2  123.0  DER
2  3  563.0  ERC
3  4  678.0  DFE
4  5    NaN  HJI
5  6  672.0  JKL
6  7  785.0  SDH
7  8  786.0  NaN


问:
overflow:hidden not working in colgroups for very long cells
I have searched for quite a bit in stackoverflow and google. But failed to find a solution.
I have a 11 column table, of which the first column can get long text (without spaces). I have adapted to colgroup approach but it is not working for me.

.mytable {
  table-layout: fixed;
  width: 1000px;
}

th,
td {
  padding: 5px;
}

.ten {
  width: 100px;
  overflow: hidden;
}

.others {
  font-size: 13px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><table border=1 class="mytable">

  <colgroup>
    <col class="ten" />
    <col class="others" />
    <col class="others" />
    <col class="others" />
    <col class="others" />
    <col class="others" />
    <col class="others" />
    <col class="others" />
    <col class="others" />
    <col class="others" />
    <col class="others" />
  </colgroup>

  <thead>
    <tr>
      <th>VERY LONG COLUMN</th>
      <th>A</th>
      <th>B</th>
      <th>C</th>
      <th>D</th>
      <th>E</th>
      <th>F</th>
      <th>G</th>
      <th>H</th>
      <th>I</th>
      <th>J</th>

    </tr>
  </thead>
  <tbody>
    <tr>
      <td>looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong</td>
      <td>not so long</td>
      <td>small</td>
      <td>small</td>
      <td>small</td>
      <td>small</td>
      <td>small</td>
      <td>small</td>
      <td>small</td>
      <td>small</td>
      <td>small</td>
    </tr>
    <tr>
      <td>looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong</td>
      <td>not so long</td>
      <td>small</td>
      <td>small</td>
      <td>small</td>
      <td>small</td>
      <td>small</td>
      <td>small</td>
      <td>small</td>
      <td>small</td>
      <td>small</td>
    </tr>
    <tr>
      <td>looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong</td>
      <td>not so long</td>
      <td>small</td>
      <td>small</td>
      <td>small</td>
      <td>small</td>
      <td>small</td>
      <td>small</td>
      <td>small</td>
      <td>small</td>
      <td>small</td>
    </tr>
    <tr>
      <td>looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong</td>
      <td>not so long</td>
      <td>small</td>
      <td>small</td>
      <td>small</td>
      <td>small</td>
      <td>small</td>
      <td>small</td>
      <td>small</td>
      <td>small</td>
      <td>small</td>
    </tr>
    <tr>
      <td>looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong</td>
      <td>not so long</td>
      <td>small</td>
      <td>small</td>
      <td>small</td>
      <td>small</td>
      <td>small</td>
      <td>small</td>
      <td>small</td>
      <td>small</td>
      <td>small</td>
    </tr>
  </tbody>
</table></code>```

I need to have a fixed width table. And I am looking for a solution where i can wrap the text. I tried with word-wrap: break-word; but it gives me the exact output.
Any help is much appreciated.

Solutions I have tried:

Word-wrap in an HTML table

how-do-i-wrap-text-with-no-whitespace-inside-a-td

答:
Use word-wrap: break-all instead:

.mytable {
  table-layout: fixed;
  width: 1000px;
}

th,
td {
  padding: 5px;
  word-break: break-all;
}

.ten {
  width: 100px;
  overflow: hidden;
}

.others {
  font-size: 13px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><table border=1 class="mytable">

  <colgroup>
    <col class="ten" />
    <col class="others" />
    <col class="others" />
    <col class="others" />
    <col class="others" />
    <col class="others" />
    <col class="others" />
    <col class="others" />
    <col class="others" />
    <col class="others" />
    <col class="others" />
  </colgroup>

  <thead>
    <tr>
      <th>VERY LONG COLUMN</th>
      <th>A</th>
      <th>B</th>
      <th>C</th>
      <th>D</th>
      <th>E</th>
      <th>F</th>
      <th>G</th>
      <th>H</th>
      <th>I</th>
      <th>J</th>

    </tr>
  </thead>
  <tbody>
    <tr>
      <td>looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong</td>
      <td>not so long</td>
      <td>small</td>
      <td>small</td>
      <td>small</td>
      <td>small</td>
      <td>small</td>
      <td>small</td>
      <td>small</td>
      <td>small</td>
      <td>small</td>
    </tr>
    <tr>
      <td>looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong</td>
      <td>not so long</td>
      <td>small</td>
      <td>small</td>
      <td>small</td>
      <td>small</td>
      <td>small</td>
      <td>small</td>
      <td>small</td>
      <td>small</td>
      <td>small</td>
    </tr>
    <tr>
      <td>looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong</td>
      <td>not so long</td>
      <td>small</td>
      <td>small</td>
      <td>small</td>
      <td>small</td>
      <td>small</td>
      <td>small</td>
      <td>small</td>
      <td>small</td>
      <td>small</td>
    </tr>
    <tr>
      <td>looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong</td>
      <td>not so long</td>
      <td>small</td>
      <td>small</td>
      <td>small</td>
      <td>small</td>
      <td>small</td>
      <td>small</td>
      <td>small</td>
      <td>small</td>
      <td>small</td>
    </tr>
    <tr>
      <td>looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong</td>
      <td>not so long</td>
      <td>small</td>
      <td>small</td>
      <td>small</td>
      <td>small</td>
      <td>small</td>
      <td>small</td>
      <td>small</td>
      <td>small</td>
      <td>small</td>
    </tr>
  </tbody>
</table></code>```

Body:
I have searched for quite a bit in stackoverflow and google. But failed to find a solution.
I have a 11 column table, of which the first column can get long text (without spaces). I have adapted to colgroup approach but it is not working for me.

.mytable {
  table-layout: fixed;
  width: 1000px;
}

th,
td {
  padding: 5px;
}

.ten {
  width: 100px;
  overflow: hidden;
}

.others {
  font-size: 13px;
}

  <colgroup>
    <col class="ten" />
    <col class="others" />
    <col class="others" />
    <col class="others" />
    <col class="others" />
    <col class="others" />
    <col class="others" />
    <col class="others" />
    <col class="others" />
    <col class="others" />
    <col class="others" />
  </colgroup>

      VERY LONG COLUMN
      A
      B
      C
      D
      E
      F
      G
      H
      I
      J

      looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong
      not so long
      small
      small
      small
      small
      small
      small
      small
      small
      small

      looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong
      not so long
      small
      small
      small
      small
      small
      small
      small
      small
      small

      looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong
      not so long
      small
      small
      small
      small
      small
      small
      small
      small
      small

      looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong
      not so long
      small
      small
      small
      small
      small
      small
      small
      small
      small

      looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong
      not so long
      small
      small
      small
      small
      small
      small
      small
      small
      small

I need to have a fixed width table. And I am looking for a solution where i can wrap the text. I tried with word-wrap: break-word; but it gives me the exact output.
Any help is much appreciated.

Solutions I have tried:

Word-wrap in an HTML table

how-do-i-wrap-text-with-no-whitespace-inside-a-td

Body:
Use word-wrap: break-all instead:

.mytable {
  table-layout: fixed;
  width: 1000px;
}

th,
td {
  padding: 5px;
  word-break: break-all;
}

.ten {
  width: 100px;
  overflow: hidden;
}

.others {
  font-size: 13px;
}

<table border=1 class="mytable">

  <colgroup>
    <col class="ten" />
    <col class="others" />
    <col class="others" />
    <col class="others" />
    <col class="others" />
    <col class="others" />
    <col class="others" />
    <col class="others" />
    <col class="others" />
    <col class="others" />
    <col class="others" />
  </colgroup>

  <thead>
    <tr>
      <th>VERY LONG COLUMN</th>
      <th>A</th>
      <th>B</th>
      <th>C</th>
      <th>D</th>
      <th>E</th>
      <th>F</th>
      <th>G</th>
      <th>H</th>
      <th>I</th>
      <th>J</th>

    </tr>
  </thead>
  <tbody>
    <tr>
      <td>looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong</td>
      <td>not so long</td>
      <td>small</td>
      <td>small</td>
      <td>small</td>
      <td>small</td>
      <td>small</td>
      <td>small</td>
      <td>small</td>
      <td>small</td>
      <td>small</td>
    </tr>
    <tr>
      <td>looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong</td>
      <td>not so long</td>
      <td>small</td>
      <td>small</td>
      <td>small</td>
      <td>small</td>
      <td>small</td>
      <td>small</td>
      <td>small</td>
      <td>small</td>
      <td>small</td>
    </tr>
    <tr>
      <td>looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong</td>
      <td>not so long</td>
      <td>small</td>
      <td>small</td>
      <td>small</td>
      <td>small</td>
      <td>small</td>
      <td>small</td>
      <td>small</td>
      <td>small</td>
      <td>small</td>
    </tr>
    <tr>
      <td>looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong</td>
      <td>not so long</td>
      <td>small</td>
      <td>small</td>
      <td>small</td>
      <td>small</td>
      <td>small</td>
      <td>small</td>
      <td>small</td>
      <td>small</td>
      <td>small</td>
    </tr>
    <tr>
      <td>looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong</td>
      <td>not so long</td>
      <td>small</td>
      <td>small</td>
      <td>small</td>
      <td>small</td>
      <td>small</td>
      <td>small</td>
      <td>small</td>
      <td>small</td>
      <td>small</td>
    </tr>
  </tbody>
</table>


问:
How to create a set with pair of consecutive operations gams
Hi I am resolving a scheduling problem and I don't know how to put a set with pair of consecutive operations of a job as it says on the images:

how could i code this in gams?

答:
I believe that this might help:

```<code>
Set a       "operations"     / 1, 2, 3 /
    b       "operations"     / 1, 2, 3 /
    in(a,b) "Mapping all to all" / #a.#b /
    in2(a,b) "Selection of pairs of operations" ;
    in2(a,b)$(ord(b)=ord(a)+1)=yes;

display in, in2;

</code>```

Here are the resulting sets:

It might be possible for you to make the code more efficient, but at least it works :)
For more information you might want to check the GAMS documentation pages:
Set Definition_Multi-dimensional Sets and
Dynamic sets_ Dollar Control Indexed Operations. (the ones I used)

Body:
I believe that this might help:

Set a       "operations"     / 1, 2, 3 /
    b       "operations"     / 1, 2, 3 /
    in(a,b) "Mapping all to all" / #a.#b /
    in2(a,b) "Selection of pairs of operations" ;
    in2(a,b)$(ord(b)=ord(a)+1)=yes;

display in, in2;

Here are the resulting sets:

It might be possible for you to make the code more efficient, but at least it works :)
For more information you might want to check the GAMS documentation pages:
Set Definition_Multi-dimensional Sets and
Dynamic sets_ Dollar Control Indexed Operations. (the ones I used)


问:
Android EditText requestFocus
I want to create to do items (radio button's) dynamically. So i create linear layout with horizontal orientation and push radioButton and editText to it, and i need to set focus on this EditText. I try to use method requestFocus() but in my case it doesn't work. Am I doing something wrong?</p>

```<code>btnToDo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                LinearLayout llNew= new LinearLayout(NewNote.this);
                llNew.setOrientation(LinearLayout.HORIZONTAL);
                RadioButton rbNew= new RadioButton(NewNote.this);
                rbNew.setPadding(10,0,10,0);

                //set radio button color:
                if(Build.VERSION.SDK_INT>=21)
                {
                    ColorStateList colorStateList = new ColorStateList(
                            new int[][]{
                                    new int[]{-android.R.attr.state_enabled}, //disabled
                                    new int[]{android.R.attr.state_enabled} //enabled
                            },
                            new int[] {
                                    Color.BLACK //disabled
                                    ,Color.BLACK //enabled
                            }
                    );
                    rbNew.setButtonTintList(colorStateList);//set the color tint list
                    rbNew.invalidate(); //could not be necessary
                }

                final EditText edNew = new EditText(NewNote.this);
                edNew.setTypeface(typefaceDunkin);
                edNew.setTextSize(25);
                edNew.setText("Some text");
                edNew.setBackgroundColor(Color.WHITE);

                edNew.requestFocus(); //HERE

                //cross text after click on radio button
                rbNew.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        edNew.setPaintFlags(edNew.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG);
                    }
                });

                llNew.addView(rbNew);
                llNew.addView(edNew);
                content.addView(llNew);
                scrollViewDown();
            }
        });```
</code>```

答:
add these line after call requestFocus:</p>

```<code>  edNew.requestFocus();
  InputMethodManager im= (InputMethodManager)
                        getSystemService(Context.INPUT_METHOD_SERVICE);
  im.showSoftInput(edNew, InputMethodManager.SHOW_IMPLICIT);
</code>```

Title: Android EditText requestFocus

Body:
I want to create to do items (radio button's) dynamically. So i create linear layout with horizontal orientation and push radioButton and editText to it, and i need to set focus on this EditText. I try to use method requestFocus() but in my case it doesn't work. Am I doing something wrong?

btnToDo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                LinearLayout llNew= new LinearLayout(NewNote.this);
                llNew.setOrientation(LinearLayout.HORIZONTAL);
                RadioButton rbNew= new RadioButton(NewNote.this);
                rbNew.setPadding(10,0,10,0);

                //set radio button color:
                if(Build.VERSION.SDK_INT>=21)
                {
                    ColorStateList colorStateList = new ColorStateList(
                            new int[][]{
                                    new int[]{-android.R.attr.state_enabled}, //disabled
                                    new int[]{android.R.attr.state_enabled} //enabled
                            },
                            new int[] {
                                    Color.BLACK //disabled
                                    ,Color.BLACK //enabled
                            }
                    );
                    rbNew.setButtonTintList(colorStateList);//set the color tint list
                    rbNew.invalidate(); //could not be necessary
                }

                final EditText edNew = new EditText(NewNote.this);
                edNew.setTypeface(typefaceDunkin);
                edNew.setTextSize(25);
                edNew.setText("Some text");
                edNew.setBackgroundColor(Color.WHITE);

                edNew.requestFocus(); //HERE

                //cross text after click on radio button
                rbNew.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        edNew.setPaintFlags(edNew.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG);
                    }
                });

                llNew.addView(rbNew);
                llNew.addView(edNew);
                content.addView(llNew);
                scrollViewDown();
            }
        });```

Body:
add these line after call requestFocus:

  edNew.requestFocus();
  InputMethodManager im= (InputMethodManager)
                        getSystemService(Context.INPUT_METHOD_SERVICE);
  im.showSoftInput(edNew, InputMethodManager.SHOW_IMPLICIT);


问:
Creating a maze graph from a text file : Java
I need to make a graph from a text file containing multiple 'mazes' represented as adjacency lists. The list is as follows:

```<code>A,G
A,B,F
B,A,C,G
C,B,D,G
D,C,E
E,D,F,G
F,A,E
G,B,C,E

D,F
A,B,G
B,A,C,E,G
C,B,D,E,G
D,C
E,B,C,G
F,G
G,A,B,C,E,F

F,A
A,B,G
B,A,G
C,D,G
D,C,G
E,F,G
F,E,G
G,A,B,C,D,E,F
</code>```

The first line of each 'maze' contains the starting node of the maze (first letter) and the ending node of the maze (second letter).

I've parsed the text file into an ArrayList of all lines (including blank lines), then into an ArrayList of ArrayLists of lines (a list of separate mazes). I did this by splitting the complete text on blank lines. My problem is now that I cannot figure out how to use my node class to construct a graph from these 'mazes'. Here's my node class:

```<code>package algo2;

import java.util.ArrayList;

public class Node<T>{

    private T value; //this Node<T>'s value
    public ArrayList<Node<T>> connections;
    public boolean isStart;
    public boolean isEnd;
    public boolean visited;

    public Node(T value){
        this.value = value;
        connections = new ArrayList<Node<T>>();
    }

    //returns the value of this Node<T>
    public T getValue(){
        return value;
    }

    //returns true if the node is connected to any other nodes
    public boolean isConnected(){
        if(connections == null){
            return false;
        }
        return true;
    }

    //returns a list of nodes connected to this node
    public ArrayList<Node<T>> getConnections(){
        return connections;
    }

    //sets the node's value
    public void setValue(T value){
        this.value = value;
    }

    //adds a connection from this node to the passed node
    public void connect(Node<T> node){
        connections.add(node);
    }

    public String toString(){
        return value+"";
    }
}
</code>```

Can someone point me in the right direction, please?

答:
One solution would be to use split() on the input with an appropriate Node constructor (note that I have substituted String for the parameter T for simplicity):

```<code>class Node {
    public String value;
    public String[] connections;
    public boolean visited;

    public Node (String value, String[] connections) {
        this.value = value;
        this.connections = connections;
        visited = false;
    }

    public boolean isConnected(Node that) {
        boolean res = false;
        for (int i=0; !res && i<this.connections.length; i++) {
            res = (this.connections[i] == that.value);
        }
        return res;
    }

    // more stuff ... :)
}

//read start, end nodes

ArrayList<Node> nodes = new ArrayList<Node>();
for (each line in maze) {
    String[] nodeList = line.split(",");
    nodes.add(nodeList[0], Arrays.copyOfRange(nodeList, 1, nodeList.length));
}
</code>```

I think this would be simpler than trying to maintain a list of Nodes inside each Node, as long as the rest of your application makes it easy to simply check if two Nodes are connected or if one has been visited.  (also note that you would probably want to add more code to the Node class to keep track of the start and end nodes.)

ContentLicense: CC BY-SA 3.0

Body:
I need to make a graph from a text file containing multiple 'mazes' represented as adjacency lists. The list is as follows:

A,G
A,B,F
B,A,C,G
C,B,D,G
D,C,E
E,D,F,G
F,A,E
G,B,C,E

D,F
A,B,G
B,A,C,E,G
C,B,D,E,G
D,C
E,B,C,G
F,G
G,A,B,C,E,F

F,A
A,B,G
B,A,G
C,D,G
D,C,G
E,F,G
F,E,G
G,A,B,C,D,E,F

The first line of each 'maze' contains the starting node of the maze (first letter) and the ending node of the maze (second letter).

I've parsed the text file into an ArrayList of all lines (including blank lines), then into an ArrayList of ArrayLists of lines (a list of separate mazes). I did this by splitting the complete text on blank lines. My problem is now that I cannot figure out how to use my node class to construct a graph from these 'mazes'. Here's my node class:

package algo2;

import java.util.ArrayList;

public class Node<T>{

    private T value; //this Node<T>'s value
    public ArrayList<Node<T>> connections;
    public boolean isStart;
    public boolean isEnd;
    public boolean visited;

    public Node(T value){
        this.value = value;
        connections = new ArrayList<Node<T>>();
    }

    //returns the value of this Node<T>
    public T getValue(){
        return value;
    }

    //returns true if the node is connected to any other nodes
    public boolean isConnected(){
        if(connections == null){
            return false;
        }
        return true;
    }

    //returns a list of nodes connected to this node
    public ArrayList<Node<T>> getConnections(){
        return connections;
    }

    //sets the node's value
    public void setValue(T value){
        this.value = value;
    }

    //adds a connection from this node to the passed node
    public void connect(Node<T> node){
        connections.add(node);
    }

    public String toString(){
        return value+"";
    }
}

Can someone point me in the right direction, please?

Body:
One solution would be to use split() on the input with an appropriate Node constructor (note that I have substituted String for the parameter T for simplicity):

class Node {
    public String value;
    public String[] connections;
    public boolean visited;

    public Node (String value, String[] connections) {
        this.value = value;
        this.connections = connections;
        visited = false;
    }

    public boolean isConnected(Node that) {
        boolean res = false;
        for (int i=0; !res && i<this.connections.length; i++) {
            res = (this.connections[i] == that.value);
        }
        return res;
    }

    // more stuff ... :)
}

//read start, end nodes

ArrayList<Node> nodes = new ArrayList<Node>();
for (each line in maze) {
    String[] nodeList = line.split(",");
    nodes.add(nodeList[0], Arrays.copyOfRange(nodeList, 1, nodeList.length));
}

I think this would be simpler than trying to maintain a list of Nodes inside each Node, as long as the rest of your application makes it easy to simply check if two Nodes are connected or if one has been visited.  (also note that you would probably want to add more code to the Node class to keep track of the start and end nodes.)


问:
Avoiding Template operator overload collisions for float and non float on the operator first argument
I have a situation where my template modulus operator does play nice between floats and integer-ish types.
As I recall there is a way to make it select the more specific one over the broader scope one, but i can't seem to find or remember how to do this.

Basically I have 2 methods which are coliding (redefinition error.)

What I am trying to do is get the specialized modulus operator overload to be used when its the type (T_COORDS) is float, the the broader one when it's not float.

The specialized one (notice it uses the math fmod function):

```<code>template <size_t N
    , enable_if_t<N != 0 && N <= C_COORDS*N_COORDS && N % C_COORDS == 0, bool> = false>
friend Coords operator % (const Coords<float,C_COORDS,N_COORDS>& coords0, const auto (& coords1)[N])
{
  Coords<float,C_COORDS,N_COORDS> result = coords0;
  for (int i=0; i < C_COORDS*N_COORDS; i++)
      result.coords[i] = fmod(result.coords[i], coords1[i%N]);
  return result;
}
</code>```

The broader one (notice it uses the standard float modulus):

```<code>template <std::size_t N
    , std::enable_if_t<N != 0 && N <= C_COORDS*N_COORDS && N % C_COORDS == 0
    , bool> = false>
friend Coords operator % (const Coords<T_COORDS,C_COORDS,N_COORDS>& coords0, const auto (& coords1)[N])
{
  Coords<T_COORDS,C_COORDS,N_COORDS> result = coords0;
  for (int i=0; i < C_COORDS*N_COORDS; i++)
      result.coords[i] %= coords1[i%N];
  return result;
}
</code>```

Those overloads are enclosed with a Template class definition:

```<code>template <class T_COORDS, size_t C_COORDS, size_t N_COORDS>
class Coords {
public:

  T_COORDS coords[C_COORDS*N_COORDS];

  // (body in here)

};
</code>```

答:
I would keep just one of those overloads but change its for loop to this:

```<code>for (int i=0; i < C_COORDS*N_COORDS; i++)
    result.coords[i] = my_mod(result.coords[i], coords1[i%N]);
</code>```

After defining my_mod like this (in the outer scope):

```<code>template <typename T>
T my_mod(const T& x, const T& y) { return x % y; }

float my_mod(float x, float y) { return fmod(x, y); }
// maybe define it for double as well
</code>```

Body:
I have a situation where my template modulus operator does play nice between floats and integer-ish types.
As I recall there is a way to make it select the more specific one over the broader scope one, but i can't seem to find or remember how to do this.

Basically I have 2 methods which are coliding (redefinition error.)

What I am trying to do is get the specialized modulus operator overload to be used when its the type (T_COORDS) is float, the the broader one when it's not float.

The specialized one (notice it uses the math fmod function):

template <size_t N
    , enable_if_t<N != 0 && N <= C_COORDS*N_COORDS && N % C_COORDS == 0, bool> = false>
friend Coords operator % (const Coords<float,C_COORDS,N_COORDS>& coords0, const auto (& coords1)[N])
{
  Coords<float,C_COORDS,N_COORDS> result = coords0;
  for (int i=0; i < C_COORDS*N_COORDS; i++)
      result.coords[i] = fmod(result.coords[i], coords1[i%N]);
  return result;
}

The broader one (notice it uses the standard float modulus):

template <std::size_t N
    , std::enable_if_t<N != 0 && N <= C_COORDS*N_COORDS && N % C_COORDS == 0
    , bool> = false>
friend Coords operator % (const Coords<T_COORDS,C_COORDS,N_COORDS>& coords0, const auto (& coords1)[N])
{
  Coords<T_COORDS,C_COORDS,N_COORDS> result = coords0;
  for (int i=0; i < C_COORDS*N_COORDS; i++)
      result.coords[i] %= coords1[i%N];
  return result;
}

Those overloads are enclosed with a Template class definition:

template <class T_COORDS, size_t C_COORDS, size_t N_COORDS>
class Coords {
public:

  T_COORDS coords[C_COORDS*N_COORDS];

  // (body in here)

};

Body:
I would keep just one of those overloads but change its for loop to this:

for (int i=0; i < C_COORDS*N_COORDS; i++)
    result.coords[i] = my_mod(result.coords[i], coords1[i%N]);

After defining my_mod like this (in the outer scope):

template <typename T>
T my_mod(const T& x, const T& y) { return x % y; }

float my_mod(float x, float y) { return fmod(x, y); }
// maybe define it for double as well


问:
Keyboard input without upper and lower case discrimination in Python
I want to create something like this:

```<code>answer = input("What's your name?")
if answer == "Mike":
    # code
if answer == "John":
    # code
else:
    # code
</code>```

What I want to do is to write Mike or MIKE or mIke ... (and same with John) and make all of that cases True, but I don't know how to do that instead of using answer.lower(), answer.upper() ...

答:
How about do it manually by an easy list comprehension if don't use .lower() or .upper()?

```<code>def convert(s):
    return "".join(i if 65 <= ord(i) <= 90 else chr(ord(i) - 32) for i in s)

answer = input("What's your name?")
if convert(answer) == convert("Mike"):
    # code
</code>```

Body:
I want to create something like this:

answer = input("What's your name?")
if answer == "Mike":
    # code
if answer == "John":
    # code
else:
    # code

What I want to do is to write Mike or MIKE or mIke ... (and same with John) and make all of that cases True, but I don't know how to do that instead of using answer.lower(), answer.upper() ...

Body:
How about do it manually by an easy list comprehension if don't use .lower() or .upper()?

def convert(s):
    return "".join(i if 65 <= ord(i) <= 90 else chr(ord(i) - 32) for i in s)

answer = input("What's your name?")
if convert(answer) == convert("Mike"):
    # code


问:
Redirecting/Rendering different component upon validation ionic react
I'm fairly new Ionic React and trying to create an App using Ionic framework. I have a use case where I would like to redirect to another page upon a button press and validation from a function.

Here is the component I am working with

```<code>import React, { useState } from 'react';
import {
    IonContent,
    IonHeader,
    IonPage,
    IonTitle,
    IonToolbar,
    IonInput,
    IonButton,
    IonRow,
    IonCol,
    useIonViewWillEnter,
    useIonViewWillLeave,
    IonLabel
} from '@ionic/react';

import './LogIn.css'
import MainMenu from "../MainMenu";

const LogIn: React.FC<{register?: boolean; onClose?: any}> = () => {

    const [email, setEmail] = useState<string>();
    const [password, setPassword] = useState<string>();

    function handleLoginButtonPress() {
        if (validateEmail() && password !== undefined && password.trim() !== "") {
            // Network call here to check if a valid user
            console.log("valid email")
            return <MainMenu/>
        }
    }
    function validateEmail () {
        if (email !== undefined && email.trim() !== "") {
            const regexp = /^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
            return regexp.test(email);
        }
        return false;
    }

    useIonViewWillEnter(() => {
        console.log("Entering LogIn");
    });

    useIonViewWillLeave(() => {
        console.log("Exiting LogIn");
    });

    return (
        <IonPage id="loginIonPage">
            <IonHeader>
                <IonToolbar color="primary" mode="md">
                    <IonTitle class="ion-text-center">Login or Register</IonTitle>
                </IonToolbar>
            </IonHeader>

            <IonContent id="loginPage">
                <div id="loginDialog">
                    <form>
                        <IonLabel>Email</IonLabel>
                        <IonRow>
                            <IonCol id="userName">
                                <IonInput
                                    name="email"
                                    value={email}
                                    onIonChange={e => setEmail(e.detail.value!)}
                                    clearInput
                                    type="email"
                                    placeholder="Email"
                                    class="input"
                                    padding-horizontal
                                    clear-input="true"
                                    required/>
                            </IonCol>
                        </IonRow>
                        <IonLabel>Password</IonLabel>
                        <IonRow>
                            <IonCol id="password">
                                <IonInput
                                    clearInput
                                    name="password"
                                    value={password}
                                    onIonChange={e => setPassword(e.detail.value!)}
                                    type="password"
                                    placeholder="Password"
                                    class="input"
                                    padding-horizontal
                                    clear-input="true"
                                    required/>
                            </IonCol>
                        </IonRow>
                    </form>
                </div>
                <div id="buttons">
                        <IonButton
                            onClick={handleLoginButtonPress}
                            type="submit"
                            strong={true}
                            expand="full"
                            style={{ margin: 20 }}>
                            Log in
                        </IonButton>
                        <IonButton
                            routerLink="/registerUser"
                            type="submit"
                            strong={true}
                            expand="full"
                            style={{ margin: 20 }}>
                            Register
                        </IonButton>
                </div>
            </IonContent>
        </IonPage>
    );
};

export default LogIn;
</code>```

How can I redirect to another page from the function handleLoginButtonPress which is invoked upon clicking on Login button. I tried reading through ionic doc but that did not help as it redirects whenever there is button click or click on an IonElement like IonLabel.

答:
Use react-router-dom hooks
https://reacttraining.com/react-router/web/api/Hooks/usehistory

```<code>import { useHistory } from "react-router-dom";
const ExampleComponent: React.FC = () => {
  const history = useHistory();

  const handleLoginButtonPress = () => {
    history.push("/main");
  };

  return <IonButton onClick={handleLoginButtonPress}>Log in</IonButton>;
};
export default ExampleComponent;
</code>```

Body:
I'm fairly new Ionic React and trying to create an App using Ionic framework. I have a use case where I would like to redirect to another page upon a button press and validation from a function.

Here is the component I am working with

import React, { useState } from 'react';
import {
    IonContent,
    IonHeader,
    IonPage,
    IonTitle,
    IonToolbar,
    IonInput,
    IonButton,
    IonRow,
    IonCol,
    useIonViewWillEnter,
    useIonViewWillLeave,
    IonLabel
} from '@ionic/react';

import './LogIn.css'
import MainMenu from "../MainMenu";

const LogIn: React.FC<{register?: boolean; onClose?: any}> = () => {

    const [email, setEmail] = useState<string>();
    const [password, setPassword] = useState<string>();

    function handleLoginButtonPress() {
        if (validateEmail() && password !== undefined && password.trim() !== "") {
            // Network call here to check if a valid user
            console.log("valid email")
            return <MainMenu/>
        }
    }
    function validateEmail () {
        if (email !== undefined && email.trim() !== "") {
            const regexp = /^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
            return regexp.test(email);
        }
        return false;
    }

    useIonViewWillEnter(() => {
        console.log("Entering LogIn");
    });

    useIonViewWillLeave(() => {
        console.log("Exiting LogIn");
    });

    return (
        <IonPage id="loginIonPage">
            <IonHeader>
                <IonToolbar color="primary" mode="md">
                    <IonTitle class="ion-text-center">Login or Register</IonTitle>
                </IonToolbar>
            </IonHeader>

            <IonContent id="loginPage">

                    <form>
                        <IonLabel>Email</IonLabel>
                        <IonRow>
                            <IonCol id="userName">
                                <IonInput
                                    name="email"
                                    value={email}
                                    onIonChange={e => setEmail(e.detail.value!)}
                                    clearInput
                                    type="email"
                                    placeholder="Email"
                                    class="input"
                                    padding-horizontal
                                    clear-input="true"
                                    required/>
                            </IonCol>
                        </IonRow>
                        <IonLabel>Password</IonLabel>
                        <IonRow>
                            <IonCol id="password">
                                <IonInput
                                    clearInput
                                    name="password"
                                    value={password}
                                    onIonChange={e => setPassword(e.detail.value!)}
                                    type="password"
                                    placeholder="Password"
                                    class="input"
                                    padding-horizontal
                                    clear-input="true"
                                    required/>
                            </IonCol>
                        </IonRow>
                    </form>

                        <IonButton
                            onClick={handleLoginButtonPress}
                            type="submit"
                            strong={true}
                            expand="full"
                            style={{ margin: 20 }}>
                            Log in
                        </IonButton>
                        <IonButton
                            routerLink="/registerUser"
                            type="submit"
                            strong={true}
                            expand="full"
                            style={{ margin: 20 }}>
                            Register
                        </IonButton>

            </IonContent>
        </IonPage>
    );
};

export default LogIn;

How can I redirect to another page from the function handleLoginButtonPress which is invoked upon clicking on Login button. I tried reading through ionic doc but that did not help as it redirects whenever there is button click or click on an IonElement like IonLabel.

Body:
Use react-router-dom hooks
https://reacttraining.com/react-router/web/api/Hooks/usehistory

import { useHistory } from "react-router-dom";
const ExampleComponent: React.FC = () => {
  const history = useHistory();

  const handleLoginButtonPress = () => {
    history.push("/main");
  };

  return <IonButton onClick={handleLoginButtonPress}>Log in</IonButton>;
};
export default ExampleComponent;


问:
Usemin "Different sources attempting to write to the same destination"
I have an AngularJS app I'm working on usemin tasks for.  This app has 2 html pages, both include a block minified into a common.js and the other pages include js minified for those specific pages.

page1.html

```<code><!-- build:js scripts/common.js -->
<!-- bower:js -->
<script src="a.js"></script>
<script src="b.js"></script>
<!-- endbower -->
<!-- endbuild -->

<!-- build:js scripts/page1.js -->
<!-- bower:js -->
<script src="c.js"></script>
<script src="d.js"></script>
<!-- endbower -->
<!-- endbuild -->
</code>```

page2.html

```<code><!-- build:js scripts/common.js -->
<!-- bower:js -->
<script src="a.js"></script>
<script src="b.js"></script>
<!-- endbower -->
<!-- endbuild -->

<!-- build:js scripts/page2.js -->
<!-- bower:js -->
<script src="e.js"></script>
<script src="f.js"></script>
<!-- endbower -->
<!-- endbuild -->
</code>```

Gruntfile.js

```<code>useminPrepare: {
    html: ['<%= yeoman.app %>/page1.html', '<%= yeoman.app %>/page2.html'],
        options: {
            dest: '<%= yeoman.dist %>'
        }
    },
</code>```

Usemin is upset because common.js is defined in both files with the error: Fatal error: Different sources attempting to write to the same destination:.  I (think) I need to include both page1 and page2 in the useminPrepare in order to correctly get page1.js and page2.js generated.  How do people solve this issue?

答:
Below changes worked like charm for me:    </p>

```<code>useminPrepare: {
  page1: {
    dest: 'dist',
    src: ['page1.html']
  },
  page2: {
    dest: 'dist',
    src: ['page2.html']
  },
  options: {
     ...
  }
}
</code>```

Body:
I have an AngularJS app I'm working on usemin tasks for.  This app has 2 html pages, both include a block minified into a common.js and the other pages include js minified for those specific pages.

page1.html

page2.html

Gruntfile.js

useminPrepare: {
    html: ['<%= yeoman.app %>/page1.html', '<%= yeoman.app %>/page2.html'],
        options: {
            dest: '<%= yeoman.dist %>'
        }
    },

Usemin is upset because common.js is defined in both files with the error: Fatal error: Different sources attempting to write to the same destination:.  I (think) I need to include both page1 and page2 in the useminPrepare in order to correctly get page1.js and page2.js generated.  How do people solve this issue?

Body:
Below changes worked like charm for me:

useminPrepare: {
  page1: {
    dest: 'dist',
    src: ['page1.html']
  },
  page2: {
    dest: 'dist',
    src: ['page2.html']
  },
  options: {
     ...
  }
}


问:
Regex to get string between curly braces
Unfortunately, despite having tried to learn regex at least one time a year for as many years as I can remember, I always forget as I use them so infrequently. This year my new year's resolution is to not try and learn regex again - So this year to save me from tears I'll give it to Stack Overflow. (Last Christmas remix).

I want to pass in a string in this format {getThis}, and be returned the string getThis. Could anyone be of assistance in helping to stick to my new year's resolution?

Related questions on Stack Overflow:

How can one turn regular quotes (i.e. ', ") into LaTeX/TeX quotes (i.e. `', ``'')

Regex: To pull out a sub-string between two tags in a string

Regex to replace all \n in a String, but no those inside [code] [/code] tag

答:
Even this helps me while trying to solve someone's problem,

Split the contents inside curly braces ({}) having a pattern like,
  {'day': 1, 'count': 100}.

For example:

#include <iostream>
#include <regex>
#include<string>
using namespace std;

int main()
{
    //string to be searched
    string s = "{'day': 1, 'count': 100}, {'day': 2, 'count': 100}";

    // regex expression for pattern to be searched
    regex e ("\\{[a-z':, 0-9]+\\}");
    regex_token_iterator<string::iterator> rend;

    regex_token_iterator<string::iterator> a ( s.begin(), s.end(), e );
    while (a!=rend) cout << " [" << *a++ << "]";
    cout << endl;

    return 0;
}
```

<p>Output:</p>

```[{'day': 1, 'count': 100}] [{'day': 2, 'count': 100}]
```

OwnerDisplayName: ChrisInCambo

LastEditorDisplayName: dmckee

Body:
Even this helps me while trying to solve someone's problem,

Split the contents inside curly braces ({}) having a pattern like,
  {'day': 1, 'count': 100}.

For example:

#include <iostream>
#include <regex>
#include<string>
using namespace std;

int main()
{
    //string to be searched
    string s = "{'day': 1, 'count': 100}, {'day': 2, 'count': 100}";

    // regex expression for pattern to be searched
    regex e ("\\{[a-z':, 0-9]+\\}");
    regex_token_iterator<string::iterator> rend;

    regex_token_iterator<string::iterator> a ( s.begin(), s.end(), e );
    while (a!=rend) cout << " [" << *a++ << "]";
    cout << endl;

    return 0;
}

Output:

[{'day': 1, 'count': 100}] [{'day': 2, 'count': 100}]


问:
Java sum of repetitive items inside for loop
I have two arrays :

```<code>String[] matnr = new String[] { "16400", "56000", "56000", "50000", "16400" };
String[] lfimg = new String[] { "4.000", "5.000", "6.000", "9.000", "10.560" };
</code>```

I want to find sum of lfimg items having same matnr value i.e. for matnr 16400 sum output will be 14.560, for 56000 output will be 11.000 and matnr 50000 sum output will be 9.000

below block is written by me :

```<code>    public static void main(String[] args) {

        String[] matnr = new String[] { "16400", "56000", "56000", "50000", "16400" };
        String[] lfimg = new String[] { "4.000", "5.000", "6.000", "9.000", "10.56" };

        int n = matnr.length;

        int i, j, x;
        int count = 0;
        int count1 = 0;
        double value = 0.0;

        // calculate unique material count
        for (i = 0; i < n; ++i)
            System.out.println(i + 1 + "compartment material : " + matnr[i]);

        for (i = 0; i < n; i++) {
            for (j = 0; j < i; j++)
                if (matnr[i] == matnr[j])
                    break;
            if (i == j) {
                count = count + 1;
            }

        }
        System.out.println("final count >>" + count);
        String materialArray[] = new String[count];

        for (i = 0; i < n; i++) {
            for (j = 0; j < i; j++)
                if (matnr[i] == matnr[j])
                    break;
            if (i == j) {

                materialArray[count1] = matnr[i];
                System.out.println("Material array xxxx >>" + materialArray[count1]);
                System.out.println("count1 before >>" + count1);
                count1 = count1 + 1;
                System.out.println("count1 after >>" + count1);

            }

        }

        System.out.println("matnr.length >>" + matnr.length);
        System.out.println("materialArray.length >>" + materialArray.length);

        for (i = 0; i < matnr.length; i++) {
            System.out.println("111Value   >>> " + matnr[i]);
        }

        for (j = 0; j < materialArray.length; j++) {
            System.out.println("222Value >>> " + materialArray[j]);
        }

        System.out.println("---- ******* ------------ *********** -------- ********** ------");

        for (i = 0; i < materialArray.length; i++) {
            for (j = 0; j < matnr.length; j++) {
                if (materialArray[i].contains(matnr[j])) {

                    value = value + Double.parseDouble(lfimg[j]);

                    System.out.println("Value1   >>>  " + value);

                }

            }

        }

    }
</code>```

But I'm not getting desired output. It is coming as :

```<code>Value1   >>>  4.0
Value1   >>>  14.56
Value1   >>>  19.560000000000002
Value1   >>>  25.560000000000002
Value1   >>>  34.56
</code>```

Where as I want output as :

```<code>Value1   >>>  14.560
Value1   >>>  11.000
Value1   >>>  9.000
</code>```

Can anybody please assist in this regard.

答:
You do not reset the value variable in your final forloop, hence why you're getting ever increasing numbers in your print, ending in 34.56. You want one value for each materialArray entry, so immediately after for (i = 0; i < materialArray.length; i++) {, you'd want value = 0.

You're using materialArray[i].contains(matnr[j]) - that's asking if matnr[j] is a substring of materialArray[i]. It seems rather clear you wanted equals instead. Minor nit and doesn't break here, but a bug nonetheless.

Your printer tool will print every time an individual entry matches, and prints nothing after you're gone through the whole list, resulting in this weird output. Your intent, presumably, is to let the inner loop (for (int j = 0; j < matnr.length; j++)) complete, and THEN you want to print. Thus, your sysout statement needs to be shifted two lines down, after the closing bracket of the inner for loop. Combine that with resetting your value and...

```<code>Value1   >>>  14.56
Value1   >>>  11.0
Value1   >>>  9.0
</code>```

NB: A second issue is rounding errors. You basically should never toString() or otherwise directly print a float or double value. If you do, you get wonky weirdness like 19.560000000000002.

If I ask you, using decimal notation, to write down the result of 'one third', you must round. You can't write an infinite processing of .3333333, right? Computers (specifically, doubles and floats) are no different, but computers count in binary, not decimal. So, the computer has to round a bit, and then 'render' the value it has in decimal, and this is where the weirdness comes from. The inaccuracies introduced by this rounding cannot be avoided (at least, not with doubles and floats), but usually the inaccuracies do not creep into the relevant significance of your numbers. The solution is therefore to ALWAYS guide the libraries when printing your numbers, by telling it how many digits you are expecting. So, make it:

```<code>System.out.printf("Value1   >>>   %.4f\n", value);
</code>```

The %.4f tells the printer to print with no more than 4 digits after the dot, and printf does not automatically newline, so the \n tells it to print that newline explicitly.

Finally, there's the matter of this code style. This can be done far simpler (and more efficiently) using java's built in tools, such as HashMap:

```<code>    public static void main(String[] args) {
        String[] matnr = new String[] { "16400", "56000", "56000", "50000", "16400" };
        String[] lfimg = new String[] { "4.000", "5.000", "6.000", "9.000", "10.56" };
        var values = new HashMap<String, Double>();

        // load values into the map.
        for (int i = 0; i < matnr.length; i++) {
            double z = Double.parseDouble(lfimg[i]);
            values.compute(matnr[i], (m, v) -> v == null ? z : v + z); // [1]
        }

        // print them to show it works
        for (var e : values.entrySet()) {
            System.out.printf("%s: %.4f\n", e.getKey(), e.getValue());
        }
    }
</code>```

The key line is the line marked [1]: It says: To compute the value for the value at the current matnr entry, if there is no existing value yet (v would be null), it's just the corresponding entry from lfimg, and if there is an existing value, it is the sum of what we had, plus the corresponding entry from lfimg.

Body:
I have two arrays :

String[] matnr = new String[] { "16400", "56000", "56000", "50000", "16400" };
String[] lfimg = new String[] { "4.000", "5.000", "6.000", "9.000", "10.560" };

I want to find sum of lfimg items having same matnr value i.e. for matnr 16400 sum output will be 14.560, for 56000 output will be 11.000 and matnr 50000 sum output will be 9.000

below block is written by me :

    public static void main(String[] args) {

        String[] matnr = new String[] { "16400", "56000", "56000", "50000", "16400" };
        String[] lfimg = new String[] { "4.000", "5.000", "6.000", "9.000", "10.56" };

        int n = matnr.length;

        int i, j, x;
        int count = 0;
        int count1 = 0;
        double value = 0.0;

        // calculate unique material count
        for (i = 0; i < n; ++i)
            System.out.println(i + 1 + "compartment material : " + matnr[i]);

        for (i = 0; i < n; i++) {
            for (j = 0; j >" + count);
        String materialArray[] = new String[count];

        for (i = 0; i < n; i++) {
            for (j = 0; j >" + materialArray[count1]);
                System.out.println("count1 before >>" + count1);
                count1 = count1 + 1;
                System.out.println("count1 after >>" + count1);

            }

        }

        System.out.println("matnr.length >>" + matnr.length);
        System.out.println("materialArray.length >>" + materialArray.length);

        for (i = 0; i < matnr.length; i++) {
            System.out.println("111Value   >>> " + matnr[i]);
        }

        for (j = 0; j < materialArray.length; j++) {
            System.out.println("222Value >>> " + materialArray[j]);
        }

        System.out.println("---- ******* ------------ *********** -------- ********** ------");

        for (i = 0; i < materialArray.length; i++) {
            for (j = 0; j < matnr.length; j++) {
                if (materialArray[i].contains(matnr[j])) {

                    value = value + Double.parseDouble(lfimg[j]);

                    System.out.println("Value1   >>>  " + value);

                }

            }

        }

    }

But I'm not getting desired output. It is coming as :

Value1   >>>  4.0
Value1   >>>  14.56
Value1   >>>  19.560000000000002
Value1   >>>  25.560000000000002
Value1   >>>  34.56

Where as I want output as :

Value1   >>>  14.560
Value1   >>>  11.000
Value1   >>>  9.000

Can anybody please assist in this regard.

Body:
You do not reset the value variable in your final forloop, hence why you're getting ever increasing numbers in your print, ending in 34.56. You want one value for each materialArray entry, so immediately after for (i = 0; i < materialArray.length; i++) {, you'd want value = 0.

You're using materialArray[i].contains(matnr[j]) - that's asking if matnr[j] is a substring of materialArray[i]. It seems rather clear you wanted equals instead. Minor nit and doesn't break here, but a bug nonetheless.

Your printer tool will print every time an individual entry matches, and prints nothing after you're gone through the whole list, resulting in this weird output. Your intent, presumably, is to let the inner loop (for (int j = 0; j < matnr.length; j++)) complete, and THEN you want to print. Thus, your sysout statement needs to be shifted two lines down, after the closing bracket of the inner for loop. Combine that with resetting your value and...

Value1   >>>  14.56
Value1   >>>  11.0
Value1   >>>  9.0

NB: A second issue is rounding errors. You basically should never toString() or otherwise directly print a float or double value. If you do, you get wonky weirdness like 19.560000000000002.

If I ask you, using decimal notation, to write down the result of 'one third', you must round. You can't write an infinite processing of .3333333, right? Computers (specifically, doubles and floats) are no different, but computers count in binary, not decimal. So, the computer has to round a bit, and then 'render' the value it has in decimal, and this is where the weirdness comes from. The inaccuracies introduced by this rounding cannot be avoided (at least, not with doubles and floats), but usually the inaccuracies do not creep into the relevant significance of your numbers. The solution is therefore to ALWAYS guide the libraries when printing your numbers, by telling it how many digits you are expecting. So, make it:

System.out.printf("Value1   >>>   %.4f\n", value);

The %.4f tells the printer to print with no more than 4 digits after the dot, and printf does not automatically newline, so the \n tells it to print that newline explicitly.

Finally, there's the matter of this code style. This can be done far simpler (and more efficiently) using java's built in tools, such as HashMap:

    public static void main(String[] args) {
        String[] matnr = new String[] { "16400", "56000", "56000", "50000", "16400" };
        String[] lfimg = new String[] { "4.000", "5.000", "6.000", "9.000", "10.56" };
        var values = new HashMap<String, Double>();

        // load values into the map.
        for (int i = 0; i < matnr.length; i++) {
            double z = Double.parseDouble(lfimg[i]);
            values.compute(matnr[i], (m, v) -> v == null ? z : v + z); // [1]
        }

        // print them to show it works
        for (var e : values.entrySet()) {
            System.out.printf("%s: %.4f\n", e.getKey(), e.getValue());
        }
    }

The key line is the line marked [1]: It says: To compute the value for the value at the current matnr entry, if there is no existing value yet (v would be null), it's just the corresponding entry from lfimg, and if there is an existing value, it is the sum of what we had, plus the corresponding entry from lfimg.


问:
AttributeError: Cannot use remove() on a ManyToManyField which specifies an intermediary model. Use songs.Playlist_Activity's Manager instead
I followed the documentation on figuring out how to remove an item in the manytomanyfield below but it doesn't seem to work and I am getting an attribute error. The remove method works totally fine without the intermediary model.

models.py

```<code>   class Song (models.Model):
        author=models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, default=1)
        timestamp= models.DateTimeField(auto_now_add=True, editable=False)
        songname = models.CharField(max_length=500, null=False, blank=False)
        tags = TaggableManager()

        def __str__(self):
            return self.songname

    class Playlist (models.Model):
        name = models.CharField(max_length=150, null=False, blank=False)
        author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, default=1)
        song = models.ManyToManyField(Song, through='Playlist_Activity')

    class Playlist_Activity(models.Model):
        song= models.ForeignKey(Song, on_delete=models.CASCADE)
        playlist= models.ForeignKey(Playlist, on_delete=models.CASCADE)
        timestamp= models.DateTimeField(auto_now_add=True, editable=False)

        class Meta:
            ordering = ('timestamp',)
</code>```

Views.py

```<code>@login_required
def Playlist_Remove(request, id, P_id):
    p = Playlist.objects.get(id=P_id)
    s = p.song.get(id=id)
    p.song.remove(s)
    return redirect('account')
</code>```

答:
You can remove the intermediary instance:

p = Playlist.objects.get(id=P_id)
s = Song.objects.get(id=id)
Playlist_Activity.objects.get(song=s, playlist=p).delete()
```

Body:
I followed the documentation on figuring out how to remove an item in the manytomanyfield below but it doesn't seem to work and I am getting an attribute error. The remove method works totally fine without the intermediary model.

models.py

   class Song (models.Model):
        author=models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, default=1)
        timestamp= models.DateTimeField(auto_now_add=True, editable=False)
        songname = models.CharField(max_length=500, null=False, blank=False)
        tags = TaggableManager()

        def __str__(self):
            return self.songname

    class Playlist (models.Model):
        name = models.CharField(max_length=150, null=False, blank=False)
        author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, default=1)
        song = models.ManyToManyField(Song, through='Playlist_Activity')

    class Playlist_Activity(models.Model):
        song= models.ForeignKey(Song, on_delete=models.CASCADE)
        playlist= models.ForeignKey(Playlist, on_delete=models.CASCADE)
        timestamp= models.DateTimeField(auto_now_add=True, editable=False)

        class Meta:
            ordering = ('timestamp',)

Views.py

@login_required
def Playlist_Remove(request, id, P_id):
    p = Playlist.objects.get(id=P_id)
    s = p.song.get(id=id)
    p.song.remove(s)
    return redirect('account')


问:
Lumen 5.5 JSON API File Upload test breaks with UploadedFile
I am building a file upload JSON API with Lumen and trying to write phpunit API tests.

The problem I am having though is that as soon as I try to simulate a file upload with a real image constructed like ["file" => new UploadedFile(TestUtils::tempPath('test.jpg'), 'test.jpg', "image\jpeg", 100, null, true)] and sending it via $this->json('POST', '/chunk', $data);,
I can't do anything with the uploaded file because it is an array and I get the error Call to a member function move() on array in ...

Oddly enough if I use UploadedFile::fake()->image('test.jpg') it mangles my request and the other data I send with it isn't available in the controller.

If I dd the file object in my controller, it shows an "array(0){}". I am thinking it has something to do with the transfer via json('POST'), as unit tests that use an UploadedFileObject directly run successfully.

If I dd the entire request, it shows:

```<code>["request"]=>
  object(Symfony\Component\HttpFoundation\ParameterBag)#52 (1) {
    ["parameters":protected]=>
    array(5) {
      ["chunkType"]=>
      string(4) "flow"
      ["flowIdentifier"]=>
      string(13) "Testing123Bnu"
      ["flowChunkNumber"]=>
      int(1)
      ["flowTotalChunks"]=>
      int(2)
      ["file"]=>
      array(0) {
      }
    }
  }

 ...

["files"]=>
object(Symfony\Component\HttpFoundation\FileBag)#71 (1) {
    ["parameters":protected]=>
    array(0) {
    }
  }

...

["content":protected]=> string(103) "{(otherData..), "file":{}}"
</code>```

I have no idea how to circumvent this or test a file upload in this situation and have been searching for hours. The symfony test mode in the UploadedFile constructor has no effect.

Here is my test:

```<code>    public function testChunkUpload_FlowChunk()
    {
        $data = [   (otherData)
                    "file"              => new UploadedFile(TestUtils::tempPath('test.jpg'), 'test.jpg', "image\jpeg", 100, null, true)
                    //UploadedFile::fake()->image('test.jpg')
                ];

        $this->assertFileExists(TestUtils::tempPath('test.jpg'));

        $this->json('POST', '/chunk', $data);

        $this->assertEquals(200, $this->response->status());
        $this->assertEquals('application/json', $this->response->headers->get('Content-Type'));
    }
</code>```

And here is the relevant method in my controller:

```<code>public function receiveChunk(Request $request){
    if (! $request->has('chunkType')) {
        return response()->json(["Invalid Chunk Type"], 400);
    }
    $data = $this->chunkNormalizer->normalizeInput($request->all());
    $chunk = $this->chunkFactory->createChunk(  (otherData)
                                                $data['fileHandle']);

    $this->fileAssembler->processChunk($chunk);

    return response()->json(["Success"], 200);
}
</code>```

And the error occurs in processChunk:

```<code>public function processChunk(FileChunk $chunk){
    ...
    $chunkName  = "..." . ".chunk";

    $fileHandle = $chunk->getFileHandle();
    $fileHandle->move($this->assemblePath, $chunkName);
}
</code>```

Any ideas would be greatly appreciated!

答:
this is working for me. just simple. this can submit data (name and email) and file upload on the same route.

1.condition without authentication

5*1000 is file size (in KB). so i made a test with 5 MB file.

```<code>use Faker\Factory as Faker;
use Illuminate\Http\UploadedFile;

class SampleTest extends TestCase
{
    public function testItCanCreateUser()
    {
        $faker = Faker::create();
        $data = array(
            'name' => $faker->name
        );
        $files = [
            'file' => UploadedFile::fake()->create('file.jpg', 5*1000)
        ];
        $response = $this->call('POST', '/chunk', $data, [], $files);
        $this->assertEquals(200, $response->getStatusCode());
    }
}
</code>```

2.condition with authentication (logged in user)

```<code>use Faker\Factory as Faker;
use Illuminate\Http\UploadedFile;

class SampleTest extends TestCase
{
    public function testItCanUpdateProfileUser()
    {
        $faker = Faker::create();
        $data = array(
            'name' => $faker->name
        );
        $files = [
            'file' => UploadedFile::fake()->create('file.jpg', 5*1000)
        ];

        $headers = [
            'Accept' => 'application/json',
            'Authorization' => 'your-jwt-token'
        ];
        $servers = [];
        foreach ($headers as $k => $header) {
            $servers["HTTP_" . $k] = $header;
        }

        $response = $this->call('POST', '/chunk', $data, [], $files, $servers);
        $this->assertEquals(200, $response->getStatusCode());
    }
}
</code>```

you need to add HTTP_ on every request header. i'm not sure why. but it will work.

Body:
I am building a file upload JSON API with Lumen and trying to write phpunit API tests.

The problem I am having though is that as soon as I try to simulate a file upload with a real image constructed like ["file" => new UploadedFile(TestUtils::tempPath('test.jpg'), 'test.jpg', "image\jpeg", 100, null, true)] and sending it via $this->json('POST', '/chunk', $data);,
I can't do anything with the uploaded file because it is an array and I get the error Call to a member function move() on array in ...

Oddly enough if I use UploadedFile::fake()->image('test.jpg') it mangles my request and the other data I send with it isn't available in the controller.

If I dd the file object in my controller, it shows an "array(0){}". I am thinking it has something to do with the transfer via json('POST'), as unit tests that use an UploadedFileObject directly run successfully.

If I dd the entire request, it shows:

["request"]=>
  object(Symfony\Component\HttpFoundation\ParameterBag)#52 (1) {
    ["parameters":protected]=>
    array(5) {
      ["chunkType"]=>
      string(4) "flow"
      ["flowIdentifier"]=>
      string(13) "Testing123Bnu"
      ["flowChunkNumber"]=>
      int(1)
      ["flowTotalChunks"]=>
      int(2)
      ["file"]=>
      array(0) {
      }
    }
  }

 ...

["files"]=>
object(Symfony\Component\HttpFoundation\FileBag)#71 (1) {
    ["parameters":protected]=>
    array(0) {
    }
  }

...

["content":protected]=> string(103) "{(otherData..), "file":{}}"

I have no idea how to circumvent this or test a file upload in this situation and have been searching for hours. The symfony test mode in the UploadedFile constructor has no effect.

Here is my test:

    public function testChunkUpload_FlowChunk()
    {
        $data = [   (otherData)
                    "file"              => new UploadedFile(TestUtils::tempPath('test.jpg'), 'test.jpg', "image\jpeg", 100, null, true)
                    //UploadedFile::fake()->image('test.jpg')
                ];

        $this->assertFileExists(TestUtils::tempPath('test.jpg'));

        $this->json('POST', '/chunk', $data);

        $this->assertEquals(200, $this->response->status());
        $this->assertEquals('application/json', $this->response->headers->get('Content-Type'));
    }

And here is the relevant method in my controller:

public function receiveChunk(Request $request){
    if (! $request->has('chunkType')) {
        return response()->json(["Invalid Chunk Type"], 400);
    }
    $data = $this->chunkNormalizer->normalizeInput($request->all());
    $chunk = $this->chunkFactory->createChunk(  (otherData)
                                                $data['fileHandle']);

    $this->fileAssembler->processChunk($chunk);

    return response()->json(["Success"], 200);
}

And the error occurs in processChunk:

public function processChunk(FileChunk $chunk){
    ...
    $chunkName  = "..." . ".chunk";

    $fileHandle = $chunk->getFileHandle();
    $fileHandle->move($this->assemblePath, $chunkName);
}

Any ideas would be greatly appreciated!

Body:
this is working for me. just simple. this can submit data (name and email) and file upload on the same route.

1.condition without authentication

5*1000 is file size (in KB). so i made a test with 5 MB file.

use Faker\Factory as Faker;
use Illuminate\Http\UploadedFile;

class SampleTest extends TestCase
{
    public function testItCanCreateUser()
    {
        $faker = Faker::create();
        $data = array(
            'name' => $faker->name
        );
        $files = [
            'file' => UploadedFile::fake()->create('file.jpg', 5*1000)
        ];
        $response = $this->call('POST', '/chunk', $data, [], $files);
        $this->assertEquals(200, $response->getStatusCode());
    }
}

2.condition with authentication (logged in user)

use Faker\Factory as Faker;
use Illuminate\Http\UploadedFile;

class SampleTest extends TestCase
{
    public function testItCanUpdateProfileUser()
    {
        $faker = Faker::create();
        $data = array(
            'name' => $faker->name
        );
        $files = [
            'file' => UploadedFile::fake()->create('file.jpg', 5*1000)
        ];

        $headers = [
            'Accept' => 'application/json',
            'Authorization' => 'your-jwt-token'
        ];
        $servers = [];
        foreach ($headers as $k => $header) {
            $servers["HTTP_" . $k] = $header;
        }

        $response = $this->call('POST', '/chunk', $data, [], $files, $servers);
        $this->assertEquals(200, $response->getStatusCode());
    }
}

you need to add HTTP_ on every request header. i'm not sure why. but it will work.