问:
Socket-CAN does not work when using linux socket-communication(via wifi)
this is Server-side code (raspberry pi)

```<code>#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>

#include <unistd.h>
#include <wiringPi.h>
#include <softPwm.h>
#include <pthread.h>

void error( char *msg ) {
  perror(  msg );
  exit(1);
}

int func( int a ) {
   return 2 * a;
}

void sendData( int sockfd, int x ) {
  int n;

  char buffer[32];
  sprintf( buffer, "%dn", x );
  if ( (n = write( sockfd, buffer, strlen(buffer) ) ) < 0 )
    error( const_cast<char *>( "ERROR writing to socket") );
  buffer[n] = '';
}

int getData( int sockfd ) {
  char buffer[32];
  int n;

  if ( (n = read(sockfd,buffer,31) ) < 0 )
    error( const_cast<char *>( "ERROR reading from socket") );
  buffer[n] = '';

  printf("buffer: %s n",buffer);

  return atoi( buffer );
}

int main(int argc, char *argv[]) {

    char buf[30];
     int sockfd, newsockfd, portno = 1219, clilen;
     char buffer[256];
     struct sockaddr_in serv_addr, cli_addr;
     int n;
     int data;

     printf( "using port #%dn", portno );

     sockfd = socket(AF_INET, SOCK_STREAM, 0);
     if (sockfd < 0)
         error( const_cast<char *>("ERROR opening socket") );
     bzero((char *) &serv_addr, sizeof(serv_addr));

     serv_addr.sin_family = AF_INET;
     serv_addr.sin_addr.s_addr = INADDR_ANY;
     serv_addr.sin_port = htons( portno );
     if (bind(sockfd, (struct sockaddr *) &serv_addr,
              sizeof(serv_addr)) < 0)
       error( const_cast<char *>( "ERROR on binding" ) );
     listen(sockfd,5);
     clilen = sizeof(cli_addr);

     //--- infinite wait on a connection ---
     while ( 1 ) {
        printf( "waiting for new client.....n" );

        if ( ( newsockfd = accept( sockfd, (struct sockaddr *) &cli_addr, (socklen_t*) &clilen) ) < 0 )
            error( const_cast<char *>("ERROR on accept") );

        recv(newsockfd,buf,31,0);
        printf( "opened new communication with clientn" );
        printf( "sockfd: %dn",sockfd );
        printf( "newsockfd: %d n ",newsockfd );

        int res = strcmp(buf,"go");
        printf("res: %dn",res);
        write(newsockfd,"message received! [ from raspi server ! ]",50);

        while ( 1 ) {

             //---- wait for a number from client ---
            data = getData( newsockfd );
            //recv(newsockfd,buf,31,0);
            // printf("%s n",buf);

             printf( "got %dn", data );
             if ( data < 0 )
                break;

             data = func( data );

             //--- send new data back ---
             printf( "sending back %dn", data );
             sendData( newsockfd, data );

        }

        close( newsockfd );

        //--- if -2 sent by client, we can quit ---
        if ( data == -2 )
          break;
     }

     return 0;
}
</code>```

As soon as start using this linux socket communication program(when mylaptop, which is the client, gets connected to linux machine ), socket-CAN based program(CAN communication open source library based mcp 2515..) does not work saying that
"write : no buffer space available" when i tried to do candump
check below picture

Image

I guess it has something to do with the linux socket program i used above code for socket communication between linux machine(raspberry, linux) and my laptop(window). but i don't know how to avoid problem related 'buffer space' and what caused it. Maybe I should flush buffer every time i get socket frame?
anyone have some idea what i should do for getting both Socket-CAN and linux socket communication work at the same time?

答:
Try initializing your clilen in your first while loop where the accept() and write() functions are called. </p>

```<code>while ( 1 ) {
    printf( "waiting for new client.....n" );

    clilen = sizeof(struct sockaddr_in);
    if ( ( newsockfd = accept( sockfd, (struct sockaddr *) &cli_addr, &clilen) ) < 0 )
        error( const_cast<char *>("ERROR on accept") );
</code>```

Body:
this is Server-side code (raspberry pi)

#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>

#include <unistd.h>
#include <wiringPi.h>
#include <softPwm.h>
#include <pthread.h>

void error( char *msg ) {
  perror(  msg );
  exit(1);
}

int func( int a ) {
   return 2 * a;
}

void sendData( int sockfd, int x ) {
  int n;

  char buffer[32];
  sprintf( buffer, "%dn", x );
  if ( (n = write( sockfd, buffer, strlen(buffer) ) ) < 0 )
    error( const_cast<char *>( "ERROR writing to socket") );
  buffer[n] = '';
}

int getData( int sockfd ) {
  char buffer[32];
  int n;

  if ( (n = read(sockfd,buffer,31) ) < 0 )
    error( const_cast<char *>( "ERROR reading from socket") );
  buffer[n] = '';

  printf("buffer: %s n",buffer);

  return atoi( buffer );
}

int main(int argc, char *argv[]) {

    char buf[30];
     int sockfd, newsockfd, portno = 1219, clilen;
     char buffer[256];
     struct sockaddr_in serv_addr, cli_addr;
     int n;
     int data;

     printf( "using port #%dn", portno );

     sockfd = socket(AF_INET, SOCK_STREAM, 0);
     if (sockfd < 0)
         error( const_cast<char *>("ERROR opening socket") );
     bzero((char *) &serv_addr, sizeof(serv_addr));

     serv_addr.sin_family = AF_INET;
     serv_addr.sin_addr.s_addr = INADDR_ANY;
     serv_addr.sin_port = htons( portno );
     if (bind(sockfd, (struct sockaddr *) &serv_addr,
              sizeof(serv_addr)) < 0)
       error( const_cast<char *>( "ERROR on binding" ) );
     listen(sockfd,5);
     clilen = sizeof(cli_addr);

     //--- infinite wait on a connection ---
     while ( 1 ) {
        printf( "waiting for new client.....n" );

        if ( ( newsockfd = accept( sockfd, (struct sockaddr *) &cli_addr, (socklen_t*) &clilen) ) < 0 )
            error( const_cast<char *>("ERROR on accept") );

        recv(newsockfd,buf,31,0);
        printf( "opened new communication with clientn" );
        printf( "sockfd: %dn",sockfd );
        printf( "newsockfd: %d n ",newsockfd );

        int res = strcmp(buf,"go");
        printf("res: %dn",res);
        write(newsockfd,"message received! [ from raspi server ! ]",50);

        while ( 1 ) {

             //---- wait for a number from client ---
            data = getData( newsockfd );
            //recv(newsockfd,buf,31,0);
            // printf("%s n",buf);

             printf( "got %dn", data );
             if ( data < 0 )
                break;

             data = func( data );

             //--- send new data back ---
             printf( "sending back %dn", data );
             sendData( newsockfd, data );

        }

        close( newsockfd );

        //--- if -2 sent by client, we can quit ---
        if ( data == -2 )
          break;
     }

     return 0;
}

As soon as start using this linux socket communication program(when mylaptop, which is the client, gets connected to linux machine ), socket-CAN based program(CAN communication open source library based mcp 2515..) does not work saying that
"write : no buffer space available" when i tried to do candump
check below picture

Image

I guess it has something to do with the linux socket program i used above code for socket communication between linux machine(raspberry, linux) and my laptop(window). but i don't know how to avoid problem related 'buffer space' and what caused it. Maybe I should flush buffer every time i get socket frame?
anyone have some idea what i should do for getting both Socket-CAN and linux socket communication work at the same time?

Body:
Try initializing your clilen in your first while loop where the accept() and write() functions are called.

while ( 1 ) {
    printf( "waiting for new client.....n" );

    clilen = sizeof(struct sockaddr_in);
    if ( ( newsockfd = accept( sockfd, (struct sockaddr *) &cli_addr, &clilen) ) < 0 )
        error( const_cast<char *>("ERROR on accept") );


来源: stackexchange

问:
Rails gem/plugin that gives suggestions how to optimize your DB queries
Some time ago I saw in a screencast showing a gem or plugin, which was able to suggest how to optimize your Rails DB queries, like where to use include or add an index and so on... Now I can't remember which screencast that was, but maybe somebody knows what I am talking about, I mean that gem/plugin.

答: Actually I have found it was on this screencast, and it is called bullet</p>

ContentLicense: CC BY-SA 2.5


问:
Tell whether video is loaded or not in Javascript
So, I've been using a listener on

```<code>document.getElementById("video").buffered.length
</code>```

to see if it's greater than 0 for when a video's loaded or not. This works for a very small video, and only in Google Chrome. It doesn't work in Firefox at all. Any ideas for how to get this to work?

I essentially want to wait till 3 seperate videos are loaded to take a specific action, how do I go about this?

答:
To make this into a listener, under normal circumstances, you'll want to listen to the suspend event. It's triggered when download is paused or stopped for any reason, including it's finished.

You'll also want to listen to playing for the cases when the content is already loaded (like, from cache)

```<code>video.addEventListener("playing", function() {
    console.log("[Playing] loading of video");
    if ( video.readyState == 4 ) {
        console.log("[Finished] loading of video");
    }
});
video.addEventListener("suspend", function(e) {
    console.log("[Suspended] loading of video");
    if ( video.readyState == 4 ) {
        console.log("[Finished] loading of video");
    }
});
</code>```

Source: https://developer.mozilla.org/en/docs/Web/Guide/Events/Media_events

ContentLicense: CC BY-SA 3.0

Body:
So, I've been using a listener on

document.getElementById("video").buffered.length

to see if it's greater than 0 for when a video's loaded or not. This works for a very small video, and only in Google Chrome. It doesn't work in Firefox at all. Any ideas for how to get this to work?

I essentially want to wait till 3 seperate videos are loaded to take a specific action, how do I go about this?

Body:
To make this into a listener, under normal circumstances, you'll want to listen to the suspend event. It's triggered when download is paused or stopped for any reason, including it's finished.

You'll also want to listen to playing for the cases when the content is already loaded (like, from cache)

video.addEventListener("playing", function() {
    console.log("[Playing] loading of video");
    if ( video.readyState == 4 ) {
        console.log("[Finished] loading of video");
    }
});
video.addEventListener("suspend", function(e) {
    console.log("[Suspended] loading of video");
    if ( video.readyState == 4 ) {
        console.log("[Finished] loading of video");
    }
});

Source: https://developer.mozilla.org/en/docs/Web/Guide/Events/Media_events


问:
Slower while generating the XML from the bunch of model object
```<code>class GenericFormatter < Formatter
 attr_accessor :tag_name,:objects

 def generate_xml
   builder = Nokogiri::XML::Builder.new do |xml|
   xml.send(tag_name.pluralize) {
   objects.each do |obj|
        xml.send(tag_name.singularize){

            self.generate_obj_row obj,xml
        }
    end
    }
   end
   builder.to_xml
 end

def initialize tag_name,objects
  self.tag_name = tag_name
  self.objects = objects
end

def generate_obj_row obj,xml
   obj.attributes.except("updated_at").map do |key,value|
     xml.send(key, value)
   end
   xml.updated_at obj.updated_at.try(:strftime,"%m/%d/%Y %H:%M:%S") if obj.attributes.key?('updated_at')
end
 end
</code>```

In the above code, I have implemented the formatter where I have used the nokogiri XML Builder to generate the XML by manipulating the objects passing out inside the code.It's generated the faster XML when the data is not too large if data is larger like more than 10,000 records then It's slow down the XML to generate and takes at least 50-60 seconds.

Problem: Is there any way to generate the XML faster, I have tried XML Builders on view as well but did n't work.How can I generate the XML Faster? Should the solution be an application on rails 3 and suggestions to optimized above code?

答:
Your main problem is processing everything in one go instead of splitting your data into batches. It all requires a lot of memory, first to build all those ActiveRecord models and then to build memory representation of the whole xml document. Meta-programming is also quite expensive (I mean those send methods).

Take a look at this code:

```<code>class XmlGenerator
  attr_accessor :tag_name, :ar_relation

  def initialize(tag_name, ar_relation)
    @ar_relation = ar_relation
    @tag_name = tag_name
  end

  def generate_xml
    singular_tag_name = tag_name.singularize
    plural_tag_name = tag_name.pluralize

    xml = ""
    xml << "<#{plural_tag_name}>"

    ar_relation.find_in_batches(batch_size: 1000) do |batch|
      batch.each do |obj|
        xml << "<#{singular_tag_name}>"

        obj.attributes.except("updated_at").each do |key, value|
          xml << "<#{key}>#{value}</#{key}>"
        end

        if obj.attributes.key?("updated_at")
          xml << "<updated_at>#{obj.updated_at.strftime('%m/%d/%Y %H:%M:%S')}</updated_at>"
        end

        xml << "</#{singular_tag_name}>"
      end
    end

    xml << "</#{tag_name.pluralize}>"
    xml
  end
end

# example usage
XmlGenerator.new("user", User.where("age < 21")).generate_xml
</code>```

Major improvements are:

fetching data from database in batches, you need to pass ActiveRecord collection instead of array of ActiveRecord models

generating xml by constructing strings, this has a risk of producing invalid xml, but it is much faster than using builder

I tested it on over 60k records. It took around 40 seconds to generate such xml document.

There is much more that can be done to improve this even further, but it all depends on your application.

Here are some ideas:

do not use ActiveRecord to fetch data, instead use lighter library or plain database driver

fetch only data that you need

tweak batch size

write generated xml directly to a file (if that is your use case) to save memory

Body:
class GenericFormatter < Formatter
 attr_accessor :tag_name,:objects

 def generate_xml
   builder = Nokogiri::XML::Builder.new do |xml|
   xml.send(tag_name.pluralize) {
   objects.each do |obj|
        xml.send(tag_name.singularize){

            self.generate_obj_row obj,xml
        }
    end
    }
   end
   builder.to_xml
 end

def initialize tag_name,objects
  self.tag_name = tag_name
  self.objects = objects
end

def generate_obj_row obj,xml
   obj.attributes.except("updated_at").map do |key,value|
     xml.send(key, value)
   end
   xml.updated_at obj.updated_at.try(:strftime,"%m/%d/%Y %H:%M:%S") if obj.attributes.key?('updated_at')
end
 end

In the above code, I have implemented the formatter where I have used the nokogiri XML Builder to generate the XML by manipulating the objects passing out inside the code.It's generated the faster XML when the data is not too large if data is larger like more than 10,000 records then It's slow down the XML to generate and takes at least 50-60 seconds.

Problem: Is there any way to generate the XML faster, I have tried XML Builders on view as well but did n't work.How can I generate the XML Faster? Should the solution be an application on rails 3 and suggestions to optimized above code?

Body:
Your main problem is processing everything in one go instead of splitting your data into batches. It all requires a lot of memory, first to build all those ActiveRecord models and then to build memory representation of the whole xml document. Meta-programming is also quite expensive (I mean those send methods).

Take a look at this code:

class XmlGenerator
  attr_accessor :tag_name, :ar_relation

  def initialize(tag_name, ar_relation)
    @ar_relation = ar_relation
    @tag_name = tag_name
  end

  def generate_xml
    singular_tag_name = tag_name.singularize
    plural_tag_name = tag_name.pluralize

    xml = ""
    xml << "<#{plural_tag_name}>"

    ar_relation.find_in_batches(batch_size: 1000) do |batch|
      batch.each do |obj|
        xml << "<#{singular_tag_name}>"

        obj.attributes.except("updated_at").each do |key, value|
          xml << "<#{key}>#{value}</#{key}>"
        end

        if obj.attributes.key?("updated_at")
          xml << "<updated_at>#{obj.updated_at.strftime('%m/%d/%Y %H:%M:%S')}</updated_at>"
        end

        xml << "</#{singular_tag_name}>"
      end
    end

    xml << "</#{tag_name.pluralize}>"
    xml
  end
end

# example usage
XmlGenerator.new("user", User.where("age < 21")).generate_xml

Major improvements are:

fetching data from database in batches, you need to pass ActiveRecord collection instead of array of ActiveRecord models

generating xml by constructing strings, this has a risk of producing invalid xml, but it is much faster than using builder

I tested it on over 60k records. It took around 40 seconds to generate such xml document.

There is much more that can be done to improve this even further, but it all depends on your application.

Here are some ideas:

do not use ActiveRecord to fetch data, instead use lighter library or plain database driver

fetch only data that you need

tweak batch size

write generated xml directly to a file (if that is your use case) to save memory


问:
Calling a function inside a class to set the element of list
I'm trying to implement my first class, partly as a way to break up the modeling and solving of a math problem I'm having trouble with. I don't think my problem relates to the class, but...?

The error keeps telling me that: "NameError: global name 'corner2' is not defined"

I tried moving the function call, but it still doesn't recognize it, so I put it back into the list declaration in my init function.

Here is my code:

```<code>class RotatedRectangle(object):

def corner1(a,b):
    a/=2
    b/=2
    x=(a-b)*math.sin(math.pi/4)
    y=(a+b)*math.sin(math.pi/4)
    return (x,y)

def corner2(a,b):
    a/=-2
    b/=2
    x=(a-b)*math.sin(math.pi/4)
    y=(a+b)*math.sin(math.pi/4)
    return (x,y)

def corner3(a,b):
    a/=-2
    b/=-2
    x=(a-b)*math.sin(math.pi/4)
    y=(a+b)*math.sin(math.pi/4)
    return (x,y)

def corner4(a,b):
    a/=2
    b/=2
    x=(a-b)*math.sin(math.pi/4)
    y=(a+b)*math.sin(math.pi/4)
    return (x,y)

def __init__(self, a, b,):
        """Return a Rotated rectangle object whose name is a function of a and b."""
        self.name = str(a) + "," + str(b) + "-rectangle"
        self.corners = [corner1(a,b), corner2(a,b), corner3(a,b), corner4(a,b)]

"""A rectangle with sides equal to even integers a and b is drawn on the          Cartesian plane.Its center (the intersection point of its diagonals) coincides with the point (0, 0),but the sides of the rectangle are not parallel to the axes; instead, they are forming 45 degree angles with the axes.

How many points with integer coordinates are located inside the given   rectangle (including on its sides)? """
</code>```

答:
You have to use self as the first parameter of your class methods

When calling class methods inside your class you have to pass self as their first parameter(so that the class knows that you are talking about the current object)

You have to indent when defining a method inside your class

```<code>import math
class RotatedRectangle(object):
    def corner1(self,a,b):
        a/=2
        b/=2
        x=(a-b)*math.sin(math.pi/4)
        y=(a+b)*math.sin(math.pi/4)
        return (x,y)

    def corner2(self,a,b):
        a/=-2
        b/=2
        x=(a-b)*math.sin(math.pi/4)
        y=(a+b)*math.sin(math.pi/4)
        return (x,y)

    def corner3(self,a,b):
        a/=-2
        b/=-2
        x=(a-b)*math.sin(math.pi/4)
        y=(a+b)*math.sin(math.pi/4)
        return (x,y)

    def corner4(self,a,b):
        a/=2
        b/=2
        x=(a-b)*math.sin(math.pi/4)
        y=(a+b)*math.sin(math.pi/4)
        return (x,y)

    def __init__(self, a, b,):
        """Return a Rotated rectangle object whose name is a function of a and b."""
        self.name = str(a) + "," + str(b) + "-rectangle"
        self.corners = [self.corner1(a,b), self.corner2(a,b), self.corner3(a,b), self.corner4(a,b)]
</code>```

Body:
I'm trying to implement my first class, partly as a way to break up the modeling and solving of a math problem I'm having trouble with. I don't think my problem relates to the class, but...?

The error keeps telling me that: "NameError: global name 'corner2' is not defined"

I tried moving the function call, but it still doesn't recognize it, so I put it back into the list declaration in my init function.

Here is my code:

class RotatedRectangle(object):

def corner1(a,b):
    a/=2
    b/=2
    x=(a-b)*math.sin(math.pi/4)
    y=(a+b)*math.sin(math.pi/4)
    return (x,y)

def corner2(a,b):
    a/=-2
    b/=2
    x=(a-b)*math.sin(math.pi/4)
    y=(a+b)*math.sin(math.pi/4)
    return (x,y)

def corner3(a,b):
    a/=-2
    b/=-2
    x=(a-b)*math.sin(math.pi/4)
    y=(a+b)*math.sin(math.pi/4)
    return (x,y)

def corner4(a,b):
    a/=2
    b/=2
    x=(a-b)*math.sin(math.pi/4)
    y=(a+b)*math.sin(math.pi/4)
    return (x,y)

def __init__(self, a, b,):
        """Return a Rotated rectangle object whose name is a function of a and b."""
        self.name = str(a) + "," + str(b) + "-rectangle"
        self.corners = [corner1(a,b), corner2(a,b), corner3(a,b), corner4(a,b)]

"""A rectangle with sides equal to even integers a and b is drawn on the          Cartesian plane.Its center (the intersection point of its diagonals) coincides with the point (0, 0),but the sides of the rectangle are not parallel to the axes; instead, they are forming 45 degree angles with the axes.

How many points with integer coordinates are located inside the given   rectangle (including on its sides)? """

Body:
You have to use self as the first parameter of your class methods

When calling class methods inside your class you have to pass self as their first parameter(so that the class knows that you are talking about the current object)

You have to indent when defining a method inside your class

import math
class RotatedRectangle(object):
    def corner1(self,a,b):
        a/=2
        b/=2
        x=(a-b)*math.sin(math.pi/4)
        y=(a+b)*math.sin(math.pi/4)
        return (x,y)

    def corner2(self,a,b):
        a/=-2
        b/=2
        x=(a-b)*math.sin(math.pi/4)
        y=(a+b)*math.sin(math.pi/4)
        return (x,y)

    def corner3(self,a,b):
        a/=-2
        b/=-2
        x=(a-b)*math.sin(math.pi/4)
        y=(a+b)*math.sin(math.pi/4)
        return (x,y)

    def corner4(self,a,b):
        a/=2
        b/=2
        x=(a-b)*math.sin(math.pi/4)
        y=(a+b)*math.sin(math.pi/4)
        return (x,y)

    def __init__(self, a, b,):
        """Return a Rotated rectangle object whose name is a function of a and b."""
        self.name = str(a) + "," + str(b) + "-rectangle"
        self.corners = [self.corner1(a,b), self.corner2(a,b), self.corner3(a,b), self.corner4(a,b)]


问:
Is there an optimized method for finding the farthest corner of a cube in 3D
If a have a cube C with 8 corners ( not axis aligned ) and a random point P can I do better than just checking all the corners and picking the corner with the greatest distance from P or is it possible to reduce the number of checks by taking into account the symmetrical nature of the cube?

答:
The farthest corner satisfies that at least one "delta" of |xc-xp| or |yc-yp|or |zc-zp| is maximum.

Test each "delta", storing the "candidates". A corner is "candidate" if its delta is greater or equal to the same delta for another candidate.

If a previous candidate is defeated in its "maximum condition", delete it from the list of candidates. For example, if corner 4 became candidate because its delta-y was the maximum but now corner 6 has a greater delta-y (the other deltas were not reason for corner 4) then corner 4 can not longer be candidate.

The first tested corner has the three maximum, so it needs to be defeated three times (on x, y and z) to get out of the list of candidates.

Note that the test to become a candidate is d1>=d2 not just d1>d2

Now test distances (squared distances is enough) only for the candidates.

Note that all corners can be at the same distance from point if it lies in center of the cube. The solution can be not only one corner, but two, four or eight.


问:
Read sqoop compressed snappy datafile using pyspark sql into data frame
I am using Cloudera VM 5.8
getting an error while reading sqoop imported Avro file, compressed using snappy codec

```<code>conf = (SparkConf().setMaster("local").setAppName("anoterApp1").set("spark.executor.memory", "1g"))
sc=SparkContext(conf= conf)
sqlc = SQLContext(sc)
df = sqlc.read.format("com.databricks.spark.avro").load("/sqoopimported/avro/compressed/directorypath")
</code>```

getting following error:
      py4j.protocol.Py4JJavaError: An error occurred while calling o266.load.

the code works fine if I am not compressing the file using snappy codec

答:
try adding this configuration

```<code> spark.conf.set("spark.sql.avro.compression.codec", "snappy")
</code>```

Also this doc can be useful

https://docs.databricks.com/spark/latest/data-sources/read-avro.html

Body:
I am using Cloudera VM 5.8
getting an error while reading sqoop imported Avro file, compressed using snappy codec

conf = (SparkConf().setMaster("local").setAppName("anoterApp1").set("spark.executor.memory", "1g"))
sc=SparkContext(conf= conf)
sqlc = SQLContext(sc)
df = sqlc.read.format("com.databricks.spark.avro").load("/sqoopimported/avro/compressed/directorypath")

getting following error:
      py4j.protocol.Py4JJavaError: An error occurred while calling o266.load.

the code works fine if I am not compressing the file using snappy codec

Body:
try adding this configuration

 spark.conf.set("spark.sql.avro.compression.codec", "snappy")

Also this doc can be useful

https://docs.databricks.com/spark/latest/data-sources/read-avro.html


问:
Typescript: Check if object keys and values fits to current class properties
I need to check if object keys and values fits to current class properties.

I have class instance and the changes in separate object then I call Object.assign to modify properties. Is there any way how to check if the object key and values are valid for certain class?

```<code>class MyClass {
  icon = 'home'
  size = 12
  color = 'blue'
}

var instance = new MyClass()

var changeProperties: MyClass = { size: 10 }
// throws Property 'icon' is missing in type { size: number; }

Object.assign(instance, changeProperties)
</code>```

Now got errors for not defined properties (property icon is missing).

I have tried var changeProperties: { [string: keyof MyClass]: any } = { size: true } with no success.

Note: I can't change the class itself (eg. make class properties optional).

答:
I found the answer in lib.es6.d.ts

```<code>/**
 * Make all properties in T optional
 */
type Partial<T> = {
    [P in keyof T]?: T[P];
};
</code>```

So the answer is:

```<code>class MyClass {
  icon = 'home'
  size = 12
  color = 'blue'
}

var instance = new MyClass()

var changeProperties: Partial<MyClass> = { size: 10 }

Object.assign(instance, changeProperties)
</code>```

Body:
I need to check if object keys and values fits to current class properties.

I have class instance and the changes in separate object then I call Object.assign to modify properties. Is there any way how to check if the object key and values are valid for certain class?

class MyClass {
  icon = 'home'
  size = 12
  color = 'blue'
}

var instance = new MyClass()

var changeProperties: MyClass = { size: 10 }
// throws Property 'icon' is missing in type { size: number; }

Object.assign(instance, changeProperties)

Now got errors for not defined properties (property icon is missing).

I have tried var changeProperties: { [string: keyof MyClass]: any } = { size: true } with no success.

Note: I can't change the class itself (eg. make class properties optional).

Body:
I found the answer in lib.es6.d.ts

/**
 * Make all properties in T optional
 */
type Partial<T> = {
    [P in keyof T]?: T[P];
};

So the answer is:

class MyClass {
  icon = 'home'
  size = 12
  color = 'blue'
}

var instance = new MyClass()

var changeProperties: Partial<MyClass> = { size: 10 }

Object.assign(instance, changeProperties)


问:
Update ejs variable on server side using socket.io, node.js, and mongodb
I am using mongodb with mongoose to maintain a list of stocks across clients. I want to simultaneously update the list using socket.io when one user makes a change. I can connect to the socket and update client javascript but not make changes to variable on server side.

app.js - Server

```<code>// connect to socket.io
io.on('connection', function (socket) {
   console.log('Client Connected..');

    ///retrieve new stock from client
    socket.on('submitStock', function (data) {
       console.log(data);
       ///do mongodb stuff here

       ///send new stocks to all clients
       socket.emit('activeStocks', data);
     });
});
</code>```

script.js - client

```<code>var socket = io.connect();

///connect to socket
socket.on('connect', function (data) {
   socket.emit('join', 'Hello World from client');
});

///use submit button to send the new stock to server
$('#addStock').on('submit', function(e){
    //var stockList = $('#stockList');
    socket.emit('submitStock', 'here is the data');
});

//retrieve the new stock from the server and update list
socket.on('activeStocks', function(data) {
   //how to update activeStocks here??
   console.log(data);
});
</code>```

index.ejs

```<code><% if (message.length > 0) { %>
   <div class="alert alert-danger"><p><%= message %></p></div>
<% } %>

<div class="container">
  <form id="addStock" action="/add" method="post">
    <div class="form-inline">
      <input type="text" class="form-control" name="stockTicker" placeholder="Enter a stock ticker">
      <button type="submit" class="btn btn-primary"><span>Add Stock</span></button>
    </div>
  </form>
</div>

<% if (activeStocks) { %>
  <% for (var i=0; i< activeStocks.length; i++) { %>
    <div> <%- activeStocks[i] %></div>
  <% } %>
<% } %>
</code>```

答:
Since I was using mongoDB and the variable activeStocks in index.ejs I couldn't rewrite or append the html. I needed the mongo Id's for potential removal in the future. I went with a partial refresh of the div taken from this question: Refresh/reload the content in Div using jquery/ajax

index.js

```<code>var io = require('../server');

io.on('connection', function (socket) {
  console.log('Client Connected..');

  ///retrieve new stock from client
  socket.on('submitStockToServer', function (data) {
    ///send new stocks to all clients except socket that started it.
    socket.broadcast.emit('newStockToClient', data);
  });

  socket.on('updateMyStocks', function (data) {
    ///only send to each updated client
    socket.emit('updated', data);
  });
});
</code>```

script.js

```<code>var socket = io.connect();

//connect to socket
socket.on('connect', function () {
  console.log('connected');
});

//use submit button to send the new stock to server
$('#addStock').on('submit', function(e){
  //var stockList = $('#stockList');
  socket.emit('submitStockToServer');
  console.log('submitted');
});

//retrieve information on new stock and send back request to server
socket.on('newStockToClient', function() {
  socket.emit('updateMyStocks', 'Your stocks are now updated');
});

//check if its updated
socket.on('updated', function () {
  ///partially reload stock div
  $("#stockContainer").load(location.href+" #stockContainer>*","");
});
</code>```

index.ejs

```<code><div id="stockContainer">
  <% if (activeStocks) { %>
    <% for (var i=0; i< activeStocks.length; i++) { %>
      <div> <%- activeStocks[i] %></div>
    <% } %>
  <% } %>
</div>
</code>```

Body:
I am using mongodb with mongoose to maintain a list of stocks across clients. I want to simultaneously update the list using socket.io when one user makes a change. I can connect to the socket and update client javascript but not make changes to variable on server side.

app.js - Server

// connect to socket.io
io.on('connection', function (socket) {
   console.log('Client Connected..');

    ///retrieve new stock from client
    socket.on('submitStock', function (data) {
       console.log(data);
       ///do mongodb stuff here

       ///send new stocks to all clients
       socket.emit('activeStocks', data);
     });
});

script.js - client

var socket = io.connect();

///connect to socket
socket.on('connect', function (data) {
   socket.emit('join', 'Hello World from client');
});

///use submit button to send the new stock to server
$('#addStock').on('submit', function(e){
    //var stockList = $('#stockList');
    socket.emit('submitStock', 'here is the data');
});

//retrieve the new stock from the server and update list
socket.on('activeStocks', function(data) {
   //how to update activeStocks here??
   console.log(data);
});

index.ejs

<% if (message.length > 0) { %>

<%= message %>

<% } %>

  <form id="addStock" action="/add" method="post">

      <input type="text" class="form-control" name="stockTicker" placeholder="Enter a stock ticker">
      <button type="submit" class="btn btn-primary">Add Stock</button>

  </form>

<% if (activeStocks) { %>
  <% for (var i=0; i< activeStocks.length; i++) { %>

 <%- activeStocks[i] %>

  <% } %>
<% } %>

Body:
Since I was using mongoDB and the variable activeStocks in index.ejs I couldn't rewrite or append the html. I needed the mongo Id's for potential removal in the future. I went with a partial refresh of the div taken from this question: Refresh/reload the content in Div using jquery/ajax

index.js

var io = require('../server');

io.on('connection', function (socket) {
  console.log('Client Connected..');

  ///retrieve new stock from client
  socket.on('submitStockToServer', function (data) {
    ///send new stocks to all clients except socket that started it.
    socket.broadcast.emit('newStockToClient', data);
  });

  socket.on('updateMyStocks', function (data) {
    ///only send to each updated client
    socket.emit('updated', data);
  });
});

script.js

var socket = io.connect();

//connect to socket
socket.on('connect', function () {
  console.log('connected');
});

//use submit button to send the new stock to server
$('#addStock').on('submit', function(e){
  //var stockList = $('#stockList');
  socket.emit('submitStockToServer');
  console.log('submitted');
});

//retrieve information on new stock and send back request to server
socket.on('newStockToClient', function() {
  socket.emit('updateMyStocks', 'Your stocks are now updated');
});

//check if its updated
socket.on('updated', function () {
  ///partially reload stock div
  $("#stockContainer").load(location.href+" #stockContainer>*","");
});

index.ejs

<div id="stockContainer">
  <% if (activeStocks) { %>
    <% for (var i=0; i< activeStocks.length; i++) { %>
      <div> <%- activeStocks[i] %></div>
    <% } %>
  <% } %>
</div>


问:
Inserting into Access database
How do I resolve the error in inserting memo in Access from a Java program?

4159 the size of the string

the error

```<code>java.sql.SQLException: [Microsoft][ODBC Microsoft Access Driver]COUNT field incorrect
</code>```

The source code that executes the insert statement:

```<code>statement.executeUpdate("INSERT INTO webData VALUES ("+"'" + list.get(y)+"','"+data+ "')");
</code>```

4159 the size of data

my schma is :

table name webData with 2 coulmun the

first ID of type text

the second Field1 of type memo

i have update the statment but i have get the same error:

statement.executeUpdate("INSERT INTO webData (ID,Field1) VALUES ("+"'" + list.get(y)+"','"+data+ "')");

Thank you

答: Does the comma have to be in speech marks and inverted commas?  You can simplify this, just a tip :).  But yes, post your DB scheme.</p>

Title: Inserting into Access database

Body:
How do I resolve the error in inserting memo in Access from a Java program?

4159 the size of the string

the error

java.sql.SQLException: [Microsoft][ODBC Microsoft Access Driver]COUNT field incorrect

The source code that executes the insert statement:

statement.executeUpdate("INSERT INTO webData VALUES ("+"'" + list.get(y)+"','"+data+ "')");

4159 the size of data

my schma is :

table name webData with 2 coulmun the

first ID of type text

the second Field1 of type memo

i have update the statment but i have get the same error:

statement.executeUpdate("INSERT INTO webData (ID,Field1) VALUES ("+"'" + list.get(y)+"','"+data+ "')");

Thank you


问:
iOS Swift - CollectionView INSIDE UIView XIB INSIDE UIViewController
I can't seem to find any information on how to achieve this, and what I'm trying to achieve is kind of hard to explain, but here it is:

I have a UIViewController that loads a "stack" of reusable UIViews that I've created with a XIB. Within each reusable UIView is a CollectionView, that creates a custom CollectionViewCell for each string in an array.

I have no idea how to accomplish this. No clue whatsoever, and nothing online covers this exact situation. It seems to be one level deeper than any other explanation provides. Every time I try to create the cells for the CollectionView I get a "Must register a nib or a class for the identifier or connect a prototype cell in a storyboard" error.

答:
Figured it out. Yes, if you want to use a CollectionView inside a XIB, and you have a custom CollectionViewCell, you have to create a XIB for the CollectionViewCell. You cannot just have a CollectionViewCell without a XIB in this case. Then, in the ViewController that contains the XIB, you have to use:

```<code>xibView.collectionView.register(UINib(nibName: "CustomCollectionViewCell", bundle: nil), forCellWithReuseIdentifier: "CustomCollectionViewCell")
</code>```

Most tutorials say to do this in viewDidLoad, however I'm creating not just one XIB in the ViewController, but a bunch of them based on data pulled from a database. So I do this within the loop that builds each XIB. I was worried this wouldn't work, but it does.

The reason why you have to do this continues to elude me.

Body:
Figured it out. Yes, if you want to use a CollectionView inside a XIB, and you have a custom CollectionViewCell, you have to create a XIB for the CollectionViewCell. You cannot just have a CollectionViewCell without a XIB in this case. Then, in the ViewController that contains the XIB, you have to use:

xibView.collectionView.register(UINib(nibName: "CustomCollectionViewCell", bundle: nil), forCellWithReuseIdentifier: "CustomCollectionViewCell")

Most tutorials say to do this in viewDidLoad, however I'm creating not just one XIB in the ViewController, but a bunch of them based on data pulled from a database. So I do this within the loop that builds each XIB. I was worried this wouldn't work, but it does.

The reason why you have to do this continues to elude me.


问:
How can I make all of the buttons selected revert back to original when the other buttons are clicked?
When I designed my switch I made it so when the on button was clicked the off color changed back to the original color and when the off button is clicked the on button changed back to the original color.

However, when I use more than one switch in my div I want the on button of one switch to turn off any other on buttons that were clicked. I've tried to do this code my self using this:

$("#darkmodeon, #colorfulon").click(function() {
  $('#responsiveoff').css({
    "background-color": "#d8d8d8",
    "color": "#777777",
    "transition": "all 0.2s ease"
  });
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#dropdowns > div {
  display: block !important;
}

body {
  margin: 0 auto;
  width: 950px;
  /* border: solid;
     border-color: black; */
  background-color: #f2f2f2;
}

/*--------------Navigation Bar------------*/

#navbar {
  width: 100%;
  background-color: white;
  overflow: auto;
  position: fixed;
  left: 0px;
  top: 0px;
  border-bottom: solid;
  border-width: 1px;
  border-color: #d8d8d8;
  overflow: hidden;
  z-index: 10;
}

#nav-container {
  max-width: 950px;
  min-width: 875px;
  margin: 0 auto;
}

#nav-container h1 {
  float: left;
  margin: 0 auto;
  padding-top: 10px;
  font-family: "calibri light";
  font-size: 25px;
  letter-spacing: 0.3em;
  margin-left: 5px;
  transition: color 0.3s ease;
}

#nav-container a {
  float: right;
  display: block;
  padding: 15px 15px;
  text-decoration: none;
  color: black;
  font-family: "calibri light", sans-serif;
  font-size: 18px;
  transition: background-color 0.5s ease;
}

#nav-container a:hover {
  background-color: #f4f4f4;
  transition: background-color 0.5s ease;
}

#nav-container a:active {
  background-color: #bfbfbf;
}

#nav-container h1:hover {
  color: #aaaaaa;
  transition: color 0.3s ease;
}

#webdsn-drop {
  padding: 75px 0 0 0;
  background-color: rgba(252, 252, 252, 0.95);
  border-bottom: solid 1px #d8d8d8;
  height: 200px;
  position: fixed;
  width: 100%;
  left: 0px;
  top: 0px;
  box-shadow: 0 10px 10px -5px rgba(0, 0, 0, 0.3);
  z-index: 9;
  display: none;
}

#webdsn-content {
  width: 950px;
  margin: 0 auto;
}

#pfdsn-drop {
  padding: 75px 0 0 0;
  background-color: rgba(252, 252, 252, 0.95);
  border-bottom: solid 1px #d8d8d8;
  height: 200px;
  position: fixed;
  width: 100%;
  left: 0px;
  top: 0px;
  box-shadow: 0 10px 10px -5px rgba(0, 0, 0, 0.3);
  z-index: 9;
  display: none;
}

#pfdsn-content {
  width: 950px;
  margin: 0 auto;
}

#bc-drop {
  padding: 75px 0 0 0;
  background-color: rgba(252, 252, 252, 0.95);
  border-bottom: solid 1px #d8d8d8;
  height: 200px;
  position: fixed;
  width: 100%;
  left: 0px;
  top: 0px;
  box-shadow: 0 10px 10px -5px rgba(0, 0, 0, 0.3);
  z-index: 9;
  display: none;
}

#bcdsn-content {
  width: 950px;
  margin: 0 auto;
}

#ldsn-drop {
  padding: 75px 0 0 0;
  background-color: rgba(252, 252, 252, 0.95);
  border-bottom: solid 1px #d8d8d8;
  height: 200px;
  position: fixed;
  width: 100%;
  left: 0px;
  top: 0px;
  box-shadow: 0 10px 10px -5px rgba(0, 0, 0, 0.3);
  z-index: 9;
  display: none;
}

#ldsn-content {
  width: 950px;
  margin: 0 auto;
}

/*----------THEMES-DROPDOWN-AREA--------*/

#switches-container {
  display: flex;
  justify-content: space-between;
  padding: 15px;
}

#themes-drop {
  padding: 75px 0 0 0;
  background-color: rgba(252, 252, 252, 0.95);
  border-bottom: solid 1px #d8d8d8;
  position: fixed;
  width: 100%;
  left: 0px;
  top: 0px;
  box-shadow: 0 10px 10px -5px rgba(0, 0, 0, 0.3);
  z-index: 9;
  display: none;
}

#themes-content {
  width: 950px;
  margin: 0 auto;
}

/*--SWITCH--*/

.theme-switch {
  display: flex;
  justify-content: space-between;
  position: relative;
  width: 295px;
}

.themename {
  font-family: 'calibri light';
  font-weight: bold;
  font-size: 20.5px;
  color: #777777;
  position: relative;
  top: 15.5px;
  display: inline-block;
}

#darkmodebox {
  width: 240px;
}

.switchcontainer {
  background-color: white;
  display: flex;
  justify-content: space-between;
  border: solid 2px #d8d8d8;
  border-radius: 50px;
  width: 100px;
  padding: 5px;
  margin: 25px 10px;
}

button {
  width: 37px;
  height: 37px;
  border: none;
  border-radius: 50px;
  background-color: #d8d8d8;
  color: #777777;
  font-family: 'calibri light';
  font-size: 17px;
  font-weight: bold;
  cursor: pointer;
  outline: none;
}

/*--------------------------------------*/

.subname-container {
  display: block;
}

.subname {
  color: black;
  border: solid;
  border-width: 1px;
  border-radius: 7.5px;
  padding: 5px 15px;
  display: inline;
  font-family: 'calibri light';
  letter-spacing: 2.5px;
  transition: background-color, color, 0.5s ease;
}

.subname:hover {
  background-color: #353535;
  border-color: white;
  color: white;
  transition: background-color, color, 0.5s ease;
}</code>```

<!DOCTYPE HTML>

  <title>Home</title>
  <link id="defaultcss" rel="stylesheet" type="text/css" href="main.css">

PORTFOLIO

      Theme Settings
      Logo Design
      Business Cards
      Posters & Flyers
      Website Design

WEBSITE DESIGN

POSTERS & FLYERS

BUSINESS CARDS

LOGO DESIGN

THEME SETTINGS

DARK MODE

              <button id="darkmodeon">ON</button>
              <button id="darkmodeoff">OFF</button>

COLOURFUL MODE

              <button id="colorfulon">ON</button>
              <button id="colorfuloff">OFF</button>

RESPONSIVE MODE

              <button id="responsiveon">ON</button>
              <button id="responsiveoff">OFF</button>

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

<p>Entire JavaScript:</p>

<p><div class="snippet" data-lang="js" data-hide="true" data-console="true" data-babel="false">
<div class="snippet-code snippet-currently-hidden">
<pre class="snippet-code-js lang-js prettyprint-override"><code>$(document).ready(function(){

        $('#web').hover(function(){
            $('#webdsn-drop').slideDown(250);
        },
        function(){
          $('#webdsn-drop').hover(function(){}, function(){$(this).slideUp(250);});

     if($('#webdsn-drop').is(':visible'))
      $('#webdsn-drop').slideUp(250);

     });

     $('#webdsn-drop').mouseenter(function(){
            $(this).stop();
        });

     $('#pf').hover(function(){
            $('#pfdsn-drop').slideDown(250);
        },
        function(){
          $('#pfdsn-drop').hover(function(){}, function(){$(this).slideUp(250);});
     if($('#pfdsn-drop').is(':visible'))
      $('#pfdsn-drop').slideUp(250);
     });
     $('#pfdsn-drop').mouseenter(function(){
            $(this).stop();
        });

     $('#bc').hover(function(){
            $('#bc-drop').slideDown(250);
        },
        function(){
          $('#bc-drop').hover(function(){}, function(){$(this).slideUp(250);});
     if($('#bc-drop').is(':visible'))
      $('#bc-drop').slideUp(250);
     });
     $('#bc-drop').mouseenter(function(){
            $(this).stop();
        });

     $('#ld').hover(function(){
            $('#ldsn-drop').slideDown(250);
        },
        function(){
          $('#ldsn-drop').hover(function(){}, function(){$(this).slideUp(250);});
     if($('#ldsn-drop').is(':visible'))
      $('#ldsn-drop').slideUp(250);
     });
     $('#ldsn-drop').mouseenter(function(){
            $(this).stop();
        });

     $('#themes').hover(function(){
            $('#themes-drop').slideDown(250);
        },
        function(){
          $('#themes-drop').hover(function(){}, function(){$(this).slideUp(250);});
     if($('#themes-drop').is(':visible'))
      $('#themes-drop').slideUp(250);
     });
     $('#themes-drop').mouseenter(function(){
            $(this).stop();
        });

    //-----------DARK-MODE-SWITCH-----------

     var darkon = '#darkmodeon';
     var darkoff = '#darkmodeoff';

     $('#darkmodeoff')[0].style.backgroundColor = "#85c452";
      $('#darkmodeoff')[0].style.color = "white";

      $(darkon).click(function() {
        $(this).css({
          "background-color": "#85c452",
          "color": "white",
          "transition": "all 0.2s ease"
        });
        $('#darkmodeoff').css({
          "background-color": "#d8d8d8",
          "color": "#777777",
          "transition": "all 0.2s ease"
        });
      });

      $(darkoff).click(function() {
        $(this).css({
          "background-color": "#85c452",
          "color": "white",
          "transition": "all 0.2s ease"
        });
        $('#darkmodeon').css({
          "background-color": "#d8d8d8",
          "color": "#777777",
          "transition": "all 0.2s ease"
        });
      });

      var colorfulon = '#colorfulon';
     var colorfuloff = '#colorfuloff';

     $('#colorfuloff')[0].style.backgroundColor = "#85c452";
      $('#colorfuloff')[0].style.color = "white";

      $(colorfulon).click(function() {
        $(this).css({
          "background-color": "#85c452",
          "color": "white",
          "transition": "all 0.2s ease"
        });
        $('#colorfuloff').css({
          "background-color": "#d8d8d8",
          "color": "#777777",
          "transition": "all 0.2s ease"
        });
      });

      $(colorfuloff).click(function() {
        $(this).css({
          "background-color": "#85c452",
          "color": "white",
          "transition": "all 0.2s ease"
        });
        $('#colorfulon').css({
          "background-color": "#d8d8d8",
          "color": "#777777",
          "transition": "all 0.2s ease"
        });
      });

      var responson = '#responsiveon';
     var responsoff = '#responsiveoff';

     $('#responsiveoff')[0].style.backgroundColor = "#85c452";
      $('#responsiveoff')[0].style.color = "white";

      $(responson).click(function() {
        $(this).css({
          "background-color": "#85c452",
          "color": "white",
          "transition": "all 0.2s ease"
        });
        $('#responsiveoff').css({
          "background-color": "#d8d8d8",
          "color": "#777777",
          "transition": "all 0.2s ease"
        });
      });

      $(responsoff).click(function() {
        $(this).css({
          "background-color": "#85c452",
          "color": "white",
          "transition": "all 0.2s ease"
        });
        $('#responsiveon').css({
          "background-color": "#d8d8d8",
          "color": "#777777",
          "transition": "all 0.2s ease"
        });
      });

    //-------------CSS-STYLES-------------------

     $('#darkmodeon').click(function (){
        $('link[href="main.css"]').attr('href','dark-main.css');
     });
     $('#darkmodeoff').click(function (){
        $('link[href="dark-main.css"]').attr('href','main.css');
     });

     $('#colorfulon').click(function (){
        $('link[href="main.css"]').attr('href','colorful-main.css');
     });
     $('#colorfuloff').click(function (){
        $('link[href="colorful-main.css"]').attr('href','main.css');
     });

     $('#responsiveon').click(function (){
        $('link[href="main.css"]').attr('href','responsive-main.css');
     });
     $('#responsiveoff').click(function (){
        $('link[href="responsive-main.css"]').attr('href','main.css');
     });

    });

    //-----------------RESET-ALL-SWITCH----------------

    $("#darkmodeon, #colorfulon").click(function(){
       $('#responsiveoff').css({
          "background-color": "#d8d8d8",
          "color": "#777777",
          "transition": "all 0.2s ease"
        });
      });

    });</code>```

答:
I suggest you use a class oriented approach for buttons and a data attribute for each theme. Then you only need one event listener for all buttons

```<code><div class="switchcontainer" data-theme="colorful">
      <button class="on-btn">ON</button>
      <button class="off-btn">OFF</button>
</div>
</code>```

Then toggle an active class on the parent switchcontainer when a button is clicked...simultaneously removing the active class from others.

Simplified example:

$('.switchcontainer button').click(function(e) {
  var $btn = $(this),
    isOnBtn = $btn.hasClass('on-btn'),
    $cont = $btn.parent(),
    theme = $cont.data('theme');

  if (isOnBtn) {
    // remove active class from other button groups
    $('.switchcontainer.active').removeClass('active');
    //do something with new theme
    console.log('New theme:', theme)
  }
  // toggle active class on current container
  $cont.toggleClass('active', isOnBtn);
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.switchcontainer.active .on-btn {
  background: green;
  color:yellow;
}</code>```

COLOURFUL MODE

      <button class="on-btn">ON</button>
      <button class="off-btn">OFF</button>

RESPONSIVE MODE

      <button class="on-btn">ON</button>
      <button class="off-btn">OFF</button>

```

ContentLicense: CC BY-SA 4.0

Body:
When I designed my switch I made it so when the on button was clicked the off color changed back to the original color and when the off button is clicked the on button changed back to the original color.

However, when I use more than one switch in my div I want the on button of one switch to turn off any other on buttons that were clicked. I've tried to do this code my self using this:

$("#darkmodeon, #colorfulon").click(function() {
  $('#responsiveoff').css({
    "background-color": "#d8d8d8",
    "color": "#777777",
    "transition": "all 0.2s ease"
  });
});

#dropdowns > div {
  display: block !important;
}

body {
  margin: 0 auto;
  width: 950px;
  /* border: solid;
     border-color: black; */
  background-color: #f2f2f2;
}

/*--------------Navigation Bar------------*/

#navbar {
  width: 100%;
  background-color: white;
  overflow: auto;
  position: fixed;
  left: 0px;
  top: 0px;
  border-bottom: solid;
  border-width: 1px;
  border-color: #d8d8d8;
  overflow: hidden;
  z-index: 10;
}

#nav-container {
  max-width: 950px;
  min-width: 875px;
  margin: 0 auto;
}

#nav-container h1 {
  float: left;
  margin: 0 auto;
  padding-top: 10px;
  font-family: "calibri light";
  font-size: 25px;
  letter-spacing: 0.3em;
  margin-left: 5px;
  transition: color 0.3s ease;
}

#nav-container a {
  float: right;
  display: block;
  padding: 15px 15px;
  text-decoration: none;
  color: black;
  font-family: "calibri light", sans-serif;
  font-size: 18px;
  transition: background-color 0.5s ease;
}

#nav-container a:hover {
  background-color: #f4f4f4;
  transition: background-color 0.5s ease;
}

#nav-container a:active {
  background-color: #bfbfbf;
}

#nav-container h1:hover {
  color: #aaaaaa;
  transition: color 0.3s ease;
}

#webdsn-drop {
  padding: 75px 0 0 0;
  background-color: rgba(252, 252, 252, 0.95);
  border-bottom: solid 1px #d8d8d8;
  height: 200px;
  position: fixed;
  width: 100%;
  left: 0px;
  top: 0px;
  box-shadow: 0 10px 10px -5px rgba(0, 0, 0, 0.3);
  z-index: 9;
  display: none;
}

#webdsn-content {
  width: 950px;
  margin: 0 auto;
}

#pfdsn-drop {
  padding: 75px 0 0 0;
  background-color: rgba(252, 252, 252, 0.95);
  border-bottom: solid 1px #d8d8d8;
  height: 200px;
  position: fixed;
  width: 100%;
  left: 0px;
  top: 0px;
  box-shadow: 0 10px 10px -5px rgba(0, 0, 0, 0.3);
  z-index: 9;
  display: none;
}

#pfdsn-content {
  width: 950px;
  margin: 0 auto;
}

#bc-drop {
  padding: 75px 0 0 0;
  background-color: rgba(252, 252, 252, 0.95);
  border-bottom: solid 1px #d8d8d8;
  height: 200px;
  position: fixed;
  width: 100%;
  left: 0px;
  top: 0px;
  box-shadow: 0 10px 10px -5px rgba(0, 0, 0, 0.3);
  z-index: 9;
  display: none;
}

#bcdsn-content {
  width: 950px;
  margin: 0 auto;
}

#ldsn-drop {
  padding: 75px 0 0 0;
  background-color: rgba(252, 252, 252, 0.95);
  border-bottom: solid 1px #d8d8d8;
  height: 200px;
  position: fixed;
  width: 100%;
  left: 0px;
  top: 0px;
  box-shadow: 0 10px 10px -5px rgba(0, 0, 0, 0.3);
  z-index: 9;
  display: none;
}

#ldsn-content {
  width: 950px;
  margin: 0 auto;
}

/*----------THEMES-DROPDOWN-AREA--------*/

#switches-container {
  display: flex;
  justify-content: space-between;
  padding: 15px;
}

#themes-drop {
  padding: 75px 0 0 0;
  background-color: rgba(252, 252, 252, 0.95);
  border-bottom: solid 1px #d8d8d8;
  position: fixed;
  width: 100%;
  left: 0px;
  top: 0px;
  box-shadow: 0 10px 10px -5px rgba(0, 0, 0, 0.3);
  z-index: 9;
  display: none;
}

#themes-content {
  width: 950px;
  margin: 0 auto;
}

/*--SWITCH--*/

.theme-switch {
  display: flex;
  justify-content: space-between;
  position: relative;
  width: 295px;
}

.themename {
  font-family: 'calibri light';
  font-weight: bold;
  font-size: 20.5px;
  color: #777777;
  position: relative;
  top: 15.5px;
  display: inline-block;
}

#darkmodebox {
  width: 240px;
}

.switchcontainer {
  background-color: white;
  display: flex;
  justify-content: space-between;
  border: solid 2px #d8d8d8;
  border-radius: 50px;
  width: 100px;
  padding: 5px;
  margin: 25px 10px;
}

button {
  width: 37px;
  height: 37px;
  border: none;
  border-radius: 50px;
  background-color: #d8d8d8;
  color: #777777;
  font-family: 'calibri light';
  font-size: 17px;
  font-weight: bold;
  cursor: pointer;
  outline: none;
}

/*--------------------------------------*/

.subname-container {
  display: block;
}

.subname {
  color: black;
  border: solid;
  border-width: 1px;
  border-radius: 7.5px;
  padding: 5px 15px;
  display: inline;
  font-family: 'calibri light';
  letter-spacing: 2.5px;
  transition: background-color, color, 0.5s ease;
}

.subname:hover {
  background-color: #353535;
  border-color: white;
  color: white;
  transition: background-color, color, 0.5s ease;
}

<!DOCTYPE HTML>

  <title>Home</title>
  <link id="defaultcss" rel="stylesheet" type="text/css" href="main.css">

PORTFOLIO

      Theme Settings
      Logo Design
      Business Cards
      Posters & Flyers
      Website Design

WEBSITE DESIGN

POSTERS & FLYERS

BUSINESS CARDS

LOGO DESIGN

THEME SETTINGS

DARK MODE

              <button id="darkmodeon">ON</button>
              <button id="darkmodeoff">OFF</button>

COLOURFUL MODE

              <button id="colorfulon">ON</button>
              <button id="colorfuloff">OFF</button>

RESPONSIVE MODE

              <button id="responsiveon">ON</button>
              <button id="responsiveoff">OFF</button>

Entire JavaScript:

$(document).ready(function(){

        $('#web').hover(function(){
            $('#webdsn-drop').slideDown(250);
        },
        function(){
          $('#webdsn-drop').hover(function(){}, function(){$(this).slideUp(250);});

     if($('#webdsn-drop').is(':visible'))
      $('#webdsn-drop').slideUp(250);

     });

     $('#webdsn-drop').mouseenter(function(){
            $(this).stop();
        });

     $('#pf').hover(function(){
            $('#pfdsn-drop').slideDown(250);
        },
        function(){
          $('#pfdsn-drop').hover(function(){}, function(){$(this).slideUp(250);});
     if($('#pfdsn-drop').is(':visible'))
      $('#pfdsn-drop').slideUp(250);
     });
     $('#pfdsn-drop').mouseenter(function(){
            $(this).stop();
        });

     $('#bc').hover(function(){
            $('#bc-drop').slideDown(250);
        },
        function(){
          $('#bc-drop').hover(function(){}, function(){$(this).slideUp(250);});
     if($('#bc-drop').is(':visible'))
      $('#bc-drop').slideUp(250);
     });
     $('#bc-drop').mouseenter(function(){
            $(this).stop();
        });

     $('#ld').hover(function(){
            $('#ldsn-drop').slideDown(250);
        },
        function(){
          $('#ldsn-drop').hover(function(){}, function(){$(this).slideUp(250);});
     if($('#ldsn-drop').is(':visible'))
      $('#ldsn-drop').slideUp(250);
     });
     $('#ldsn-drop').mouseenter(function(){
            $(this).stop();
        });

     $('#themes').hover(function(){
            $('#themes-drop').slideDown(250);
        },
        function(){
          $('#themes-drop').hover(function(){}, function(){$(this).slideUp(250);});
     if($('#themes-drop').is(':visible'))
      $('#themes-drop').slideUp(250);
     });
     $('#themes-drop').mouseenter(function(){
            $(this).stop();
        });

    //-----------DARK-MODE-SWITCH-----------

     var darkon = '#darkmodeon';
     var darkoff = '#darkmodeoff';

     $('#darkmodeoff')[0].style.backgroundColor = "#85c452";
      $('#darkmodeoff')[0].style.color = "white";

      $(darkon).click(function() {
        $(this).css({
          "background-color": "#85c452",
          "color": "white",
          "transition": "all 0.2s ease"
        });
        $('#darkmodeoff').css({
          "background-color": "#d8d8d8",
          "color": "#777777",
          "transition": "all 0.2s ease"
        });
      });

      $(darkoff).click(function() {
        $(this).css({
          "background-color": "#85c452",
          "color": "white",
          "transition": "all 0.2s ease"
        });
        $('#darkmodeon').css({
          "background-color": "#d8d8d8",
          "color": "#777777",
          "transition": "all 0.2s ease"
        });
      });

      var colorfulon = '#colorfulon';
     var colorfuloff = '#colorfuloff';

     $('#colorfuloff')[0].style.backgroundColor = "#85c452";
      $('#colorfuloff')[0].style.color = "white";

      $(colorfulon).click(function() {
        $(this).css({
          "background-color": "#85c452",
          "color": "white",
          "transition": "all 0.2s ease"
        });
        $('#colorfuloff').css({
          "background-color": "#d8d8d8",
          "color": "#777777",
          "transition": "all 0.2s ease"
        });
      });

      $(colorfuloff).click(function() {
        $(this).css({
          "background-color": "#85c452",
          "color": "white",
          "transition": "all 0.2s ease"
        });
        $('#colorfulon').css({
          "background-color": "#d8d8d8",
          "color": "#777777",
          "transition": "all 0.2s ease"
        });
      });

      var responson = '#responsiveon';
     var responsoff = '#responsiveoff';

     $('#responsiveoff')[0].style.backgroundColor = "#85c452";
      $('#responsiveoff')[0].style.color = "white";

      $(responson).click(function() {
        $(this).css({
          "background-color": "#85c452",
          "color": "white",
          "transition": "all 0.2s ease"
        });
        $('#responsiveoff').css({
          "background-color": "#d8d8d8",
          "color": "#777777",
          "transition": "all 0.2s ease"
        });
      });

      $(responsoff).click(function() {
        $(this).css({
          "background-color": "#85c452",
          "color": "white",
          "transition": "all 0.2s ease"
        });
        $('#responsiveon').css({
          "background-color": "#d8d8d8",
          "color": "#777777",
          "transition": "all 0.2s ease"
        });
      });

    //-------------CSS-STYLES-------------------

     $('#darkmodeon').click(function (){
        $('link[href="main.css"]').attr('href','dark-main.css');
     });
     $('#darkmodeoff').click(function (){
        $('link[href="dark-main.css"]').attr('href','main.css');
     });

     $('#colorfulon').click(function (){
        $('link[href="main.css"]').attr('href','colorful-main.css');
     });
     $('#colorfuloff').click(function (){
        $('link[href="colorful-main.css"]').attr('href','main.css');
     });

     $('#responsiveon').click(function (){
        $('link[href="main.css"]').attr('href','responsive-main.css');
     });
     $('#responsiveoff').click(function (){
        $('link[href="responsive-main.css"]').attr('href','main.css');
     });

    });

    //-----------------RESET-ALL-SWITCH----------------

    $("#darkmodeon, #colorfulon").click(function(){
       $('#responsiveoff').css({
          "background-color": "#d8d8d8",
          "color": "#777777",
          "transition": "all 0.2s ease"
        });
      });

    });

Body:
I suggest you use a class oriented approach for buttons and a data attribute for each theme. Then you only need one event listener for all buttons

<div class="switchcontainer" data-theme="colorful">
      <button class="on-btn">ON</button>
      <button class="off-btn">OFF</button>
</div>

Then toggle an active class on the parent switchcontainer when a button is clicked...simultaneously removing the active class from others.

Simplified example:

$('.switchcontainer button').click(function(e) {
  var $btn = $(this),
    isOnBtn = $btn.hasClass('on-btn'),
    $cont = $btn.parent(),
    theme = $cont.data('theme');

  if (isOnBtn) {
    // remove active class from other button groups
    $('.switchcontainer.active').removeClass('active');
    //do something with new theme
    console.log('New theme:', theme)
  }
  // toggle active class on current container
  $cont.toggleClass('active', isOnBtn);
});

.switchcontainer.active .on-btn {
  background: green;
  color:yellow;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="switches-container">

  <div class="theme-switch">
    <p class="themename">COLOURFUL MODE</p>
    <div class="switchcontainer" data-theme="colorful">
      <button class="on-btn">ON</button>
      <button class="off-btn">OFF</button>
    </div>
  </div>

  <div class="theme-switch">
    <p class="themename">RESPONSIVE MODE</p>
    <div class="switchcontainer" data-theme="responsive">
      <button class="on-btn">ON</button>
      <button class="off-btn">OFF</button>
    </div>
  </div>

</div>


问:
Get the clicked element ID in javascript
I have a jQuery like :

```<code>jQuery("#id1,#id2").click(function(){
     //do stuff
});
</code>```

I am checking that either id1 or id2 is clicked then do something. But in the function I need to get which ID is clicked.
Can somebody help me in that?

答:
Try this...</p>

```<code>var idClicked = jQuery(this).attr('id');
</code>```

Body:
I have a jQuery like :

jQuery("#id1,#id2").click(function(){
     //do stuff
});

I am checking that either id1 or id2 is clicked then do something. But in the function I need to get which ID is clicked.
Can somebody help me in that?

Body:
Try this...

var idClicked = jQuery(this).attr('id');


问:
How can I access an object's property in Ruby
My user object has a boolean property that I want to check as a user logs in.

This is what I'm trying to do, but I am getting a 500 error:

```<code>user = User.find_by_email(params['email'])
if user.is_mentor
    #do something
end
</code>```

答:
you need to add a check to see if you found an user</p>

```<code>if user.is_a?(User) && user.is_mentor
</code>```

Body:
My user object has a boolean property that I want to check as a user logs in.

This is what I'm trying to do, but I am getting a 500 error:

user = User.find_by_email(params['email'])
if user.is_mentor
    #do something
end

Body:
you need to add a check to see if you found an user

if user.is_a?(User) && user.is_mentor


问:
c++ conversion operators no candidate is better
```<code>    #include <iostream>
#include <string>

using namespace std;

class test {
    private:
        std::string strValue;
        int value;

    public:
        test():value(0) { };
        test(int a):value(a) { };
        test(std::string a):strValue(a) { };
        ~test(){};

        operator int () { return value; }
        operator const char* () { return strValue.c_str(); }
};

int main() {
    test v1(100);
    cout << v1  << endl;
    return 0;
}
</code>```

When I run the above, with gcc I get an error saying no candidate is better for conversion.. Aren't they exclusive types?

答:
std::ostream has numerous operator<< overloads, including both of the following:

```<code>std::ostream& operator<<(std::ostream&, const char*);
std::ostream& operator<<(std::ostream&, int);
</code>```

Your test class is convertible to both const char* and to int.  The compiler can't select which conversion to use because both conversions would work equally well.  Thus, the conversion is ambiguous.

Body:
    #include <iostream>
#include <string>

using namespace std;

class test {
    private:
        std::string strValue;
        int value;

    public:
        test():value(0) { };
        test(int a):value(a) { };
        test(std::string a):strValue(a) { };
        ~test(){};

        operator int () { return value; }
        operator const char* () { return strValue.c_str(); }
};

int main() {
    test v1(100);
    cout << v1  << endl;
    return 0;
}

When I run the above, with gcc I get an error saying no candidate is better for conversion.. Aren't they exclusive types?

Body:
std::ostream has numerous operator<< overloads, including both of the following:

std::ostream& operator<<(std::ostream&, const char*);
std::ostream& operator<<(std::ostream&, int);

Your test class is convertible to both const char* and to int.  The compiler can't select which conversion to use because both conversions would work equally well.  Thus, the conversion is ambiguous.


问:
Array to String conversion
here's my code:

```<code>$menu .= $this->$item['type']($item);
</code>```

$item['type'] is a string - 'single' and it uses method single(). Yet the browser shows me this error:

```<code>Array to string conversion
</code>```

I have no idea why, since single returns a string, $item['type'] also is a string. I even tried checking this:

```<code>var_dump($this->$item['type']([]));
</code>```

and it still returns the same error. Do you know why?

答:
You need to wrap the string that was found in the array element in curly brackets before using it as a method name to your object:

```<code>$menu .= $this->{$item['type']}($item);
</code>```

See here: http://php.net/manual/en/language.types.object.php

Title: Array to String conversion

Body:
here's my code:

$menu .= $this->$item['type']($item);

$item['type'] is a string - 'single' and it uses method single(). Yet the browser shows me this error:

Array to string conversion

I have no idea why, since single returns a string, $item['type'] also is a string. I even tried checking this:

var_dump($this->$item['type']([]));

and it still returns the same error. Do you know why?

Body:
You need to wrap the string that was found in the array element in curly brackets before using it as a method name to your object:

$menu .= $this->{$item['type']}($item);

See here: http://php.net/manual/en/language.types.object.php


问:
How can I scroll down a webpage using Selenium with VBA
I've written a script using VBA in combination with selenium to get all the company links from a webpage which doesn't display all the links until scrolled downmost. However, when I run my script, I get only 20 links but there are 1000 links in total. I've heard that it is possible to accomplish this type of task executing javascript function between the code. At this point, I can't get any idea how can I place that within my script. Here is what I've tried so far:</p>

```<code>Sub Testing_scroll()

Dim driver As New WebDriver
Dim posts As Object, post As Object

driver.Start "chrome", "http://fortune.com/fortune500"
driver.get "/list/"

driver.execute_script ("window.scrollTo(0, document.body.scrollHeight);") --It doesn't support here

Set posts = driver.FindElementsByXPath("//li[contains(concat(' ', @class, ' '), ' small-12 ')]")

For Each post In posts
    i = i + 1
    Cells(i, 1) = post.FindElementByXPath(".//a").Attribute("href")
Next post

End Sub
</code>```

答:
According to the examples included with SeleniumBasic you should be using

```<code>driver.ExecuteScript("window.scrollTo(0, document.body.scrollHeight);")
</code>```

not "driver.execute_script", which is the python equivalent from the previous solution I gave you :) You are going to have to loop that in the same way until you've got all 1000 links on the page.

Body:
I've written a script using VBA in combination with selenium to get all the company links from a webpage which doesn't display all the links until scrolled downmost. However, when I run my script, I get only 20 links but there are 1000 links in total. I've heard that it is possible to accomplish this type of task executing javascript function between the code. At this point, I can't get any idea how can I place that within my script. Here is what I've tried so far:

Sub Testing_scroll()

Dim driver As New WebDriver
Dim posts As Object, post As Object

driver.Start "chrome", "http://fortune.com/fortune500"
driver.get "/list/"

driver.execute_script ("window.scrollTo(0, document.body.scrollHeight);") --It doesn't support here

Set posts = driver.FindElementsByXPath("//li[contains(concat(' ', @class, ' '), ' small-12 ')]")

For Each post In posts
    i = i + 1
    Cells(i, 1) = post.FindElementByXPath(".//a").Attribute("href")
Next post

End Sub

Body:
According to the examples included with SeleniumBasic you should be using

driver.ExecuteScript("window.scrollTo(0, document.body.scrollHeight);")

not "driver.execute_script", which is the python equivalent from the previous solution I gave you :) You are going to have to loop that in the same way until you've got all 1000 links on the page.


问:
What is a 'Closure'?
I asked a question about Currying and closures were mentioned.
What is a closure? How does it relate to currying?</p>

答:
tl;dr

A closure is a function and its scope assigned to (or used as) a variable. Thus, the name closure: the scope and the function is enclosed and used just like any other entity.

In depth Wikipedia style explanation

According to Wikipedia, a closure is:

Techniques for implementing lexically scoped name binding in languages with first-class functions.

What does that mean? Lets look into some definitions.

I will explain closures and other related definitions by using this example:

function startAt(x) {
    return function (y) {
        return x + y;
    }
}

var closure1 = startAt(1);
var closure2 = startAt(5);

console.log(closure1(3)); // 4 (x == 1, y == 3)
console.log(closure2(3)); // 8 (x == 5, y == 3)```

First-class functions

Basically that means we can use functions just like any other entity. We can modify them, pass them as arguments, return them from functions or assign them for variables. Technically speaking, they are first-class citizens, hence the name: first-class functions.

In the example above, startAt returns an (anonymous) function which function get assigned to closure1 and closure2. So as you see JavaScript treats functions just like any other entities (first-class citizens).

Name binding

Name binding is about finding out what data a variable (identifier) references. The scope is really important here, as that is the thing that will determine how a binding is resolved.

In the example above:

In the inner anonymous function's scope, y is bound to 3.

In startAt's scope, x is bound to 1 or 5 (depending on the closure).

Inside the anonymous function's scope, x is not bound to any value, so it needs to be resolved in an upper (startAt's) scope.

Lexical scoping

As Wikipedia says, the scope:

Is the region of a computer program where the binding is valid: where the name can be used to refer to the entity.

There are two techniques:

Lexical (static) scoping: A variable's definition is resolved by searching its containing block or function, then if that fails searching the outer containing block, and so on.

Dynamic scoping: Calling function is searched, then the function which called that calling function, and so on, progressing up the call stack.

For more explanation, check out this question and take a look at Wikipedia.

In the example above, we can see that JavaScript is lexically scoped, because when x is resolved, the binding is searched in the upper (startAt's) scope, based on the source code (the anonymous function that looks for x is defined inside startAt) and not based on the call stack, the way (the scope where) the function was called.

Wrapping (closuring) up

In our example, when we call startAt, it will return a (first-class) function that will be assigned to closure1 and closure2 thus a closure is created, because the passed variables 1 and 5 will be saved within startAt's scope, that will be enclosed with the returned anonymous function. When we call this anonymous function via closure1 and closure2 with the same argument (3), the value of y will be found immediately (as that is the parameter of that function), but x is not bound in the scope of the anonymous function, so the resolution continues in the (lexically) upper function scope (that was saved in the closure) where x is found to be bound to either 1 or 5. Now we know everything for the summation so the result can be returned, then printed.

Now you should understand closures and how they behave, which is a fundamental part of JavaScript.

Currying

Oh, and you also learned what currying is about: you use functions (closures) to pass each argument of an operation instead of using one functions with multiple parameters.

OwnerDisplayName: Ben

Title: What is a 'Closure'?

LastEditorDisplayName: Ben

Body:
tl;dr

A closure is a function and its scope assigned to (or used as) a variable. Thus, the name closure: the scope and the function is enclosed and used just like any other entity.

In depth Wikipedia style explanation

According to Wikipedia, a closure is:

Techniques for implementing lexically scoped name binding in languages with first-class functions.

What does that mean? Lets look into some definitions.

I will explain closures and other related definitions by using this example:

function startAt(x) {
    return function (y) {
        return x + y;
    }
}

var closure1 = startAt(1);
var closure2 = startAt(5);

console.log(closure1(3)); // 4 (x == 1, y == 3)
console.log(closure2(3)); // 8 (x == 5, y == 3)

First-class functions

Basically that means we can use functions just like any other entity. We can modify them, pass them as arguments, return them from functions or assign them for variables. Technically speaking, they are first-class citizens, hence the name: first-class functions.

In the example above, startAt returns an (anonymous) function which function get assigned to closure1 and closure2. So as you see JavaScript treats functions just like any other entities (first-class citizens).

Name binding

Name binding is about finding out what data a variable (identifier) references. The scope is really important here, as that is the thing that will determine how a binding is resolved.

In the example above:

In the inner anonymous function's scope, y is bound to 3.

In startAt's scope, x is bound to 1 or 5 (depending on the closure).

Inside the anonymous function's scope, x is not bound to any value, so it needs to be resolved in an upper (startAt's) scope.

Lexical scoping

As Wikipedia says, the scope:

Is the region of a computer program where the binding is valid: where the name can be used to refer to the entity.

There are two techniques:

Lexical (static) scoping: A variable's definition is resolved by searching its containing block or function, then if that fails searching the outer containing block, and so on.

Dynamic scoping: Calling function is searched, then the function which called that calling function, and so on, progressing up the call stack.

For more explanation, check out this question and take a look at Wikipedia.

In the example above, we can see that JavaScript is lexically scoped, because when x is resolved, the binding is searched in the upper (startAt's) scope, based on the source code (the anonymous function that looks for x is defined inside startAt) and not based on the call stack, the way (the scope where) the function was called.

Wrapping (closuring) up

In our example, when we call startAt, it will return a (first-class) function that will be assigned to closure1 and closure2 thus a closure is created, because the passed variables 1 and 5 will be saved within startAt's scope, that will be enclosed with the returned anonymous function. When we call this anonymous function via closure1 and closure2 with the same argument (3), the value of y will be found immediately (as that is the parameter of that function), but x is not bound in the scope of the anonymous function, so the resolution continues in the (lexically) upper function scope (that was saved in the closure) where x is found to be bound to either 1 or 5. Now we know everything for the summation so the result can be returned, then printed.

Now you should understand closures and how they behave, which is a fundamental part of JavaScript.

Currying

Oh, and you also learned what currying is about: you use functions (closures) to pass each argument of an operation instead of using one functions with multiple parameters.


问:
GCloud: Copying Files from Local Machine into a Docker Container
Is there a straightforward way to copy files from a local machine into a docker container within a VM instance on Google Compute Engine?

I know gcloud compute ssh --container=XX is an easy way to execute commands on a container, but there's no analogous gcloud compute scp --container=XX. Note: I created this VM and docker container with the command gcloud alpha compute instances create-from-container ...

Note, better than just being able to transfer files, it would be nice to have an rsync type functionality.

答:
Unfortunately, looks like it's not available without some setup on your part (and it's not in beta): creating a volume map notwithstanding, you could do it by running sshd inside the container listening on it's own port mapped to the host:

gcloud compute firewall-rules create CONTAINER-XX-SSH-RULE --allow
tcp:2022 --target-tags=XX-HOST

gcloud compute scp --port 2022 --recurse stuff/ user@XX-HOSTNAME:

or

scp -r -P 2022 stuff/ user@xx-host-ip:


问:
Serializing a proxy
I am trying to serialize an invocation handler to a file. I am only trying to serialize the following part as it is the only part of the program that will change:

```<code> public Object invoke(Object proxy, Method method, Object[] args) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException{
        System.out.println("BEFORE");
        method.invoke(original, args);
        System.out.println("AFTER");
        //System.out.println(method);
        return null;

    }
</code>```

I get the following error
run:Exception in thread "main" java.lang.RuntimeException: Uncompilable source code - Erroneous tree type: <any>
    at jdkproxydemo.JdkProxyDemo.main(JdkProxyDemo.java:69)
C:\Users\ACK\AppData\Local\NetBeans\Cache\8.1\executor-snippets\run.xml:53: Java returned: 1
BUILD FAILED (total time: 1 second)

Here is the full code:

```<code>public class JdkProxyDemo {

interface If {
    int originalMethod(String s);
}

static class Original implements If {
    public int originalMethod(String s) {
        System.out.println(s);
        return 0;
    }
}

public static class Handler implements InvocationHandler, Serializable {

    private final If original;

    public Handler(If original) {
        this.original = original;
    }

    public Object invoke(Object proxy, Method method, Object[] args) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException{
        System.out.println("BEFORE");
        method.invoke(original, args);
        System.out.println("AFTER");
        //System.out.println(method);
        return null;

    }
}

public static void main(String[] args) throws FileNotFoundException, IOException{

      ///  OutputStream file = null;

        Original original = new Original();
        Handler handler = new Handler(original);
        If f = (If) Proxy.newProxyInstance(If.class.getClassLoader(),new Class[] { If.class },handler);
                OutputStream file = new FileOutputStream("quarks.ser");
  OutputStream buffer = new BufferedOutputStream(file);
   ObjectOutput output = new ObjectOutputStream(buffer);
   output.writeObject(handler.invoke(f,handler.original,"a"));
   output.close();
}
</code>```

}

What is the best way to achieve this result, serializing a proxy object?

答:
Your code is currently trying to serialize private final If original because it's part of Handler. However the If interface does not extend Serializable, so you cannot serialize Handler. You should either change to

```<code>interface If extends Serializable
</code>```

Or if that is not possible, you should use a different serialization method than Java serialization.

Title: Serializing a proxy

Body:
I am trying to serialize an invocation handler to a file. I am only trying to serialize the following part as it is the only part of the program that will change:

 public Object invoke(Object proxy, Method method, Object[] args) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException{
        System.out.println("BEFORE");
        method.invoke(original, args);
        System.out.println("AFTER");
        //System.out.println(method);
        return null;

    }

I get the following error
run:Exception in thread "main" java.lang.RuntimeException: Uncompilable source code - Erroneous tree type: <any>
    at jdkproxydemo.JdkProxyDemo.main(JdkProxyDemo.java:69)
C:\Users\ACK\AppData\Local\NetBeans\Cache\8.1\executor-snippets\run.xml:53: Java returned: 1
BUILD FAILED (total time: 1 second)

Here is the full code:

public class JdkProxyDemo {

interface If {
    int originalMethod(String s);
}

static class Original implements If {
    public int originalMethod(String s) {
        System.out.println(s);
        return 0;
    }
}

public static class Handler implements InvocationHandler, Serializable {

    private final If original;

    public Handler(If original) {
        this.original = original;
    }

    public Object invoke(Object proxy, Method method, Object[] args) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException{
        System.out.println("BEFORE");
        method.invoke(original, args);
        System.out.println("AFTER");
        //System.out.println(method);
        return null;

    }
}

public static void main(String[] args) throws FileNotFoundException, IOException{

      ///  OutputStream file = null;

        Original original = new Original();
        Handler handler = new Handler(original);
        If f = (If) Proxy.newProxyInstance(If.class.getClassLoader(),new Class[] { If.class },handler);
                OutputStream file = new FileOutputStream("quarks.ser");
  OutputStream buffer = new BufferedOutputStream(file);
   ObjectOutput output = new ObjectOutputStream(buffer);
   output.writeObject(handler.invoke(f,handler.original,"a"));
   output.close();
}

}

What is the best way to achieve this result, serializing a proxy object?

Body:
Your code is currently trying to serialize private final If original because it's part of Handler. However the If interface does not extend Serializable, so you cannot serialize Handler. You should either change to

interface If extends Serializable

Or if that is not possible, you should use a different serialization method than Java serialization.


答:
You could try a simpler code:
Add the same class to the elements you want to attach the click listener and when clicked just retrieve the attribute's value.</p>

```<code>jQuery(".my-class").click(function(){
    var element_id = jQuery(this).attr("id");
});
</code>```

Title: Get the clicked element ID in javascript

Body:
You could try a simpler code:
Add the same class to the elements you want to attach the click listener and when clicked just retrieve the attribute's value.

jQuery(".my-class").click(function(){
    var element_id = jQuery(this).attr("id");
});