问:
Need help Centering some Content
I have two boxes set up and i wanted to put some buttons and text in the middle but when ever I try to add text there it makes the far right box go down one. I want them to stay aligned.

I tried adding another  between the 2 boxes but this did not work. im new at html so im not sure how to format this.

    <!Doctype html>

        <title> Basic Clicker</title>
        <link rel="stylesheet" href="css/style.css" />

Home

SkillTree

Equipment

Pets

Skills

Quests

                <title>HTML div</title>

                                              Inventory

                    Bronze: 0

                    Silver: 0

                    Gold: 0

                    Diamond: 0

                                                 Skills

                    Strength: Lv 1 0 / 100

                    Magic: Lv 1 0 / 100

                        <button onclick="Magicexp()">Click Me!</button>

    ```

I expect the buttons / words I want to put in the middle of these 2 boxes to not upset the alignment. But my actual output is words and buttons move the far right box down.

答:
There are multiple ways to approach this problem, just to include a few here in the below code:

You can use bootstrap to implement a grid system, here's the bootstrap grid system reference.

I have included the grid system in your code. To do that, first is to include bootstrap:

```<code><link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap.min.css">
</code>```

What the grid system does is it breaks the width of your row into 12 equal columns, and in the code below, the left box takes 5 columns and the right box takes 5 columns, and the center where you want to add text and stuff will take 2 columns, totaled 12 columns. To do that we add class="col-sm-5" for 5 columns for example, (you can use col-lg-5 etc. you can look it up for more details, basically this has to do with the Responsiveness of your page).

We can also implement max-width to limit the maximum width of your center div, and use overflow wrap to control the overflow. Look up CSS overflow to see what are your options. One of them is to make a scrolling effect if the elements in the center is too big. That way if it overflows and push the right box to the bottom, you can do a scrolling effect so the right box stays where it is.

In the code below overflow-wrap: break-word; is used if you were to put text in the middle.

You can also utilize the position:absolute; attribute to position your right box in a absolute position, that way it won't be pushed down. See position for reference.

```<code><!Doctype html>
<html>
    <head>
        <title> Basic Clicker</title>
          <link rel="stylesheet" href="css/style.css" />
          <!-- Latest compiled and minified CSS -->
          <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap.min.css">
    </head>
<body>
    <div class="nav_bar">
        <ul>
            <li>
                <a href="GameMainWindow.html">Home</a>
            </li>
            <li>
                <a href="SkillTree.html">SkillTree</a>
            </li>
            <li>
                <a href="Equipment.html">Equipment</a>
            </li>
            <li>
                <a href="Pets.html">Pets</a>
            </li>
            <li>
                <a href="Skills.html" id="onlink">Skills</a>
            </li>
            <li>
                <a href="Quests.html">Quests</a>
            </li>
        </ul>
    </div>
    <div class="main_container">
        <p>
            <html>
                <head>
                    <title>HTML div</title>
                </head>
                <body>
                    <div class="container">
                        <div class="row">
                            <div style="float:left; border: 15px solid green; height:300px; background:white; margin:10px" class="col-sm-5">
                                          Inventory

                                <br />Bronze:
                                <span id="Bronze">0</span>
                                <br />Silver:
                                <span id="Bronze">0</span>
                                <br />Gold:
                                <span id="Bronze">0</span>
                                <br />Diamond:
                                <span id="Bronze">0</span>
                            </div>
                            <div style="max-width: 30px; overflow-wrap: break-word;" class="col-sm-2">
                                <h1>lkjdlfkjdlkfjdljfdlkjfdlkjfd</h1>
                            </div>
                            <div style="width: 300px;  float:right; border: 15px solid green; height:300px; background:white; margin:10px;" class="col-sm-5">
                                             Skills

                                <br />Strength: Lv
                                <span id="Strengthlv">1</span>
                                <span id="StrengthCexp">0</span> /
                                <span id="StrengthMexp">100</span>
                                <br />Magic: Lv
                                <span id="Magiclv">1</span>
                                <span
id="MagicCexp">0</span> /
                                <span id="MagicMexp">100</span>
                                <br />
                                <button onclick="Magicexp()">Click Me!</button>
                                <br />
                            </div>
                        </div>
                    </div>
                    <script type="text/javascript" src="Skills.js"></script>
                </body>
            </html>
        </p>
    </div>
</body>
</html>
</code>```

Title: Need help Centering some Content

Body:
I have two boxes set up and i wanted to put some buttons and text in the middle but when ever I try to add text there it makes the far right box go down one. I want them to stay aligned.

I tried adding another  between the 2 boxes but this did not work. im new at html so im not sure how to format this.

    <!Doctype html>

        <title> Basic Clicker</title>
        <link rel="stylesheet" href="css/style.css" />

Home

SkillTree

Equipment

Pets

Skills

Quests

                <title>HTML div</title>

                                              Inventory

                    Bronze: 0

                    Silver: 0

                    Gold: 0

                    Diamond: 0

                                                 Skills

                    Strength: Lv 1 0 / 100

                    Magic: Lv 1 0 / 100

                        <button onclick="Magicexp()">Click Me!</button>

I expect the buttons / words I want to put in the middle of these 2 boxes to not upset the alignment. But my actual output is words and buttons move the far right box down.

Body:
There are multiple ways to approach this problem, just to include a few here in the below code:

You can use bootstrap to implement a grid system, here's the bootstrap grid system reference.

I have included the grid system in your code. To do that, first is to include bootstrap:

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap.min.css">

What the grid system does is it breaks the width of your row into 12 equal columns, and in the code below, the left box takes 5 columns and the right box takes 5 columns, and the center where you want to add text and stuff will take 2 columns, totaled 12 columns. To do that we add class="col-sm-5" for 5 columns for example, (you can use col-lg-5 etc. you can look it up for more details, basically this has to do with the Responsiveness of your page).

We can also implement max-width to limit the maximum width of your center div, and use overflow wrap to control the overflow. Look up CSS overflow to see what are your options. One of them is to make a scrolling effect if the elements in the center is too big. That way if it overflows and push the right box to the bottom, you can do a scrolling effect so the right box stays where it is.

In the code below overflow-wrap: break-word; is used if you were to put text in the middle.

You can also utilize the position:absolute; attribute to position your right box in a absolute position, that way it won't be pushed down. See position for reference.

<!Doctype html>
<html>
    <head>
        <title> Basic Clicker</title>
          <link rel="stylesheet" href="css/style.css" />
          <!-- Latest compiled and minified CSS -->
          <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap.min.css">
    </head>
<body>
    <div class="nav_bar">
        <ul>
            <li>
                <a href="GameMainWindow.html">Home</a>
            </li>
            <li>
                <a href="SkillTree.html">SkillTree</a>
            </li>
            <li>
                <a href="Equipment.html">Equipment</a>
            </li>
            <li>
                <a href="Pets.html">Pets</a>
            </li>
            <li>
                <a href="Skills.html" id="onlink">Skills</a>
            </li>
            <li>
                <a href="Quests.html">Quests</a>
            </li>
        </ul>
    </div>
    <div class="main_container">
        <p>
            <html>
                <head>
                    <title>HTML div</title>
                </head>
                <body>
                    <div class="container">
                        <div class="row">
                            <div style="float:left; border: 15px solid green; height:300px; background:white; margin:10px" class="col-sm-5">
                &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Inventory

                                <br />Bronze:
                                <span id="Bronze">0</span>
                                <br />Silver:
                                <span id="Bronze">0</span>
                                <br />Gold:
                                <span id="Bronze">0</span>
                                <br />Diamond:
                                <span id="Bronze">0</span>
                            </div>
                            <div style="max-width: 30px; overflow-wrap: break-word;" class="col-sm-2">
                                <h1>lkjdlfkjdlkfjdljfdlkjfdlkjfd</h1>
                            </div>
                            <div style="width: 300px;  float:right; border: 15px solid green; height:300px; background:white; margin:10px;" class="col-sm-5">
                &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;  &nbsp; &nbsp; &nbsp; &nbsp; Skills

                                <br />Strength: Lv
                                <span id="Strengthlv">1</span>
                                <span id="StrengthCexp">0</span> /
                                <span id="StrengthMexp">100</span>
                                <br />Magic: Lv
                                <span id="Magiclv">1</span>
                                <span
id="MagicCexp">0</span> /
                                <span id="MagicMexp">100</span>
                                <br />
                                <button onclick="Magicexp()">Click Me!</button>
                                <br />
                            </div>
                        </div>
                    </div>
                    <script type="text/javascript" src="Skills.js"></script>
                </body>
            </html>
        </p>
    </div>
</body>
</html>


来源: stackexchange

问:
PHP array sort with forced the first row
How to sort an array at PHP to force selected row as a first ?

My array is

```<code>array[]=array(id=>'a', content=>'lemon');
array[]=array(id=>'b', content=>'apple');
array[]=array(id=>'c', content=>'banana');
array[]=array(id=>'d', content=>'cherry');
</code>```

How to sort the array to force

```<code>array[]=array(id=>'b', content=>'apple');
</code>```

as a first row and doesn't matter the rest (apple is the key).

And in other example turn sort to get

```<code>array[]=array(id=>'d', content=>'cherry');
</code>```

as a first row and doesn't matter the rest (cherry is the key).

答:
Another way to do this is to effectively rotate the array using array_slice, bringing the element you want to the start:

```<code>$first = 'apple';
$k = array_search($first, array_column($array, 'content'));
$array = array_merge(array_slice($array, $k), array_slice($array, 0, $k));
print_r($array);
</code>```

Output:

```<code>Array (
  [0] => Array ( [id] => b [content] => apple )
  [1] => Array ( [id] => c [content] => banana )
  [2] => Array ( [id] => d [content] => cherry )
  [3] => Array ( [id] => a [content] => lemon )
)
</code>```

Demo on 3v4l.org

ContentLicense: CC BY-SA 4.0

Body:
How to sort an array at PHP to force selected row as a first ?

My array is

array[]=array(id=>'a', content=>'lemon');
array[]=array(id=>'b', content=>'apple');
array[]=array(id=>'c', content=>'banana');
array[]=array(id=>'d', content=>'cherry');

How to sort the array to force

array[]=array(id=>'b', content=>'apple');

as a first row and doesn't matter the rest (apple is the key).

And in other example turn sort to get

array[]=array(id=>'d', content=>'cherry');

as a first row and doesn't matter the rest (cherry is the key).

Body:
Another way to do this is to effectively rotate the array using array_slice, bringing the element you want to the start:

$first = 'apple';
$k = array_search($first, array_column($array, 'content'));
$array = array_merge(array_slice($array, $k), array_slice($array, 0, $k));
print_r($array);

Output:

Array (
  [0] => Array ( [id] => b [content] => apple )
  [1] => Array ( [id] => c [content] => banana )
  [2] => Array ( [id] => d [content] => cherry )
  [3] => Array ( [id] => a [content] => lemon )
)

Demo on 3v4l.org


问:
Save list of records and fields into django model
I receive this list from my website admin:

```<code>[['present', '2'],['present', '1'], ['study', '1'], ['study', '3'], ['present', '4'], ['study', '4'],
</code>```

The first option is actually the field name that needs to be edit in Rollcall model and the second option is the user ID.

Now I want to save this list to the Rollcall model:

```<code>#models.py
class Rollcall(models.Model):
    student = models.ForeignKey(User)
    present = models.BooleanField(default=False)
    study = models.BooleanField(default=False)
</code>```

So I first check and find the various fields that a particular user has in the list,
 and then I will save all those fields for one user in my model. How can I do this?

--Update 1:
this is HTML file:

```<code>{% forstudent in students %}
                            <tr>
                                <td>{{student}} </td>
                                <td> <input type="radio" name="present_{{student.id}}" value="1"></td>
                                <td> <input type="radio" name="study_{{student.id}}" value="1"></td>
                            </tr>
                        {% endfor %}
</code>```

I get the data in this way and put them into the list that I explain in the first of this question:

```<code>data_list = [key.split('_') for key in request.POST.keys()][1:]
</code>```

Each student can be present or absent or can study or not.my exactly question is: How can save data of all my student?Is there another way to solve this problem without data_list or any other way to create better data_list?

答:
You can iterate over list, create Rollcall instances and use bulk_create() Manager/QuerySet method (This avoids a lot of database hits (Only one INSERT query will be enough) and gives you guarantee of atomicity).

```<code>data_list = [['present', '2'], ['present', '3'], ['present', '4'], ['study', '1']]

Rollcall.objects.bulk_create([
    Rollcall(present=True if present == 'present' else False, student_id=int(student_id)) for present, student_id in data_list)
])
</code>```

Hope, it helps you.

Body:
I receive this list from my website admin:

[['present', '2'],['present', '1'], ['study', '1'], ['study', '3'], ['present', '4'], ['study', '4'],

The first option is actually the field name that needs to be edit in Rollcall model and the second option is the user ID.

Now I want to save this list to the Rollcall model:

#models.py
class Rollcall(models.Model):
    student = models.ForeignKey(User)
    present = models.BooleanField(default=False)
    study = models.BooleanField(default=False)

So I first check and find the various fields that a particular user has in the list,
 and then I will save all those fields for one user in my model. How can I do this?

--Update 1:
this is HTML file:

{% forstudent in students %}

                                {{student}}
                                 <input type="radio" name="present_{{student.id}}" value="1">
                                 <input type="radio" name="study_{{student.id}}" value="1">

                        {% endfor %}

I get the data in this way and put them into the list that I explain in the first of this question:

data_list = [key.split('_') for key in request.POST.keys()][1:]

Each student can be present or absent or can study or not.my exactly question is: How can save data of all my student?Is there another way to solve this problem without data_list or any other way to create better data_list?

Body:
You can iterate over list, create Rollcall instances and use bulk_create() Manager/QuerySet method (This avoids a lot of database hits (Only one INSERT query will be enough) and gives you guarantee of atomicity).

data_list = [['present', '2'], ['present', '3'], ['present', '4'], ['study', '1']]

Rollcall.objects.bulk_create([
    Rollcall(present=True if present == 'present' else False, student_id=int(student_id)) for present, student_id in data_list)
])

Hope, it helps you.


问:
object dumper class
I'm looking for a class that can output an object and all its leaf values in a format similar to this:

```<code>User
  - Name: Gordon
  - Age : 60
  - WorkAddress
     - Street: 10 Downing Street
     - Town: London
     - Country: UK
  - HomeAddresses[0]
    ...
  - HomeAddresses[1]
    ...
</code>```

(Or a clearer format). This would be equivalent to:

```<code>public class User
{
    public string Name { get;set; }
    public int Age { get;set; }
    public Address WorkAddress { get;set; }
    public List<Address> HomeAddresses { get;set; }
}

public class Address
{
    public string Street { get;set; }
    public string Town { get;set; }
    public string Country { get;set; }
}
</code>```

A kind of string representation of the PropertyGrid control, minus having to implement a large set of designers for each type.

PHP has something that does this called var_dump. I don't want to use a watch, as this is for printing out.

Could anyone point me to something like this if it exists? Or, write one for a bounty.

答:
I just came across a similar requirement in a Blazor project, and came up with the following very simple component to output an object's (and it's child objects') data to the screen:

ObjectDumper.razor:

```<code>@using Microsoft.AspNetCore.Components
@using Newtonsoft.Json

  <div>
    <button onclick="@DumpVMToConsole">@ButtonText</button>
    <pre id="json">@_objectAsJson```

@functions {

  // This component allows the easy visualisation of the values currently held in
  // an object and its child objects.  Add this component to a page and pass in a
  // param for the object to monitor, then press the button to see the object's data
  // as nicely formatted JSON
  // Use like this:  <ObjectDumper ObjectToDump="@_billOfLadingVM" />

  [Parameter]
  private object ObjectToDump { get; set; }

  [Parameter]
  private string ButtonText { get; set; } = "Show object's data";

  string _buttonText;

  string _objectAsJson = "";

  public void DumpVMToConsole()
  {
    _objectAsJson = GetObjectAsFormattedJson(ObjectToDump);
    Console.WriteLine(_objectAsJson);
  }

  public string GetObjectAsFormattedJson(object obj)
  {
    return JsonConvert.SerializeObject(
      value: obj,
      formatting: Formatting.Indented,
      settings: new JsonSerializerSettings
      {
        PreserveReferencesHandling = PreserveReferencesHandling.Objects
      });
  }

}
```

<p>You then stick that somewhere on a Blazor page as follows:</p>

```<ObjectDumper ObjectToDump="@YourObjectToVisualise" />
```

Which then renders a button you can press to see the current values of the bound object:

I've stuck that in a GitHub repo: tomRedox/BlazorObjectDumper

ContentLicense: CC BY-SA 3.0

Title: object dumper class

Body:
I'm looking for a class that can output an object and all its leaf values in a format similar to this:

User
  - Name: Gordon
  - Age : 60
  - WorkAddress
     - Street: 10 Downing Street
     - Town: London
     - Country: UK
  - HomeAddresses[0]
    ...
  - HomeAddresses[1]
    ...

(Or a clearer format). This would be equivalent to:

public class User
{
    public string Name { get;set; }
    public int Age { get;set; }
    public Address WorkAddress { get;set; }
    public List<Address> HomeAddresses { get;set; }
}

public class Address
{
    public string Street { get;set; }
    public string Town { get;set; }
    public string Country { get;set; }
}

A kind of string representation of the PropertyGrid control, minus having to implement a large set of designers for each type.

PHP has something that does this called var_dump. I don't want to use a watch, as this is for printing out.

Could anyone point me to something like this if it exists? Or, write one for a bounty.

Body:
I just came across a similar requirement in a Blazor project, and came up with the following very simple component to output an object's (and it's child objects') data to the screen:

ObjectDumper.razor:

@using Microsoft.AspNetCore.Components
@using Newtonsoft.Json

  <div>
    <button onclick="@DumpVMToConsole">@ButtonText</button>
    <pre id="json">@_objectAsJson</pre>
  </div>

@functions {

  // This component allows the easy visualisation of the values currently held in
  // an object and its child objects.  Add this component to a page and pass in a
  // param for the object to monitor, then press the button to see the object's data
  // as nicely formatted JSON
  // Use like this:  <ObjectDumper ObjectToDump="@_billOfLadingVM" />

  [Parameter]
  private object ObjectToDump { get; set; }

  [Parameter]
  private string ButtonText { get; set; } = "Show object's data";

  string _buttonText;

  string _objectAsJson = "";

  public void DumpVMToConsole()
  {
    _objectAsJson = GetObjectAsFormattedJson(ObjectToDump);
    Console.WriteLine(_objectAsJson);
  }

  public string GetObjectAsFormattedJson(object obj)
  {
    return JsonConvert.SerializeObject(
      value: obj,
      formatting: Formatting.Indented,
      settings: new JsonSerializerSettings
      {
        PreserveReferencesHandling = PreserveReferencesHandling.Objects
      });
  }

}

You then stick that somewhere on a Blazor page as follows:

<ObjectDumper ObjectToDump="@YourObjectToVisualise" />

Which then renders a button you can press to see the current values of the bound object:

I've stuck that in a GitHub repo: tomRedox/BlazorObjectDumper


问:
Prevent users from login to same system using different browsers (IE and FF)
We have a web application where users can login.

Now what we want is that the same user should not be able to login using different browsers.

Basically currently a user using two different browsers (IE and FF) can log in to the same account at the same time.  When you hit the login button, is it possible to invalidate all other logins for that account.

What is the best possible approach to do this?

PS: We are using Struts, Spring and Hibernate in our web application.

Thanks !

答: You can store the logged in user information in database or you can get it from Application context. and if the user is logged in already don't allow to make him another session.</p>


问:
How to create a shape with a hole in QML?
I want to create a kind of masking layer which consists of a black area with holes in it. Through the holes it should be possible to see the background. In the simplest version I it's just an rectangle covering the whole screen with an opening in the middle. As shown in the sample picture below.

My first approach was to use QML's Context2D feature: https://doc.qt.io/qt-5/qml-qtquick-context2d.html. Maybe it's totally wrong to do it this way, but maybe it's a good starting point. I tried to create an rectangle (which works) and a clipping area (which doesn't work). Besides the fact my implementation of the clipping doesn't work I would have the problem that the clip() command erases the area outside its path but not inside (at least that's what I understood from the docs: https://doc.qt.io/qt-5/qml-qtquick-context2d.html#clip-method).

```<code>Canvas {

    anchors.fill: parent

    onPaint: {
        var ctx = getContext("2d");
        ctx.fillStyle = "black"

        ctx.beginPath();
        ctx.fillRect(0, 0, Sizes.rootWindow.width, Sizes.rootWindow.height);
        ctx.fill();
    }
</code>```

答:
if the hole is exactly centered and the borders are all have the same size, you could use a transparent rectangle with borders:</p>

```<code>Rectangle {
    anchors.fill: parent
    color: "transparent"
    border.color: "black"
    border.width: 50
}
</code>```

Body:
I want to create a kind of masking layer which consists of a black area with holes in it. Through the holes it should be possible to see the background. In the simplest version I it's just an rectangle covering the whole screen with an opening in the middle. As shown in the sample picture below.

My first approach was to use QML's Context2D feature: https://doc.qt.io/qt-5/qml-qtquick-context2d.html. Maybe it's totally wrong to do it this way, but maybe it's a good starting point. I tried to create an rectangle (which works) and a clipping area (which doesn't work). Besides the fact my implementation of the clipping doesn't work I would have the problem that the clip() command erases the area outside its path but not inside (at least that's what I understood from the docs: https://doc.qt.io/qt-5/qml-qtquick-context2d.html#clip-method).

Canvas {

    anchors.fill: parent

    onPaint: {
        var ctx = getContext("2d");
        ctx.fillStyle = "black"

        ctx.beginPath();
        ctx.fillRect(0, 0, Sizes.rootWindow.width, Sizes.rootWindow.height);
        ctx.fill();
    }

Body:
if the hole is exactly centered and the borders are all have the same size, you could use a transparent rectangle with borders:

Rectangle {
    anchors.fill: parent
    color: "transparent"
    border.color: "black"
    border.width: 50
}


问:
How to set padding in custom view?
In my application I have a custom TextView that has some arrow on the left in onDraw method on Canvas. The problem I have is with gravity of the text, as I want it to be centered.

The only way I have found to solve this problem is to set custom left padding, so that text will be centered only in the area that it should be. In order to find out this padding I need to calculate size of the view first.

The problem is that if I put it into onMeasure or onLayout then I get stuck into the loop, so that padding is increasing until maximum value. This is happening, because setPadding is causing those methods to execute again.

How to solve this problem?

答:
If your view is static and does not change its padding while inflating, you can call setPadding in onAttachedToWindow().

It calls just when view added to the window!

Title: How to set padding in custom view?


问:
R - Add columns to dataframes in list by looping through elements in a vector
I am working with several datasets that measure the same variables over many years. I am trying to add a year variable to each dataset, but more generally I want to loop through elements in a vector and add each as a new column in a list of dataframes. This question was similar to mine but I want to iteratively add each element in a vector to the corresponding dataframe as a new column:
R - New variables over several data frames in a loop

Here's sample data:

```<code>year <- c(1:3)
data1 <- data.frame(var1 = c(1:5))
data2 <- data.frame(var1 = c(11:15))
data3 <- data.frame(var1 = c(21:25))
data_list <- list(data1 = data1, data2 = data2, data3 = data3)
</code>```

I want to do this but think there's probably some way to loop (or lapply) that I haven't been able to figure out yet:

```<code>data1$year <- year[1]
data2$year <- year[2]
data3$year <- year[3]
</code>```

Since I have many years and datasets to work with, it'd be great to have a more efficient solution. Thanks!

答:
The full answer based on @@thelatemail comment:

The function Map(cbind, data_list, year=year) should do the job. Step by step:

Map function indicates a loop through elements in a list

cbind attaches newly created column

year = years creates new column named year based on elements in a vector years

Having your dummy example:

```<code># vector of values you wish to add
years <- c(1:3)     # changed to plural to indicate vector of values rather than single value

# make dummy list of dataframes
data1 <- data.frame(var1 = c(1:5))
data2 <- data.frame(var1 = c(11:15))
data3 <- data.frame(var1 = c(21:25))
data_list <- list(data1 = data1, data2 = data2, data3 = data3)

# Loop through list of dataframes and to each dataframe add a new column
Map(cbind, data_list, year=years)
</code>```

The output you wish:

```<code>$`data1`
  var1 year
1    1    1
2    2    1
3    3    1
4    4    1
5    5    1

$data2
  var1 year
1   11    2
2   12    2
3   13    2
4   14    2
5   15    2

$data3
  var1 year
1   21    3
2   22    3
3   23    3
4   24    3
5   25    3
</code>```

Body:
I am working with several datasets that measure the same variables over many years. I am trying to add a year variable to each dataset, but more generally I want to loop through elements in a vector and add each as a new column in a list of dataframes. This question was similar to mine but I want to iteratively add each element in a vector to the corresponding dataframe as a new column:
R - New variables over several data frames in a loop

Here's sample data:

year <- c(1:3)
data1 <- data.frame(var1 = c(1:5))
data2 <- data.frame(var1 = c(11:15))
data3 <- data.frame(var1 = c(21:25))
data_list <- list(data1 = data1, data2 = data2, data3 = data3)

I want to do this but think there's probably some way to loop (or lapply) that I haven't been able to figure out yet:

data1$year <- year[1]
data2$year <- year[2]
data3$year <- year[3]

Since I have many years and datasets to work with, it'd be great to have a more efficient solution. Thanks!

Body:
The full answer based on @@thelatemail comment:

The function Map(cbind, data_list, year=year) should do the job. Step by step:

Map function indicates a loop through elements in a list

cbind attaches newly created column

year = years creates new column named year based on elements in a vector years

Having your dummy example:

# vector of values you wish to add
years <- c(1:3)     # changed to plural to indicate vector of values rather than single value

# make dummy list of dataframes
data1 <- data.frame(var1 = c(1:5))
data2 <- data.frame(var1 = c(11:15))
data3 <- data.frame(var1 = c(21:25))
data_list <- list(data1 = data1, data2 = data2, data3 = data3)

# Loop through list of dataframes and to each dataframe add a new column
Map(cbind, data_list, year=years)

The output you wish:

$`data1`
  var1 year
1    1    1
2    2    1
3    3    1
4    4    1
5    5    1

$data2
  var1 year
1   11    2
2   12    2
3   13    2
4   14    2
5   15    2

$data3
  var1 year
1   21    3
2   22    3
3   23    3
4   24    3
5   25    3


问:
hive date cast issue
Hi in my Hive table I have a column with the date values like this .

```<code>cl1
31102019000000
30112019000000
31122019000000
</code>```

I have tried to convert the column values to date format like this

```<code>Select from_unixtime(unix_timestamp(cl1,'yyyy/MM/dd'),'yyyy-MM-dd') from table1;
</code>```

it prints NUll. Any help will be appreciated.

答:
Try using this

```<code>Select from_unixtime(unix_timestamp(REGEXP_REPLACE(cl1,'0+$',''),'ddMMyyyy'),'yyyy-MM-dd') from table1;
</code>```

but this would fail for years 2020,2010.
So the below query would be a better alternative

```<code>Select from_unixtime(unix_timestamp(cast(cast(cl1/1000000 as bigint) as string),'ddMMyyyy'),'yyyy-MM-dd') from table1;
</code>```

Title: hive date cast issue

Body:
Hi in my Hive table I have a column with the date values like this .

cl1
31102019000000
30112019000000
31122019000000

I have tried to convert the column values to date format like this

Select from_unixtime(unix_timestamp(cl1,'yyyy/MM/dd'),'yyyy-MM-dd') from table1;

it prints NUll. Any help will be appreciated.

Body:
Try using this

Select from_unixtime(unix_timestamp(REGEXP_REPLACE(cl1,'0+$',''),'ddMMyyyy'),'yyyy-MM-dd') from table1;

but this would fail for years 2020,2010.
So the below query would be a better alternative

Select from_unixtime(unix_timestamp(cast(cast(cl1/1000000 as bigint) as string),'ddMMyyyy'),'yyyy-MM-dd') from table1;


答:
The UnixTimeStamp which you are trying to convert to date format is out of range.
Your Time stamp corresponds to :

```<code>GMT: Saturday, August 2, 2955 1:43:20 AM
Your time zone: Saturday, August 2, 2955 5:43:20 AM GMT+04:00
Relative: In 936 years
</code>```

It is an open bug in MYSql community. Please check the below URL for reference.
https://forums.mysql.com/read.php?20,385047,385132#msg-385132

MySQL database's built-in functions like UNIX_TIMESTAMP() will return 0 after 03:14:07 UTC on 19 January 2038. (Source: https://en.wikipedia.org/wiki/Year_2038_problem)

Title: hive date cast issue

Body:
The UnixTimeStamp which you are trying to convert to date format is out of range.
Your Time stamp corresponds to :

GMT: Saturday, August 2, 2955 1:43:20 AM
Your time zone: Saturday, August 2, 2955 5:43:20 AM GMT+04:00
Relative: In 936 years

It is an open bug in MYSql community. Please check the below URL for reference.
https://forums.mysql.com/read.php?20,385047,385132#msg-385132

MySQL database's built-in functions like UNIX_TIMESTAMP() will return 0 after 03:14:07 UTC on 19 January 2038. (Source: https://en.wikipedia.org/wiki/Year_2038_problem)


问:
How do I specify an absolute path?
I wrote this code, but I couldn't get the html. I don't know why. I want to know why this is when the route is not wrong.</p>

```<code><img id = "navLogo" src = "C:/Bitnami/wampstack-7.1.27-0/apache2/htdocs/TermProject/imgs/navLogo.jpg"></img>
</code>```

答:
Ray Hatfield's answer is good but I don't have enough rep to comment.

I think you are misunderstanding absolute vs relative paths here.

You are thinking of absolute as starting with your c: drive, but on a web server, the absolute path starts at the root of your site, which is always just a forward slash "/".

Relative paths begin from the current directory of the source file(s) that specify them.

Neither of them can go higher in the file system than your site's root folder.

To put it simply (specifically answering "How do I specify an absolute path?"):

All absolute paths on the web start with a /

All relative paths on the web do not.

Given the path in your example:

C:/Bitnami/wampstack-7.1.27-0/apache2/htdocs/TermProject/imgs/navLogo.jpg

A default apache installation considers the site root to be the "htdocs" in this path.

This means that the absolute path / on your website is found at C:/Bitnami/wampstack-7.1.27-0/apache2/htdocs/ on your hard drive.

If you have a file C:/Bitnami/wampstack-7.1.27-0/apache2/htdocs/TermProject/index.html then you can access the navLogo image from that page

with an absolute path at:

/TermProject/imgs/navLogo.jpg

or a relative path at (note the missing forward slash):

imgs/navLogo.jpg

Title: How do I specify an absolute path?


问:
No module named import_export although it is installed
I'm trying to use django-import-export in my django site. I installed it in my virtual environment using "pip install django-import-export" and I know it's there because I ran pip freeze but it still gives an error when I do "eb create django-env": "ModuleNotFoundError: No module named 'import_export'".

It is included in INSTALLED_APPS in settings.py and I ran "python manage.py collectstatic" before I got the error.

```<code>2019-05-26 06:21:41    ERROR   [Instance: i-08f7c48c9afd84a8f] Command failed on instance. Return code: 1 Output: (TRUNCATED)...ile "<frozen importlib._bootstrap>", line 994, in _gcd_import
File "<frozen importlib._bootstrap>", line 971, in _find_and_load
File "<frozen importlib._bootstrap>", line 953, in _find_and_load_unlocked
ModuleNotFoundError: No module named 'import_export'.
container_command 01_migrate in .ebextensions/db-migrate.config failed. For more detail, check /var/log/eb-activity.log using console or EB CLI.
2019-05-26 06:21:41    INFO    Command execution completed on all instances. Summary: [Successful: 0, Failed: 1].
2019-05-26 06:22:44    ERROR   Create environment operation is complete, but with errors. For more information, see troubleshooting documentation.

ERROR: ServiceError - Create environment operation is complete, but with errors. For more information, see troubleshooting documentation.
</code>```

I am a beginner and this is my first question on StackOverflow. I appreciate any help.

答: Maybe you didn't install django-import-export successfully.Try to check your virtual environment.</p>

Body:
I'm trying to use django-import-export in my django site. I installed it in my virtual environment using "pip install django-import-export" and I know it's there because I ran pip freeze but it still gives an error when I do "eb create django-env": "ModuleNotFoundError: No module named 'import_export'".

It is included in INSTALLED_APPS in settings.py and I ran "python manage.py collectstatic" before I got the error.

2019-05-26 06:21:41    ERROR   [Instance: i-08f7c48c9afd84a8f] Command failed on instance. Return code: 1 Output: (TRUNCATED)...ile "<frozen importlib._bootstrap>", line 994, in _gcd_import
File "<frozen importlib._bootstrap>", line 971, in _find_and_load
File "<frozen importlib._bootstrap>", line 953, in _find_and_load_unlocked
ModuleNotFoundError: No module named 'import_export'.
container_command 01_migrate in .ebextensions/db-migrate.config failed. For more detail, check /var/log/eb-activity.log using console or EB CLI.
2019-05-26 06:21:41    INFO    Command execution completed on all instances. Summary: [Successful: 0, Failed: 1].
2019-05-26 06:22:44    ERROR   Create environment operation is complete, but with errors. For more information, see troubleshooting documentation.

ERROR: ServiceError - Create environment operation is complete, but with errors. For more information, see troubleshooting documentation.

I am a beginner and this is my first question on StackOverflow. I appreciate any help.


问:
How data backup is handled in production via Docker
I've a following Docker file that runs a MySQL image.

```<code>version: '3'

services:

  mysql:
    image: "mysql:5.7"
    container_name: "mysql"
    ports:
      - "6603:3306"
    volumes:
      - ./assets/schema.sql:/docker-entrypoint-initdb.d/init.sql
    environment:
      DATABASE_HOST: mysql
      MYSQL_ROOT_PASSWORD: rootpass
      MYSQL_DATABASE: mydb
      MYSQL_USER: mysql
      MYSQL_PASSWORD: pass
</code>```

I'm running it locally but I've concerns before I go in production.

How the data backup occurs? Shall I keep committing container to an image?

I'm new to Docker so wondering how things are handled in production when it comes to database deployed via Docker.

答:
You should add volumes to contain the actual db files. You currently have only the schema, for some reason, and when your container will go down, your data will be lost.
After adding the volumes as persistent, you could use standard backup method, such as a cron job.</p>

Body:
I've a following Docker file that runs a MySQL image.

version: '3'

services:

  mysql:
    image: "mysql:5.7"
    container_name: "mysql"
    ports:
      - "6603:3306"
    volumes:
      - ./assets/schema.sql:/docker-entrypoint-initdb.d/init.sql
    environment:
      DATABASE_HOST: mysql
      MYSQL_ROOT_PASSWORD: rootpass
      MYSQL_DATABASE: mydb
      MYSQL_USER: mysql
      MYSQL_PASSWORD: pass

I'm running it locally but I've concerns before I go in production.

How the data backup occurs? Shall I keep committing container to an image?

I'm new to Docker so wondering how things are handled in production when it comes to database deployed via Docker.


问:
When is std::thread destructor called?
I know that std::thread destructors are called on main exit, or when a thread object goes out of scope.

But is it also destroyed when a function that it is calling is done executing?

If not what happens to such a thread, can I still join() it?

答:
But is it also destroyed when a function that it is calling is done executing? If not what happens to such a thread, can I still join() it?

No it isn't destroyed, but marked joinable(). So yes you can still join() it.

Otherwise as from the title of your question ("When is std::thread destructor called?") and what you say in your post

I know that std::thread destructors are called on main exit, or when a thread object goes out of scope.

It's like with any other instance: The destructor is called when the instance goes out of scope or delete is called in case the instances were allocated dynamically.

Here's a small example code

```<code>#include <thread>
#include <iostream>
#include <chrono>

using namespace std::chrono_literals;

void foo() {
    std::cout  << "Hello from thread!" << std::endl;
}

int main() {
    std::thread t(foo);
    std::this_thread::sleep_for(1s);
    std::cout << "t.joinable() is " << t.joinable() << std::endl;
    t.join();
}
</code>```

The output is

```<code>Hello from thread!
t.joinable() is 1
</code>```

See it live.

Title: When is std::thread destructor called?

Body:
But is it also destroyed when a function that it is calling is done executing? If not what happens to such a thread, can I still join() it?

No it isn't destroyed, but marked joinable(). So yes you can still join() it.

Otherwise as from the title of your question ("When is std::thread destructor called?") and what you say in your post

I know that std::thread destructors are called on main exit, or when a thread object goes out of scope.

It's like with any other instance: The destructor is called when the instance goes out of scope or delete is called in case the instances were allocated dynamically.

Here's a small example code

#include <thread>
#include <iostream>
#include <chrono>

using namespace std::chrono_literals;

void foo() {
    std::cout  << "Hello from thread!" << std::endl;
}

int main() {
    std::thread t(foo);
    std::this_thread::sleep_for(1s);
    std::cout << "t.joinable() is " << t.joinable() << std::endl;
    t.join();
}

The output is

Hello from thread!
t.joinable() is 1

See it live.


问:
How to avoid a thread being completed in C#?
I have a RabbitMQ client program written in C#. While the application works in console based application (because execution is blocked by Console.ReadLine) it does not work in Windows Form based application. In Windows Form application, execution doesn't wait on Console.ReadLine and terminates on completion. I am looking for solution where my listener keeps monitoring for new messages from server without being terminated.
Here is the the client code :</p>

```<code>    try {
            var factory = new ConnectionFactory() { HostName = "xxx" , UserName ="xxx", Password="xxx"};
            using(var connection = factory.CreateConnection())
            using(var channel = connection.CreateModel())
            {
                channel.ExchangeDeclare(exchange: "call_notify", type: "fanout");

                var queueName = channel.QueueDeclare().QueueName;
                channel.QueueBind(queue: queueName,
                                  exchange: "call_notify",
                                  routingKey: "");

                var consumer = new EventingBasicConsumer(channel);
                consumer.Received += (model, ea) =>
                {
                    var body = ea.Body;
                    var message = Encoding.UTF8.GetString(body);
                    Console.WriteLine(message);
                };
                channel.BasicConsume(queue: queueName,
                                     autoAck: true,
                                     consumer: consumer);

                Console.WriteLine(" Press [enter] to exit.");
                Console.ReadLine();  // Program does'nt wait here in windows form based application
            }
        }
</code>```

答:
If you want the code to work on both platforms, you'll be much better off creating an abstraction layer that exposes the messages and deals with the start/stop logic.

```<code>public class RabbitMQManager : IDisposable
{
    private bool _disposed = false;
    private IModel _channel;
    private IConnection _connection;

    public event EventHandler<string> MessageReceived;

    protected virtual void Dispose(bool disposing)
    {
        if (!_disposed)
        {
            if (disposing)
            {
                _channel?.Dispose();
                _connection?.Dispose();
            }

            _disposed = true;
        }
    }

    public void Dispose()
    {
        Dispose(true);
    }

    public void Connect()
    {
        var factory = new ConnectionFactory { HostName = "xxx", UserName = "xxx", Password = "xxx" };
        _connection = factory.CreateConnection();
        _channel = _connection.CreateModel();

        _channel.ExchangeDeclare(exchange: "call_notify", type: "fanout");

        string queueName = _channel.QueueDeclare().QueueName;
        _channel.QueueBind(queue: queueName,
                          exchange: "call_notify",
                          routingKey: "");

        var consumer = new EventingBasicConsumer(_channel);
        consumer.Received += (model, ea) =>
        {
            byte[] body = ea.Body;
            string message = Encoding.UTF8.GetString(body);
            MessageReceived?.Invoke(this, message);
        };

        _channel.BasicConsume(queue: queueName,
                             autoAck: true,
                             consumer: consumer);
    }
}
</code>```

You can then use this in any project type you want by creating an instance of the class and subscribing to the MessageReceived event. For example, a WinForms implementation would be just:

```<code>public class MyForm : Form
{
    private RabbitMQManager _rabbitMQManager;

    public MyForm() { _rabbitMQManager = new RabbitMQManager(); }

    // you can call this from constructor or some event
    public void Connect()
    {
        _rabbitMQManager.MessageReceived = (sender, msg) => someLabel.Text = msg;
        _rabbitMQManager.Connect();
    }
}
</code>```

Look at this Q&A to know how to override MyForm.Dispose so that resources are properly disposed: How do I extend a WinForm's Dispose method?

And in a console application, this could just be:

```<code>using (var manager = new RabbitMQManager())
{
    manager.MessageReceived += (sender, msg) => Console.WriteLine(msg);
    manager.Connect();
    Console.Read();
}
</code>```

Body:
I have a RabbitMQ client program written in C#. While the application works in console based application (because execution is blocked by Console.ReadLine) it does not work in Windows Form based application. In Windows Form application, execution doesn't wait on Console.ReadLine and terminates on completion. I am looking for solution where my listener keeps monitoring for new messages from server without being terminated.
Here is the the client code :

    try {
            var factory = new ConnectionFactory() { HostName = "xxx" , UserName ="xxx", Password="xxx"};
            using(var connection = factory.CreateConnection())
            using(var channel = connection.CreateModel())
            {
                channel.ExchangeDeclare(exchange: "call_notify", type: "fanout");

                var queueName = channel.QueueDeclare().QueueName;
                channel.QueueBind(queue: queueName,
                                  exchange: "call_notify",
                                  routingKey: "");

                var consumer = new EventingBasicConsumer(channel);
                consumer.Received += (model, ea) =>
                {
                    var body = ea.Body;
                    var message = Encoding.UTF8.GetString(body);
                    Console.WriteLine(message);
                };
                channel.BasicConsume(queue: queueName,
                                     autoAck: true,
                                     consumer: consumer);

                Console.WriteLine(" Press [enter] to exit.");
                Console.ReadLine();  // Program does'nt wait here in windows form based application
            }
        }

Body:
If you want the code to work on both platforms, you'll be much better off creating an abstraction layer that exposes the messages and deals with the start/stop logic.

public class RabbitMQManager : IDisposable
{
    private bool _disposed = false;
    private IModel _channel;
    private IConnection _connection;

    public event EventHandler<string> MessageReceived;

    protected virtual void Dispose(bool disposing)
    {
        if (!_disposed)
        {
            if (disposing)
            {
                _channel?.Dispose();
                _connection?.Dispose();
            }

            _disposed = true;
        }
    }

    public void Dispose()
    {
        Dispose(true);
    }

    public void Connect()
    {
        var factory = new ConnectionFactory { HostName = "xxx", UserName = "xxx", Password = "xxx" };
        _connection = factory.CreateConnection();
        _channel = _connection.CreateModel();

        _channel.ExchangeDeclare(exchange: "call_notify", type: "fanout");

        string queueName = _channel.QueueDeclare().QueueName;
        _channel.QueueBind(queue: queueName,
                          exchange: "call_notify",
                          routingKey: "");

        var consumer = new EventingBasicConsumer(_channel);
        consumer.Received += (model, ea) =>
        {
            byte[] body = ea.Body;
            string message = Encoding.UTF8.GetString(body);
            MessageReceived?.Invoke(this, message);
        };

        _channel.BasicConsume(queue: queueName,
                             autoAck: true,
                             consumer: consumer);
    }
}

You can then use this in any project type you want by creating an instance of the class and subscribing to the MessageReceived event. For example, a WinForms implementation would be just:

public class MyForm : Form
{
    private RabbitMQManager _rabbitMQManager;

    public MyForm() { _rabbitMQManager = new RabbitMQManager(); }

    // you can call this from constructor or some event
    public void Connect()
    {
        _rabbitMQManager.MessageReceived = (sender, msg) => someLabel.Text = msg;
        _rabbitMQManager.Connect();
    }
}

Look at this Q&A to know how to override MyForm.Dispose so that resources are properly disposed: How do I extend a WinForm's Dispose method?

And in a console application, this could just be:

using (var manager = new RabbitMQManager())
{
    manager.MessageReceived += (sender, msg) => Console.WriteLine(msg);
    manager.Connect();
    Console.Read();
}


答:
I do not think you should commit container to an image. Data is something managed by the container but it is not "part" of db container. If you want to store data between container restarts you should use volumes - this way you will be able to save data on your host volume and run more mysql cointainers with this volume, sharing same data. How to use volumes with mysql image is described in their documentation - section Where to Store Data.

And also if you wanted to make dumps of your database it is also described in the documentation in section Creating database dumps.

In case you are running more db containers and you want to make dumps you should automate this process somehow for example as Jenkins job that has access to your containers, or some scripts run as cron job on your docker host - it all depends what tools you are using.

Title: How data backup is handled in production via Docker


问:
Emulator: emulator: ERROR: Running multiple emulators with the same AVD is an experimental feature
I removed the emulator and reinstalled it and got the same error.

Emulator: emulator: ERROR: Running multiple emulators with the same AVD is an experimental feature.

Emulator: Process finished with exit code 1.

答:
It can be solved using this method. It worked for me.
Follow the steps:

Open Android Studio.

Go to AVD Manager.

In the Actions column, for the respective avd, click on the down arrow and click on Stop.

This will stop the Emulator and then you can restart it from the command line.


问:
Kotlin lambda with explicit return type
I have the following Kotlin classes:

```<code>sealed class Result {
  data class Success()
  data class Failure()
}

class Single<R>(val value: R?, throwable: Throwable?) {
  fun map(mapper: (R) -> T): Single<T> {
    return Single(mapper(value!!), null)
  }
  fun onError(recover: (Throwable) -> T): Single<T> {
    return Single(recover(throwable!!))
  }
}
</code>```

And I have the following function:

```<code>fun handle(single: Single<String>): Single<Result> {
  return single
    .map { Single.Success() }
    .onError { Single.Error() }
}
</code>```

But onError fails with:

```<code>Type Mismatch.
  Required: Single.Success
  Found:    Single.Error
</code>```

I realize I can work around this with:

```<code>fun handle(single: Single<String>): Single<Result> {
  return single
    .map { Single.Success() as Single<Result> }
    .onError { Single.Error() as Single<Result> }
}
</code>```

But I prefer to force type inference to work left-to-right as much as possible. That is, I'd prefer the { Single.Success() } lambda to specify and explicit return type.

Is an explicit return type allowed in Kotlin? the functionLiteral Grammar makes it look like it can't, but I'm not an expert in reading grammars.

答:
You actually cannot explicitly declare the return type in a Kotlin lambda:

One thing missing from the lambda expression syntax presented above is the ability to specify the return type of the function.

https://kotlinlang.org/docs/reference/lambdas.html#anonymous-functions

Title: Kotlin lambda with explicit return type

Body:
I have the following Kotlin classes:

sealed class Result {
  data class Success()
  data class Failure()
}

class Single<R>(val value: R?, throwable: Throwable?) {
  fun map(mapper: (R) -> T): Single<T> {
    return Single(mapper(value!!), null)
  }
  fun onError(recover: (Throwable) -> T): Single<T> {
    return Single(recover(throwable!!))
  }
}

And I have the following function:

fun handle(single: Single<String>): Single<Result> {
  return single
    .map { Single.Success() }
    .onError { Single.Error() }
}

But onError fails with:

Type Mismatch.
  Required: Single.Success
  Found:    Single.Error

I realize I can work around this with:

fun handle(single: Single<String>): Single<Result> {
  return single
    .map { Single.Success() as Single<Result> }
    .onError { Single.Error() as Single<Result> }
}

But I prefer to force type inference to work left-to-right as much as possible. That is, I'd prefer the { Single.Success() } lambda to specify and explicit return type.

Is an explicit return type allowed in Kotlin? the functionLiteral Grammar makes it look like it can't, but I'm not an expert in reading grammars.


问:
Clone and rename a component
I have a component that is used often and for many porpuses - <Box />.

I'd like to rename it to declare it's functional meaning in the code, something along these lines:

```<code>import Box from '../reusable-components/Box'

const Wrapper = Box
const Card = Box
const TopSection = Box

// Or like this?
// const [Wrapper, Card, TopSection] = cloneComponent(Box)

function MyComponent() {
  return (
    <Wrapper>
      <TopSection style={{display: 'flex'}}>
        <Card>Item A</Card>
        <Card>Item B</Card>
        <Card>Item C</Card>
      </TopSection>
    </Wrapper>
  )
}
</code>```

答:
If its a react component, there is no point "cloning" it. Since When you use it in , it will create a new instance. In fact I am not clear why you need to rename it at all, but here is how you can do it</p>

```<code>import Wrapper from '../reusable-components/Box'
import Card from '../reusable-components/Box'
import TopSection from '../reusable-components/Box'
//Or
 const [Wrapper, Card, TopSection] = [Box,Box,Box]

function MyComponent() {
  return (
    <Wrapper>
      <TopSection style={{display: 'flex'}}>
        <Card>Item A</Card>
        <Card>Item B</Card>
        <Card>Item C</Card>
      </TopSection>
    </Wrapper>
  )
}
</code>```

Title: Clone and rename a component

Body:
I have a component that is used often and for many porpuses - <Box />.

I'd like to rename it to declare it's functional meaning in the code, something along these lines:

import Box from '../reusable-components/Box'

const Wrapper = Box
const Card = Box
const TopSection = Box

// Or like this?
// const [Wrapper, Card, TopSection] = cloneComponent(Box)

function MyComponent() {
  return (
    <Wrapper>
      <TopSection style={{display: 'flex'}}>
        <Card>Item A</Card>
        <Card>Item B</Card>
        <Card>Item C</Card>
      </TopSection>
    </Wrapper>
  )
}

Body:
If its a react component, there is no point "cloning" it. Since When you use it in , it will create a new instance. In fact I am not clear why you need to rename it at all, but here is how you can do it

import Wrapper from '../reusable-components/Box'
import Card from '../reusable-components/Box'
import TopSection from '../reusable-components/Box'
//Or
 const [Wrapper, Card, TopSection] = [Box,Box,Box]

function MyComponent() {
  return (
    <Wrapper>
      <TopSection style={{display: 'flex'}}>
        <Card>Item A</Card>
        <Card>Item B</Card>
        <Card>Item C</Card>
      </TopSection>
    </Wrapper>
  )
}


问:
Saving changed clip into file
How can I save an opened audio file with changed volume?

I trying this:

```<code>AudioInputStream audioInputStream = AudioSystem.getAudioInputStream(new File("some_file.wav"));

Clip clip = AudioSystem.getClip();
clip.open(audioInputStream);
FloatControl gainControl = (FloatControl) clip.getControl(FloatControl.Type.MASTER_GAIN);

gainControl.setValue(-30.0f); // Reduce volume by 10 decibels.
File file = new File("new.wav");
AudioSystem.write(audioInputStream, AudioFileFormat.Type.WAVE, file);
</code>```

But this is saving an empty file.

答:
I think your best bet will be to take the bytes from the AudioInputStream and convert them to PCM values, then multiply the PCM values by a factor that matches -10 db. I don't know what that factor would be. Then convert back to bytes and write that.

The first code example in the tutorial Using Files and Format Converters shows a while loop where the conversions would take place, at the comment: "// Here, do something useful with the audio..."

The prior tutorial on the Audio Trail: "Processing Audio with Controls" might also be helpful, but the built-in controls are limited and dependent on the host computer and OS. For example, if you want to change volumes (put in a fade-in or fade-out) the control lines probably don't work very well due to the granularity being tied to the size of the audio buffer. So I recommend the advice of the final paragraphs of the "Processing Audio with Controls" tutorial, the section "Manipulating the Audio Data Directly".

Title: Saving changed clip into file

Body:
How can I save an opened audio file with changed volume?

I trying this:

AudioInputStream audioInputStream = AudioSystem.getAudioInputStream(new File("some_file.wav"));

Clip clip = AudioSystem.getClip();
clip.open(audioInputStream);
FloatControl gainControl = (FloatControl) clip.getControl(FloatControl.Type.MASTER_GAIN);

gainControl.setValue(-30.0f); // Reduce volume by 10 decibels.
File file = new File("new.wav");
AudioSystem.write(audioInputStream, AudioFileFormat.Type.WAVE, file);

But this is saving an empty file.


问:
Change sound button image on clicking another button swift 2.2
I am creating a Tableview inside which is Tableviewcell and on cell there is a label and sound button. For each label there is a sound on button click. When I click for the first time on btn1 the sound plays and the button image changes to "pause" when I click again the same button sound stops and the image changes to "play" works perfectly in this manner but when I click for the first time on one button let suppose btn1 and without clicking it again (stoping sound) I click on btn2, the sound of the btn1 stops and the image of btn1 nor  btn2 changes. I want that when I click on btn 2,3, or 4 the previous sound should stop, the  image of previous button (means all buttons except the current) should change to "play" and the current clicked button should change to "pause"  and the sound of the previous click should stop and the current  clicked should play.

```<code>import UIKit

class TableViewCell: UITableViewCell {

    @IBOutlet weak var titleLable: UILabel!
    @IBOutlet weak var sound: UIButton!
    override func awakeFromNib() {
        super.awakeFromNib()
    }

class ViewController: UIViewController , UITableViewDataSource , UITableViewDelegate , GADInterstitialDelegate {

    var countsNumberOfButtonClicks = 0
    var countsNumberOfInfoBtnClicks = 0
    var isFirstTime = false
    var player : AVAudioPlayer! = nil
    var titleAlert: String!

    @IBOutlet weak var myTableView: UITableView!
    var toggleState = 1

 func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell.

    {

    let myCell = self.myTableView.dequeueReusableCellWithIdentifier("myCell", forIndexPath: indexPath) as! TableViewCell

        myCell.titleLable.text = self.Duck[indexPath.row]

        myCell.sound.tag = indexPath.row
        myCell.sound.addTarget(self, action: #selector(self.playSound), forControlEvents: .TouchUpInside)
     return myCell
    }

   @IBAction func playSound(sender: UIButton) {

            if toggleState == 1 {
            let fullName: String = self.Duck[sender.tag]
            let fullNameArr = fullName.componentsSeparatedByString(" ")
            let path = NSBundle.mainBundle().pathForResource(fullNameArr[0], ofType:"wav", inDirectory: "sounds")
            let fileURL = NSURL(fileURLWithPath: path!)
            do {
                player = try AVAudioPlayer(contentsOfURL: fileURL)
                player.prepareToPlay()
            } catch {
                print("Problem in getting File")
              }
            player.play()
            sender.setImage(UIImage(named: "pause.png"), forState: UIControlState.Normal)
            print("toggle state 1")
            toggleState = 2
        }
        else {
            player.pause()
            toggleState = 1
            sender.setImage(UIImage(named: "play.png"), forState: UIControlState.Normal)
            print("Toggle state else")
 }
</code>```

Simulator result

答:
In you class, declare a variable,

var currentlyPlaying : UIButton?

And wherever you play the sound, store the button which played the sound in this variable and whenever this variable is about to be change, reset the previous ones image and store the new one.

```<code>@IBAction func playSound(sender: UIButton) {

        if currentlyPlaying != sender || toggleState == 1 {

        //Set image in previous
        currentlyPlaying?.setImage(UIImage(named: "play.png")

        if player != nil{
            player.pause()
        }

        let fullName: String = self.Duck[sender.tag]
        let fullNameArr = fullName.componentsSeparatedByString(" ")
        let path = NSBundle.mainBundle().pathForResource(fullNameArr[0], ofType:"wav", inDirectory: "sounds")
        let fileURL = NSURL(fileURLWithPath: path!)
        do {
            player = try AVAudioPlayer(contentsOfURL: fileURL)
            player.prepareToPlay()
        } catch {
            print("Problem in getting File")
          }
        player.play()

        sender.setImage(UIImage(named: "pause.png"), forState: UIControlState.Normal)

        //Store new
        currentlyPlaying = sender

        print("toggle state 1")

        if sender != currentlyPlaying{
            toggleState = 2
        }

        myTableView.reloadData()

    }
    else {
        player.pause()
        toggleState = 1
        sender.setImage(UIImage(named: "play.png"), forState: UIControlState.Normal)
        print("Toggle state else")
}
</code>```

Body:
I am creating a Tableview inside which is Tableviewcell and on cell there is a label and sound button. For each label there is a sound on button click. When I click for the first time on btn1 the sound plays and the button image changes to "pause" when I click again the same button sound stops and the image changes to "play" works perfectly in this manner but when I click for the first time on one button let suppose btn1 and without clicking it again (stoping sound) I click on btn2, the sound of the btn1 stops and the image of btn1 nor  btn2 changes. I want that when I click on btn 2,3, or 4 the previous sound should stop, the  image of previous button (means all buttons except the current) should change to "play" and the current clicked button should change to "pause"  and the sound of the previous click should stop and the current  clicked should play.

import UIKit

class TableViewCell: UITableViewCell {

    @IBOutlet weak var titleLable: UILabel!
    @IBOutlet weak var sound: UIButton!
    override func awakeFromNib() {
        super.awakeFromNib()
    }

class ViewController: UIViewController , UITableViewDataSource , UITableViewDelegate , GADInterstitialDelegate {

    var countsNumberOfButtonClicks = 0
    var countsNumberOfInfoBtnClicks = 0
    var isFirstTime = false
    var player : AVAudioPlayer! = nil
    var titleAlert: String!

    @IBOutlet weak var myTableView: UITableView!
    var toggleState = 1

 func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell.

    {

    let myCell = self.myTableView.dequeueReusableCellWithIdentifier("myCell", forIndexPath: indexPath) as! TableViewCell

        myCell.titleLable.text = self.Duck[indexPath.row]

        myCell.sound.tag = indexPath.row
        myCell.sound.addTarget(self, action: #selector(self.playSound), forControlEvents: .TouchUpInside)
     return myCell
    }

   @IBAction func playSound(sender: UIButton) {

            if toggleState == 1 {
            let fullName: String = self.Duck[sender.tag]
            let fullNameArr = fullName.componentsSeparatedByString(" ")
            let path = NSBundle.mainBundle().pathForResource(fullNameArr[0], ofType:"wav", inDirectory: "sounds")
            let fileURL = NSURL(fileURLWithPath: path!)
            do {
                player = try AVAudioPlayer(contentsOfURL: fileURL)
                player.prepareToPlay()
            } catch {
                print("Problem in getting File")
              }
            player.play()
            sender.setImage(UIImage(named: "pause.png"), forState: UIControlState.Normal)
            print("toggle state 1")
            toggleState = 2
        }
        else {
            player.pause()
            toggleState = 1
            sender.setImage(UIImage(named: "play.png"), forState: UIControlState.Normal)
            print("Toggle state else")
 }

Simulator result

Body:
In you class, declare a variable,

var currentlyPlaying : UIButton?

And wherever you play the sound, store the button which played the sound in this variable and whenever this variable is about to be change, reset the previous ones image and store the new one.

@IBAction func playSound(sender: UIButton) {

        if currentlyPlaying != sender || toggleState == 1 {

        //Set image in previous
        currentlyPlaying?.setImage(UIImage(named: "play.png")

        if player != nil{
            player.pause()
        }

        let fullName: String = self.Duck[sender.tag]
        let fullNameArr = fullName.componentsSeparatedByString(" ")
        let path = NSBundle.mainBundle().pathForResource(fullNameArr[0], ofType:"wav", inDirectory: "sounds")
        let fileURL = NSURL(fileURLWithPath: path!)
        do {
            player = try AVAudioPlayer(contentsOfURL: fileURL)
            player.prepareToPlay()
        } catch {
            print("Problem in getting File")
          }
        player.play()

        sender.setImage(UIImage(named: "pause.png"), forState: UIControlState.Normal)

        //Store new
        currentlyPlaying = sender

        print("toggle state 1")

        if sender != currentlyPlaying{
            toggleState = 2
        }

        myTableView.reloadData()

    }
    else {
        player.pause()
        toggleState = 1
        sender.setImage(UIImage(named: "play.png"), forState: UIControlState.Normal)
        print("Toggle state else")
}


答:
Try to reset the password using drush</p>

```<code>drush upwd USERNAME PASSWORD
</code>```

Title: Password reset but Dupal doesn't have pass field in the users table?

Body:
I'm trying to reset the admin password for a Drupal account, but it doesn't seem to have a pass field in the users table.

UPDATE users
SET pass ='$S$CTo9G7Lx28rzCfpn4WB2hUlknDKv6QTqHaf82WLbhPT2K5TzKzML'
WHERE uid = 1;

Instead it has a pass field in the table users_field_data. What does this mean about Drupal?

I can't find any docs on the users_field_data table.

I'm on Drupal VERSION = '8.2.7';

mysql> show create table users;
+-------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| Table | Create Table                                                                                |
+-------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| users | CREATE TABLE `users` (
  `uid` int(10) unsigned NOT NULL,
  `uuid` varchar(128) CHARACTER SET ascii NOT NULL,
  `langcode` varchar(12) CHARACTER SET ascii NOT NULL,
  PRIMARY KEY (`uid`),
  UNIQUE KEY `user_field__uuid__value` (`uuid`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='The base table for user entities.' |
+-------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
1 row in set (0.00 sec)

Body:
Try to reset the password using drush

drush upwd USERNAME PASSWORD


问:
How to delete digits-only lines from a text file?
Let's say I have a text file which contains both alphanumerical values and only numerical values of length 10 digits line by line, like the one shown below:

```<code>abcdefgh
0123456789
edf6543jewjew
9876543219
</code>```

I want to delete all the lines which contains only those random 10 digit numbers, i.e. expected output for the above example is the following:

```<code>abcdefgh
edf6543jewjew
</code>```

How can one do this in Python 3.x?

答:
Open the input file, read all its lines, filter out the lines that contain only digits, then write the filtered lines back to a new file.

import re

with open(input_file_path) as file:
    lines = file.readlines()

output_lines = [line for line in lines if not re.match(r'^[0-9]+$', line.strip('\n'))]

with open(output_file_path, 'w') as file:
    file.write('\n'.join(output_lines))
```

Body:
Let's say I have a text file which contains both alphanumerical values and only numerical values of length 10 digits line by line, like the one shown below:

abcdefgh
0123456789
edf6543jewjew
9876543219

I want to delete all the lines which contains only those random 10 digit numbers, i.e. expected output for the above example is the following:

abcdefgh
edf6543jewjew

How can one do this in Python 3.x?


问:
NHibernate SaveOrUpdate Child Collection Not Updated With Identity Ids
I am clearly missing something (hopefully obvious), and I have had no luck with Google so far.

I have a Parent-Child relationship mapped as follows

Simplified Parent Map

```<code>  public sealed class ParentMap : ClassMap<ParentEntity>
  {
    public ParentMap()
    {
      Table("Parent");
      Component(x => x.Thumbprint);
      Id(x => x.Id).GeneratedBy.Identity();

      Map(x => x.ServeralNotNullableProperties).Not.Nullable();

      HasMany(x => x.Children).KeyColumn("ChildId")
                              .Inverse()
                              .LazyLoad()
                              .Cascade
                              .AllDeleteOrphan();

      References(x => x.SomeUnrelatedLookupColumn).Column("LookupColumnId").Not.Nullable();
    }
  }
</code>```

Simplified Child Map

```<code>  public sealed class ChildMap : ClassMap<ChildEntity>
  {
    public ChildMap()
    {
      Table("Child");
      Component(x => x.Thumbprint);
      Id(x => x.Id).GeneratedBy.Identity();

      Map(x => x.MoreNotNullableProperties).Not.Nullable();

      References(x => x.Parent).Column("ParentId").Not.Nullable();
    }
  }
</code>```

Simplified Service Method Steps

I then have a service method that retrieves Parent and adds a new Child via some domain method. The underlying NHibernate code boils down to:

1) Session Opened on WCF AfterReceiveRequest (IDispatchMessageInspector)

```<code>_sessionFactory.OpenSession();
</code>```

2) Retrieve existing instance of parent via .Query

```<code>_session.Query<ParentEntity>()
        .Where(item => item.Id == parentId)
        .Fetch(item => item.SomeLookupColumn)
        .First();
</code>```

3) Add new 'Child' entity to 'Parent' via domain object method such as...

```<code>public ChildEntity CreateChild()
{
  var child = new ChildEntity{ Parent = this };

  Children.Add(child);

  return child;
}
</code>```

4) Ultimately calls SaveOrUpdate on 'Parent' entity.

```<code> // ChildEntity Id is 0
 _session.SaveOrUpdate(parentEntity)
 // Expect ChildEntity Id to NOT be 0
</code>```

Note: Use of SaveOrUpdate Does persist changes to database; use of Merge results in TransientObjectException mentioned below.

5) Finally, transaction committed on WCF BeforeSendReply (IDispatchMessageInspector)

```<code> _session.Commit();
</code>```

The Problem

Typically when an entity is saved, after the call to SaveOrUpdate, the Id of said entity refects the Identity generated by the INSERT statement. However, when I add a new child entity to an existing parent, the associated entity in Children does not get assigned an Id. I need to pass this Id back to the caller so subsequent calls result in UPDATES and not additional INSERTS.

Why is NHibernate not updating the underlying entity?
Do I explicitly have to call SaveOrUpdate on the child (that sucks if that is the case)?

Any thoughts on the matter greatly appreciated. Thanks!

EDIT
I should note, that the new child entity IS being saved as expected; I just don't get back the Id assigned.

UPDATE
Tried switching to .Merge(~) as suggested by Michael Buen below; resulting in a TransientObjectException telling me to explicitly save my modified child entity before calling merge. I also experimented with .Persist(~) to no avail. Any additional insight greatly appreciated.

object is an unsaved transient instance - save the transient instance before merging: My.NameSpace.ChildEntity

答:
Maybe this will help (It's about Inverse attribute):
http://www.emadashi.com/index.php/2008/08/nhibernate-inverse-attribute/</p>

Body:
I am clearly missing something (hopefully obvious), and I have had no luck with Google so far.

I have a Parent-Child relationship mapped as follows

Simplified Parent Map

  public sealed class ParentMap : ClassMap<ParentEntity>
  {
    public ParentMap()
    {
      Table("Parent");
      Component(x => x.Thumbprint);
      Id(x => x.Id).GeneratedBy.Identity();

      Map(x => x.ServeralNotNullableProperties).Not.Nullable();

      HasMany(x => x.Children).KeyColumn("ChildId")
                              .Inverse()
                              .LazyLoad()
                              .Cascade
                              .AllDeleteOrphan();

      References(x => x.SomeUnrelatedLookupColumn).Column("LookupColumnId").Not.Nullable();
    }
  }

Simplified Child Map

  public sealed class ChildMap : ClassMap<ChildEntity>
  {
    public ChildMap()
    {
      Table("Child");
      Component(x => x.Thumbprint);
      Id(x => x.Id).GeneratedBy.Identity();

      Map(x => x.MoreNotNullableProperties).Not.Nullable();

      References(x => x.Parent).Column("ParentId").Not.Nullable();
    }
  }

Simplified Service Method Steps

I then have a service method that retrieves Parent and adds a new Child via some domain method. The underlying NHibernate code boils down to:

1) Session Opened on WCF AfterReceiveRequest (IDispatchMessageInspector)

_sessionFactory.OpenSession();

2) Retrieve existing instance of parent via .Query

_session.Query<ParentEntity>()
        .Where(item => item.Id == parentId)
        .Fetch(item => item.SomeLookupColumn)
        .First();

3) Add new 'Child' entity to 'Parent' via domain object method such as...

public ChildEntity CreateChild()
{
  var child = new ChildEntity{ Parent = this };

  Children.Add(child);

  return child;
}

4) Ultimately calls SaveOrUpdate on 'Parent' entity.

 // ChildEntity Id is 0
 _session.SaveOrUpdate(parentEntity)
 // Expect ChildEntity Id to NOT be 0

Note: Use of SaveOrUpdate Does persist changes to database; use of Merge results in TransientObjectException mentioned below.

5) Finally, transaction committed on WCF BeforeSendReply (IDispatchMessageInspector)

 _session.Commit();

The Problem

Typically when an entity is saved, after the call to SaveOrUpdate, the Id of said entity refects the Identity generated by the INSERT statement. However, when I add a new child entity to an existing parent, the associated entity in Children does not get assigned an Id. I need to pass this Id back to the caller so subsequent calls result in UPDATES and not additional INSERTS.

Why is NHibernate not updating the underlying entity?
Do I explicitly have to call SaveOrUpdate on the child (that sucks if that is the case)?

Any thoughts on the matter greatly appreciated. Thanks!

EDIT
I should note, that the new child entity IS being saved as expected; I just don't get back the Id assigned.

UPDATE
Tried switching to .Merge(~) as suggested by Michael Buen below; resulting in a TransientObjectException telling me to explicitly save my modified child entity before calling merge. I also experimented with .Persist(~) to no avail. Any additional insight greatly appreciated.

object is an unsaved transient instance - save the transient instance before merging: My.NameSpace.ChildEntity


问:
Does the Project Lombok @Data annotation create a constructor of any kind?
I have a class with a @Data annotation, but I'm not sure whether a constructor with arguments is generated or the only generated constructor is the default (no arguments) one from vanilla Java.

答:
@Data is only creating a @RequiredArgsConstructor. Lombok documentation site for the Data annotation and constructors explains:

@RequiredArgsConstructor generates a constructor with 1 parameter for
each field that requires special handling. All non-initialized final
fields get a parameter, as well as any fields that are marked as
@NonNull that aren't initialized where they are declared. For those
fields marked with @NonNull, an explicit null check is also generated.
The constructor will throw a NullPointerException if any of the
parameters intended for the fields marked with @NonNull contain null.
The order of the parameters match the order in which the fields appear
in your class.

Suppose you have a POJO that uses Lombok @Data annotation:

```<code>public @Data class Z {
    private String x;
    private String y;
}
</code>```

You can't create the object as Z z = new Z(x, y); because there is no arg on your Z class that is "required". It is  creating the constructor with zero parameters because @Data gives you Setters and Getters for your properties and  you can call setX and setY after creating your instance.

You can either make x and y @NonNull or final so they must be passed through the constructor or annotate your class Z with @AllArgsConstructor.

Body:
@Data is only creating a @RequiredArgsConstructor. Lombok documentation site for the Data annotation and constructors explains:

@RequiredArgsConstructor generates a constructor with 1 parameter for
each field that requires special handling. All non-initialized final
fields get a parameter, as well as any fields that are marked as
@NonNull that aren't initialized where they are declared. For those
fields marked with @NonNull, an explicit null check is also generated.
The constructor will throw a NullPointerException if any of the
parameters intended for the fields marked with @NonNull contain null.
The order of the parameters match the order in which the fields appear
in your class.

Suppose you have a POJO that uses Lombok @Data annotation:

public @Data class Z {
    private String x;
    private String y;
}

You can't create the object as Z z = new Z(x, y); because there is no arg on your Z class that is "required". It is  creating the constructor with zero parameters because @Data gives you Setters and Getters for your properties and  you can call setX and setY after creating your instance.

You can either make x and y @NonNull or final so they must be passed through the constructor or annotate your class Z with @AllArgsConstructor.


问:
.replace() is not replacing elements
new to pandas, learning.
Have a column in my df where I need to replace certain elements in it with specific data.

Daily_Report is my df. I need to replace "LI" and "MC" in my "Country" column with "CH", "FR". I wrote the below which worked at first, but at rerunning the notebook from the beginning in Jupyter notebook, it doesn;t do anything anymore)

```<code>Daily_Report['Country'].replace('LI', 'CH', inplace=True)
Daily_Report['Country'].replace('MC', 'FR', inplace=True)
Daily_Report['Country'].value_counts()

GB    8132
FR    5811
DE    3390
ES    2280
IT    1930
CH    1516
NL    1414
SE     938
LI      31
MC      24
Name: Country, dtype: int64
</code>```

For a successful replace, LI an MC would not show after running value.counts()
What am I missing here?

Thanks a lot

答:
```<code>Daily_Report['Country'].replace('LI', 'CH', inplace=True)
Daily_Report['Country'].replace('MC', 'FR', inplace=True)
</code>```

As you did should work unless 'LI' and 'MC' have tracing or leading whitespaces like
'LI ' or ' MC. Try checking if this is the case

Title: .replace() is not replacing elements

Body:
new to pandas, learning.
Have a column in my df where I need to replace certain elements in it with specific data.

Daily_Report is my df. I need to replace "LI" and "MC" in my "Country" column with "CH", "FR". I wrote the below which worked at first, but at rerunning the notebook from the beginning in Jupyter notebook, it doesn;t do anything anymore)

Daily_Report['Country'].replace('LI', 'CH', inplace=True)
Daily_Report['Country'].replace('MC', 'FR', inplace=True)
Daily_Report['Country'].value_counts()

GB    8132
FR    5811
DE    3390
ES    2280
IT    1930
CH    1516
NL    1414
SE     938
LI      31
MC      24
Name: Country, dtype: int64

For a successful replace, LI an MC would not show after running value.counts()
What am I missing here?

Thanks a lot

Body:
Daily_Report['Country'].replace('LI', 'CH', inplace=True)
Daily_Report['Country'].replace('MC', 'FR', inplace=True)

As you did should work unless 'LI' and 'MC' have tracing or leading whitespaces like
'LI ' or ' MC. Try checking if this is the case


问:
Disable "Phone number" field in CKEditor
I use CKEditor for DNN version 4.11.4 with the "CKHtmlEditorProvider".

How to disable the "Phone number" field in the Link-Button in the CKEditor?

See the screenshot:

CKEditor Phone number

It is makeable by CSS, but i search for the solution through the config.js, something like

```<code>   if ( dialogName === 'link' ) {
       dialogDefinition.removeContents( 'tel' );
    }
</code>```

答:
What CKeditor are you using? I use DNNConnect.CKE and that has no link to phone either.
If you go to http://yoursite.com/Host/HTMLEditorManager I can verify that in the editor config tab and search for linktype. </p>

Body:
I use CKEditor for DNN version 4.11.4 with the "CKHtmlEditorProvider".

How to disable the "Phone number" field in the Link-Button in the CKEditor?

See the screenshot:

CKEditor Phone number

It is makeable by CSS, but i search for the solution through the config.js, something like

   if ( dialogName === 'link' ) {
       dialogDefinition.removeContents( 'tel' );
    }


问:
How to get rid of extra characters in linux process ID using shell script
I m trying to kill a process by its pid, and this is the script that I found from web.

```<code>PID=`ps -ef | grep myProcess | grep -v grep | awk '{print $2}'`
echo -e Killing myProcess with pid: $PID..
</code>```

Output: Killing myProcesswith pid: 13275^M..

Does anyone know why is there a ^M , how do I get rid of that because the kill command failed to run :

```<code>**arguments must be process or job IDs**
</code>```

I searched online but still got no idea how to overcome this..
Any help is appreciated!! Thanks!

答:
first, your syntax is wrong. Use $() to call a command and store its output to variable

```<code>PID=$(ps -ef | grep myProcess | grep -v grep | awk '{print $2}')
</code>```

second, you can do this all in one awk statement without the need for extra grep processes.

```<code>ps -eo pid,args | awk '/myProces[s]/{cmd="kill  "$1;print cmd; }'
</code>```

Body:
I m trying to kill a process by its pid, and this is the script that I found from web.

PID=`ps -ef | grep myProcess | grep -v grep | awk '{print $2}'`
echo -e Killing myProcess with pid: $PID..

Output: Killing myProcesswith pid: 13275^M..

Does anyone know why is there a ^M , how do I get rid of that because the kill command failed to run :

**arguments must be process or job IDs**

I searched online but still got no idea how to overcome this..
Any help is appreciated!! Thanks!

Body:
first, your syntax is wrong. Use $() to call a command and store its output to variable

PID=$(ps -ef | grep myProcess | grep -v grep | awk '{print $2}')

second, you can do this all in one awk statement without the need for extra grep processes.

ps -eo pid,args | awk '/myProces[s]/{cmd="kill  "$1;print cmd; }'


问:
How to override a property setter using short form?
I just wanna override a default setter using short form but I failed:

```<code>class MyViewModel: ViewModel() {
    var progress: Int = 0
        set(value) = MathUtils.clamp(value, 0, 100)
}
</code>```

It says Required: Unit but found: Int.

What am I doing wrongly?

答:
The property setter is the actual setter of the property and the short form is just a simplified form to have the function return the result of a single expression.

```<code>set(value) {
    field = MathUtils.clamp(value, 0, 100)
}
</code>```

Now field = value is an assignment, not an expression, thus it can't be used here. But if you really want to implement it with the shorter form, it's still possible with a little more verbosity.

```<code>set(value) = run { field = MathUtils.clamp(value, 0, 100) }
</code>```

Body:
I just wanna override a default setter using short form but I failed:

class MyViewModel: ViewModel() {
    var progress: Int = 0
        set(value) = MathUtils.clamp(value, 0, 100)
}

It says Required: Unit but found: Int.

What am I doing wrongly?

Body:
The property setter is the actual setter of the property and the short form is just a simplified form to have the function return the result of a single expression.

set(value) {
    field = MathUtils.clamp(value, 0, 100)
}

Now field = value is an assignment, not an expression, thus it can't be used here. But if you really want to implement it with the shorter form, it's still possible with a little more verbosity.

set(value) = run { field = MathUtils.clamp(value, 0, 100) }


问:
Upgrading from 0.9.19 to 1.1.0 seems to break Page objects
I have a page object with this code:

```<code>var MyToolComp = require('./MyToolComponent').MyToolComponent;

var MyToolCommand = {

    get: function (cssLocator, timeout) {
        return new MyToolComp({client: this, locator: cssLocator, timeout: timeout});
    },

    assertMyToolCount: function (expectedMyToolesCount, timeoutMs) {
        console.log('Validate number of MyTool in the page to be [' + expectedMyToolesCount + ']');
        this.waitForElementsCount(this.section.john_container.selector, expectedMyToolesCount, timeoutMs);
        return this;
    },

};

module.exports = {
    commands: [MyToolCommand],

    sections: {
        john_container: {
            selector: '.john_container',
            elements: {
                john_MyTool: {
                    selector: '.john_MyTool'
                },
                header: {
                    selector: '.john_MyTool_header'
                }
            }
        },
        multi_widget: {
            selector: '.john_multi_widget'
        }
    }
};
</code>```

After upgrading to 1.1.0, I can't run this code in my test:
    var myToolPage = browser.page.myTool();
    myToolPage.assertMyToolCount(1);

When debugging, I see myToolPage has "section" var, but no commands.
If I remove sections and only do
module.exports = MyToolCommand;

or

```<code>module.exports = {
    commands: [MyToolCommand]

}
</code>```

Then I can run
myToolPage.assertMyToolCount(1);

But then it failes since
this.section.john_container.selector
Isn't defined.

What am I doing wrong? I can't find anything here or here. Is there anything else I can read that'll help me? What else should I know when upgrading NW? (This is my first time seeing anything nightwatch-related so I kinda have to learn as I go).

Thanks in advance :)

答:
The way I fixed this was replacing

```<code>module.exports = {
    commands: [MyToolCommand],

    sections: {
        john_container: {
            selector: '.john_container',
            elements: {
                john_MyTool: {
                    selector: '.john_MyTool'
                },
                header: {
                    selector: '.john_MyTool_header'
                }
            }
        },
        multi_widget: {
            selector: '.john_multi_widget'
        }
    }
};
</code>```

With

```<code>exports.commands = MyToolCommand;
exports.sections = {
        john_container: {
            selector: '.john_container',
            elements: {
                john_MyTool: {
                    selector: '.john_MyTool'
                },
                header: {
                    selector: '.john_MyTool_header'
                }
            }
        },
        multi_widget: {
            selector: '.john_multi_widget'
        }
    };
</code>```

Body:
I have a page object with this code:

var MyToolComp = require('./MyToolComponent').MyToolComponent;

var MyToolCommand = {

    get: function (cssLocator, timeout) {
        return new MyToolComp({client: this, locator: cssLocator, timeout: timeout});
    },

    assertMyToolCount: function (expectedMyToolesCount, timeoutMs) {
        console.log('Validate number of MyTool in the page to be [' + expectedMyToolesCount + ']');
        this.waitForElementsCount(this.section.john_container.selector, expectedMyToolesCount, timeoutMs);
        return this;
    },

};

module.exports = {
    commands: [MyToolCommand],

    sections: {
        john_container: {
            selector: '.john_container',
            elements: {
                john_MyTool: {
                    selector: '.john_MyTool'
                },
                header: {
                    selector: '.john_MyTool_header'
                }
            }
        },
        multi_widget: {
            selector: '.john_multi_widget'
        }
    }
};

After upgrading to 1.1.0, I can't run this code in my test:
    var myToolPage = browser.page.myTool();
    myToolPage.assertMyToolCount(1);

When debugging, I see myToolPage has "section" var, but no commands.
If I remove sections and only do
module.exports = MyToolCommand;

or

module.exports = {
    commands: [MyToolCommand]

}

Then I can run
myToolPage.assertMyToolCount(1);

But then it failes since
this.section.john_container.selector
Isn't defined.

What am I doing wrong? I can't find anything here or here. Is there anything else I can read that'll help me? What else should I know when upgrading NW? (This is my first time seeing anything nightwatch-related so I kinda have to learn as I go).

Thanks in advance :)

Body:
The way I fixed this was replacing

module.exports = {
    commands: [MyToolCommand],

    sections: {
        john_container: {
            selector: '.john_container',
            elements: {
                john_MyTool: {
                    selector: '.john_MyTool'
                },
                header: {
                    selector: '.john_MyTool_header'
                }
            }
        },
        multi_widget: {
            selector: '.john_multi_widget'
        }
    }
};

With

exports.commands = MyToolCommand;
exports.sections = {
        john_container: {
            selector: '.john_container',
            elements: {
                john_MyTool: {
                    selector: '.john_MyTool'
                },
                header: {
                    selector: '.john_MyTool_header'
                }
            }
        },
        multi_widget: {
            selector: '.john_multi_widget'
        }
    };


问:
How to update certain tuples after deletion in a table
I am trying to model a music streaming service data base in SQLite and I want to create this trigger: When a song is deleted from a playlist, every song that came after it needs to have its position decremented. I'm not really sure how to write this trigger.

Here is an example of the playlist's table (Sorry for the portuguese names. idMusica = Song ID; posicao = song's position in the playlist)

To further explain what I want here's an example:
If I delete song 6 from playlist 1, the position of song 11 would become 3.

答:
I'd argue that this approach is fundamentally wrong and overly fragile. Instead of tracking the absolute position in a playlist, track the relative position. That way you don't have to update positions when inserting or deleting songs:

If the first three songs have posicao values of 1,2,3, and you want to add a song at position 2, instead of updating the current 2 to 3, the current 3 to 4 and so on, use a new value halfway between the current 1 and 2 position's posicao's: 1.5 in this case.

When deleting, don't worry about filling in the gap; the posicao's on either side of the deleted song are still in the right order.

If you need the absolute position for some reason, you can calculate it in a SELECT on the fly with modern versions of sqlite (3.25 or newer) with something like

```<code>SELECT idMusica, row_number() OVER (ORDER BY posicao) AS pos
FROM playlist_songs
WHERE idPlaylist = :playlistid
ORDER BY posicao
</code>```

or by just incrementing a counter in your program every time you fetch a row froma  given playlist as long as it's ordered by posicao.

Window function based queries for inserting into the middle of a playlist and deleting, given an absolute position (Though for deleting, if your junction table isn't a WITHOUT ROWID one, it's easier to track the rowid of the songs in your program and delete using the one for the selected song):

```<code>INSERT INTO playlist_songs(idMusica, idPlaylist, posicao)
VALUES(:songid, :playlistid
     , (SELECT (pos + prev_pos) / 2.0
        FROM (SELECT posicao AS pos
                   , lag(posicao, 1, 0.0) OVER (ORDER BY posicao) AS prev_pos
                   , row_number() OVER (ORDER BY posicao) AS rn
              FROM playlist_songs WHERE idPlaylist = :playlistid)
        WHERE rn = :position));

DELETE FROM playlist_songs
WHERE rowid = (SELECT rowid
               FROM (SELECT rowid, row_number() OVER (ORDER BY posicao) AS rn
                     FROM playlist_songs WHERE idPlaylist = :playlistid)
               WHERE rn = :position);
</code>```

Body:
I'd argue that this approach is fundamentally wrong and overly fragile. Instead of tracking the absolute position in a playlist, track the relative position. That way you don't have to update positions when inserting or deleting songs:

If the first three songs have posicao values of 1,2,3, and you want to add a song at position 2, instead of updating the current 2 to 3, the current 3 to 4 and so on, use a new value halfway between the current 1 and 2 position's posicao's: 1.5 in this case.

When deleting, don't worry about filling in the gap; the posicao's on either side of the deleted song are still in the right order.

If you need the absolute position for some reason, you can calculate it in a SELECT on the fly with modern versions of sqlite (3.25 or newer) with something like

SELECT idMusica, row_number() OVER (ORDER BY posicao) AS pos
FROM playlist_songs
WHERE idPlaylist = :playlistid
ORDER BY posicao

or by just incrementing a counter in your program every time you fetch a row froma  given playlist as long as it's ordered by posicao.

Window function based queries for inserting into the middle of a playlist and deleting, given an absolute position (Though for deleting, if your junction table isn't a WITHOUT ROWID one, it's easier to track the rowid of the songs in your program and delete using the one for the selected song):

INSERT INTO playlist_songs(idMusica, idPlaylist, posicao)
VALUES(:songid, :playlistid
     , (SELECT (pos + prev_pos) / 2.0
        FROM (SELECT posicao AS pos
                   , lag(posicao, 1, 0.0) OVER (ORDER BY posicao) AS prev_pos
                   , row_number() OVER (ORDER BY posicao) AS rn
              FROM playlist_songs WHERE idPlaylist = :playlistid)
        WHERE rn = :position));

DELETE FROM playlist_songs
WHERE rowid = (SELECT rowid
               FROM (SELECT rowid, row_number() OVER (ORDER BY posicao) AS rn
                     FROM playlist_songs WHERE idPlaylist = :playlistid)
               WHERE rn = :position);