问:
Improving O(n) while looping through a 2d array in C++
A goal of mine is to reduce my O(n^2) algorithms into O(n), as it's a common algorithm in my Array2D class. Array2D holds a multidimensional array of type T. A common issue I see is using doubly-nested for loops to traverse through an array, which is slow depending on the size.

As you can see, I reduced my doubly-nested for loops into a single for loop here. It's running fine when I execute it. Speed has surely improved. Is there any other way to improve the speed of this member function? I'm hoping to use this algorithm as a model for my other member functions that have similar operations on multidimensional arrays.

```<code>        /// <summary>
        /// Fills all items within the array with a value.
        /// </summary>
        /// <param name="ob">The object to insert.</param>
        void fill(const T &ob)
        {
            if (m_array == NULL)
                return;

            //for (int y = 0; y < m_height; y++)
            //{
            //  for (int x = 0; x < m_width; x++)
            //  {
            //      get(x, y) = ob;
            //  }
            //}

            int size = m_width * m_height;
            int y = 0;
            int x = 0;

            for (int i = 0; i < size; i++)
            {
                get(x, y) = ob;

                x++;

                if (x >= m_width)
                {
                    x = 0;
                    y++;
                }
            }
        }
</code>```

答:
Make sure things are contiguous in memory as cache behavior is likely to dominate the run-time of any code which performs only simple operations.

For instance, don't use this:

```<code>int* a[10];
for(int i=0;i<10;i++)
  a[i] = new int[10];
//Also not this
std::vector< std::vector<int> > a(std::vector<int>(10),10);
</code>```

Use this:

```<code>int a[100];
//or
std::vector<int> a(100);
</code>```

Now, if you need 2D access use:

```<code>for(int y=0;y<HEIGHT;y++)
for(int x=0;x<WIDTH;x++)
  a[y*WIDTH+x];
</code>```

Use 1D accesses for tight loops, whole-array operations which don't rely on knowledge of neighbours, or for situations where you need to store indices:

```<code>for(int i=0;i<HEIGHT*WIDTH;i++)
  a[i];
</code>```

Note that in the above two loops the number of items touched is HEIGHT*WIDTH in both cases. Though it may appear that one has a time complexity of O(N^2) and the other O(n), it should be obvious that the net amount of work done is HEIGHT*WIDTH in both cases. It is better to think of N as the total number of items touched by an operation, rather than a property of the way in which they are touched.

Body:
A goal of mine is to reduce my O(n^2) algorithms into O(n), as it's a common algorithm in my Array2D class. Array2D holds a multidimensional array of type T. A common issue I see is using doubly-nested for loops to traverse through an array, which is slow depending on the size.

As you can see, I reduced my doubly-nested for loops into a single for loop here. It's running fine when I execute it. Speed has surely improved. Is there any other way to improve the speed of this member function? I'm hoping to use this algorithm as a model for my other member functions that have similar operations on multidimensional arrays.

        ///
        /// Fills all items within the array with a value.
        ///
        /// <param name="ob">The object to insert.</param>
        void fill(const T &ob)
        {
            if (m_array == NULL)
                return;

            //for (int y = 0; y < m_height; y++)
            //{
            //  for (int x = 0; x < m_width; x++)
            //  {
            //      get(x, y) = ob;
            //  }
            //}

            int size = m_width * m_height;
            int y = 0;
            int x = 0;

            for (int i = 0; i < size; i++)
            {
                get(x, y) = ob;

                x++;

                if (x >= m_width)
                {
                    x = 0;
                    y++;
                }
            }
        }

Body:
Make sure things are contiguous in memory as cache behavior is likely to dominate the run-time of any code which performs only simple operations.

For instance, don't use this:

int* a[10];
for(int i=0;i<10;i++)
  a[i] = new int[10];
//Also not this
std::vector< std::vector<int> > a(std::vector<int>(10),10);

Use this:

int a[100];
//or
std::vector<int> a(100);

Now, if you need 2D access use:

for(int y=0;y<HEIGHT;y++)
for(int x=0;x<WIDTH;x++)
  a[y*WIDTH+x];

Use 1D accesses for tight loops, whole-array operations which don't rely on knowledge of neighbours, or for situations where you need to store indices:

for(int i=0;i<HEIGHT*WIDTH;i++)
  a[i];

Note that in the above two loops the number of items touched is HEIGHT*WIDTH in both cases. Though it may appear that one has a time complexity of O(N^2) and the other O(n), it should be obvious that the net amount of work done is HEIGHT*WIDTH in both cases. It is better to think of N as the total number of items touched by an operation, rather than a property of the way in which they are touched.


来源: stackexchange

问:
Not getting first character after an attempt to downcast an object in java using charAt();
I'm trying to get the first character from the Object after attempting to downcast the object but my code seems to be missing something I don't know what's wrong.

```<code>String name = "Mike";
</code>```

if I try the charAt() method it works fine using the above code.

```<code>name.charAt(0);
</code>```

gives us "M". right?

I tried to downcast(not sure if that's the right term) the object say:

```<code>Object obj = (String) name;

obj ==> "Mike"; // is what we get
</code>```

But if I use the method:

```<code>obj.charAt(0);
</code>```

I'm expecting the same result "M" but it gives me an error instead. Am I missing something?

答:
Well, Casting means taking an Object of one particular type and turning it into another Object type.

Downcast means taking the Object and casting it into a more specific type of Object. For example:

```<code>Object obj = "This is an object";
String s = (String)obj;
</code>```

Now you can invoke the methods in the String Class upon the String s object. But not the opposite. So you cannot invoke Directly the methods that exist in String Class upon an instance of Class Object.

To use the method charAt(int index) in the above example on the Object obj directly, you need to downcast first then you can go ahead:

```<code>((String)obj).charAt(0); // it will give "T";
</code>```

Furthermore, If I do:

```<code>obj.charAt(0);
</code>```

And when I try to compile it, it gives me this error:

```<code>The method charAt(int) is undefined for the type Object
</code>```

Which basically means that method doesn't exist in Object Class.

ContentLicense: CC BY-SA 3.0

Body:
I'm trying to get the first character from the Object after attempting to downcast the object but my code seems to be missing something I don't know what's wrong.

String name = "Mike";

if I try the charAt() method it works fine using the above code.

name.charAt(0);

gives us "M". right?

I tried to downcast(not sure if that's the right term) the object say:

Object obj = (String) name;

obj ==> "Mike"; // is what we get

But if I use the method:

obj.charAt(0);

I'm expecting the same result "M" but it gives me an error instead. Am I missing something?

Body:
Well, Casting means taking an Object of one particular type and turning it into another Object type.

Downcast means taking the Object and casting it into a more specific type of Object. For example:

Object obj = "This is an object";
String s = (String)obj;

Now you can invoke the methods in the String Class upon the String s object. But not the opposite. So you cannot invoke Directly the methods that exist in String Class upon an instance of Class Object.

To use the method charAt(int index) in the above example on the Object obj directly, you need to downcast first then you can go ahead:

((String)obj).charAt(0); // it will give "T";

Furthermore, If I do:

obj.charAt(0);

And when I try to compile it, it gives me this error:

The method charAt(int) is undefined for the type Object

Which basically means that method doesn't exist in Object Class.


问:
Eclipse: how to open header file from #include line
In Visual Studio one can right click on the #include line and open the header file. Is this possible in Eclipse?</p>

答: Yes it is, just put your cursor on the included file, right click and select Open Declaration:


问:
recursive find for specific text for last n lines
I want to find some specific text in recursive way, I have read this very popular answer:

```<code>grep -rnw '/path/to/somewhere/' -e 'pattern'
</code>```

But it doesn't work to me due to I have files HUGE that can takes so long to find in the whole file, so I want just to search in the last N lines to improve the performance and time required to do the action, for instance:

答:
Use find command specifying the last N lines via n argument:

```<code>n=11
find /path/to/somewhere/ -type f -exec sh -c 'tail -n '$n' {} | grep -wn pattern' \; -print
</code>```

Body:
I want to find some specific text in recursive way, I have read this very popular answer:

grep -rnw '/path/to/somewhere/' -e 'pattern'

But it doesn't work to me due to I have files HUGE that can takes so long to find in the whole file, so I want just to search in the last N lines to improve the performance and time required to do the action, for instance:

Body:
Use find command specifying the last N lines via n argument:

n=11
find /path/to/somewhere/ -type f -exec sh -c 'tail -n '$n' {} | grep -wn pattern' \; -print


问:
Which Package or assembly had ISession?
I used this series to work on CQRS/ES with ASP.NET:

https://www.exceptionnotfound.net/real-world-cqrs-es-with-asp-net-and-redis-part-2-the-write-model/

My problem is somewhere in the code it uses ISession,that I don't know what assembly/package has it. Bases on document I need to install CQRSLite but when I try to install it I get an error.

```<code>private readonly ISession _session;
</code>```

This is the error I am getting:

```<code>Could not install package 'CqrsLite 0.12.9'. You are trying to install this package into a project that targets '.NETFramework,Version=v4.5', but the package does not contain any assembly references or content files that are compatible with that framework. For more information, contact the package author.
</code>```

I am using Visual studio 2015 and .net 4.5.

答: I need to change the version of the project to NETFramework 4.6.1 and install CQRSLite package.</p>

Title: Which Package or assembly had ISession?

Body:
I used this series to work on CQRS/ES with ASP.NET:

https://www.exceptionnotfound.net/real-world-cqrs-es-with-asp-net-and-redis-part-2-the-write-model/

My problem is somewhere in the code it uses ISession,that I don't know what assembly/package has it. Bases on document I need to install CQRSLite but when I try to install it I get an error.

private readonly ISession _session;

This is the error I am getting:

Could not install package 'CqrsLite 0.12.9'. You are trying to install this package into a project that targets '.NETFramework,Version=v4.5', but the package does not contain any assembly references or content files that are compatible with that framework. For more information, contact the package author.

I am using Visual studio 2015 and .net 4.5.


问:
how to find time using python?
i want to run my function and then I want to find now's time using python.

then lets say after 2 hours my function should run again.

what should i do?

答:
There are several ways of finding the time in Python:</p>

```<code>import time
print time.time() # unix timestamp, seconds from 1970

import datetime
print datetime.datetime.now()

time.sleep(7200) # sleep for 2 hours
</code>```

ContentLicense: CC BY-SA 2.5

Title: how to find time using python?

Body:
There are several ways of finding the time in Python:

import time
print time.time() # unix timestamp, seconds from 1970

import datetime
print datetime.datetime.now()

time.sleep(7200) # sleep for 2 hours


问:
alternative for saxon:assign and saxon:assignable
I am trying to upgrade my project to Java 8 and my project uses Saxon old version (i think saxon9). I was getting some issue after upgrading my project to Java 8 and in saxonia said Java 8 issues fixed in Saxon 9.5 version, so I have changed to Saxon HE 9.7 and supposed to use HE version alone. The inbuilt functions saxon:assign and saxon:assignable moved to EE version it seems.

So I am looking for an alternative approach to achieve saxon:assign and saxon:assignable.

Any suggestions? or any working examples would be helpful.

My Requirement is same as stated in https://www.altova.com/forum/default.aspx?g=posts&t=1000001577 .. How to increase variable count? without using saxon:assign and saxon:assignable.

I want have a global variable and need to increment when processing the element.

Updating more info.This is my requirement.
My Input xml is

```<code><?xml version="1.0" encoding="UTF-8"?>
<employees>
    <employee>
        <name>Anbu</name>
        <address>Chennai</address>
        <dob>1990-05-15</dob>
        <phone>9600096000</phone>
        <email>anbu@email.com</email>
    </employee>
    <employee>
        <name>Bala</name>
        <address>Hydrabad</address>
        <dob>1989-01-04</dob>
        <phone>9700097000</phone>
        <email>bala@email.com</email>
    </employee>
    <employee>
        <name>Chandru</name>
        <address>Mumbai</address>
        <dob>1995-11-10</dob>
        <phone>9900099000</phone>
        <email>chandru@email.com</email>
    </employee>
</employees>
</code>```

Need output like:

```<code><html>
   <body>
      <h2>Employee Details</h2>
      <table border="1">
         <tr bgcolor="#9acd32">
            <th style="text-align:left">Name</th>
            <th style="text-align:left">Age</th>
         </tr>
         <tr>
            <td>Anbu</td>
            <td>1</td>
         </tr>
         <tr>
            <td>Bala</td>
            <td>2</td>
         </tr>
         <tr>
            <td>Chandru</td>
            <td>3</td>
         </tr>
      </table>
   </body>
</html>
</code>```

I want to have a global variable and increment it. I have tried with below xsl, but not works.

```<code><?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0"
    xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:variable name="count" select="0" />
    <xsl:template match="/">
        <html>
            <body>
                <h2>Employee Details</h2>
                <table border="1">
                    <tr bgcolor="#9acd32">
                        <th style="text-align:left">Name</th>
                        <th style="text-align:left">Age</th>
                    </tr>
                    <xsl:for-each select="employees/employee">
                        <tr>
                            <td>
                                <xsl:value-of select="name" />
                            </td>
                            <td>
                                <xsl:value-of select="$count+1" />
                            </td>
                        </tr>
                    </xsl:for-each>
                </table>
            </body>
        </html>
    </xsl:template>
</xsl:stylesheet>
</code>```

can I achive this by creating Custom functions with ExtensionFunctionDefinition ?

答:
The best answer is to wean yourself off the use of mutable variables. This may need a different approach, but if you learn to think declaratively then everything is possible. The changes you need to make will depend very much on how and why you are using saxon:assign.

If you can't do that, an alternative is to use stateful (impure) extension functions.

The specific example in the Altova forum post that you cite can be done very easily without saxon:assign. It's a somewhat strange example because it appears to depend on the order of attributes, but you can do it like this:

```<code><xsl:variable name="days"
   select="'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday'"/>

<xsl:variable name="orderedAtts" as="attribute()*">
  <xsl:perform-sort select="//content-list/@*">
    <xsl:sort select="index-of($days, name())"/>
  </xsl:perform-sort>
</xsl:variable>

<xsl:for-each select="$orderedAtts[.='true']">
  <xsl:value-of select="position(), name(), '
'"/>
</xsl:for-each>
</code>```

There are a few cases where saxon:assign can be really useful, but the vast majority of cases where it is used (including this one) are simply because the stylesheet author hasn't learnt to think declaratively rather than procedurally.

LATER

The second example you have posted is even simpler. All it needs is:

```<code><xsl:for-each select="employee">
  <tr>
    <td><xsl:value-of select="name"/></td>
    <td><xsl:value-of select="position()"/></td>
  </tr>
</xsl:for-each>
</code>```

Body:
I am trying to upgrade my project to Java 8 and my project uses Saxon old version (i think saxon9). I was getting some issue after upgrading my project to Java 8 and in saxonia said Java 8 issues fixed in Saxon 9.5 version, so I have changed to Saxon HE 9.7 and supposed to use HE version alone. The inbuilt functions saxon:assign and saxon:assignable moved to EE version it seems.

So I am looking for an alternative approach to achieve saxon:assign and saxon:assignable.

Any suggestions? or any working examples would be helpful.

My Requirement is same as stated in https://www.altova.com/forum/default.aspx?g=posts&t=1000001577 .. How to increase variable count? without using saxon:assign and saxon:assignable.

I want have a global variable and need to increment when processing the element.

Updating more info.This is my requirement.
My Input xml is

<?xml version="1.0" encoding="UTF-8"?>
<employees>
    <employee>
        <name>Anbu</name>
        <address>Chennai</address>
        <dob>1990-05-15</dob>
        <phone>9600096000</phone>
        <email>anbu@email.com</email>
    </employee>
    <employee>
        <name>Bala</name>
        <address>Hydrabad</address>
        <dob>1989-01-04</dob>
        <phone>9700097000</phone>
        <email>bala@email.com</email>
    </employee>
    <employee>
        <name>Chandru</name>
        <address>Mumbai</address>
        <dob>1995-11-10</dob>
        <phone>9900099000</phone>
        <email>chandru@email.com</email>
    </employee>
</employees>

Need output like:

Employee Details

            Name
            Age

            Anbu
            1

            Bala
            2

            Chandru
            3

I want to have a global variable and increment it. I have tried with below xsl, but not works.

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0"
    xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:variable name="count" select="0" />
    <xsl:template match="/">

Employee Details

                        Name
                        Age

                    <xsl:for-each select="employees/employee">

                                <xsl:value-of select="name" />

                                <xsl:value-of select="$count+1" />

                    </xsl:for-each>

    </xsl:template>
</xsl:stylesheet>

can I achive this by creating Custom functions with ExtensionFunctionDefinition ?

Body:
The best answer is to wean yourself off the use of mutable variables. This may need a different approach, but if you learn to think declaratively then everything is possible. The changes you need to make will depend very much on how and why you are using saxon:assign.

If you can't do that, an alternative is to use stateful (impure) extension functions.

The specific example in the Altova forum post that you cite can be done very easily without saxon:assign. It's a somewhat strange example because it appears to depend on the order of attributes, but you can do it like this:

<xsl:variable name="days"
   select="'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday'"/>

<xsl:variable name="orderedAtts" as="attribute()*">
  <xsl:perform-sort select="//content-list/@*">
    <xsl:sort select="index-of($days, name())"/>
  </xsl:perform-sort>
</xsl:variable>

<xsl:for-each select="$orderedAtts[.='true']">
  <xsl:value-of select="position(), name(), '&#xa;'"/>
</xsl:for-each>

There are a few cases where saxon:assign can be really useful, but the vast majority of cases where it is used (including this one) are simply because the stylesheet author hasn't learnt to think declaratively rather than procedurally.

LATER

The second example you have posted is even simpler. All it needs is:

<xsl:for-each select="employee">
  <tr>
    <td><xsl:value-of select="name"/></td>
    <td><xsl:value-of select="position()"/></td>
  </tr>
</xsl:for-each>


问:
How to get correct status messages for a Python script?
I have a part of a Python script. This script will be invoked using a shell script.

```<code>try:
    sqlContext.sql("create table {}.`{}` as select * from mytempTable".format(hivedb,table))
except Exception as e:
    status = 'fail'
    error_message = e
else:
    status = 'success'
    error_message = 'No error'
print ("{},{},{},{}".format(hivedb,table,status,error_message))

status == 'success'
sys.exit(1)
</code>```

In this above code if I use status == 'success' I am getting success for all the time when the script runs, even for failed jobs.

If I use sys.exit(1) or both together I am getting failed all the time.

What should I do to get the script execution to be successful when status is 'success' and fail when status is 'fail'?

答:
The simplest answer would be to remove the the try/except. If you just make the call, on an exception, you'll get the full traceback to stderr and python will exit with a non zero exit status. </p>

<p>E.g. </p>

```<code>$ python -c "raise Exception('ha');" 1>stdout 2>stderr
$ echo $?
1
$ cat stderr
Traceback (most recent call last):
  File "<string>", line 1, in <module>
Exception: ha
</code>```

Body:
I have a part of a Python script. This script will be invoked using a shell script.

try:
    sqlContext.sql("create table {}.`{}` as select * from mytempTable".format(hivedb,table))
except Exception as e:
    status = 'fail'
    error_message = e
else:
    status = 'success'
    error_message = 'No error'
print ("{},{},{},{}".format(hivedb,table,status,error_message))

status == 'success'
sys.exit(1)

In this above code if I use status == 'success' I am getting success for all the time when the script runs, even for failed jobs.

If I use sys.exit(1) or both together I am getting failed all the time.

What should I do to get the script execution to be successful when status is 'success' and fail when status is 'fail'?

Body:
The simplest answer would be to remove the the try/except. If you just make the call, on an exception, you'll get the full traceback to stderr and python will exit with a non zero exit status.

E.g.

$ python -c "raise Exception('ha');" 1>stdout 2>stderr
$ echo $?
1
$ cat stderr
Traceback (most recent call last):
  File "<string>", line 1, in <module>
Exception: ha


问:
Does parity check always work in error detecting?
I'm confused about how a parity check will check if the data received is correct.  To my understanding it just checks if there is an even or odd number of 1's.  Because of this wouldn't it only find an error 50% of the time?  Like if I send the number 110011 with an even parity and the last 2 bits get cut off (leaving 1100) wouldn't it still pass the test even though some of the signal was lost?</p>

答:
The simple parity check can only detect an odd number of bit errors, but it will detect it 100% of the time.

There are more sophisticated error correction techniques. The Hamming code can detect up to two-bit errors or correct one-bit errors.

I'm not an expert on this.


问:
how to use jquery datatables with ajax calls
How to use ajax callbacks with jquery datatables i.e. call function on click?:

THIS WORKS

```<code>$(document).ready(function() {
    var table = $('#example').DataTable();

    $('#example tbody').on('click', 'tr', function () {
        var data = table.row( this ).data();
        alert( 'You clicked on '+data[0]+'\'s row' );
    } );
} );
</code>```

replacing alert( 'You clicked on '+data[0]+'\'s row' ); with Ajax call:

DOES NOT WORK

```<code>$(document).ready(function() {
    var table = $('#example').DataTable();

    $('#example tbody').on('click', 'tr', function () {
        var data = table.row( this ).data();
        //alert( 'You clicked on '+data[0]+'\'s row' );

         $.ajax({
                url: '/process',
                data: data[0],
                type: 'POST',
                success: function(response) {
                    $("#response_placeholder").html(response);
                },
                error: function(error) {
                    console.log(error);
                }
         });

    } );
} );
</code>```

backend

```<code>#--app.py----

@app.route('/process', methods=['POST'])
def process_data():
    data =  request.form['data[0]'];
    print data
    return render_template('mypage.html', result=data)
</code>```

答:
try to use this.

```<code> $('body').delegate('#example tbody tr','click' , function () {

} );
</code>```

Delegate helps to add events on elements that get added to the dom after it has been loaded.

also it is handy to put the data in an object like this

```<code>data: {data: data[0]},
</code>```

and the url should contain a extension probably

```<code>url: '/process.js', // or process.php depends on what extension it has.
</code>```

and for standards you should define the 3 attributes that will be returned with error eg.

```<code>error: function(jqXHR, textStatus, errorThrown) {
</code>```

Body:
How to use ajax callbacks with jquery datatables i.e. call function on click?:

THIS WORKS

$(document).ready(function() {
    var table = $('#example').DataTable();

    $('#example tbody').on('click', 'tr', function () {
        var data = table.row( this ).data();
        alert( 'You clicked on '+data[0]+'\'s row' );
    } );
} );

replacing alert( 'You clicked on '+data[0]+'\'s row' ); with Ajax call:

DOES NOT WORK

$(document).ready(function() {
    var table = $('#example').DataTable();

    $('#example tbody').on('click', 'tr', function () {
        var data = table.row( this ).data();
        //alert( 'You clicked on '+data[0]+'\'s row' );

         $.ajax({
                url: '/process',
                data: data[0],
                type: 'POST',
                success: function(response) {
                    $("#response_placeholder").html(response);
                },
                error: function(error) {
                    console.log(error);
                }
         });

    } );
} );

backend

#--app.py----

@app.route('/process', methods=['POST'])
def process_data():
    data =  request.form['data[0]'];
    print data
    return render_template('mypage.html', result=data)

Body:
try to use this.

 $('body').delegate('#example tbody tr','click' , function () {

} );

Delegate helps to add events on elements that get added to the dom after it has been loaded.

also it is handy to put the data in an object like this

data: {data: data[0]},

and the url should contain a extension probably

url: '/process.js', // or process.php depends on what extension it has.

and for standards you should define the 3 attributes that will be returned with error eg.

error: function(jqXHR, textStatus, errorThrown) {


问:
WordPress child theme style overridden by parent stylesheet
I have followed official and unofficial guides, and yet I simply cannot seem to be able to get certain styles in a child theme to overwrite its parents styles.

The only solution for me right now is to directly modify the main stylesheet, which is quite annoying as that gets overwritten every time there's an update for said theme.

I know the child-sheet works as some styles I set there do get shown.

The theme I'm using is Twenty Thirteen with a custom child theme.
I only have the default WP plugins active.
WordPress core, themes and plugins are up-to-date.

In both Chrome and Firefox I see the style, it's just ignored I guess.

I'm trying to change the background-color of the footer, I tried multiple selectors (ID, class, parent-child, element...

This may very well be something really simple I'm overseeing but I just can't figure it out.

Thanks in advance.

PS: sorry if I sound frustrated (I am, lol)

答:
I had the same problem and it was caused by Chrome caching the css. I renamed the style.css in the parent theme and refreshed my page and to my surprise nothing changed. Using F12 to inspect the element the styles section had a link to styles.css (even though I had renamed it) I was able to right click and open styles.css in a new tab.

The Ctrl-F5 shortcut clears the cache.
Doing this totally messed up my page because now it was not reading the parent style.css. Then all I had to do was rename it back and it correctly loaded it but also had the correct entries from the child style.css.

You might be able to just Ctrl-F5 (all the renaming bit was just exploration to force it not to load)


问:
Python/sockets/ssl EOF occurred in violation of protocol
I would like to authenticate the server at client's side in my echo client/server program. I'm using python 2.7.12 and the ssl module on

```<code>Distributor ID: Ubuntu
Description:    Ubuntu 14.04.5 LTS
Release:        14.04
Codename:       trusty
</code>```

I've generated client's and server's certificates and keys using the openssl commands:

```<code>openssl req -new -x509 -days 365 -nodes -out client.pem -keyout client.key
openssl req -new -x509 -days 365 -nodes -out server.pem -keyout server.key
</code>```

Versions of openssl library itself and openssl used by python are the same:

```<code>openssl version -a
OpenSSL 1.0.1f 6 Jan 2014
built on: Fri Sep 23 12:19:57 UTC 2016
platform: debian-amd64
options:  bn(64,64) rc4(16x,int) des(idx,cisc,16,int) blowfish(idx)
compiler: cc -fPIC -DOPENSSL_PIC -DOPENSSL_THREADS -D_REENTRANT -DDSO_DLFCN -DHAVE_DLFCN_H -m64 -DL_ENDIAN -DTERMIO -g -O2 -fstack-protector --param=ssp-buffer-size=4 -Wformat -Werror=format-security -D_FORTIFY_SOURCE=2 -Wl,-Bsymbolic-functions -Wl,-z,relro -Wa,--noexecstack -Wall -DMD32_REG_T=int -DOPENSSL_IA32_SSE2 -DOPENSSL_BN_ASM_MONT -DOPENSSL_BN_ASM_MONT5 -DOPENSSL_BN_ASM_GF2m -DSHA1_ASM -DSHA256_ASM -DSHA512_ASM -DMD5_ASM -DAES_ASM -DVPAES_ASM -DBSAES_ASM -DWHIRLPOOL_ASM -DGHASH_ASM
OPENSSLDIR: "/usr/lib/ssl"

python -c "import ssl; print ssl.OPENSSL_VERSION"
OpenSSL 1.0.1f 6 Jan 2014
</code>```

However, the code below shows some errors, at server's side: EOF occurred in violation of protocol (_ssl.c:1645) (but the server still works), and at client's side:

```<code>Traceback (most recent call last):
  File "/http_ssl_client.py", line 36, in <module>
    if not cert or ('commonName', 'test') not in cert['subject'][4]: raise Exception("Invalid SSL cert for host %s. Check if this is a man-in-themiddle attack!" )
Exception: Invalid SSL cert for host %s. Check if this is a man-in-themiddle attack!
{'notBefore': u'Jun  3 11:54:21 2017 GMT', 'serialNumber': u'BBDCBEED69655B6E', 'notAfter': 'Jun  3 11:54:21 2018 GMT', 'version': 3L, 'subject': ((('countryName', u'pl'),), (('stateOrProvinceName', u'test'),), (('localityName', u'test'),), (('organizationName', u'test'),), (('organizationalUnitName', u'test'),), (('commonName', u'test'),), (('emailAddress', u'test'),)), 'issuer': ((('countryName', u'pl'),), (('stateOrProvinceName', u'test'),), (('localityName', u'test'),), (('organizationName', u'test'),), (('organizationalUnitName', u'test'),), (('commonName', u'test'),), (('emailAddress', u'test'),))}
</code>```

Server's code:

```<code>#!/bin/usr/env python
import socket
import ssl

def main():
    HOST = '127.0.0.1'
    PORT = 1234

    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    sock.bind((HOST, PORT))
    sock.listen(5)

    while True:
        conn = None
        client_sock, addr = sock.accept()
        try:
            ssl_client = ssl.wrap_socket(client_sock, server_side=True, certfile="server.pem", keyfile="server.key", ssl_version=ssl.PROTOCOL_TLSv1_2)
            data =  ssl_client.read(1024)
            print data
            ssl_client.write(data)
        except ssl.SSLError as e:
            print(e)
        finally:
            if conn:
                conn.close()
if __name__ == '__main__':
    main()
</code>```

Client:

```<code>#!/bin/usr/env python
import socket
import ssl

if __name__ == '__main__':

    HOST = '127.0.0.1'
    PORT = 1234

    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    sock.connect((HOST, PORT))

    context = ssl.SSLContext(ssl.PROTOCOL_TLSv1_2)
    context.verify_mode = ssl.CERT_REQUIRED
    context.load_verify_locations('server.pem')

    if ssl.HAS_SNI:
        secure_sock = context.wrap_socket(sock, server_hostname=HOST)
    else:
        secure_sock = context.wrap_socket(sock)

    cert = secure_sock.getpeercert()
    print cert

    if not cert or ('commonName', 'test') not in cert['subject'][4]: raise Exception("Error" )

    secure_sock.write('hello')

    print secure_sock.read(1024)

    secure_sock.close()
    sock.close()
</code>```

All files are in the same directory.

答:
I'm going to walk through the issues I've spotted (although some are already spotted by someone else, and also fixed). Note that I've tried on Win 10 using Python 2.7.10, 2.7.13, 3.4.4, 3.5.3 and OpenSSL 1.0.2d, 1.0.2j (w/wo fips):

server.py:

conn variable is initialized to None and that's it. The if clause under finally is useless. client_sock should probably be tested

Hint: the server socket (sock) could probably be wrapped (instead of client_sock); that way client_sock (returned by sock.accept()) would already be wrapped

client.py:

The 1st one is minor: the code in the snippet (raise Exception("Error")) is not the same as the one in the traceback (raise Exception("Invalid SSL cert for host %s. Check if this is a man-in-themiddle attack!"))

The way of searching for certificate attributes. As @TomaszPlaskota noticed, the commonName tuple index is wrong. Here's the pretty-printed certificate from my machine (the field values might/will differ):

{
    'issuer': ((('countryName', 'AU'),),
               (('stateOrProvinceName', 'Some-State'),),
               (('localityName', 'CJ'),),
               (('organizationName', 'Internet Widgits Pty Ltd'),),
               (('organizationalUnitName', 'OU'),),
               (('commonName', 'cfati-e5550-0'),),
               (('emailAddress', 'a@a.com'),)),
    'notAfter': 'Jun  5 17:21:03 2018 GMT',
    'notBefore': 'Jun  5 17:21:03 2017 GMT',
    'serialNumber': 'C4A03B2BE4F959A9',
    'subject': ((('countryName', 'AU'),),
                (('stateOrProvinceName', 'Some-State'),),
                (('localityName', 'CJ'),),
                (('organizationName', 'Internet Widgits Pty Ltd'),),
                (('organizationalUnitName', 'OU'),),
                (('commonName', 'cfati-e5550-0'),),
                (('emailAddress', 'a@a.com'),)),
    'version': 3
}
```

<p>There might be cases (at least theoretically) when the certificate would be incomplete. A more robust form of the check would be:</p>

<pre class="lang-py prettyprint-override"><code>def check_certificate(cert, field=("commonName", "test")):
    if not cert:
        return False
    for pairs in cert.get("subject", ()):
        if field in pairs:
            return True
    return False

# ....

if not check_certificate(cert):
    raise Exception("Error")
</code>```

The way of handling errors. If the server certificate is not OK, you simply raise an error which breaks the communication and exits the client program abnormally. That fact, on the server side triggers ssl.SSLEOFError: EOF occurred in violation of protocol (_ssl.c:590) (from your other question: [SO]: Mutual ssl authentication in simple ECHO client/server [Python / sockets / ssl modules], ssl.SSLEOFError: EOF occurred in violation of protocol), when the server tries to write back to the client (ssl_client.write(data)).
Although in some cases at program termination the OS cleans up the resources, it's recommended to always do the cleanup from code. So, instead of just raising an exception, do something like (as @JamesKPolk suggested):

plain_sock = secure_sock.unwrap()
plain_sock.shutdown(socket.SHUT_RDWR)
plain_sock.close()
# Any other cleanup action here
```

The biggest problem is that you are using 2 self-signed certificates (that have nothing to each other). A certificate being self-signed means:

It's its own signer (or parent). That's why the Issuer and Subject fields are the same (or to be more rigorous: its Issuer Key Identifier and Subject Key Identifier extensions are the same)

It's a CA (Certificate Authority) certificate (if looking in its Basic Constraints, you'll notice Subject Type is CA). This is like a consequence of the former bullet

Few words about certificates: they are organized in trees: meaning that there will be a root node also known as Root CA certificate. That node might have several child nodes (a child node means that it's signed by its parent). Those nodes can also be CA or end user (EU) certs. Each CA cert might also have children, and there is our tree. Its leafs are EU certificates. The path between the Root CA and a  leaf certificate (composed by the Root CA, Intermediate CAs and EU) is called a certificate chain.

A self-signed cert can be represented as a tree consisting of a single node. Note that being a CA cert (as in our case) it can also be used to sign other certs (it can have children).

Certificate validation - when a certificate is verified to make sure that it is "who" it claims it is. That is done by checking it against its parent CA (and recursively all the CAs in the chain are checked til the Root CA is reached). If everything is OK, then the certificate is valid. This is of course a very simplistic version, the subject is quite complex, but there's lots of info that can be found on the Internet. Needless to say that the entity that performs the validation needs to have access to the CAs in the chain. You can take the Web browser as an example, its certificate "vault" contains:

Optionally: certificates (EU) that were supplied to you in order to be able to connect to some sites (e.g. Personal Certificates)

Certificates (CA) required to validate other certificates presented by web servers (Trusted Root/Intermediate Certification Authorities)

[IBM]: An overview of the SSL or TLS handshake (although there are many other places) briefly describes how SSL connection works.
Typically a secure system, will emit a (unique) certificate (EU) for each of its clients; that certificate will be bond to the client machine (*IP8 address or FQDN); here CRL and OCSP worth being mentioned.

Back to the question: because we have a particular situation (2 certs where each is CA, but they are also used as EUs), it may not be so obvious, but I'll do my best to explain. Considering that certificate validation will happen at both communication ends (two-way), both certificates must be loaded in both applications. For example, in server app:

server certificate must be loaded in order to be presented to any client that connects, in order for the client to verify it

client certificate must be loaded (as a CA) in order to verify the certificate that any client presents (which will be the same certificate). Take look at [Python 2.Docs]: ssl.wrap_socket(sock, keyfile=None, certfile=None, server_side=False, cert_reqs=CERT_NONE, ssl_version={see docs}, ca_certs=None, do_handshake_on_connect=True, suppress_ragged_eofs=True, ciphers=None)(ca_certs argument)

Obviously, for client, it will be the other way around.

Body:
I would like to authenticate the server at client's side in my echo client/server program. I'm using python 2.7.12 and the ssl module on

Distributor ID: Ubuntu
Description:    Ubuntu 14.04.5 LTS
Release:        14.04
Codename:       trusty

I've generated client's and server's certificates and keys using the openssl commands:

openssl req -new -x509 -days 365 -nodes -out client.pem -keyout client.key
openssl req -new -x509 -days 365 -nodes -out server.pem -keyout server.key

Versions of openssl library itself and openssl used by python are the same:

openssl version -a
OpenSSL 1.0.1f 6 Jan 2014
built on: Fri Sep 23 12:19:57 UTC 2016
platform: debian-amd64
options:  bn(64,64) rc4(16x,int) des(idx,cisc,16,int) blowfish(idx)
compiler: cc -fPIC -DOPENSSL_PIC -DOPENSSL_THREADS -D_REENTRANT -DDSO_DLFCN -DHAVE_DLFCN_H -m64 -DL_ENDIAN -DTERMIO -g -O2 -fstack-protector --param=ssp-buffer-size=4 -Wformat -Werror=format-security -D_FORTIFY_SOURCE=2 -Wl,-Bsymbolic-functions -Wl,-z,relro -Wa,--noexecstack -Wall -DMD32_REG_T=int -DOPENSSL_IA32_SSE2 -DOPENSSL_BN_ASM_MONT -DOPENSSL_BN_ASM_MONT5 -DOPENSSL_BN_ASM_GF2m -DSHA1_ASM -DSHA256_ASM -DSHA512_ASM -DMD5_ASM -DAES_ASM -DVPAES_ASM -DBSAES_ASM -DWHIRLPOOL_ASM -DGHASH_ASM
OPENSSLDIR: "/usr/lib/ssl"

python -c "import ssl; print ssl.OPENSSL_VERSION"
OpenSSL 1.0.1f 6 Jan 2014

However, the code below shows some errors, at server's side: EOF occurred in violation of protocol (_ssl.c:1645) (but the server still works), and at client's side:

Traceback (most recent call last):
  File "/http_ssl_client.py", line 36, in <module>
    if not cert or ('commonName', 'test') not in cert['subject'][4]: raise Exception("Invalid SSL cert for host %s. Check if this is a man-in-themiddle attack!" )
Exception: Invalid SSL cert for host %s. Check if this is a man-in-themiddle attack!
{'notBefore': u'Jun  3 11:54:21 2017 GMT', 'serialNumber': u'BBDCBEED69655B6E', 'notAfter': 'Jun  3 11:54:21 2018 GMT', 'version': 3L, 'subject': ((('countryName', u'pl'),), (('stateOrProvinceName', u'test'),), (('localityName', u'test'),), (('organizationName', u'test'),), (('organizationalUnitName', u'test'),), (('commonName', u'test'),), (('emailAddress', u'test'),)), 'issuer': ((('countryName', u'pl'),), (('stateOrProvinceName', u'test'),), (('localityName', u'test'),), (('organizationName', u'test'),), (('organizationalUnitName', u'test'),), (('commonName', u'test'),), (('emailAddress', u'test'),))}

Server's code:

#!/bin/usr/env python
import socket
import ssl

def main():
    HOST = '127.0.0.1'
    PORT = 1234

    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    sock.bind((HOST, PORT))
    sock.listen(5)

    while True:
        conn = None
        client_sock, addr = sock.accept()
        try:
            ssl_client = ssl.wrap_socket(client_sock, server_side=True, certfile="server.pem", keyfile="server.key", ssl_version=ssl.PROTOCOL_TLSv1_2)
            data =  ssl_client.read(1024)
            print data
            ssl_client.write(data)
        except ssl.SSLError as e:
            print(e)
        finally:
            if conn:
                conn.close()
if __name__ == '__main__':
    main()

Client:

#!/bin/usr/env python
import socket
import ssl

if __name__ == '__main__':

    HOST = '127.0.0.1'
    PORT = 1234

    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    sock.connect((HOST, PORT))

    context = ssl.SSLContext(ssl.PROTOCOL_TLSv1_2)
    context.verify_mode = ssl.CERT_REQUIRED
    context.load_verify_locations('server.pem')

    if ssl.HAS_SNI:
        secure_sock = context.wrap_socket(sock, server_hostname=HOST)
    else:
        secure_sock = context.wrap_socket(sock)

    cert = secure_sock.getpeercert()
    print cert

    if not cert or ('commonName', 'test') not in cert['subject'][4]: raise Exception("Error" )

    secure_sock.write('hello')

    print secure_sock.read(1024)

    secure_sock.close()
    sock.close()

All files are in the same directory.

Body:
I'm going to walk through the issues I've spotted (although some are already spotted by someone else, and also fixed). Note that I've tried on Win 10 using Python 2.7.10, 2.7.13, 3.4.4, 3.5.3 and OpenSSL 1.0.2d, 1.0.2j (w/wo fips):

server.py:

conn variable is initialized to None and that's it. The if clause under finally is useless. client_sock should probably be tested

Hint: the server socket (sock) could probably be wrapped (instead of client_sock); that way client_sock (returned by sock.accept()) would already be wrapped

client.py:

The 1st one is minor: the code in the snippet (raise Exception("Error")) is not the same as the one in the traceback (raise Exception("Invalid SSL cert for host %s. Check if this is a man-in-themiddle attack!"))

The way of searching for certificate attributes. As @TomaszPlaskota noticed, the commonName tuple index is wrong. Here's the pretty-printed certificate from my machine (the field values might/will differ):

{
    'issuer': ((('countryName', 'AU'),),
               (('stateOrProvinceName', 'Some-State'),),
               (('localityName', 'CJ'),),
               (('organizationName', 'Internet Widgits Pty Ltd'),),
               (('organizationalUnitName', 'OU'),),
               (('commonName', 'cfati-e5550-0'),),
               (('emailAddress', 'a@a.com'),)),
    'notAfter': 'Jun  5 17:21:03 2018 GMT',
    'notBefore': 'Jun  5 17:21:03 2017 GMT',
    'serialNumber': 'C4A03B2BE4F959A9',
    'subject': ((('countryName', 'AU'),),
                (('stateOrProvinceName', 'Some-State'),),
                (('localityName', 'CJ'),),
                (('organizationName', 'Internet Widgits Pty Ltd'),),
                (('organizationalUnitName', 'OU'),),
                (('commonName', 'cfati-e5550-0'),),
                (('emailAddress', 'a@a.com'),)),
    'version': 3
}

There might be cases (at least theoretically) when the certificate would be incomplete. A more robust form of the check would be:

def check_certificate(cert, field=("commonName", "test")):
    if not cert:
        return False
    for pairs in cert.get("subject", ()):
        if field in pairs:
            return True
    return False

# ....

if not check_certificate(cert):
    raise Exception("Error")

The way of handling errors. If the server certificate is not OK, you simply raise an error which breaks the communication and exits the client program abnormally. That fact, on the server side triggers ssl.SSLEOFError: EOF occurred in violation of protocol (_ssl.c:590) (from your other question: [SO]: Mutual ssl authentication in simple ECHO client/server [Python / sockets / ssl modules], ssl.SSLEOFError: EOF occurred in violation of protocol), when the server tries to write back to the client (ssl_client.write(data)).
Although in some cases at program termination the OS cleans up the resources, it's recommended to always do the cleanup from code. So, instead of just raising an exception, do something like (as @JamesKPolk suggested):

plain_sock = secure_sock.unwrap()
plain_sock.shutdown(socket.SHUT_RDWR)
plain_sock.close()
# Any other cleanup action here

The biggest problem is that you are using 2 self-signed certificates (that have nothing to each other). A certificate being self-signed means:

It's its own signer (or parent). That's why the Issuer and Subject fields are the same (or to be more rigorous: its Issuer Key Identifier and Subject Key Identifier extensions are the same)

It's a CA (Certificate Authority) certificate (if looking in its Basic Constraints, you'll notice Subject Type is CA). This is like a consequence of the former bullet

Few words about certificates: they are organized in trees: meaning that there will be a root node also known as Root CA certificate. That node might have several child nodes (a child node means that it's signed by its parent). Those nodes can also be CA or end user (EU) certs. Each CA cert might also have children, and there is our tree. Its leafs are EU certificates. The path between the Root CA and a  leaf certificate (composed by the Root CA, Intermediate CAs and EU) is called a certificate chain.

A self-signed cert can be represented as a tree consisting of a single node. Note that being a CA cert (as in our case) it can also be used to sign other certs (it can have children).

Certificate validation - when a certificate is verified to make sure that it is "who" it claims it is. That is done by checking it against its parent CA (and recursively all the CAs in the chain are checked til the Root CA is reached). If everything is OK, then the certificate is valid. This is of course a very simplistic version, the subject is quite complex, but there's lots of info that can be found on the Internet. Needless to say that the entity that performs the validation needs to have access to the CAs in the chain. You can take the Web browser as an example, its certificate "vault" contains:

Optionally: certificates (EU) that were supplied to you in order to be able to connect to some sites (e.g. Personal Certificates)

Certificates (CA) required to validate other certificates presented by web servers (Trusted Root/Intermediate Certification Authorities)

[IBM]: An overview of the SSL or TLS handshake (although there are many other places) briefly describes how SSL connection works.
Typically a secure system, will emit a (unique) certificate (EU) for each of its clients; that certificate will be bond to the client machine (*IP8 address or FQDN); here CRL and OCSP worth being mentioned.

Back to the question: because we have a particular situation (2 certs where each is CA, but they are also used as EUs), it may not be so obvious, but I'll do my best to explain. Considering that certificate validation will happen at both communication ends (two-way), both certificates must be loaded in both applications. For example, in server app:

server certificate must be loaded in order to be presented to any client that connects, in order for the client to verify it

client certificate must be loaded (as a CA) in order to verify the certificate that any client presents (which will be the same certificate). Take look at [Python 2.Docs]: ssl.wrap_socket(sock, keyfile=None, certfile=None, server_side=False, cert_reqs=CERT_NONE, ssl_version={see docs}, ca_certs=None, do_handshake_on_connect=True, suppress_ragged_eofs=True, ciphers=None)(ca_certs argument)

Obviously, for client, it will be the other way around.

ContentLicense: CC BY-SA 4.0


问:
position:absolute breaks CSS dropdown
I am making something with ace editor. As part of this, I have a dropdown menu that allows theme selection. This is on a bar at the top, (which will eventually have more options). I know that, in order to position the bar at the very top, I need to use position:absolute in the CSS code. However, this breaks the dropdown, and it no longer actually drops down. To see what I mean, here is a fiddle. (To compare, removing position: absolute in the CSS for #navbar makes it work fine, but is not at the very top [most visible in a full window].)
Note: In the fiddle, I have removed everything not related to the navbar, such as the ace code.

答:
Seems to work fine if you remove the max-height from .dropChoices, the bottom and overflow on #navbar

// The function changeTheme() is defined in the full code
function toggle(button) {
    var dropList = button.nextElementSibling;

    function isDropdown() {
        return (" " + dropList.className + " ").indexOf(" dropChoices ") > -1;
    }
    while (!isDropdown) {
        dropList = dropList.nextElementSibling;
    }
    dropList.classList.toggle("hidden");
    window.onclick = function(e) {
        if (!e.target.matches('.dropButton') && !e.target.matches('.dropChoices')) {
            if (!dropList.classList.contains('hidden')) {
                dropList.classList.add('hidden');
            }
        }
    }
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#navbar {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    background-color: dimgray;
}
.navOption {
    font-size: 12px;
    color: white;
    padding: 1px 13px;
}
.dropButton {
  box-sizing: border-box;
  cursor: pointer;
  font-size: 16px;
  border: none;
  color: white;
  padding: 13px 16px;
  background-color: inherit;
}
.navOption:hover, .navOption:active, .navOption:focus {
    background-color: gray;
    outline: none;
}
.dropChoices {
    font-size: 16px;
    overflow: auto;
    display: block;
    position: absolute;
    background-color: #f9f9f9;
    min-width: 160px;
    z-index: 5;
    max-height: calc(100vh - 50px);
}
.dropChoices p {
    color: black;
    outline: none;
    padding: 12px 16px;
    cursor: pointer;
    margin: 0;
    text-align: left;
}
.dropChoices p:hover, .dropChoices p:focus {
    background-color: lightgray;
}
p.dropTitle {
    cursor: initial;
}
p.dropTitle:hover {
    background-color: #f9f9f9;
}
.hidden {
    display: none;
}</code>```

   <button onclick="toggle(this)" class="dropButton navOption">Themes</button>

Light

Chrome

Clouds

Crimson Editor

Dawn

Dreamweaver

Eclipse

GitHub

IPlastic

Solarized Light

TextMate

Tomorrow

XCode

Kuroir

KatzenMilch

SQL Server

Dark

Ambiance

Chaos

Clouds Midnight

Cobalt

Gruvbox

idle Fingers

krTheme

Merbivore

Merbivore Soft

Mono Industrial

Monokai

Pastel on dark

Solarized Dark

Terminal

Tomorrow Night

Tomorrow Night Blue

Tomorrow Night Bright

Tomorrow Night 80s

Twilight

Vibrant Ink

 ```

Title: position:absolute breaks CSS dropdown

Body:
Seems to work fine if you remove the max-height from .dropChoices, the bottom and overflow on #navbar

// The function changeTheme() is defined in the full code
function toggle(button) {
    var dropList = button.nextElementSibling;

    function isDropdown() {
        return (" " + dropList.className + " ").indexOf(" dropChoices ") > -1;
    }
    while (!isDropdown) {
        dropList = dropList.nextElementSibling;
    }
    dropList.classList.toggle("hidden");
    window.onclick = function(e) {
        if (!e.target.matches('.dropButton') && !e.target.matches('.dropChoices')) {
            if (!dropList.classList.contains('hidden')) {
                dropList.classList.add('hidden');
            }
        }
    }
}

#navbar {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    background-color: dimgray;
}
.navOption {
    font-size: 12px;
    color: white;
    padding: 1px 13px;
}
.dropButton {
  box-sizing: border-box;
  cursor: pointer;
  font-size: 16px;
  border: none;
  color: white;
  padding: 13px 16px;
  background-color: inherit;
}
.navOption:hover, .navOption:active, .navOption:focus {
    background-color: gray;
    outline: none;
}
.dropChoices {
    font-size: 16px;
    overflow: auto;
    display: block;
    position: absolute;
    background-color: #f9f9f9;
    min-width: 160px;
    z-index: 5;
    max-height: calc(100vh - 50px);
}
.dropChoices p {
    color: black;
    outline: none;
    padding: 12px 16px;
    cursor: pointer;
    margin: 0;
    text-align: left;
}
.dropChoices p:hover, .dropChoices p:focus {
    background-color: lightgray;
}
p.dropTitle {
    cursor: initial;
}
p.dropTitle:hover {
    background-color: #f9f9f9;
}
.hidden {
    display: none;
}

<!-- This code is slightly shortened, and only contains the relevant things -->
<div id="navbar">
   <button onclick="toggle(this)" class="dropButton navOption">Themes</button>
   <div id="themesList" class="dropChoices hidden">
    <p class="dropTitle"><b>Light</b></p>
                <p tabindex="0" id="chrome" onclick="changeTheme(this.id)">Chrome</p>
                <p tabindex="0" id="clouds" onclick="changeTheme(this.id)">Clouds</p>
                <p tabindex="0" id="crimson_editor" onclick="changeTheme(this.id)">Crimson Editor</p>
                <p tabindex="0" id="dawn" onclick="changeTheme(this.id)">Dawn</p>
                <p tabindex="0" id="dreamweaver" onclick="changeTheme(this.id)">Dreamweaver</p>
                <p tabindex="0" id="eclipse" onclick="changeTheme(this.id)">Eclipse</p>
                <p tabindex="0" id="gitHub" onclick="changeTheme(this.id)">GitHub</p>
                <p tabindex="0" id="iplastic" onclick="changeTheme(this.id)">IPlastic</p>
                <p tabindex="0" id="solarized_light" onclick="changeTheme(this.id)">Solarized Light</p>
                <p tabindex="0" id="textmate" onclick="changeTheme(this.id)">TextMate</p>
                <p tabindex="0" id="tomorrow" onclick="changeTheme(this.id)">Tomorrow</p>
                <p tabindex="0" id="xcode" onclick="changeTheme(this.id)">XCode</p>
                <p tabindex="0" id="kuroir" onclick="changeTheme(this.id)">Kuroir</p>
                <p tabindex="0" id="katzenmilch" onclick="changeTheme(this.id)">KatzenMilch</p>
                <p tabindex="0" id="sqlserver" onclick="changeTheme(this.id)">SQL Server</p>
    <p class="dropTitle"><b>Dark</b></p>
                <p tabindex="0" id="ambiance" onclick="changeTheme(this.id)">Ambiance</p>
                <p tabindex="0" id="chaos" onclick="changeTheme(this.id)">Chaos</p>
                <p tabindex="0" id="clouds_midnight" onclick="changeTheme(this.id)">Clouds Midnight</p>
                <p tabindex="0" id="cobalt" onclick="changeTheme(this.id)">Cobalt</p>
                <p tabindex="0" id="gruvbox" onclick="changeTheme(this.id)">Gruvbox</p>
                <p tabindex="0" id="idle_fingers" onclick="changeTheme(this.id)">idle Fingers</p>
                <p tabindex="0" id="kr_theme" onclick="changeTheme(this.id)">krTheme</p>
                <p tabindex="0" id="merbivore" onclick="changeTheme(this.id)">Merbivore</p>
                <p tabindex="0" id="merbivore_soft" onclick="changeTheme(this.id)">Merbivore Soft</p>
                <p tabindex="0" id="mono_industrial" onclick="changeTheme(this.id)">Mono Industrial</p>
                <p tabindex="0" id="monokai" onclick="changeTheme(this.id)">Monokai</p>
                <p tabindex="0" id="pastel_on_dark" onclick="changeTheme(this.id)">Pastel on dark</p>
                <p tabindex="0" id="solarized_dark" onclick="changeTheme(this.id)">Solarized Dark</p>
                <p tabindex="0" id="terminal" onclick="changeTheme(this.id)">Terminal</p>
                <p tabindex="0" id="tomorrow_night" onclick="changeTheme(this.id)">Tomorrow Night</p>
                <p tabindex="0" id="tomorrow_night_blue" onclick="changeTheme(this.id)">Tomorrow Night Blue</p>
                <p tabindex="0" id="tomorrow_night_bright" onclick="changeTheme(this.id)">Tomorrow Night Bright</p>
                <p tabindex="0" id="tomorrow_night_eighties" onclick="changeTheme(this.id)">Tomorrow Night 80s</p>
                <p tabindex="0" id="twilight" onclick="changeTheme(this.id)">Twilight</p>
                <p tabindex="0" id="vibrant_ink" onclick="changeTheme(this.id)">Vibrant Ink</p>
   </div>
  </div>


问:
contour extraction
Example: I as a user I have a database with 20 images but only 3 images obtain scene with sun. I would like to retrieve images from this database only with sun scene. I am using Fourier descriptor for discribing shape and I would like to obtain features vector from the image and this features vector compare and calculation Euclidian distance between real image and reference image database. BUT I would like to obtain features vector for reference sun image. I use segmentation and then I make converting image to binary format. I want to describe only object in image not background. How can I describe coutour image and obtain features vector? </p>

答:
What is the "background" here?

Now think ...

How did you decide?
Used colors?
Used size?
Used position?
Used some "sense of beauty"? ...

You can define the background only if you can tell some predicate about the foreground ... and that means knowing something about the object. That knowledge perhaps could be translated to code ...

Title: contour extraction


问:
Sliding window over numerical sequence
I am trying to build a sliding window approach that will slide over the numerical sequence of the elements in a list. This is important and, I believe, different from other sliding window approaches found in SO, in which the slide is usually made over the indexes of the list.

What I mean is something like the following. Having the list of integers

li = [1, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]

with a window=3 and step=2, the expected output would be the:

```<code>[1, 3]
[3, 4, 5]
[5, 6, 7]
[7, 8, 9]
[9, 10, 11]
[11, 12]
</code>```

The code I have so far:

```<code>window = 3
step = 2

last_pos = 0
w_start = 1
w_end = window
next_start = w_start + step
dat = []  # values for window
next_dat = []  # values for the next window

li = [1, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]

for e in li:
    ipos = int(e)
    if ipos > last_pos:
        dat.append(ipos)

        if ipos == w_end:  # end of window
            w_start += step
            w_end += step
            print(dat)
            dat = next_dat  # reset window...

        if ipos >= next_start:  # ipos is in the next window
            next_dat.append(ipos)

        if w_start == next_start:  # move next window
            next_start += step
            next_dat = []  # reset next window...
    else:
        raise Exception('List is not sorted')

    last_pos += 1

# the last window if not empty
print(dat) if dat else 'false'
</code>```

The output is the expected:

```<code>[1, 3]
[3, 4, 5]
[5, 6, 7]
[7, 8, 9]
[9, 10, 11]
[11, 12]
</code>```

However, besides not being much elegant, this code seems to fail when more than two windows overlap. For example, with window=5 and step=2 it produces the wrong output:

```<code>[1, 3, 4, 5]
[3, 4, 5, 6, 7]
[6, 7, 8, 9]
[8, 9, 10, 11]
[10, 11, 12]
</code>```

The 1st and 2nd windows are OK, but from the 3rd onwards, things get messy. For example, the third window should have started at 5 and should have 5 elements, not four. I'm aiming to get the following windows instead:

```<code>[1, 3, 4, 5]
[3, 4, 5, 6, 7]
[5, 6, 7, 8, 9]
[7, 8, 9, 10, 11]
[9, 10, 11, 12]
</code>```

Any ideas on how to fix this behaviour?

Please note that it isn't the list indexes but the list values itselves to slide. I believe these two approaches are different in the particular case that some values are missing from the list. In the case shown above the first three items in the list are 1, 3, 4. I think that iterating over the indexes (window=2 and step=2) would result in the following output (but this is not tested):

```<code>[1, 3]
[4]
</code>```

whereas what I would like to do is to iterate over the values of the list, so that the resulting windows would be:

```<code>[1]
[3, 4]
</code>```

So the value 2 is missing from the first window because it wasn't in the original list.

Although this is illustrated here with a list in the end I will want to read these from a huge file that will hardly fit into memory.

答:
The problem with the code in the question is that it is uncertain how many windows you will need to keep track of beforehand.
The best approach for this task is likely to use just one list for the window and then copy those values that overlap with the next window and so forth.

The code below is working for all the windows I tested:

```<code>window = 3
step = 2

last_pos = 0
w_start = 1
w_end = window
dat = []  # values for window
next_dat = []  # values for the next window

li = [1, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]

for e in li:
    ipos = int(e)
    if ipos > last_pos:

        if ipos > w_end:  # end of window
            print(dat)
            w_start += step
            w_end += step

            if step == window:  # non-overlapping
                next_dat = []  # reset next window...
            else:
                next_dat = [x for x in dat if x >= (w_start)]

            dat = next_dat  # reset window...

        dat.append(ipos)
    else:
        raise Exception('List is not sorted')

    last_pos += 1

# the last window if not empty
print(dat) if dat else 'false'
</code>```

(window=3 and step=2)

```<code>[1, 3]
[3, 4, 5]
[5, 6, 7]
[7, 8, 9]
[9, 10, 11]
[11, 12]
</code>```

(window=2 and step=2)

```<code>[1]
[3, 4]
[5, 6]
[7, 8]
[9, 10]
[11, 12]
</code>```

(window=5 and step=2)

```<code>[1, 3, 4, 5]
[3, 4, 5, 6, 7]
[5, 6, 7, 8, 9]
[7, 8, 9, 10, 11]
[9, 10, 11, 12]
</code>```

Again, this code is not very elegant I think, but it does the job so I'll mark this answer as accepted. However, I'm still open to any improvements/advises for this code.

Title: Sliding window over numerical sequence

Body:
I am trying to build a sliding window approach that will slide over the numerical sequence of the elements in a list. This is important and, I believe, different from other sliding window approaches found in SO, in which the slide is usually made over the indexes of the list.

What I mean is something like the following. Having the list of integers

li = [1, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]

with a window=3 and step=2, the expected output would be the:

[1, 3]
[3, 4, 5]
[5, 6, 7]
[7, 8, 9]
[9, 10, 11]
[11, 12]

The code I have so far:

window = 3
step = 2

last_pos = 0
w_start = 1
w_end = window
next_start = w_start + step
dat = []  # values for window
next_dat = []  # values for the next window

li = [1, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]

for e in li:
    ipos = int(e)
    if ipos > last_pos:
        dat.append(ipos)

        if ipos == w_end:  # end of window
            w_start += step
            w_end += step
            print(dat)
            dat = next_dat  # reset window...

        if ipos >= next_start:  # ipos is in the next window
            next_dat.append(ipos)

        if w_start == next_start:  # move next window
            next_start += step
            next_dat = []  # reset next window...
    else:
        raise Exception('List is not sorted')

    last_pos += 1

# the last window if not empty
print(dat) if dat else 'false'

The output is the expected:

[1, 3]
[3, 4, 5]
[5, 6, 7]
[7, 8, 9]
[9, 10, 11]
[11, 12]

However, besides not being much elegant, this code seems to fail when more than two windows overlap. For example, with window=5 and step=2 it produces the wrong output:

[1, 3, 4, 5]
[3, 4, 5, 6, 7]
[6, 7, 8, 9]
[8, 9, 10, 11]
[10, 11, 12]

The 1st and 2nd windows are OK, but from the 3rd onwards, things get messy. For example, the third window should have started at 5 and should have 5 elements, not four. I'm aiming to get the following windows instead:

[1, 3, 4, 5]
[3, 4, 5, 6, 7]
[5, 6, 7, 8, 9]
[7, 8, 9, 10, 11]
[9, 10, 11, 12]

Any ideas on how to fix this behaviour?

Please note that it isn't the list indexes but the list values itselves to slide. I believe these two approaches are different in the particular case that some values are missing from the list. In the case shown above the first three items in the list are 1, 3, 4. I think that iterating over the indexes (window=2 and step=2) would result in the following output (but this is not tested):

[1, 3]
[4]

whereas what I would like to do is to iterate over the values of the list, so that the resulting windows would be:

[1]
[3, 4]

So the value 2 is missing from the first window because it wasn't in the original list.

Although this is illustrated here with a list in the end I will want to read these from a huge file that will hardly fit into memory.

Body:
The problem with the code in the question is that it is uncertain how many windows you will need to keep track of beforehand.
The best approach for this task is likely to use just one list for the window and then copy those values that overlap with the next window and so forth.

The code below is working for all the windows I tested:

window = 3
step = 2

last_pos = 0
w_start = 1
w_end = window
dat = []  # values for window
next_dat = []  # values for the next window

li = [1, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]

for e in li:
    ipos = int(e)
    if ipos > last_pos:

        if ipos > w_end:  # end of window
            print(dat)
            w_start += step
            w_end += step

            if step == window:  # non-overlapping
                next_dat = []  # reset next window...
            else:
                next_dat = [x for x in dat if x >= (w_start)]

            dat = next_dat  # reset window...

        dat.append(ipos)
    else:
        raise Exception('List is not sorted')

    last_pos += 1

# the last window if not empty
print(dat) if dat else 'false'

(window=3 and step=2)

[1, 3]
[3, 4, 5]
[5, 6, 7]
[7, 8, 9]
[9, 10, 11]
[11, 12]

(window=2 and step=2)

[1]
[3, 4]
[5, 6]
[7, 8]
[9, 10]
[11, 12]

(window=5 and step=2)

[1, 3, 4, 5]
[3, 4, 5, 6, 7]
[5, 6, 7, 8, 9]
[7, 8, 9, 10, 11]
[9, 10, 11, 12]

Again, this code is not very elegant I think, but it does the job so I'll mark this answer as accepted. However, I'm still open to any improvements/advises for this code.


问:
Non-greedy search for beginning of string
I have the following links to be extracted:

```<code>[{"file":"https:\/\/www.rapidvideo.com\/loadthumb.php?v=FFIMB47EWD","kind":"thumbnails"}],
    "sources": [
        {"file":"https:\/\/www588.playercdn.net\/85\/1\/e_q8OBtv52BRyClYa_w0kw\/1496784287\/170512\/359E33j28Jo0ovY.mp4",
         "label":"Standard (288p)","res":"288"},
        {"file":"https:\/\/www726.playercdn.net\/86\/1\/q64Rsb8lG_CnxQAX6EZ2Sw\/1496784287\/170512\/371lbWrqzST1OOf.mp4"
</code>```

I would like to extract the links ending in mp4

My regex is as follows:

```<code>"file":"(https\:.*?\.mp4)"
</code>```

However, I matches are wrong as the first link ending in a php is matched.
I am practising here Pythex.org. How do I avoid the first link?
The link to the html page I am trying to parse is https://www.rapidvideo.com/e/FFIMB47EWD

答:
Why even use regular expressions? This looks like a JSON object/Python dict, you could just iterate through it and use str.endswith.

```<code>>>> sources = {
...     "sources": [
...         {"file": "https:\/\/www588.playercdn.net\/85\/1\/e_q8OBtv52BRyClYa_w0kw\/1496784287\/170512\/359E33j28Jo0ovY.mp4",
...          "label": "Standard (288p)","res":"288"},
...         {"file": "https:\/\/www726.playercdn.net\/86\/1\/q64Rsb8lG_CnxQAX6EZ2Sw\/1496784287\/170512\/371lbWrqzST1OOf.mp4",
...          "label": "Standard (288p)","res":"288"}
...     ]
... }
>>> for item in sources['sources']:
...     if item['file'].endswith('.mp4'):
...         print(item['file'])
...
https:\/\/www588.playercdn.net\/85\/1\/e_q8OBtv52BRyClYa_w0kw\/1496784287\/170512\/359E33j28Jo0ovY.mp4
https:\/\/www726.playercdn.net\/86\/1\/q64Rsb8lG_CnxQAX6EZ2Sw\/1496784287\/170512\/371lbWrqzST1OOf.mp4
</code>```

EDIT:

It looks like that link is available in a video tag after the javascript has loaded. You could use a headless browser but I just used selenium to  fully load the page and then save the html.

After you have the full page html, you can parse it using BeautifulSoup instead of regular expressions.

Using regular expressions to parse HTML: why not?

```<code>from bs4 import BeautifulSoup
from selenium import webdriver

def extract_mp4_link(page_html):
    soup = BeautifulSoup(page_html, 'lxml')
    return soup.find('video')['src']

def get_page_html(url):
    driver = webdriver.Chrome()
    driver.get(url)
    page_source = driver.page_source
    driver.close()
    return page_source

if __name__ == '__main__':
    page_url = 'https://www.rapidvideo.com/e/FFIMB47EWD'
    page_html = get_page_html(page_url)
    print(extract_mp4_link(page_html))
</code>```

Body:
I have the following links to be extracted:

[{"file":"https:\/\/www.rapidvideo.com\/loadthumb.php?v=FFIMB47EWD","kind":"thumbnails"}],
    "sources": [
        {"file":"https:\/\/www588.playercdn.net\/85\/1\/e_q8OBtv52BRyClYa_w0kw\/1496784287\/170512\/359E33j28Jo0ovY.mp4",
         "label":"Standard (288p)","res":"288"},
        {"file":"https:\/\/www726.playercdn.net\/86\/1\/q64Rsb8lG_CnxQAX6EZ2Sw\/1496784287\/170512\/371lbWrqzST1OOf.mp4"

I would like to extract the links ending in mp4

My regex is as follows:

"file":"(https\:.*?\.mp4)"

However, I matches are wrong as the first link ending in a php is matched.
I am practising here <a href="http://pythex.org/?regex=%22file%22%3A%22(https%5C%3A.*%3F%5C.mp4)%22&test_string=%3Cdiv%20id%3D%22home_video%22%20style%3D%22width%3A%20100%25%3B%20height%3A%20270px%3B%22%3E%3C%2Fdiv%3E%0A%3Cscript%3Evar%20secs%20%3D%200%3B%20var%20lastp%20%3D%200%3B%20var%20runc%20%3D%200%3B%20jwplayer.key%20%3D%20%22O0rbeJxNgb0uLCCzJVb4yCHD46CBXw0uno5uUQ%3D%3D%22%3B%20var%20playerInstance%20%3D%20jwplayer(%22home_video%22).setup(%7B%22autostart%22%3A%20false%2C%22controls%22%3A%20true%2C%22flashplayer%22%3A%20%22%2Fjwplayer7%2Fjwplayer.flash.swf%22%2C%22image%22%3A%20%22https%3A%2F%2Fwww755.playercdn.net%2Fthumb%2F0%2F170512%2F361d69yIyOIFcjx.jpg%22%2C%20ga%3A%20%7B%7D%2C%20%22mute%22%3A%20false%2C%20%20%22ph%22%3A%201%2C%20%20%22preload%22%3A%20%22metadata%22%2C%20%20%22primary%22%3A%20%22html%22%2C%20%20%22repeat%22%3A%20false%2C%20%20%22skin%22%3A%20%7B%20%20%20%20%22name%22%3A%20%22tube%22%20%20%7D%2C%20%20%22stagevideo%22%3A%20true%2C%20%20%22stretching%22%3A%20%22uniform%22%2C%20%20%22visualplaylist%22%3A%20true%2C%20%20%22width%22%3A%20%22100%25%22%2C%20%20%22aspectratio%22%3A%20%2216%3A9%22%2C%20%20%22provider%22%3A%20%27http%27%2C%20%20%22startparam%22%3A%20%22start%22%2C%20tracks%3A%20%5B%7B%22file%22%3A%22https%3A%5C%2F%5C%2Fwww.rapidvideo.com%5C%2Floadthumb.php%3Fv%3DFFIMB47EWD%22%2C%22kind%22%3A%22thumbnails%22%7D%5D%2C%20%22sources%22%3A%20%5B%7B%22file%22%3A%22https%3A%5C%2F%5C%2Fwww588.playercdn.net%5C%2F85%5C%2F1%5C%2Fe_q8OBtv52BRyClYa_w0kw%5C%2F1496784287%5C%2F170512%5C%2F359E33j28Jo0ovY.mp4%22%2C%22label%22%3A%22Standard%20(288p)%22%2C%22res%22%3A%22288%22%7D%2C%7B%22file%22%3A%22https%3A%5C%2F%5C%2Fwww726.playercdn.net%5C%2F86%5C%2F1%5C%2Fq64Rsb8lG_CnxQAX6EZ2Sw%5C%2F1496784287%5C%2F170512%5C%2F371lbWrqzST1OOf.mp4%22%2C%22label%22%3A%22High%20(576p)%22%2C%22res%22%3A%22576%22%2C%22default%22%3A%22true%22%7D%5D%20%2C%22logo%22%3A%20%7B%20%20%20%20%22file%22%3A%20%22%22%2C%20%20%20%20%22logoBar%22%3A%20%22https%3A%2F%2Fwww.rapidvideo.com%2Fimages%2Frapidvideo_logo_player.png%22%2C%20%22target%22%3A%20%22blank%22%2C%20%22hide%22%3A%20true%2C%20%20%20%20%22link%22%3A%20%22https%3A%2F%2Fwww.rapidvideo.com%22%2C%20%20%20%20%22margin%22%3A%20%225%22%2C%20%20%20%20%22position%22%3A%20%22top-right%22%20%20%7D%2C%22displaydescription%22%3A%20false%2C%22displaytitle%22%3A%20false%20%2C%20%22abouttext%22%3A%20%22RapidVideo%20Player%22%2C%20%22aboutlink%22%3A%20%22https%3A%2F%2Fwww.rapidvideo.com%22%20%20%7D)%3B%20playerInstance.on(%27ready%27%2Cfunction()%20%7B%20%2F*%20jwLogoBar.addLogo(playerInstance)%3B%20*%2F%20%7D)%3B%20playerInstance.on(%27time%27%2C%20function(event)%20%7B%20if(runc%20%3D%3D%3D%200)%20%7B%20var%20time%3D%20Math.floor(event.position)%3B%20if(time%20%3E%20lastp%2B10)%20%7B%20if(lastp%20!%3D%20time)%20%7B%20lastp%20%3D%20time%3B%20%24.getJSON(%22%2F%3Fc%3Dl%26i%3DFFIMB47EWD%26o%3D9786ea7fcb8c58b434f79a88754c773c%26a%3D%22%2BcanRunAds%2C%20function(%20data%20)%20%7Bif(data.status%20%3D%3D%201)%20%7B%20runc%20%3D%201%3B%20%7D%20%7D)%3B%20%7D%7D%20%20%7D%20%7D)%3B%3C%2Fscript%3E%3Cscript%3Evar%20jt%20%3D%20setInterval(t%2C%20(5*1000))%3Bvar%20tp%20%3D%200%3Bvar%20ttt%20%3D%200%3Bvar%20tt%20%3D%20true%3Bfunction%20t()%7Bif(tt%20%3D%3D%20false)%20%20%20%20%20%7B%20clearInterval(jt)%3B%20return%20false%3B%20%7Dif(jwplayer(%22home_video%22).getState().toLowerCase()%20%3D%3D%20%27playing%27)%20%7B%20tp%20%3D%20tp%2B5%3B%20%7Dif(ttt%20%3D%3D%200)%20%7B%20ttt%20%3D%20jwplayer(%22home_video%22).getDuration()%3B%20%7D%20else%20%7Bp%20%3D%200%3B%20if(tp%20%3E%200)%7Bp%20%3D%20(parseInt(tp)%2FparseInt(ttt))*100%3B%20%20%20%20%20%20%20%20%7Dif(p%20%3E%200)%7Btt%20%3D%20false%3B%20%2F*%20%24.get(%22%2F%3Fc%3Dl%26i%3DFFIMB47EWD%26o%3D9786ea7fcb8c58b434f79a88754c773c%26a%3D%22)%3B%20*%2F%20%7D%7D%7D%3C%2Fscript%3E&ignorecase=0&multiline=0&dotall=0&verbose=0" rel="nofollow noreferrer">Pythex.org. How do I avoid the first link?
The link to the html page I am trying to parse is https://www.rapidvideo.com/e/FFIMB47EWD

Body:
Why even use regular expressions? This looks like a JSON object/Python dict, you could just iterate through it and use str.endswith.

>>> sources = {
...     "sources": [
...         {"file": "https:\/\/www588.playercdn.net\/85\/1\/e_q8OBtv52BRyClYa_w0kw\/1496784287\/170512\/359E33j28Jo0ovY.mp4",
...          "label": "Standard (288p)","res":"288"},
...         {"file": "https:\/\/www726.playercdn.net\/86\/1\/q64Rsb8lG_CnxQAX6EZ2Sw\/1496784287\/170512\/371lbWrqzST1OOf.mp4",
...          "label": "Standard (288p)","res":"288"}
...     ]
... }
>>> for item in sources['sources']:
...     if item['file'].endswith('.mp4'):
...         print(item['file'])
...
https:\/\/www588.playercdn.net\/85\/1\/e_q8OBtv52BRyClYa_w0kw\/1496784287\/170512\/359E33j28Jo0ovY.mp4
https:\/\/www726.playercdn.net\/86\/1\/q64Rsb8lG_CnxQAX6EZ2Sw\/1496784287\/170512\/371lbWrqzST1OOf.mp4

EDIT:

It looks like that link is available in a video tag after the javascript has loaded. You could use a headless browser but I just used selenium to  fully load the page and then save the html.

After you have the full page html, you can parse it using BeautifulSoup instead of regular expressions.

Using regular expressions to parse HTML: why not?

from bs4 import BeautifulSoup
from selenium import webdriver

def extract_mp4_link(page_html):
    soup = BeautifulSoup(page_html, 'lxml')
    return soup.find('video')['src']

def get_page_html(url):
    driver = webdriver.Chrome()
    driver.get(url)
    page_source = driver.page_source
    driver.close()
    return page_source

if __name__ == '__main__':
    page_url = 'https://www.rapidvideo.com/e/FFIMB47EWD'
    page_html = get_page_html(page_url)
    print(extract_mp4_link(page_html))


问:
Extending VC++ compiler for instrumentation
I am very new to the windows world and development. I want to extend the VC++ compiler so that I can add some instrumentation instructions in a "pass" before creating the final shared lib. I googled somewhat, read some docs, installed Visual Studio and the compiler to play around but haven't been able to find a straightforward solution.  Any pointers will be really helpful

Thanks

答:
It really depends on what kind of instrumentation you’re looking for, and why do you need that.

But you might take a look at /Gh and /GH compiler switches, and implement custom _penter and _pexit functions in your shared library. Unfortunately, if you target AMD64 you’ll have to code these hook functions in assembly.

Update: here's an open source visual studio plugin that does exactly that, implements performance instrumentation using that mechanism.


问:
Is invalid login a use case or system operation?
Login is use case, right? But I am confused about Invalid login credential: Is it a use case or a system operation?

答:
No, "login" is not a use case. Here is why: Is it necessary to include the login for every usecase?

Login is a common precondition to real use cases.

Second step: Think about the outcomes that bring a benefit.


问:
how to interpret coefficients in log-log market mix model
I am running a multivariate OLS regression as below using weekly sales and media data. I would like to understand how to calculate the sales contribution when doing log transforms like log-linear, linear-log and log-log.

For example:
Volume_Sales = b0 + b1.TV_GRP + b2.SocialMedia + b3.PaidSearch + e

In this case, the sales contributed by TV is b1 x TV_GRPs (coefficient multiplied by the TV GRP of that month)

Now, my question is: How do we calculate sales contribution for the below cases:

Log-Linear: ln(Volume_Sales) = b0 + b1.TV_GRP + b2.SocialMedia + b3.PaidSearch + e

Linear-Log: Volume_Sales = b0 + b1.TV_GRP) + b2. ln(SocialMedia) + b3. ln(PaidSearch) + e

Log-Log: *ln(Volume_Sales) = b0 + b1.TV_GRP) + b2. ln(SocialMedia) + b3. ln(PaidSearch) + e**

答:
In general terms, a log transformation takes something that acts on the multiplicative scale and re-represents it on the additive scale so certain mathematical assumptions hold: among them, linearity.  So to step beyond the "transform data we don't like" paradigm that many of us are guilty of, I like thinking in terms of "does it make most sense if an effect to this variable is additive (+3 units) or multiplicative (3 times as much, 20% reduction, etc)?"  That and your diagnostic plots (residual, q-q, etc.) will do a good job of telling you what's the most appropriate in your case.

As for interpreting coefficients, here are some ways I've seen it done.

Linear: y = b0 + b1x + e

Interpretation: there is an estimated b1-unit increase in the mean of y for every 1-unit increase in x.

Log-linear: ln(y) = b0 + b1x + e

Interpretation: there is an estimated change in the median of y by a factor of exp(b1) for every 1-unit increase in x.

Linear-log: y = b0 + b1ln(x) + e

Interpretation: there is an estimated b1*ln(2)-unit increase in the mean of y when x is doubled.

Log-log: ln(y) = b0 + b1ln(x) + e

Interpretation: there is an estimated change in the median of y by a factor of 2^b1 when x is doubled.

Note: these can be fairly readily derived by considering what happens to y if you replace x with (x+1) or with 2x.

These generic-form interpretations tend to make more sense with a bit of context, particularly once you know the sign of the coefficient.  Say you've got a log-linear model with an estimated b1 of -0.3.  Exponentiated, this is exp(-0.3)=0.74, meaning that there is an estimated change in the median of y by a factor of 0.74 for every 1-unit increase in x ... or better yet, a 26% decrease.


问:
NSArray can't shuffle
I am trying to use the new shuffle method to shuffle my array: https://developer.apple.com/documentation/foundation/nsarray/1640855-shuffledarray?language=objc. But I just get an error saying: No visible @interface for 'NSArray' declares the selector 'shuffledArray'.

This is my code:

```<code>NSArray *shuffledArray = [array shuffledArray];
</code>```

And my project is iOS 10.0+

答:
As you can see on the right column of the documentation, although this is a method on NSArray, it's located in the GameplayKit framework.

You need to import the framework :

```<code>#import <GameplayKit/GameplayKit.h>
</code>```

Title: NSArray can't shuffle

Body:
I am trying to use the new shuffle method to shuffle my array: https://developer.apple.com/documentation/foundation/nsarray/1640855-shuffledarray?language=objc. But I just get an error saying: No visible @interface for 'NSArray' declares the selector 'shuffledArray'.

This is my code:

NSArray *shuffledArray = [array shuffledArray];

And my project is iOS 10.0+

Body:
As you can see on the right column of the documentation, although this is a method on NSArray, it's located in the GameplayKit framework.

You need to import the framework :

#import <GameplayKit/GameplayKit.h>


问:
msysgit: option to not set hidden flag
I'm using msysgit and for files starting with a slash, e.g. .classpath it automatically sets the hidden flag which makes it impossible for IDEs to overwrite it. How to prevent setting this hidden flag?

答:
Add --global to make this the default behaviour for all new repos:</p>

```<code>git config --global core.hidedotfiles "false"
</code>```

Title: msysgit: option to not set hidden flag

Body:
Add --global to make this the default behaviour for all new repos:

git config --global core.hidedotfiles "false"


问:
get numbers from a link html parsing jsoup
I am working on a software and new on Jsoup. I need help. I am parsing a website. getting links like that :

```<code><a href="/?loc=shop_view_item&item=139218679" class="market-name market-link">XXX</a>
</code>```

How can I take numbers "139218679" with Jsoup or regex. Can you help me please?

答:
example to check from javascript:
`

```<code>var links = document.getElementsByClassName("market-name market-link");
for (var i=0; i<links.length; i++) {
console.log(links[i].href.match(/\d+$/)[0]);
}
</code>```

`

Body:
I am working on a software and new on Jsoup. I need help. I am parsing a website. getting links like that :

XXX

How can I take numbers "139218679" with Jsoup or regex. Can you help me please?

Body:
example to check from javascript:
`

var links = document.getElementsByClassName("market-name market-link");
for (var i=0; i<links.length; i++) {
console.log(links[i].href.match(/\d+$/)[0]);
}

`


问:
Why are these regular expressions not working?
I want a regex to match complex mathematical expressions.
However I will ask for an easier regex because it will be the simplest case.

Example input:
1+2+3+4

I want to separate each char:
[('1', '+', '2', '+', '3', '+', '4')]

With a restriction: there has to be at least one operation (i.e. 1+2).

My regex: ([0-9]+)([+])([0-9]+)(([+])([0-9]+))*
or (\d+)(\+)(\d+)((\+)(\d+))*

Output for re.findall('(\d+)(\+)(\d+)((\+)(\d+))*',"1+2+3+4")
:

[('1', '+', '2', '+4', '+', '4')]

Why is this not working? Is Python the problem?

答:
You need ([0-9]+)([+])([0-9]+)(?:([+])([0-9]+))*

you get the '+4' for the group is out the last two expressions (([+])([0-9]+)).

the ?: indicate to python dont get de string for this group in the output.


问:
Accessing members of items in a JSONArray with Java
I'm just getting started with using json with java.  I'm not sure how to access string values within a JSONArray. For instance, my json looks like this:

```<code>{
  "locations": {
    "record": [
      {
        "id": 8817,
        "loc": "NEW YORK CITY"
      },
      {
        "id": 2873,
        "loc": "UNITED STATES"
      },
      {
        "id": 1501
        "loc": "NEW YORK STATE"
      }
    ]
  }
}
</code>```

my code:

```<code>JSONObject req = new JSONObject(join(loadStrings(data.json),""));
JSONObject locs = req.getJSONObject("locations");
JSONArray recs = locs.getJSONArray("record");
</code>```

I have access to the "record" JSONArray at this point, but am unsure as to how I'd get the "id" and "loc" values within a for loop.  Sorry if this description isn't too clear, I'm a bit new to programming.

答:
Java 8 is in the market after almost 2 decades, following is the way to iterate org.json.JSONArray with java8 Stream API.

```<code>import org.json.JSONArray;
import org.json.JSONObject;

@Test
public void access_org_JsonArray() {
    //Given: array
    JSONArray jsonArray = new JSONArray(Arrays.asList(new JSONObject(
                    new HashMap() {{
                        put("a", 100);
                        put("b", 200);
                    }}
            ),
            new JSONObject(
                    new HashMap() {{
                        put("a", 300);
                        put("b", 400);
                    }}
            )));

    //Then: convert to List<JSONObject>
    List<JSONObject> jsonItems = IntStream.range(0, jsonArray.length())
            .mapToObj(index -> (JSONObject) jsonArray.get(index))
            .collect(Collectors.toList());

    // you can access the array elements now
    jsonItems.forEach(arrayElement -> System.out.println(arrayElement.get("a")));
    // prints 100, 300
}
</code>```

If the iteration is only one time, (no need to .collect)

```<code>    IntStream.range(0, jsonArray.length())
            .mapToObj(index -> (JSONObject) jsonArray.get(index))
            .forEach(item -> {
               System.out.println(item);
            });
</code>```

Body:
I'm just getting started with using json with java.  I'm not sure how to access string values within a JSONArray. For instance, my json looks like this:

{
  "locations": {
    "record": [
      {
        "id": 8817,
        "loc": "NEW YORK CITY"
      },
      {
        "id": 2873,
        "loc": "UNITED STATES"
      },
      {
        "id": 1501
        "loc": "NEW YORK STATE"
      }
    ]
  }
}

my code:

JSONObject req = new JSONObject(join(loadStrings(data.json),""));
JSONObject locs = req.getJSONObject("locations");
JSONArray recs = locs.getJSONArray("record");

I have access to the "record" JSONArray at this point, but am unsure as to how I'd get the "id" and "loc" values within a for loop.  Sorry if this description isn't too clear, I'm a bit new to programming.

Body:
Java 8 is in the market after almost 2 decades, following is the way to iterate org.json.JSONArray with java8 Stream API.

import org.json.JSONArray;
import org.json.JSONObject;

@Test
public void access_org_JsonArray() {
    //Given: array
    JSONArray jsonArray = new JSONArray(Arrays.asList(new JSONObject(
                    new HashMap() {{
                        put("a", 100);
                        put("b", 200);
                    }}
            ),
            new JSONObject(
                    new HashMap() {{
                        put("a", 300);
                        put("b", 400);
                    }}
            )));

    //Then: convert to List<JSONObject>
    List<JSONObject> jsonItems = IntStream.range(0, jsonArray.length())
            .mapToObj(index -> (JSONObject) jsonArray.get(index))
            .collect(Collectors.toList());

    // you can access the array elements now
    jsonItems.forEach(arrayElement -> System.out.println(arrayElement.get("a")));
    // prints 100, 300
}

If the iteration is only one time, (no need to .collect)

    IntStream.range(0, jsonArray.length())
            .mapToObj(index -> (JSONObject) jsonArray.get(index))
            .forEach(item -> {
               System.out.println(item);
            });


问:
document.getElementById(id).focus() is not working for firefox or chrome
When ever I do onchange event, its going inside that function its validating, But focus is not comming I am using document.getElementById('controlid').focus();

I am using Mozilla Firefox and Google Chrome, in both its not working. I don't want any IE. Can any one tell me what could me the reason.

Here's the code:

```<code>var mnumber = document.getElementById('mobileno').value;
if(mnumber.length >=10) {
    alert("Mobile Number Should be in 10 digits only");
    document.getElementById('mobileno').value = "";
    document.getElementById('mobileno').focus();
    return false;
}
</code>```

答:
Place this source above your modal :</p>

```<code><script>
$('body').on('shown.bs.modal', '#IdYourModal', function () {
    document.getElementById('mobileno').focus();
})
</script>
</code>```

Body:
When ever I do onchange event, its going inside that function its validating, But focus is not comming I am using document.getElementById('controlid').focus();

I am using Mozilla Firefox and Google Chrome, in both its not working. I don't want any IE. Can any one tell me what could me the reason.

Here's the code:

var mnumber = document.getElementById('mobileno').value;
if(mnumber.length >=10) {
    alert("Mobile Number Should be in 10 digits only");
    document.getElementById('mobileno').value = "";
    document.getElementById('mobileno').focus();
    return false;
}

Body:
Place this source above your modal :

<script>
$('body').on('shown.bs.modal', '#IdYourModal', function () {
    document.getElementById('mobileno').focus();
})
</script>


问:
Is there a way to handle error such that the original sequence does not terminate?
In the Error Handling section of the reference guide , I read and understood the following note that even if the errors are handled through the error-handling operators, the original sequence terminates. Is there a way to handle the error such the error in the stream is replaced by a value, and the original sequence continues?

"Before you learn about error-handling operators, you must keep in mind that any error in a reactive sequence is a terminal event. Even if an error-handling operator is used, it doesn’t allow the original sequence to continue, but rather converts the onError signal into the start of a new sequence (the fallback one). As such it replaces the terminated sequence upstream."

I can see situations (including my use case) where there are only some bad elements in a stream, and we do not want to terminate the entire stream because of that.

For example in the below code, assuming that n = 2 is a bad case, I just want gracefully handle it and not terminate the stream. May be I am missing something basic here.

```<code>Flux.interval(Duration.ofSeconds(2))
        .map(n -> {if (n ==2) throw new IllegalArgumentException(); else {return "Successful-n";}})
        .onErrorReturn("Errored")
        .doOnNext(n -> log("Processed " + n))
        .blockLast();
</code>```

答:
If you simply want to resubscribe to the observable, you can use the retry() operator. It will resubscribe to the observable when an error is detected. There are variations that take a retry count, or will provide different responses depending on the Throwable.

Edit: Observables are defined to terminate when an error occurs. So, in your example, you may have to wrap your error in a container such that you can carry on when the error is identified, rather than throwing an error at that point.

Body:
In the Error Handling section of the reference guide , I read and understood the following note that even if the errors are handled through the error-handling operators, the original sequence terminates. Is there a way to handle the error such the error in the stream is replaced by a value, and the original sequence continues?

"Before you learn about error-handling operators, you must keep in mind that any error in a reactive sequence is a terminal event. Even if an error-handling operator is used, it doesn’t allow the original sequence to continue, but rather converts the onError signal into the start of a new sequence (the fallback one). As such it replaces the terminated sequence upstream."

I can see situations (including my use case) where there are only some bad elements in a stream, and we do not want to terminate the entire stream because of that.

For example in the below code, assuming that n = 2 is a bad case, I just want gracefully handle it and not terminate the stream. May be I am missing something basic here.

Flux.interval(Duration.ofSeconds(2))
        .map(n -> {if (n ==2) throw new IllegalArgumentException(); else {return "Successful-n";}})
        .onErrorReturn("Errored")
        .doOnNext(n -> log("Processed " + n))
        .blockLast();


问:
How to make sure return false; is called after onclick event in javascript
I am working on Javascript.I have a situation where i am using an anchor tag like:

```<code><a href="#" onclick="myFucntion(); return false;">Submit</a>
</code>```

I have used developer tools to debug this issue and found that on-click of Submit , it goes to myFunction(); and executes as expected until end of the function. After that it just shows a blank page and i am not really sure what is happening here.

I can understand if there is any error in myFunction(); then return false will not be called. But i do not see any issues in myFunction();. Did anyone faced this kind of weird problem before? And what could be the possible solution to figure out whats exactly happening after myFunction is executed and to make sure return false; is called after myFunction();?

Note: No Errors are found in console.

Thanks in Advance.

答:
Simply pass event to the function and then in your function write

```<code>event.preventDefault()
</code>```

in the very beginning. this will prevent the default behavior of the anchor tag and do nothing after that your function code will be executed.

Body:
I am working on Javascript.I have a situation where i am using an anchor tag like:

Submit

I have used developer tools to debug this issue and found that on-click of Submit , it goes to myFunction(); and executes as expected until end of the function. After that it just shows a blank page and i am not really sure what is happening here.

I can understand if there is any error in myFunction(); then return false will not be called. But i do not see any issues in myFunction();. Did anyone faced this kind of weird problem before? And what could be the possible solution to figure out whats exactly happening after myFunction is executed and to make sure return false; is called after myFunction();?

Note: No Errors are found in console.

Thanks in Advance.

Body:
Simply pass event to the function and then in your function write

event.preventDefault()

in the very beginning. this will prevent the default behavior of the anchor tag and do nothing after that your function code will be executed.


问:
Why exactly is this syntax error happening in C++ for me..?
why exactly is this happening?

```<code>cout << "Your choice of numbers is...?" << endl;
</code>```

error C2143: syntax error : missing
  ';' before '<<'

答:
Missing namespace?

Try use namespace std; at the beginning of your code!

Body:
why exactly is this happening?

cout << "Your choice of numbers is...?" << endl;

error C2143: syntax error : missing
  ';' before '<<'


问:
Replacing a string in Rubymine with a string with newlines
I want to use the Search and Replace dialogue in Rubymine, or something similar to replace something like "Scenario:" with "@Desktop\nScenario"

I'm trying to replace every instance of Scenario: in a large Cucumber test suite with

```<code>@desktop
Scenario:
</code>```

Any best ways to do this?

答:
Here's a cheap and sleazy alternative:

Copy a newline character from between two empty lines in the file being edited.  Temporarily add two empty lines if you don't have any.

Set up search/replace and enter the string you want to replace into the search text input box.

Paste the newline you just copied into the replacement text box plus whatever other text you want.  You will be able to see the height of the replacement text input box grow vertically by one line due to the newline.

Perform the search/replace.

For this, the use of the Rubymine regex is optional.

Body:
I want to use the Search and Replace dialogue in Rubymine, or something similar to replace something like "Scenario:" with "@Desktop\nScenario"

I'm trying to replace every instance of Scenario: in a large Cucumber test suite with

@desktop
Scenario:

Any best ways to do this?