问:
How divide or multiply every non-string columns of a PySpark dataframe with a float constant?
My input dataframe looks like the below

```<code>from pyspark.sql import SparkSession
spark = SparkSession.builder.appName("Basics").getOrCreate()

df=spark.createDataFrame(data=[('Alice',4.300,None),('Bob',float('nan'),897)],schema=['name','High','Low'])

+-----+----+----+
| name|High| Low|
+-----+----+----+
|Alice| 4.3|null|
|  Bob| NaN| 897|
+-----+----+----+
</code>```

Expected Output if divided by 10.0

```<code>+-----+----+----+
| name|High| Low|
+-----+----+----+
|Alice| 0.43|null|
|  Bob| NaN| 89.7|
+-----+----+----+
</code>```

答:
The below code should solve your problem in a time efficient manner

```<code>from pyspark.sql.functions import col

allowed_types = ['DoubleType', 'FloatType', 'LongType', 'IntegerType', 'DecimalType']

df = df.select(*[(col(field.name)/10).name(field.name) if str(field.dataType) in allowed_types else col(field.name) for field in df.schema.fields]
</code>```

Using "withColumn" iteratively might not be a good idea when the number of columns is large.

This is because PySpark dataframes are immutable, so essentially we will be creating a new DataFrame for each column casted using withColumn, which will be a very slow process.

This is where the above code comes in handy.

Body:
My input dataframe looks like the below

from pyspark.sql import SparkSession
spark = SparkSession.builder.appName("Basics").getOrCreate()

df=spark.createDataFrame(data=[('Alice',4.300,None),('Bob',float('nan'),897)],schema=['name','High','Low'])

+-----+----+----+
| name|High| Low|
+-----+----+----+
|Alice| 4.3|null|
|  Bob| NaN| 897|
+-----+----+----+

Expected Output if divided by 10.0

+-----+----+----+
| name|High| Low|
+-----+----+----+
|Alice| 0.43|null|
|  Bob| NaN| 89.7|
+-----+----+----+

Body:
The below code should solve your problem in a time efficient manner

from pyspark.sql.functions import col

allowed_types = ['DoubleType', 'FloatType', 'LongType', 'IntegerType', 'DecimalType']

df = df.select(*[(col(field.name)/10).name(field.name) if str(field.dataType) in allowed_types else col(field.name) for field in df.schema.fields]

Using "withColumn" iteratively might not be a good idea when the number of columns is large.

This is because PySpark dataframes are immutable, so essentially we will be creating a new DataFrame for each column casted using withColumn, which will be a very slow process.

This is where the above code comes in handy.


来源: stackexchange

问:
Nginx reverse proxy mapping does not redirect
I recently started tinkering to solve this problem I was having this problem. So I installed NGINX and set it up so that it forwards the incoming requests on port 80 to port 300 by creating a .conf file in /etc/nginx/conf.d/ location. Here is the configuration file.

server {
    listen 80;

    server_name xyz.xyz;

    location / {
        proxy_pass http://127.0.0.1:300;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection 'upgrade';
        proxy_set_header Host $host;
        proxy_cache_bypass $http_upgrade;
    }
}
```

But when I hit xyz.xyz I get the default page and when I go to xyz.xyz:300 I get my NodeJS app. Any suggestion?

答:
Seems like it was an issue with SELinux.
I just ran this command and it worked.

setsebool -P httpd_can_network_connect 1
```

ContentLicense: CC BY-SA 4.0

Body:
I recently started tinkering to solve this problem I was having this problem. So I installed NGINX and set it up so that it forwards the incoming requests on port 80 to port 300 by creating a .conf file in /etc/nginx/conf.d/ location. Here is the configuration file.

server {
    listen 80;

    server_name xyz.xyz;

    location / {
        proxy_pass http://127.0.0.1:300;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection 'upgrade';
        proxy_set_header Host $host;
        proxy_cache_bypass $http_upgrade;
    }
}

But when I hit xyz.xyz I get the default page and when I go to xyz.xyz:300 I get my NodeJS app. Any suggestion?


问:
PHP variable usage in JavaScript
I have PHP file with a variable called $username. Here's my script below:

```<code><script>
var chat = new Chat(<?php echo $username;?>);
</script>
</code>```

But it's not working. I am new to PHP. Let me know what I am missing. Thanks!

答:
It helped me several times to have everything echoed by PHP</p>

```<code><?php
echo "<script>";
echo "var chat = new Chat(".$username.");";
echo "</script>";
?>
</code>```

Title: PHP variable usage in JavaScript

Body:
I have PHP file with a variable called $username. Here's my script below:

But it's not working. I am new to PHP. Let me know what I am missing. Thanks!

Body:
It helped me several times to have everything echoed by PHP

<?php
echo "<script>";
echo "var chat = new Chat(".$username.");";
echo "</script>";
?>


问:
Why does the clone() function show incompatible types when assigned in Constructor?
I am working on an Ecommerce app and need to make filter and populate RecycleView following is my code for RecycleViewAdapter class:

```<code>public class RecyclerViewAdapter
        extends RecyclerView.Adapter<RecyclerViewAdapter.MyViewHolder>
        implements Filterable {
    private static final String TAG = "RecyclerViewAdapter";

    private ArrayList<Product> productArrayList;
    final private ArrayList<Product> productArrayListFull;
    private Context mContext;

    public RecyclerViewAdapter(Context context, ArrayList<Product> products){
        this.productArrayList = products;
        this.mContext = context;
        this.productArrayListFull = productArrayList.clone();
    }
}
</code>```

productArrayListFull is just assigned and used to get access to all products but never modified
productArrayList is modified based on filters

I have refferd to this for creating RecyclerView -
Recycler View
and this for creating the filters
Filter

Whereas the filtering code resets the productArrayListFull to the filtered results

I have changed the function and decided to manually add products using for loop and added logs for size of the ArrayList and in the logs show 0 for ArrayFullList

```<code>public class RecyclerViewAdapter
        extends RecyclerView.Adapter<RecyclerViewAdapter.MyViewHolder>
        implements Filterable {
    private static final String TAG = "RecyclerViewAdapter";

    private ArrayList<Product> productArrayList;
    private ArrayList<Product> productArrayListFull;
    private Context mContext;

    public RecyclerViewAdapter(Context context, ArrayList<Product> products){
        this.productArrayList = products;
        this.mContext = context;
        this.productArrayListFull = new ArrayList<>(products);
        for (Product p : products)
        {
            productArrayListFull.add(p);
        }
        Log.v(TAG,"productArrayList Size" + productArrayList.size());
        Log.v(TAG,"productArrayListFull Size" + productArrayListFull.size());
    }
</code>```

答:
java.util.ArrayList#clone returns an Object. You will need to cast it to the desired type.

Like so:

```<code>this.productArrayListFull = (ArrayList<Product>)productArrayList.clone();
</code>```

In general I would avoid using .clone() unless you have a compelling reason. Instead write your copying logic yourself. If you want to be sure that productArrayListFull doesn't change, there are a number of immutable collection libraries that can help with this.

Body:
I am working on an Ecommerce app and need to make filter and populate RecycleView following is my code for RecycleViewAdapter class:

public class RecyclerViewAdapter
        extends RecyclerView.Adapter<RecyclerViewAdapter.MyViewHolder>
        implements Filterable {
    private static final String TAG = "RecyclerViewAdapter";

    private ArrayList<Product> productArrayList;
    final private ArrayList<Product> productArrayListFull;
    private Context mContext;

    public RecyclerViewAdapter(Context context, ArrayList<Product> products){
        this.productArrayList = products;
        this.mContext = context;
        this.productArrayListFull = productArrayList.clone();
    }
}

productArrayListFull is just assigned and used to get access to all products but never modified
productArrayList is modified based on filters

I have refferd to this for creating RecyclerView -
Recycler View
and this for creating the filters
Filter

Whereas the filtering code resets the productArrayListFull to the filtered results

I have changed the function and decided to manually add products using for loop and added logs for size of the ArrayList and in the logs show 0 for ArrayFullList

public class RecyclerViewAdapter
        extends RecyclerView.Adapter<RecyclerViewAdapter.MyViewHolder>
        implements Filterable {
    private static final String TAG = "RecyclerViewAdapter";

    private ArrayList<Product> productArrayList;
    private ArrayList<Product> productArrayListFull;
    private Context mContext;

    public RecyclerViewAdapter(Context context, ArrayList<Product> products){
        this.productArrayList = products;
        this.mContext = context;
        this.productArrayListFull = new ArrayList<>(products);
        for (Product p : products)
        {
            productArrayListFull.add(p);
        }
        Log.v(TAG,"productArrayList Size" + productArrayList.size());
        Log.v(TAG,"productArrayListFull Size" + productArrayListFull.size());
    }

Body:
java.util.ArrayList#clone returns an Object. You will need to cast it to the desired type.

Like so:

this.productArrayListFull = (ArrayList<Product>)productArrayList.clone();

In general I would avoid using .clone() unless you have a compelling reason. Instead write your copying logic yourself. If you want to be sure that productArrayListFull doesn't change, there are a number of immutable collection libraries that can help with this.


问:
How to clear the console screen when introducing input in Java?
Is there a way to clear the console when the Java program detects the user it's introducing some data?

I'm executing a program that does the following:

```<code>User: //enter username
//show data of the username
</code>```

I want to make it so the user can search for as many users he want until he ends the execution.
To make it clear and nice, after each username search, I want to clear the screen when the program detects the user is typing something (filling the buffer).

Is there any way to do this?

This is the code I'm using to clear the console (this does not detect when the user is typing):

```<code>public static void clearScreen() {
    System.out.print("\033[H\033[2J");
    System.out.flush();
}
</code>```

Thanks in advance.

答:
By default, a terminal can only output text line by line.

Moving the cursor around, changing colors or clearing the screen requires special escape sequences that are interpreted by the terminal emulator in which you run your application.

C programs in Linux would usually do this via the ncurses library.

Java programs can do something similar with Lanterna (https://github.com/mabe02/lanterna) but within a GUI window. See also this article, which names other alternatives and shows how to use Lanterna: http://rememberjava.com/cli/2017/01/22/ncurses_terminal_libs.html

Body:
Is there a way to clear the console when the Java program detects the user it's introducing some data?

I'm executing a program that does the following:

User: //enter username
//show data of the username

I want to make it so the user can search for as many users he want until he ends the execution.
To make it clear and nice, after each username search, I want to clear the screen when the program detects the user is typing something (filling the buffer).

Is there any way to do this?

This is the code I'm using to clear the console (this does not detect when the user is typing):

public static void clearScreen() {
    System.out.print("\033[H\033[2J");
    System.out.flush();
}

Thanks in advance.


问:
Why don't my vtt subtittles show up on my html5 video?
I'm trying to use subtitles with my HTML5 video tag, but I can't get this to work.
I think the issue is that the video source isn't a local file.
Does anyone know how I can get around this?

```<code><html>
<head>
    <style id="stndz-style"></style>
    <meta name="viewport" content="width=device-width">
</head>
<body>
    <video id="video" controls autoplay="" name="media">
        <source src="http://localhost:8888/" type="video/mp4">
        <track label="Dutch" kind="subtitles" srclang="nl" src="/home/ubuntu/Desktop/scripts/example.vtt" default>
    </video>
</body>
</html>
</code>```

and this is my example.vtt:

```<code>WEBVTT

00:01.000 --> 00:04.000
Never drink liquid nitrogen.

00:05.000 --> 00:09.000
- It will perforate your stomach.
- You could die.
</code>```

答:
Turns out that cromium not letting me use local files was the issue. So my workaround is to run chromium like this:</p>
```<code>chromium --allow-file-access-from-files
</code>```

Body:
I'm trying to use subtitles with my HTML5 video tag, but I can't get this to work.
I think the issue is that the video source isn't a local file.
Does anyone know how I can get around this?

    <meta name="viewport" content="width=device-width">

    <video id="video" controls autoplay="" name="media">
        <source src="http://localhost:8888/" type="video/mp4">
        <track label="Dutch" kind="subtitles" srclang="nl" src="/home/ubuntu/Desktop/scripts/example.vtt" default>
    </video>

and this is my example.vtt:

WEBVTT

00:01.000 --> 00:04.000
Never drink liquid nitrogen.

00:05.000 --> 00:09.000
- It will perforate your stomach.
- You could die.

Body:
Turns out that cromium not letting me use local files was the issue. So my workaround is to run chromium like this:

chromium --allow-file-access-from-files


问:
Vim [m motion with c#
Vim provides very useful motion commands to jump to next
start/end of a method: ]m, ]M, [m and ]m.

These works for Java or similar structured language.
(as described in :help ]m  and :help 29.3)

It seems to work considering the outermost pair of curly braces as class
declaration and the next level of curly braces as method declarations.

These motion commands doesn't work when there is an outer pair of curly braces
around class definition, which is somewhat common on languages as C#.

I was wondering if there is some trick to make those commands (alone and
prefixed with operators, e.g., y[m, V]M) work on this code:

```<code>namespace ABC.DEF
{
    class A
    {
        protected string strID;
        public string PortID { get { return strID; } set { strID = value; } }

        protected MyType x;
        public MyType X
        {
            get { return x; }
            set { x = value; if ( x != null ) func1(); }
        }

        int func1()
        {
            return 1;
        }

        int func2(int flag)
        {
            if (flag == 0)
                return flag;

            if (flag > 3)
            {
                return flag;
            }
            return 2;
        }

        int func3()
        {
            return 3;
        }
    }
}
</code>```

答:
Andrew Radev gave an answer which idbrii turned into a plugin.

I have modified that plugin here: https://github.com/RobertCWebb/vim-jumpmethod/

I fixed various issues and added improved mappings for [[ and ]] as well

Fixed: failed to stop when function heading was split over multiple lines (this happens all the time for me)

Fixed: stopped at multi-line if-statements when it shouldn't

Fixed: failed to stop at template functions, like Func()

Fixed: failed to stop at functions with comments containing words like "if" or "for"

Fixed: failed to stop at functions with comment lines between the function name and the brace

Fixed previous position marker not being set, ie after using [m or ]m you should be able to use '' to go back to previous line

Also, when searching back, I made it scroll up a little so the function name is visible, even though the cursor still lands on the '{'

Added mappings for [[, ]], [] and ][ which stop at class, enum and property definitions in addition to functions.  Their standard behaviour in vim is often useless for C#.  [m and ]m still only stop at methods and functions

Regarding the latter, I found it's more useful to stop at class definitions and properties too.

Properties in C# can contain a get and a set method, but I decided it was probably sufficient to just stop once at the definition of the property itself.

For classes, I noticed that I would jump from a method in one function to a method in another, without even realising I was in a different class.  That seems dangerous to me, so it's nice to stop at the class definition too.  The [[ and ]] mappings will do this.

ContentLicense: CC BY-SA 3.0

Title: Vim [m motion with c#

Body:
Vim provides very useful motion commands to jump to next
start/end of a method: ]m, ]M, [m and ]m.

These works for Java or similar structured language.
(as described in :help ]m  and :help 29.3)

It seems to work considering the outermost pair of curly braces as class
declaration and the next level of curly braces as method declarations.

These motion commands doesn't work when there is an outer pair of curly braces
around class definition, which is somewhat common on languages as C#.

I was wondering if there is some trick to make those commands (alone and
prefixed with operators, e.g., y[m, V]M) work on this code:

namespace ABC.DEF
{
    class A
    {
        protected string strID;
        public string PortID { get { return strID; } set { strID = value; } }

        protected MyType x;
        public MyType X
        {
            get { return x; }
            set { x = value; if ( x != null ) func1(); }
        }

        int func1()
        {
            return 1;
        }

        int func2(int flag)
        {
            if (flag == 0)
                return flag;

            if (flag > 3)
            {
                return flag;
            }
            return 2;
        }

        int func3()
        {
            return 3;
        }
    }
}


问:
How do implement d3 v3 brush by specifying a increment brush slide value in steps programmatically
I am trying to implement the brush behavior as in this example. This example is in d3v4.

URL: https://bl.ocks.org/alexmacy/eb284831aff6f9d0119b

We mention this below line. So the difference between the two is always 30 when you slide:

```<code>brush.move(brushg, [20, 50].map(x));
</code>```

My query is: can we do the same in d3v3 and what I require is the 30 difference what we are getting initially on the page load should be set programmatically. I mean the difference value eg: 30,20 etc

Also, consider another example with dates (start and end date) when we slide - the increment has to be in steps of the configured value that is what value we specify programmatically.

Suppose: we specify step value as 5 and

startdate: 11/25/2019 10:00:00 AM,  enddate: 11/25/2019 10:30:00 AM

Now when we slide the slider, the values should be in seconds as:

10:00:05 am, 10:00:10 am, 10:00:15 am, 10:00:20 am, 10:00:25 am, 10:00:30 am

step value as 2 then

10:00:02 am, 10:00:04 am, 10:00:06 am, 10:00:08 am, 10:00:10 am, 10:00:12 am ...

By default the step value is 1

Iam using d3v3, for specifying domain & range:

```<code>textScale = d3.scale.linear().domain([startDate, endDate]).range([0, main_width]).clamp(true);
var axis = d3.svg.axis().scale(this.textScale).orient('Bottom');
</code>```

I am implementing in d3v3.

答:
This is too late but in case someone came across this issue for D3 v3:

var margin = {top: 20, right: 20, bottom: 20, left: 20},
    width = 900 - margin.left - margin.right,
    height = 20;

var x = d3.scale.linear()
  .domain([0,100])
  .range([0, width]);

var brush = d3.svg.brush()
  .x(x)
  .extent([20, 50]);

var svg = d3.select("#slider").append("svg")
    .attr("width", width + margin.left + margin.right)
    .attr("height", height + margin.top)
  .append("g")
    .attr("transform", "translate(" + margin.left + "," + margin.top + ")");

svg.append("g")
    .attr("class", "x axis")
  .call(d3.svg.axis()
          .scale(x)
          .orient("bottom")
          .ticks(5)
          .tickFormat(d3.format("")));

var brushg = svg.append("g")
    .attr("class", "brush")
    .call(brush);

brushg.selectAll("rect")
    .attr("height", height);

brush.on('brush', function() {brushed()})

d3.select('#start-number')
  .append('text')
  .text(brush.extent()[0]);

d3.select('#end-number')
  .append('text')
  .text(brush.extent()[1]);

function brushed() {
  d3.select('#start-number')
    .text(Math.round(brush.extent()[0]));
  d3.select('#end-number')
    .text(Math.round(brush.extent()[1]));
}

brushed();```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.axis path, .axis line {
    fill: none;
    stroke: #000;
    shape-rendering: crispEdges;
  }
  .brush .extent {
    fill-opacity: .125;
    shape-rendering: crispEdges;
  }</code>```

<!DOCTYPE html>

   <meta charset="utf-8">

       to

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

<p>For the date slider, it's not implemented same as described above in the question but a place to start from, here:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>var margin = {top: 20, right: 20, bottom: 20, left: 20},
  width = 900 - margin.left - margin.right,
  height = 20;

var x = d3.time.scale()
  .domain([new Date('11/25/2019 10:00:00 AM'), new Date('11/25/2019 10:30:00 AM')])
  .nice(d3.time.second)
  .range([0, width]);

var brush = d3.svg.brush()
  .x(x)
  .extent([new Date('11/25/2019 10:10:00 AM'), new Date('11/25/2019 10:15:00 AM')]);

var svg = d3.select("#slider").append("svg")
    .attr("width", width + margin.left + margin.right)
    .attr("height", height + margin.top)
  .append("g")
    .attr("transform", "translate(" + margin.left + "," + margin.top + ")");

svg.append("g")
    .attr("class", "x axis")
  .call(d3.svg.axis()
          .scale(x)
          .orient("bottom")
          .ticks(10)
          .tickFormat(d3.time.format("%H:%M"))
          );

var brushg = svg.append("g")
    .attr("class", "brush")
    .call(brush);

brushg.selectAll("rect")
    .attr("height", height);

brush.on('brush', function() {brushed()})

var format = d3.time.format("%H:%M:%S");

d3.select('#start-number')
  .append('text')
  .text(format(brush.extent()[0]));

d3.select('#end-number')
  .append('text')
  .text(format(brush.extent()[1]));

function brushed() {
  d3.select('#start-number')
    .text(format(brush.extent()[0]));
  d3.select('#end-number')
    .text(format(brush.extent()[1]));
}

brushed();</code>```

 .axis path, .axis line {
    fill: none;
    stroke: #000;
    shape-rendering: crispEdges;
  }
  .brush .extent {
    fill-opacity: .125;
    shape-rendering: crispEdges;
  }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html>
   <meta charset="utf-8">
   <body>
    <div id='numbers'>
      <span id='start-number'></span> to <span id='end-number'>
      </span>
    </div>
    <div id='slider' style="margin-top:1%"></div>
   <script src="//d3js.org/d3.v3.min.js"></script>
   </body>
 </html></code>```

Body:
I am trying to implement the brush behavior as in this example. This example is in d3v4.

URL: https://bl.ocks.org/alexmacy/eb284831aff6f9d0119b

We mention this below line. So the difference between the two is always 30 when you slide:

brush.move(brushg, [20, 50].map(x));

My query is: can we do the same in d3v3 and what I require is the 30 difference what we are getting initially on the page load should be set programmatically. I mean the difference value eg: 30,20 etc

Also, consider another example with dates (start and end date) when we slide - the increment has to be in steps of the configured value that is what value we specify programmatically.

Suppose: we specify step value as 5 and

startdate: 11/25/2019 10:00:00 AM,  enddate: 11/25/2019 10:30:00 AM

Now when we slide the slider, the values should be in seconds as:

10:00:05 am, 10:00:10 am, 10:00:15 am, 10:00:20 am, 10:00:25 am, 10:00:30 am

step value as 2 then

10:00:02 am, 10:00:04 am, 10:00:06 am, 10:00:08 am, 10:00:10 am, 10:00:12 am ...

By default the step value is 1

Iam using d3v3, for specifying domain & range:

textScale = d3.scale.linear().domain([startDate, endDate]).range([0, main_width]).clamp(true);
var axis = d3.svg.axis().scale(this.textScale).orient('Bottom');

I am implementing in d3v3.

Body:
This is too late but in case someone came across this issue for D3 v3:

var margin = {top: 20, right: 20, bottom: 20, left: 20},
    width = 900 - margin.left - margin.right,
    height = 20;

var x = d3.scale.linear()
  .domain([0,100])
  .range([0, width]);

var brush = d3.svg.brush()
  .x(x)
  .extent([20, 50]);

var svg = d3.select("#slider").append("svg")
    .attr("width", width + margin.left + margin.right)
    .attr("height", height + margin.top)
  .append("g")
    .attr("transform", "translate(" + margin.left + "," + margin.top + ")");

svg.append("g")
    .attr("class", "x axis")
  .call(d3.svg.axis()
          .scale(x)
          .orient("bottom")
          .ticks(5)
          .tickFormat(d3.format("")));

var brushg = svg.append("g")
    .attr("class", "brush")
    .call(brush);

brushg.selectAll("rect")
    .attr("height", height);

brush.on('brush', function() {brushed()})

d3.select('#start-number')
  .append('text')
  .text(brush.extent()[0]);

d3.select('#end-number')
  .append('text')
  .text(brush.extent()[1]);

function brushed() {
  d3.select('#start-number')
    .text(Math.round(brush.extent()[0]));
  d3.select('#end-number')
    .text(Math.round(brush.extent()[1]));
}

brushed();

.axis path, .axis line {
    fill: none;
    stroke: #000;
    shape-rendering: crispEdges;
  }
  .brush .extent {
    fill-opacity: .125;
    shape-rendering: crispEdges;
  }

<!DOCTYPE html>
<html>
   <meta charset="utf-8">
   <body>
    <div id='numbers'>
      <span id='start-number'></span> to <span id='end-number'>
      </span>
    </div>
    <div id='slider' style="margin-top:1%"></div>
   <script src="//d3js.org/d3.v3.min.js"></script>
   </body>
 </html>

For the date slider, it's not implemented same as described above in the question but a place to start from, here:

var margin = {top: 20, right: 20, bottom: 20, left: 20},
  width = 900 - margin.left - margin.right,
  height = 20;

var x = d3.time.scale()
  .domain([new Date('11/25/2019 10:00:00 AM'), new Date('11/25/2019 10:30:00 AM')])
  .nice(d3.time.second)
  .range([0, width]);

var brush = d3.svg.brush()
  .x(x)
  .extent([new Date('11/25/2019 10:10:00 AM'), new Date('11/25/2019 10:15:00 AM')]);

var svg = d3.select("#slider").append("svg")
    .attr("width", width + margin.left + margin.right)
    .attr("height", height + margin.top)
  .append("g")
    .attr("transform", "translate(" + margin.left + "," + margin.top + ")");

svg.append("g")
    .attr("class", "x axis")
  .call(d3.svg.axis()
          .scale(x)
          .orient("bottom")
          .ticks(10)
          .tickFormat(d3.time.format("%H:%M"))
          );

var brushg = svg.append("g")
    .attr("class", "brush")
    .call(brush);

brushg.selectAll("rect")
    .attr("height", height);

brush.on('brush', function() {brushed()})

var format = d3.time.format("%H:%M:%S");

d3.select('#start-number')
  .append('text')
  .text(format(brush.extent()[0]));

d3.select('#end-number')
  .append('text')
  .text(format(brush.extent()[1]));

function brushed() {
  d3.select('#start-number')
    .text(format(brush.extent()[0]));
  d3.select('#end-number')
    .text(format(brush.extent()[1]));
}

brushed();

 .axis path, .axis line {
    fill: none;
    stroke: #000;
    shape-rendering: crispEdges;
  }
  .brush .extent {
    fill-opacity: .125;
    shape-rendering: crispEdges;
  }

<!DOCTYPE html>
<html>
   <meta charset="utf-8">
   <body>
    <div id='numbers'>
      <span id='start-number'></span> to <span id='end-number'>
      </span>
    </div>
    <div id='slider' style="margin-top:1%"></div>
   <script src="//d3js.org/d3.v3.min.js"></script>
   </body>
 </html>


问:
jQuery selector chaining
We're having an issue trying to chain selectors together. We are trying to get all checkboxes that are checked and have the data-action attribute with hideplan as the value. I've got a page that has two checkboxes, one button and this javascript on it:

```<code><script type="text/javascript">
    var hiddenplans = $('input:checkbox[data-action="hideplan":checked');
    $("#hide_btn").click(function() {
        hiddenplans.each(

        function(index) {
            alert('checked' + index);
        });
    });
</script>
</code>```

This doesn't display any alerts when one or more checkboxes are selected - hiddenplans is empty. However, if we copy $('input:checkbox[data-action="hideplan":checked'); and put it into the firebug console and run it we will get results if one or more checkboxes are selected. If I remove :checked it will alert for checkboxes with data-action=hideplan.

We've tried several different ways of writing the selector (i.e. $("input[type=checkbox][data-action=hideplan]:checked") and $("input[type=checkbox][data-action=hideplan]").filter(":checked"); and more) and they work in the console but will not return alerts.

I've created a Fiddle with the full code in case we missed something obvious http://jsfiddle.net/xCnSs/5/

答:
Try this...

```<code>$('input:checkbox[data-action="hideplan"]:checked')
</code>```

jsFiddle.

Title: jQuery selector chaining

Body:
We're having an issue trying to chain selectors together. We are trying to get all checkboxes that are checked and have the data-action attribute with hideplan as the value. I've got a page that has two checkboxes, one button and this javascript on it:

This doesn't display any alerts when one or more checkboxes are selected - hiddenplans is empty. However, if we copy $('input:checkbox[data-action="hideplan":checked'); and put it into the firebug console and run it we will get results if one or more checkboxes are selected. If I remove :checked it will alert for checkboxes with data-action=hideplan.

We've tried several different ways of writing the selector (i.e. $("input[type=checkbox][data-action=hideplan]:checked") and $("input[type=checkbox][data-action=hideplan]").filter(":checked"); and more) and they work in the console but will not return alerts.

I've created a Fiddle with the full code in case we missed something obvious http://jsfiddle.net/xCnSs/5/

Body:
Try this...

$('input:checkbox[data-action="hideplan"]:checked')

jsFiddle.


问:
Issue with migrate on server
I have deployed my django project to a digital ocean server and sucessfully installed all requirements. However, when I run migrate, after makemigrations, I get the following exception:

```<code>django.db.utils.ProgrammingError: relation "auth_permission" already exists

Operations to perform:
  Synchronize unmigrated apps: formtools, django_filters, djcelery, storages
  Apply all migrations: sessions, admin, sites, auth, contenttypes, directory, easy_thumbnails
Synchronizing apps without migrations:
  Creating tables...
    Creating table celery_taskmeta
    Creating table celery_tasksetmeta
    Creating table djcelery_intervalschedule
    Creating table djcelery_crontabschedule
    Creating table djcelery_periodictasks
    Creating table djcelery_periodictask
    Creating table djcelery_workerstate
    Creating table djcelery_taskstate
  Installing custom SQL...
  Installing indexes...
Running migrations:
  Applying contenttypes.0001_initial... FAKED
  Applying auth.0001_initial...Traceback (most recent call last):
  File "manage.py", line 10, in <module>
    execute_from_command_line(sys.argv)
  File "/usr/local/lib/python2.7/dist-packages/django/core/management/__init__.py", line 385, in execute_from_command_line
    utility.execute()
  File "/usr/local/lib/python2.7/dist-packages/django/core/management/__init__.py", line 377, in execute
    self.fetch_command(subcommand).run_from_argv(self.argv)
  File "/usr/local/lib/python2.7/dist-packages/django/core/management/base.py", line 288, in run_from_argv
    self.execute(*args, **options.__dict__)
  File "/usr/local/lib/python2.7/dist-packages/django/core/management/base.py", line 338, in execute
    output = self.handle(*args, **options)
  File "/usr/local/lib/python2.7/dist-packages/django/core/management/commands/migrate.py", line 161, in handle
    executor.migrate(targets, plan, fake=options.get("fake", False))
  File "/usr/local/lib/python2.7/dist-packages/django/db/migrations/executor.py", line 68, in migrate
    self.apply_migration(migration, fake=fake)
  File "/usr/local/lib/python2.7/dist-packages/django/db/migrations/executor.py", line 102, in apply_migration
    migration.apply(project_state, schema_editor)
  File "/usr/local/lib/python2.7/dist-packages/django/db/migrations/migration.py", line 108, in apply
    operation.database_forwards(self.app_label, schema_editor, project_state, new_state)
  File "/usr/local/lib/python2.7/dist-packages/django/db/migrations/operations/models.py", line 36, in database_forwards
    schema_editor.create_model(model)
  File "/usr/local/lib/python2.7/dist-packages/django/db/backends/schema.py", line 262, in create_model
    self.execute(sql, params)
  File "/usr/local/lib/python2.7/dist-packages/django/db/backends/schema.py", line 103, in execute
    cursor.execute(sql, params)
  File "/usr/local/lib/python2.7/dist-packages/django/db/backends/utils.py", line 65, in execute
    return self.cursor.execute(sql, params)
  File "/usr/local/lib/python2.7/dist-packages/django/db/utils.py", line 94, in __exit__
    six.reraise(dj_exc_type, dj_exc_value, traceback)
  File "/usr/local/lib/python2.7/dist-packages/django/db/backends/utils.py", line 65, in execute
    return self.cursor.execute(sql, params)
django.db.utils.ProgrammingError: relation "auth_permission" already exists
</code>```

How can I fix this  - please help!

答:
In the end I had to drop my database and recreate as suggested in an earlier answer.

Never push migration files to your server. There are so many reasons this can result in disaster - different databases, versions, the timing of running makemigrations.

Only run makemigrations on the server itself - that will ensure database integrity.

Title: Issue with migrate on server

Body:
I have deployed my django project to a digital ocean server and sucessfully installed all requirements. However, when I run migrate, after makemigrations, I get the following exception:

django.db.utils.ProgrammingError: relation "auth_permission" already exists

Operations to perform:
  Synchronize unmigrated apps: formtools, django_filters, djcelery, storages
  Apply all migrations: sessions, admin, sites, auth, contenttypes, directory, easy_thumbnails
Synchronizing apps without migrations:
  Creating tables...
    Creating table celery_taskmeta
    Creating table celery_tasksetmeta
    Creating table djcelery_intervalschedule
    Creating table djcelery_crontabschedule
    Creating table djcelery_periodictasks
    Creating table djcelery_periodictask
    Creating table djcelery_workerstate
    Creating table djcelery_taskstate
  Installing custom SQL...
  Installing indexes...
Running migrations:
  Applying contenttypes.0001_initial... FAKED
  Applying auth.0001_initial...Traceback (most recent call last):
  File "manage.py", line 10, in <module>
    execute_from_command_line(sys.argv)
  File "/usr/local/lib/python2.7/dist-packages/django/core/management/__init__.py", line 385, in execute_from_command_line
    utility.execute()
  File "/usr/local/lib/python2.7/dist-packages/django/core/management/__init__.py", line 377, in execute
    self.fetch_command(subcommand).run_from_argv(self.argv)
  File "/usr/local/lib/python2.7/dist-packages/django/core/management/base.py", line 288, in run_from_argv
    self.execute(*args, **options.__dict__)
  File "/usr/local/lib/python2.7/dist-packages/django/core/management/base.py", line 338, in execute
    output = self.handle(*args, **options)
  File "/usr/local/lib/python2.7/dist-packages/django/core/management/commands/migrate.py", line 161, in handle
    executor.migrate(targets, plan, fake=options.get("fake", False))
  File "/usr/local/lib/python2.7/dist-packages/django/db/migrations/executor.py", line 68, in migrate
    self.apply_migration(migration, fake=fake)
  File "/usr/local/lib/python2.7/dist-packages/django/db/migrations/executor.py", line 102, in apply_migration
    migration.apply(project_state, schema_editor)
  File "/usr/local/lib/python2.7/dist-packages/django/db/migrations/migration.py", line 108, in apply
    operation.database_forwards(self.app_label, schema_editor, project_state, new_state)
  File "/usr/local/lib/python2.7/dist-packages/django/db/migrations/operations/models.py", line 36, in database_forwards
    schema_editor.create_model(model)
  File "/usr/local/lib/python2.7/dist-packages/django/db/backends/schema.py", line 262, in create_model
    self.execute(sql, params)
  File "/usr/local/lib/python2.7/dist-packages/django/db/backends/schema.py", line 103, in execute
    cursor.execute(sql, params)
  File "/usr/local/lib/python2.7/dist-packages/django/db/backends/utils.py", line 65, in execute
    return self.cursor.execute(sql, params)
  File "/usr/local/lib/python2.7/dist-packages/django/db/utils.py", line 94, in __exit__
    six.reraise(dj_exc_type, dj_exc_value, traceback)
  File "/usr/local/lib/python2.7/dist-packages/django/db/backends/utils.py", line 65, in execute
    return self.cursor.execute(sql, params)
django.db.utils.ProgrammingError: relation "auth_permission" already exists

How can I fix this  - please help!


问:
How do I upload a file using protractor
I'm writing a protractor script that need to upload a JPEG image. I could click on the upload button which opens up a windows file selector. But, then I need to write the path to a file in that File Selector dialog using protractor.

But, i have no idea how it works. I tried just typing the path using sendKeys and it doesn't work so far.

Anyone have an idea how to do this?

Thanks. :)

答:
```<code> uploadFile: async (locator, filepath) => {
  absolutePath = path.resolve(filepath);
  click(locator);
  element(by.css('input[type="file"]')).sendKeys(absolutePath);
  await sleep(10000, "wait to close window");
  await closePopup();
},
</code>```

Title: How do I upload a file using protractor


答:
Firstly, PHP will execute. In your code it just pastes value of $username. Then javascript will execute. So you have to write:

```<code>var chat = new Chat('<?php echo $username;?>'); // with quotes
</code>```

But much better to use AJAX or Fetch and get value asynchronously. With this approach you can do it from any .js file, but your code will execute only in .php file.

Title: PHP variable usage in JavaScript

Body:
Firstly, PHP will execute. In your code it just pastes value of $username. Then javascript will execute. So you have to write:

var chat = new Chat('<?php echo $username;?>'); // with quotes

But much better to use AJAX or Fetch and get value asynchronously. With this approach you can do it from any .js file, but your code will execute only in .php file.


问:
gitlab first login did not redirected to a password reset screen for root

I installed Gitlab 12.7.6 on CentOS7.

I followed the instruction in  here.

I had few problems in the installation and

```<code>gitlab-ctl reconfigure
</code>```

failed, to solve it I changed the file /etc/gitlab/gitlab.rb, as describe in  here:

```<code>nginx['custom_gitlab_server_config'] = "location /.well-known/acme-challenge/ {\n root /var/opt/gitlab/nginx/www/;
letsencrypt['enable'] = false\n}\n"
</code>```

When I first went to the login screen I got a regular login screen and when I tried to add root it said the "Username is already taken."

How can I set a root account in my gitlab?

答:
I've been on this situation with the exact same infra setup, I think it's a bug that does not give you root reset password on first login (I had no issue with reconfigure step, though). If you re-install, it is probably going to get fixed. But, if you want a clean and robust way of resetting the password, following the documentation here, the root password can be reset through the database or framework. In simple steps, you need to run a ruby-on-rails console and then issue a query for your root password (which is, your number 1 in user_id) list:
user = User.where(id: 1).first. Then update the password (with the confirmation step as well) and Finally save. I haven't put all of the instructions here for the sake of avoiding redundancy.

Body:
I installed Gitlab 12.7.6 on CentOS7.

I followed the instruction in  here.

I had few problems in the installation and

gitlab-ctl reconfigure

failed, to solve it I changed the file /etc/gitlab/gitlab.rb, as describe in  here:

nginx['custom_gitlab_server_config'] = "location /.well-known/acme-challenge/ {\n root /var/opt/gitlab/nginx/www/;
letsencrypt['enable'] = false\n}\n"

When I first went to the login screen I got a regular login screen and when I tried to add root it said the "Username is already taken."

How can I set a root account in my gitlab?


答:
you need to echo the script tags like this:</p>

```<code>echo '<script>';
echo 'var chat = new Chat(' . $username . ')';
echo '</script>';
</code>```

Title: PHP variable usage in JavaScript

Body:
you need to echo the script tags like this:

echo '<script>';
echo 'var chat = new Chat(' . $username . ')';
echo '</script>';


问:
C++: Using a single get function to return the variables related to an object
I am a novice programmer working on a coding project for school.

The problem domain is as follows:

Write a C++ program related to a clock

Define a class called Clock , saved in a separate file, that includes the following members:

three member variables related to the hours, minutes and seconds

one accessor function that returns the values of the three variables (hint: use pointers)

one mutator function that modifies all variables (hint: use three arguments)

functions to increment each variable with 1 (hint: three function)

overloading functions to increment the variables with a value entered by the user (hint: the value is the argument of the function)

one default constructor that sets the clock to 0 hours, 0 minutes and 0 seconds

an overloading constructor that sets the clock to a given time (hr, min, sec)

Define a second class, saved in a separate file, that includes

a static member variable

a static member function

Include in the previously defined files C++ code that insures that a class will not be loaded twice in the main program

Define a main program, saved in a separate file, that

instantiates three objects, one with the default constructor of Clock, one with the overloaded constructor of Clock, and one based on the second class

uses the objects to call all the functions defined in the two classes:

use several ”cin” statement to read from the user the desired time and use the values as parameters for the corresponding functions that required

call each function only once, using one of the defined objects

use the accessor function to print the time after each function call that modifies the variables of the Clock class

includes code that uses the static members of the second class

we have done many examples in class where we are able to use separate get\set functions but this is the first time we are trying to do this with a single get function and pointers. Quite frankly, I am lost

Here is the contents of my header file:

```<code>// default class definition
#ifndef CLOCK1_H
#define CLOCK1_H

#include "stdafx.h"
#include <iostream>
#include <conio.h>
using namespace std;

class Clock
{
private:
    int hours;
    int minutes;
    int seconds;

public:
    int Clock::getInitialTime();
    int Clock::setClockTime();
    Clock::Clock();             // default constructor
    Clock::~Clock();                // default destructor
};
#endif
</code>```

Here is the contents of my source code file:

```<code>// function declarations \ main program
//

#include "stdafx.h"
#include "Clock1.h"
#include <iostream>
#include <conio.h>
using namespace std;

int Clock::getInitialTime()
{
    return hours, minutes, seconds;
}

//void Clock::setClockTime(int hr,min,sec)
//{
//  hours=hr;
//  minutes=min;
//  seconds=sec;
//}

// default constructor
Clock::Clock()
{
    hours=0;
    minutes=0;
    seconds=0;
}

// default destructor
Clock::~Clock()
{
    cin.get();
    cin.get();
}

int main()
{
    Clock defaultObj;
    defaultObj.getInitialTime();
    cout << "The initial time is " << defaultObj.getInitialTime() << endl;
    return 0;
}
</code>```

I am trying to take this in small steps, the first goal being to be able to output the initial values for the hours, minutes, seconds. once this is done, I can add additional constructor(s) with additional arguments.

My first guess is that I need to add the following:

Constructor:
add the appropriate arguments to the default constructor

```<code>Clock::Clock(int *hourPrt, int *minutePtr, int *secondPrt)
</code>```

create the pointers

```<code>Clock *hourPtr;
Clock *minutePtr;
Clock *secondPtr;
</code>```

associate them with the object's attributes

```<code>hourPrt=defaultObj.hours
minutePtr=defaultObj.minutes
secondPrt=defaultObj.seconds
</code>```

getInitialTime function
modify it some how

function call in main
modify it some how

Can anyone help me with this?

Thanks

答:
For a first step, I would make the following changes:

Change getInitialTime() to return a Clock type

Add a method to display the value of a Clock object. (This could eventually be changed to be an ostream output operator).

```<code>void Display(const Clock& clock)
{
    cout << clock.Hour << ":" << clock.Minutes << ":" clock.Seconds << endl;
}
</code>```

Body:
I am a novice programmer working on a coding project for school.

The problem domain is as follows:

Write a C++ program related to a clock

Define a class called Clock , saved in a separate file, that includes the following members:

three member variables related to the hours, minutes and seconds

one accessor function that returns the values of the three variables (hint: use pointers)

one mutator function that modifies all variables (hint: use three arguments)

functions to increment each variable with 1 (hint: three function)

overloading functions to increment the variables with a value entered by the user (hint: the value is the argument of the function)

one default constructor that sets the clock to 0 hours, 0 minutes and 0 seconds

an overloading constructor that sets the clock to a given time (hr, min, sec)

Define a second class, saved in a separate file, that includes

a static member variable

a static member function

Include in the previously defined files C++ code that insures that a class will not be loaded twice in the main program

Define a main program, saved in a separate file, that

instantiates three objects, one with the default constructor of Clock, one with the overloaded constructor of Clock, and one based on the second class

uses the objects to call all the functions defined in the two classes:

use several ”cin” statement to read from the user the desired time and use the values as parameters for the corresponding functions that required

call each function only once, using one of the defined objects

use the accessor function to print the time after each function call that modifies the variables of the Clock class

includes code that uses the static members of the second class

we have done many examples in class where we are able to use separate get\set functions but this is the first time we are trying to do this with a single get function and pointers. Quite frankly, I am lost

Here is the contents of my header file:

// default class definition
#ifndef CLOCK1_H
#define CLOCK1_H

#include "stdafx.h"
#include <iostream>
#include <conio.h>
using namespace std;

class Clock
{
private:
    int hours;
    int minutes;
    int seconds;

public:
    int Clock::getInitialTime();
    int Clock::setClockTime();
    Clock::Clock();             // default constructor
    Clock::~Clock();                // default destructor
};
#endif

Here is the contents of my source code file:

// function declarations \ main program
//

#include "stdafx.h"
#include "Clock1.h"
#include <iostream>
#include <conio.h>
using namespace std;

int Clock::getInitialTime()
{
    return hours, minutes, seconds;
}

//void Clock::setClockTime(int hr,min,sec)
//{
//  hours=hr;
//  minutes=min;
//  seconds=sec;
//}

// default constructor
Clock::Clock()
{
    hours=0;
    minutes=0;
    seconds=0;
}

// default destructor
Clock::~Clock()
{
    cin.get();
    cin.get();
}

int main()
{
    Clock defaultObj;
    defaultObj.getInitialTime();
    cout << "The initial time is " << defaultObj.getInitialTime() << endl;
    return 0;
}

I am trying to take this in small steps, the first goal being to be able to output the initial values for the hours, minutes, seconds. once this is done, I can add additional constructor(s) with additional arguments.

My first guess is that I need to add the following:

Constructor:
add the appropriate arguments to the default constructor

Clock::Clock(int *hourPrt, int *minutePtr, int *secondPrt)

create the pointers

Clock *hourPtr;
Clock *minutePtr;
Clock *secondPtr;

associate them with the object's attributes

hourPrt=defaultObj.hours
minutePtr=defaultObj.minutes
secondPrt=defaultObj.seconds

getInitialTime function
modify it some how

function call in main
modify it some how

Can anyone help me with this?

Thanks

Body:
For a first step, I would make the following changes:

Change getInitialTime() to return a Clock type

Add a method to display the value of a Clock object. (This could eventually be changed to be an ostream output operator).

void Display(const Clock& clock)
{
    cout << clock.Hour << ":" << clock.Minutes << ":" clock.Seconds << endl;
}


问:
How can I prevent subtraction from repeating?
I'm using vb.net
My condition is this:

Dim num1,num2  As Integer

num1 = TextBox1.Text

num2 = TextBox2.Text

TextBox3.Text = num1 - num2

The subtraction is working. My problem when I continuous clicking the button for result, its still subtracting. How can I prevent it if the value on the textbox is the same.. Or how can I make it subtracting once?

Example, MyStockTextBox minus ItemSoldTextBox. After I get the result by clicking the button, when I click the button again its still subtracting even if I'm done subtracting the two.

This is my code for subtraction.

```<code>Private Sub BtnResult_Click(sender As System.Object, e As System.EventArgs) Handles Subtract.Click
    Dim num1, num2 As Integer
    num1 = TextBox1.Text
    num2 = TextBox2.Text
    TextBox3.Text = num1 - num2
End Sub
</code>```

答:
This is my code for subtraction.

Private Sub BtnResult_Click(sender As System.Object, e As System.EventArgs) Handles Subtract.Click

```<code>    Dim num1,num2  As Integer
    num1 = TextBox1.Text
    num2 = TextBox2.Text
    TextBox3.Text = num1 - num2
</code>```

End Sub

Body:
I'm using vb.net
My condition is this:

Dim num1,num2  As Integer

num1 = TextBox1.Text

num2 = TextBox2.Text

TextBox3.Text = num1 - num2

The subtraction is working. My problem when I continuous clicking the button for result, its still subtracting. How can I prevent it if the value on the textbox is the same.. Or how can I make it subtracting once?

Example, MyStockTextBox minus ItemSoldTextBox. After I get the result by clicking the button, when I click the button again its still subtracting even if I'm done subtracting the two.

This is my code for subtraction.

Private Sub BtnResult_Click(sender As System.Object, e As System.EventArgs) Handles Subtract.Click
    Dim num1, num2 As Integer
    num1 = TextBox1.Text
    num2 = TextBox2.Text
    TextBox3.Text = num1 - num2
End Sub

Body:
This is my code for subtraction.

Private Sub BtnResult_Click(sender As System.Object, e As System.EventArgs) Handles Subtract.Click

    Dim num1,num2  As Integer
    num1 = TextBox1.Text
    num2 = TextBox2.Text
    TextBox3.Text = num1 - num2

End Sub


问:
How to add button tint programmatically
In the new AppCompat library, we can tint the button this way:

```<code><Button
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="@string/follow"
    android:id="@+id/button_follow"
    android:backgroundTint="@color/blue_100"
    />
</code>```

How can I set the tint of the button programmatically in my code?
I'm basically trying to implement a conditional coloring of the button based on some user input.

答:
here's how to do it in kotlin:</p>

```<code>view.background.setTint(ContextCompat.getColor(context, textColor))
</code>```

Title: How to add button tint programmatically

Body:
In the new AppCompat library, we can tint the button this way:

<Button
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="@string/follow"
    android:id="@+id/button_follow"
    android:backgroundTint="@color/blue_100"
    />

How can I set the tint of the button programmatically in my code?
I'm basically trying to implement a conditional coloring of the button based on some user input.

Body:
here's how to do it in kotlin:

view.background.setTint(ContextCompat.getColor(context, textColor))


问:
Laravel 5.6 Notifications "Cannot send message without a sender address"
I am trying to send an email notification after a user registers through the default login page, but it's displaying this error

But checking everything and the last time I used it, it was properly sending me an email

Here are my configs:

.env file

```<code>MAIL_DRIVER=smtp
MAIL_HOST=smtp.googlemail.com
MAIL_PORT=587
MAIL_USERNAME=""
MAIL_PASSWORD=""
MAIL_FROM_ADDRESS=""
MAIL_FROM_NAME=""
MAIL_ENCRYPTION=tls
</code>```

omitted some details above, but please presume I have entered the right gmail credentials

-----------------------------------------------

mail.php:

```<code><?php

return [

    /*
    |--------------------------------------------------------------------------
    | Mail Driver
    |--------------------------------------------------------------------------
    |
    | Laravel supports both SMTP and PHP's "mail" function as drivers for the
    | sending of e-mail. You may specify which one you're using throughout
    | your application here. By default, Laravel is setup for SMTP mail.
    |
    | Supported: "smtp", "sendmail", "mailgun", "mandrill", "ses",
    |            "sparkpost", "log", "array"
    |
    */

    // 'driver' => env('MAIL_DRIVER', 'smtp'),
    'driver' => env('MAIL_DRIVER', 'sendmail'),

    /*
    |--------------------------------------------------------------------------
    | SMTP Host Address
    |--------------------------------------------------------------------------
    |
    | Here you may provide the host address of the SMTP server used by your
    | applications. A default option is provided that is compatible with
    | the Mailgun mail service which will provide reliable deliveries.
    |
    */

    'host' => env('MAIL_HOST', 'smtp.mailgun.org'),

    /*
    |--------------------------------------------------------------------------
    | SMTP Host Port
    |--------------------------------------------------------------------------
    |
    | This is the SMTP port used by your application to deliver e-mails to
    | users of the application. Like the host we have set this value to
    | stay compatible with the Mailgun e-mail application by default.
    |
    */

    'port' => env('MAIL_PORT', 587),

    /*
    |--------------------------------------------------------------------------
    | Global "From" Address
    |--------------------------------------------------------------------------
    |
    | You may wish for all e-mails sent by your application to be sent from
    | the same address. Here, you may specify a name and address that is
    | used globally for all e-mails that are sent by your application.
    |
    */

    'from' => [
        'address' => env('MAIL_FROM_ADDRESS'),
        'name' => env('MAIL_FROM_NAME'),
    ],

    /*
    |--------------------------------------------------------------------------
    | E-Mail Encryption Protocol
    |--------------------------------------------------------------------------
    |
    | Here you may specify the encryption protocol that should be used when
    | the application send e-mail messages. A sensible default using the
    | transport layer security protocol should provide great security.
    |
    */

    'encryption' => env('MAIL_ENCRYPTION', 'tls'),

    /*
    |--------------------------------------------------------------------------
    | SMTP Server Username
    |--------------------------------------------------------------------------
    |
    | If your SMTP server requires a username for authentication, you should
    | set it here. This will get used to authenticate with your server on
    | connection. You may also set the "password" value below this one.
    |
    */

    'username' => env('MAIL_USERNAME'),

    'password' => env('MAIL_PASSWORD'),

    /*
    |--------------------------------------------------------------------------
    | Sendmail System Path
    |--------------------------------------------------------------------------
    |
    | When using the "sendmail" driver to send e-mails, we will need to know
    | the path to where Sendmail lives on this server. A default path has
    | been provided here, which will work well on most of your systems.
    |
    */

    'sendmail' => '/usr/sbin/sendmail -bs',
    //'sendmail' => '/usr/sbin/sendmail -t -i',

    /*
    |--------------------------------------------------------------------------
    | Markdown Mail Settings
    |--------------------------------------------------------------------------
    |
    | If you are using Markdown based email rendering, you may configure your
    | theme and component paths here, allowing you to customize the design
    | of the emails. Or, you may simply stick with the Laravel defaults!
    |
    */

    'markdown' => [
        'theme' => 'default',

        'paths' => [
            resource_path('views/vendor/mail'),
        ],
    ],

];
</code>```

-----------------------------------------------

User Model:

```<code><?php

namespace App;

use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;

class User extends \TCG\Voyager\Models\User
{
    use Notifiable;

    const ACTIVE = 1;
    const INACTIVE = 0;
    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'name', 'fname', 'lname', 'email', 'password', 'institute', 'cellphone_no', 'telephone_no', 'token', 'active'
    ];

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password', 'remember_token',
    ];

    public function events(){
        return $this->belongsToMany('App\Event');
    }
}
</code>```

-----------------------------------------------

RegisterController@create method:

```<code>use App\User;
use App\Notifications\UserActivate;

protected function create(array $data)
{
    $user = User::create([
        'fname' => ucfirst(strtolower($data['fname'])),
        'lname' => ucfirst(strtolower($data['lname'])),
        'name'  => $data['fname'] . " " . $data['lname'],
        'institute' => $data['institute'],
        'cellphone_no' => $data['cellphone_no'],
        'telephone_no' => $data['telephone_no'],
        'lname' => ucfirst(strtolower($data['lname'])),
        'lname' => ucfirst(strtolower($data['lname'])),
        'email' => $data['email'],
        'password' => Hash::make($data['password']),
        'token' => str_random(40) . time(),
    ]);

    $user->notify(new UserActivate($user));

    return $user;
}
</code>```

-----------------------------------------------

UserActivate Notification:

```<code><?php

namespace App\Notifications;

use Illuminate\Bus\Queueable;
use Illuminate\Notifications\Messages\MailMessage;
use Illuminate\Notifications\Notification;

class UserActivate extends Notification
{
    use Queueable;

    /**
     * Create a new notification instance.
     *
     * @param $user
     * @return void
     */
    public function __construct($user)
    {
        $this->user = $user;
    }

    /**
     * Get the notification's delivery channels.
     *
     * @param  mixed  $notifiable
     * @return array
     */
    public function via($notifiable)
    {
        return ['mail'];
    }

    /**
     * Get the mail representation of the notification.
     *
     * @param  mixed  $notifiable
     * @return \Illuminate\Notifications\Messages\MailMessage
     */
    public function toMail($notifiable)
    {
        return (new MailMessage)
            ->from(env('MAIL_USERNAME'))
            ->subject('Account Activation')
            ->greeting(sprintf('Hi, %s', $this->user->name))
            ->line('We just noticed that you created a new account. You will need to activate your account to sign in.')
            ->action('Activate', route('activate', [$this->user->token]))
            ->line('Thank you and welcome!');
    }

    /**
     * Get the array representation of the notification.
     *
     * @param  mixed  $notifiable
     * @return array
     */
    public function toArray($notifiable)
    {
        return [
            //
        ];
    }
}

?>
</code>```

I'm really confused because with my previous Laravel projects, the Notification already accepts the email of the $user object and then sends it right away. But now, it's asking for the sender address... Am I missing anything? Been fixing this since yesterday

Thank you very much in advance!

答:
You need to add MAIL_FROM_ADDRESS & MAIL_FROM_NAME on your connfig.mail.php or .env

config/mail.php

```<code>'from' => [
     'address' => env('MAIL_FROM_ADDRESS', 'noreply@domain.com'),
     'name' => env('MAIL_FROM_NAME', 'System'),
 ],
</code>```

.env

```<code>MAIL_FROM_ADDRESS=noreply@domain.com
MAIL_FROM_NAME=System
</code>```

After update .env dont forget to clear your configration and cache :

```<code>$ php artisan config:clear
$ php artisan cache:clear
</code>```

Body:
I am trying to send an email notification after a user registers through the default login page, but it's displaying this error

But checking everything and the last time I used it, it was properly sending me an email

Here are my configs:

.env file

MAIL_DRIVER=smtp
MAIL_HOST=smtp.googlemail.com
MAIL_PORT=587
MAIL_USERNAME=""
MAIL_PASSWORD=""
MAIL_FROM_ADDRESS=""
MAIL_FROM_NAME=""
MAIL_ENCRYPTION=tls

omitted some details above, but please presume I have entered the right gmail credentials

-----------------------------------------------

mail.php:

<?php

return [

    /*
    |--------------------------------------------------------------------------
    | Mail Driver
    |--------------------------------------------------------------------------
    |
    | Laravel supports both SMTP and PHP's "mail" function as drivers for the
    | sending of e-mail. You may specify which one you're using throughout
    | your application here. By default, Laravel is setup for SMTP mail.
    |
    | Supported: "smtp", "sendmail", "mailgun", "mandrill", "ses",
    |            "sparkpost", "log", "array"
    |
    */

    // 'driver' => env('MAIL_DRIVER', 'smtp'),
    'driver' => env('MAIL_DRIVER', 'sendmail'),

    /*
    |--------------------------------------------------------------------------
    | SMTP Host Address
    |--------------------------------------------------------------------------
    |
    | Here you may provide the host address of the SMTP server used by your
    | applications. A default option is provided that is compatible with
    | the Mailgun mail service which will provide reliable deliveries.
    |
    */

    'host' => env('MAIL_HOST', 'smtp.mailgun.org'),

    /*
    |--------------------------------------------------------------------------
    | SMTP Host Port
    |--------------------------------------------------------------------------
    |
    | This is the SMTP port used by your application to deliver e-mails to
    | users of the application. Like the host we have set this value to
    | stay compatible with the Mailgun e-mail application by default.
    |
    */

    'port' => env('MAIL_PORT', 587),

    /*
    |--------------------------------------------------------------------------
    | Global "From" Address
    |--------------------------------------------------------------------------
    |
    | You may wish for all e-mails sent by your application to be sent from
    | the same address. Here, you may specify a name and address that is
    | used globally for all e-mails that are sent by your application.
    |
    */

    'from' => [
        'address' => env('MAIL_FROM_ADDRESS'),
        'name' => env('MAIL_FROM_NAME'),
    ],

    /*
    |--------------------------------------------------------------------------
    | E-Mail Encryption Protocol
    |--------------------------------------------------------------------------
    |
    | Here you may specify the encryption protocol that should be used when
    | the application send e-mail messages. A sensible default using the
    | transport layer security protocol should provide great security.
    |
    */

    'encryption' => env('MAIL_ENCRYPTION', 'tls'),

    /*
    |--------------------------------------------------------------------------
    | SMTP Server Username
    |--------------------------------------------------------------------------
    |
    | If your SMTP server requires a username for authentication, you should
    | set it here. This will get used to authenticate with your server on
    | connection. You may also set the "password" value below this one.
    |
    */

    'username' => env('MAIL_USERNAME'),

    'password' => env('MAIL_PASSWORD'),

    /*
    |--------------------------------------------------------------------------
    | Sendmail System Path
    |--------------------------------------------------------------------------
    |
    | When using the "sendmail" driver to send e-mails, we will need to know
    | the path to where Sendmail lives on this server. A default path has
    | been provided here, which will work well on most of your systems.
    |
    */

    'sendmail' => '/usr/sbin/sendmail -bs',
    //'sendmail' => '/usr/sbin/sendmail -t -i',

    /*
    |--------------------------------------------------------------------------
    | Markdown Mail Settings
    |--------------------------------------------------------------------------
    |
    | If you are using Markdown based email rendering, you may configure your
    | theme and component paths here, allowing you to customize the design
    | of the emails. Or, you may simply stick with the Laravel defaults!
    |
    */

    'markdown' => [
        'theme' => 'default',

        'paths' => [
            resource_path('views/vendor/mail'),
        ],
    ],

];

-----------------------------------------------

User Model:

<?php

namespace App;

use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;

class User extends \TCG\Voyager\Models\User
{
    use Notifiable;

    const ACTIVE = 1;
    const INACTIVE = 0;
    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'name', 'fname', 'lname', 'email', 'password', 'institute', 'cellphone_no', 'telephone_no', 'token', 'active'
    ];

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password', 'remember_token',
    ];

    public function events(){
        return $this->belongsToMany('App\Event');
    }
}

-----------------------------------------------

RegisterController@create method:

use App\User;
use App\Notifications\UserActivate;

protected function create(array $data)
{
    $user = User::create([
        'fname' => ucfirst(strtolower($data['fname'])),
        'lname' => ucfirst(strtolower($data['lname'])),
        'name'  => $data['fname'] . " " . $data['lname'],
        'institute' => $data['institute'],
        'cellphone_no' => $data['cellphone_no'],
        'telephone_no' => $data['telephone_no'],
        'lname' => ucfirst(strtolower($data['lname'])),
        'lname' => ucfirst(strtolower($data['lname'])),
        'email' => $data['email'],
        'password' => Hash::make($data['password']),
        'token' => str_random(40) . time(),
    ]);

    $user->notify(new UserActivate($user));

    return $user;
}

-----------------------------------------------

UserActivate Notification:

<?php

namespace App\Notifications;

use Illuminate\Bus\Queueable;
use Illuminate\Notifications\Messages\MailMessage;
use Illuminate\Notifications\Notification;

class UserActivate extends Notification
{
    use Queueable;

    /**
     * Create a new notification instance.
     *
     * @param $user
     * @return void
     */
    public function __construct($user)
    {
        $this->user = $user;
    }

    /**
     * Get the notification's delivery channels.
     *
     * @param  mixed  $notifiable
     * @return array
     */
    public function via($notifiable)
    {
        return ['mail'];
    }

    /**
     * Get the mail representation of the notification.
     *
     * @param  mixed  $notifiable
     * @return \Illuminate\Notifications\Messages\MailMessage
     */
    public function toMail($notifiable)
    {
        return (new MailMessage)
            ->from(env('MAIL_USERNAME'))
            ->subject('Account Activation')
            ->greeting(sprintf('Hi, %s', $this->user->name))
            ->line('We just noticed that you created a new account. You will need to activate your account to sign in.')
            ->action('Activate', route('activate', [$this->user->token]))
            ->line('Thank you and welcome!');
    }

    /**
     * Get the array representation of the notification.
     *
     * @param  mixed  $notifiable
     * @return array
     */
    public function toArray($notifiable)
    {
        return [
            //
        ];
    }
}

?>

I'm really confused because with my previous Laravel projects, the Notification already accepts the email of the $user object and then sends it right away. But now, it's asking for the sender address... Am I missing anything? Been fixing this since yesterday

Thank you very much in advance!

Body:
You need to add MAIL_FROM_ADDRESS & MAIL_FROM_NAME on your connfig.mail.php or .env

config/mail.php

'from' => [
     'address' => env('MAIL_FROM_ADDRESS', 'noreply@domain.com'),
     'name' => env('MAIL_FROM_NAME', 'System'),
 ],

.env

MAIL_FROM_ADDRESS=noreply@domain.com
MAIL_FROM_NAME=System

After update .env dont forget to clear your configration and cache :

$ php artisan config:clear
$ php artisan cache:clear


问:
How do I display two columns with multiple values and separate the occurances with a WHERE clause
This is my SQL query I am trying to select the names of employees from the employee table 'T' as trainer and 'S' as student. Where each student is linked to a trainer.

SQL query:

```<code>SELECT
    cc.CourseName,
    FORMAT(cs.StartDate, 'dd/MM/yyyy') AS 'Start Date',
    FORMAT(cs.EndDate, 'dd/MM/yyyy') AS 'End Date',
    a.AcademyName,
    r.RoomName,
    (SELECT e.FirstName + ' ' + e.LastName WHERE e.EmployeeType = 'T') AS 'Trainer',
    (SELECT e.FirstName + ' ' + e.LastName WHERE e.EmployeeType = 'S') AS 'Student'
FROM
    Employees e
INNER JOIN
    CourseScheduleTrainers cst ON e.EmployeeID = cst.EmployeeID
INNER JOIN
    CourseScheduleAttendees csa ON cst.TrainerID = csa.TrainerID
INNER JOIN
    CourseCatalog cc ON csa.CourseCatalogID = cc.CourseCatalogID
INNER JOIN
    CourseSchedule cs ON cc.CourseScheduleID = cs.CourseScheduleID
INNER JOIN
    Rooms r ON cs.RoomsID = r.RoomsID
INNER JOIN
    Academies a ON r.AcademyID = a.AcademyID;
</code>```

This is what it is returning:

And this is an ERD of the database I am am trying to create. Essentially Course Attendees can also be classed as employees and they are labelled using the Employee Type

Entity Relationship Diagram:

I thought it was a simple case of sub querying but that doesn't seem to work.

答:
Consider joining Employees twice and re-order the FROM and JOIN clauses to start with the main granular table, CourseScheduleAttendees, where other tables serve as lookups in a hub-spoke fashion:

```<code>SELECT cc.CourseName
       ,FORMAT(cs.StartDate, 'dd/MM/yyyy') AS 'Start Date'
       ,FORMAT(cs.EndDate, 'dd/MM/yyyy') AS 'End Date'
       ,a.AcademyName
       ,r.RoomName
       ,t.FirstName + ' ' + t.LastName AS 'Trainer'
       ,s.FirstName + ' ' + s.LastName AS 'Student'
FROM CourseScheduleAttendees csa
INNER JOIN CourseScheduleTrainers cst
   ON csa.TrainerID = cst.TrainerID
INNER JOIN Employees t
   ON cst.EmployeeID = t.EmployeeID
   AND t.EmployeeType = 'T'
INNER JOIN Employees s
   ON csa.AttendeeID = s.EmployeeID
   AND s.EmployeeType = 'S'
INNER JOIN CourseCatalog cc
   ON csa.CourseCatalogID = cc.CourseCatalogID
INNER JOIN CourseSchedule cs
   ON cc.CourseScheduleID = cs.CourseScheduleID
INNER JOIN Rooms r
   ON cs.RoomsID = r.RoomsID
INNER JOIN Academies a
   ON r.AcademyID = a.AcademyID;
</code>```

Body:
This is my SQL query I am trying to select the names of employees from the employee table 'T' as trainer and 'S' as student. Where each student is linked to a trainer.

SQL query:

SELECT
    cc.CourseName,
    FORMAT(cs.StartDate, 'dd/MM/yyyy') AS 'Start Date',
    FORMAT(cs.EndDate, 'dd/MM/yyyy') AS 'End Date',
    a.AcademyName,
    r.RoomName,
    (SELECT e.FirstName + ' ' + e.LastName WHERE e.EmployeeType = 'T') AS 'Trainer',
    (SELECT e.FirstName + ' ' + e.LastName WHERE e.EmployeeType = 'S') AS 'Student'
FROM
    Employees e
INNER JOIN
    CourseScheduleTrainers cst ON e.EmployeeID = cst.EmployeeID
INNER JOIN
    CourseScheduleAttendees csa ON cst.TrainerID = csa.TrainerID
INNER JOIN
    CourseCatalog cc ON csa.CourseCatalogID = cc.CourseCatalogID
INNER JOIN
    CourseSchedule cs ON cc.CourseScheduleID = cs.CourseScheduleID
INNER JOIN
    Rooms r ON cs.RoomsID = r.RoomsID
INNER JOIN
    Academies a ON r.AcademyID = a.AcademyID;

This is what it is returning:

And this is an ERD of the database I am am trying to create. Essentially Course Attendees can also be classed as employees and they are labelled using the Employee Type

Entity Relationship Diagram:

I thought it was a simple case of sub querying but that doesn't seem to work.

Body:
Consider joining Employees twice and re-order the FROM and JOIN clauses to start with the main granular table, CourseScheduleAttendees, where other tables serve as lookups in a hub-spoke fashion:

SELECT cc.CourseName
       ,FORMAT(cs.StartDate, 'dd/MM/yyyy') AS 'Start Date'
       ,FORMAT(cs.EndDate, 'dd/MM/yyyy') AS 'End Date'
       ,a.AcademyName
       ,r.RoomName
       ,t.FirstName + ' ' + t.LastName AS 'Trainer'
       ,s.FirstName + ' ' + s.LastName AS 'Student'
FROM CourseScheduleAttendees csa
INNER JOIN CourseScheduleTrainers cst
   ON csa.TrainerID = cst.TrainerID
INNER JOIN Employees t
   ON cst.EmployeeID = t.EmployeeID
   AND t.EmployeeType = 'T'
INNER JOIN Employees s
   ON csa.AttendeeID = s.EmployeeID
   AND s.EmployeeType = 'S'
INNER JOIN CourseCatalog cc
   ON csa.CourseCatalogID = cc.CourseCatalogID
INNER JOIN CourseSchedule cs
   ON cc.CourseScheduleID = cs.CourseScheduleID
INNER JOIN Rooms r
   ON cs.RoomsID = r.RoomsID
INNER JOIN Academies a
   ON r.AcademyID = a.AcademyID;


问:
How to get xml page by url
Ok, so I got some url link like https://stackoverflow.com/ and I'm trying to parse it in document  but getting error. Why? Because this is not xml file, so the question is how can I get data as xml if i got only url?
My code:</p>

```<code>public class URLReader {
    public static void main(String[] args) throws Exception {

// or if you prefer DOM:
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        DocumentBuilder db = dbf.newDocumentBuilder();
        Document doc = db.parse(new URL("https://stackoverflow.com/").openStream());
        int nodes = doc.getChildNodes().getLength();
        System.out.println(nodes + " nodes found");
    }
}
</code>```

答:
To parse HTML you may use JSOUP: https://jsoup.org/

This library provides also some features to transform HTML to XHTML, which some sort of XML:

```<code>Document document = Jsoup.parse(html);
document.outputSettings().syntax(Document.OutputSettings.Syntax.xml);
document.outputSettings().escapeMode(org.jsoup.nodes.Entities.EscapeMode.xhtml);
String xhtml=document.html();
</code>```

Title: How to get xml page by url

Body:
Ok, so I got some url link like https://stackoverflow.com/ and I'm trying to parse it in document  but getting error. Why? Because this is not xml file, so the question is how can I get data as xml if i got only url?
My code:

public class URLReader {
    public static void main(String[] args) throws Exception {

// or if you prefer DOM:
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        DocumentBuilder db = dbf.newDocumentBuilder();
        Document doc = db.parse(new URL("https://stackoverflow.com/").openStream());
        int nodes = doc.getChildNodes().getLength();
        System.out.println(nodes + " nodes found");
    }
}

Body:
To parse HTML you may use JSOUP: https://jsoup.org/

This library provides also some features to transform HTML to XHTML, which some sort of XML:

Document document = Jsoup.parse(html);
document.outputSettings().syntax(Document.OutputSettings.Syntax.xml);
document.outputSettings().escapeMode(org.jsoup.nodes.Entities.EscapeMode.xhtml);
String xhtml=document.html();


问:
chaining lists from class attributes
I have three classes

```<code>class Animals:
    def __init__(self):
         self.dog = []
         self.cat = []

class Dog:
    def __init__(self,age,teeth):
        self.age   = age
        self.teeth = teeth

class Cat:
    def __init__(self,age,legs):
        self.age  = age
        self.legs = legs
</code>```

and the function:

```<code>def get_animals_from_attribute_value(animals_class, attribute, value):
    from itertools import chain
    animals = []
    for animal in chain( -> all attributes of animals_class, e.g. dog and cat <- ):
        x = getattr(animal, attribute, None)
        if x == value:
            animals.append(animal)
    return animals
</code>```

The script

```<code>animals = Animals()

animals.dog.append(Dog(1, 2))
animals.dog.append(Dog(3, 1))
animals.cat.append(Cat(1, 3))

certain_animals = get_animals_from_attribute_value(animals,"age",1)
</code>```

should give a list with all class instances, where the attribute age == 1. My problem right now is how to create an iterable list from all attributes of the animals-class (see 4th line in the function script).

Thank you :)

答:
I think I'm going to handle the problem now a little different:

```<code>class Dog:
    def __init__(self,age,teeth):
        self.age   = age
        self.teeth = teeth

class Cat:
    def __init__(self,age,legs):
        self.age  = age
        self.legs = legs

def get_objects_from_attribute_value(input_list, attribute, value):
    output_list = []
    for object in input_list:
        If getattr(object, attribute, None) == value:
            output_list.append(object)
    return output_list
</code>```

with

```<code>animals = []

animals.append(Dog(1, 2))
animals.append(Dog(3, 1))
animals.append(Cat(1, 3))

output_list = get_objects_from_attribute_value(animals, "age", 1)
</code>```

I obtain the results, I wanted.

Ty everybody :)

Title: chaining lists from class attributes

Body:
I have three classes

class Animals:
    def __init__(self):
         self.dog = []
         self.cat = []

class Dog:
    def __init__(self,age,teeth):
        self.age   = age
        self.teeth = teeth

class Cat:
    def __init__(self,age,legs):
        self.age  = age
        self.legs = legs

and the function:

def get_animals_from_attribute_value(animals_class, attribute, value):
    from itertools import chain
    animals = []
    for animal in chain( -> all attributes of animals_class, e.g. dog and cat <- ):
        x = getattr(animal, attribute, None)
        if x == value:
            animals.append(animal)
    return animals

The script

animals = Animals()

animals.dog.append(Dog(1, 2))
animals.dog.append(Dog(3, 1))
animals.cat.append(Cat(1, 3))

certain_animals = get_animals_from_attribute_value(animals,"age",1)

should give a list with all class instances, where the attribute age == 1. My problem right now is how to create an iterable list from all attributes of the animals-class (see 4th line in the function script).

Thank you :)

Body:
I think I'm going to handle the problem now a little different:

class Dog:
    def __init__(self,age,teeth):
        self.age   = age
        self.teeth = teeth

class Cat:
    def __init__(self,age,legs):
        self.age  = age
        self.legs = legs

def get_objects_from_attribute_value(input_list, attribute, value):
    output_list = []
    for object in input_list:
        If getattr(object, attribute, None) == value:
            output_list.append(object)
    return output_list

with

animals = []

animals.append(Dog(1, 2))
animals.append(Dog(3, 1))
animals.append(Cat(1, 3))

output_list = get_objects_from_attribute_value(animals, "age", 1)

I obtain the results, I wanted.

Ty everybody :)


问:
Javascipt decimal multiplication and division output
Why in the output, the length of decimals differ in these two scenarios?

```<code>33 * .1 = 3.3000000000000003
</code>```

where as

```<code>33 * .01 = 0.33
</code>```

Any idea why its like that?

NB: 33 in the above calculation can be any integer

答:
When you convert .1 or 1/10 to base 2 (binary) you get a repeating
  pattern after the decimal point, just like trying to represent 1/3 in
  base 10. The value is not exact, and therefore you can't do exact math
  with it using normal floating point methods.

This is the reason why you end up answer like above.

Body:
Why in the output, the length of decimals differ in these two scenarios?

33 * .1 = 3.3000000000000003

where as

33 * .01 = 0.33

Any idea why its like that?

NB: 33 in the above calculation can be any integer


问:
Catboost: how do I pass cat_features to a saved model in Python?
I have this pre-trained saved model, where I informed my categorical features, and it's working fine if I predict right after training. Now I wanna use it again in another context but I don't know how to properly inform the categorical features. I tried this:

model = CatBoostClassifier(cat_features=var_categ)
model.load_model('catmod.cat')
```

<p>but when I try to predict:</p>

<pre class="lang-py prettyprint-override"><code>modelo.predict(base)
</code>```

I get this error:

CatBoostError: features data: pandas.DataFrame column 'cod_var1' has dtype 'category' but is not in  cat_features list
```

Yes, I double checked the column is in var_categ.

答:
First of all, you don't need to specify catboost classifier cat_features because the model already has this information from load_model.

I would guess from your error that when you use predict on the new data set, your features shifted by 1 location thus giving you the error.

Body:
I have this pre-trained saved model, where I informed my categorical features, and it's working fine if I predict right after training. Now I wanna use it again in another context but I don't know how to properly inform the categorical features. I tried this:

model = CatBoostClassifier(cat_features=var_categ)
model.load_model('catmod.cat')

but when I try to predict:

modelo.predict(base)

I get this error:

CatBoostError: features data: pandas.DataFrame column 'cod_var1' has dtype 'category' but is not in  cat_features list

Yes, I double checked the column is in var_categ.


问:
Losing reference to DOM elements after I clone them
Using MooTools, I'm caching some DOM elements in variables when the DOM is ready, like so:

```<code>var mc = $('main-content'),
    bg = $('bg'),
    arrows = $$('arrows');
</code>```

Both bg and arrows are located within the mc DOM element. I want to clone the mc node, perform some operations on it and then insert the clone into the DOM:

```<code>function updateDOM (parent) {
    var parentID = parent.id,
        oldNode = document.getElementById(parentID),
        clone = oldNode.cloneNode(true);

    // work with clone

    oldNode.parentNode.replaceChild(clone, oldNode);

}
</code>```

When I run updateDOM(mc), I find that any other subsequent functions that would change mc, bg, or arrows don't work. When I do console.log() the elements, they show up, but they don't reflect any of the changes that have been made since their initialization.

Considering that I'm cloning the element, it makes sense to me that mc no longer references div#main-content. updateDOM() is a function that could be used by any element. Do I really need to hard code a way to re-instantiate each variables that I cache or is there a more dynamic way of doing this?

答:
Change updateDOM to return the new, cloned node, and just change your calls to updateDOM to also reassign the variable.

```<code>mc = updateDOM(mc);
</code>```

Body:
Using MooTools, I'm caching some DOM elements in variables when the DOM is ready, like so:

var mc = $('main-content'),
    bg = $('bg'),
    arrows = $$('arrows');

Both bg and arrows are located within the mc DOM element. I want to clone the mc node, perform some operations on it and then insert the clone into the DOM:

function updateDOM (parent) {
    var parentID = parent.id,
        oldNode = document.getElementById(parentID),
        clone = oldNode.cloneNode(true);

    // work with clone

    oldNode.parentNode.replaceChild(clone, oldNode);

}

When I run updateDOM(mc), I find that any other subsequent functions that would change mc, bg, or arrows don't work. When I do console.log() the elements, they show up, but they don't reflect any of the changes that have been made since their initialization.

Considering that I'm cloning the element, it makes sense to me that mc no longer references div#main-content. updateDOM() is a function that could be used by any element. Do I really need to hard code a way to re-instantiate each variables that I cache or is there a more dynamic way of doing this?

Body:
Change updateDOM to return the new, cloned node, and just change your calls to updateDOM to also reassign the variable.

mc = updateDOM(mc);


问:
use look-behind in python to remove the trailing zeroes
in the following string is there a way to remove the trailing zeroes,
ie.
input is : '21006.08.094.000196'
o/p : '21006.8.94.196'

Though it works with
l = re.sub(r"\.[0]*",".",str)
I was looking for a solution using look-ahead or look-behind expressions in python.

Thanks

答:
You can use

```<code>re.sub(r"(?<=\.)0+", "", "21006.08.094.000196")
</code>```

This matches one or more zeros, but only if they are immediately preceded by a literal .. The . itself is not a part of the match, so you can replace the zeros with the empty string.

I don't see much reason to use this over re.sub("\.0+", ".", str), though.

Body:
You can use

re.sub(r"(?<=\.)0+", "", "21006.08.094.000196")

This matches one or more zeros, but only if they are immediately preceded by a literal .. The . itself is not a part of the match, so you can replace the zeros with the empty string.

I don't see much reason to use this over re.sub("\.0+", ".", str), though.


问:
Map dictionary of wind directions to new column
I have a large dataframe with wind directions, and I would like to create a new column mapping this infomation to the 16 segments of a meteorological compass, ie. N, NNE etc.. I have created a dictionary with the keys and values, but when I run the code my new column contains only NaN's. Here is a sample of my data and code. I am not sure exactly where I am going wrong... thanks for the help.

```<code>time    temperature windBearing windSpeed   ozone   pressure
0   2018-09-20 01:00:00 18.46   228 5.76    291.0   1014.5
1   2018-09-20 02:00:00 18.05   214 5.36    292.1   1014.5
2   2018-09-20 03:00:00 18.07   214 5.58    292.1   1014.3
3   2018-09-20 04:00:00 18.19   216 5.99    291.9   1013.9
4   2018-09-20 05:00:00 18.31   218 6.31    291.9   1013.5
</code>```

Dictionary for angles:

```<code>compass = {
    range(349, 11) : 'N',
    range(11, 34) : 'NNE',
    range(34, 56) : 'NE',
    range(56, 79) : 'ENE',
    range(79, 101) : 'E',
    range(101, 124) : 'ESE',
    range(124, 146) : 'SE',
    range(146, 169) : 'SSE',
    range(169, 191) : 'S',
    range(191, 214) : 'SSW',
    range(214, 236) : 'SW',
    range(236, 259) : 'WSW',
    range(259, 281) : 'w',
    range(281, 304) : 'WNW',
    range(304, 326) : 'NW',
    range(326, 349) : 'NNW'
}
</code>```

Code being run:

```<code>df_met['compass'] = df_met['windBearing'].map(compass)
</code>```

答:
You have the right idea but map works on a one-to-one level so you cant match on ranges.

instead, let us create a new data frame from your compass dictionary and merge the values on to your data frame.

```<code>df_dict = {}

for k,v in compass.items():
    for item in k:
        df_dict[int(item)] = v

wind_df = pd.DataFrame.from_dict(df_dict,orient='index').reset_index()
wind_df.columns=['windBearing', 'State']

new_df = pd.merge(wind,wind_df,on=['windBearing'],how='left')
</code>```

```<code>print(new_df)

                       time  temperature  windBearing  windSpeed  ozone  \
0  0   2018-09-20 01:00:00         18.46          228       5.76  291.0
1  1   2018-09-20 02:00:00         18.05          214       5.36  292.1
2  2   2018-09-20 03:00:00         18.07          214       5.58  292.1
3  3   2018-09-20 04:00:00         18.19          216       5.99  291.9
4  4   2018-09-20 05:00:00         18.31          218       6.31  291.9

   pressure State
0    1014.5    SW
1    1014.5    SW
2    1014.3    SW
3    1013.9    SW
4    1013.5    SW
</code>```

Body:
I have a large dataframe with wind directions, and I would like to create a new column mapping this infomation to the 16 segments of a meteorological compass, ie. N, NNE etc.. I have created a dictionary with the keys and values, but when I run the code my new column contains only NaN's. Here is a sample of my data and code. I am not sure exactly where I am going wrong... thanks for the help.

time    temperature windBearing windSpeed   ozone   pressure
0   2018-09-20 01:00:00 18.46   228 5.76    291.0   1014.5
1   2018-09-20 02:00:00 18.05   214 5.36    292.1   1014.5
2   2018-09-20 03:00:00 18.07   214 5.58    292.1   1014.3
3   2018-09-20 04:00:00 18.19   216 5.99    291.9   1013.9
4   2018-09-20 05:00:00 18.31   218 6.31    291.9   1013.5

Dictionary for angles:

compass = {
    range(349, 11) : 'N',
    range(11, 34) : 'NNE',
    range(34, 56) : 'NE',
    range(56, 79) : 'ENE',
    range(79, 101) : 'E',
    range(101, 124) : 'ESE',
    range(124, 146) : 'SE',
    range(146, 169) : 'SSE',
    range(169, 191) : 'S',
    range(191, 214) : 'SSW',
    range(214, 236) : 'SW',
    range(236, 259) : 'WSW',
    range(259, 281) : 'w',
    range(281, 304) : 'WNW',
    range(304, 326) : 'NW',
    range(326, 349) : 'NNW'
}

Code being run:

df_met['compass'] = df_met['windBearing'].map(compass)

Body:
You have the right idea but map works on a one-to-one level so you cant match on ranges.

instead, let us create a new data frame from your compass dictionary and merge the values on to your data frame.

df_dict = {}

for k,v in compass.items():
    for item in k:
        df_dict[int(item)] = v

wind_df = pd.DataFrame.from_dict(df_dict,orient='index').reset_index()
wind_df.columns=['windBearing', 'State']

new_df = pd.merge(wind,wind_df,on=['windBearing'],how='left')

print(new_df)

                       time  temperature  windBearing  windSpeed  ozone  \
0  0   2018-09-20 01:00:00         18.46          228       5.76  291.0
1  1   2018-09-20 02:00:00         18.05          214       5.36  292.1
2  2   2018-09-20 03:00:00         18.07          214       5.58  292.1
3  3   2018-09-20 04:00:00         18.19          216       5.99  291.9
4  4   2018-09-20 05:00:00         18.31          218       6.31  291.9

   pressure State
0    1014.5    SW
1    1014.5    SW
2    1014.3    SW
3    1013.9    SW
4    1013.5    SW