问:
Changing visibility of java 8 default method
I have a class (Say FOO) and it has a method with default visibility,
like below :

```<code>void sayHi() {}
</code>```

Now, If a override this method in extending class I cannot decrease it's visibility. So I can only use default or public.

```<code>public class MyClassTest extends FOO {
    @Override
    // Or I can use public void sayHi()
    void sayHi() {
        System.out.println("Overriden sayHi");
    }
}
</code>```

Now if I write an Interface in Java 8 with a default method like below :

```<code>public interface InterfaceX {

    // Java-8 defalu method
    default String printName() {
        System.out.println("Interface1 default metod");
        return "Interface1 default metod";
    }
}
</code>```

Now, if I override this method in a class It should compile if a keep overridden method's visibility default.

```<code>public class Java8InterfaceTest implements InterfaceX{
    @Override
     void printHello() {
        System.out.println("Printing..!");
        Interface1.super.printName();
    }
 }
</code>```

It says

Cannot reduce the visibility of the inherited method from InterfaceX

I already know that every method in interface in public by default, but in the above example we are using default which I think is one of the access modifier in java.

I have following questions:

Is default in interface different from default visibility which is provide when no access modifier applied?

If it's different then how it's different?

答:
default has nothing to do with default visibility. A default method in an interface is a method that has a default implementation within the interface.

The visibility of that method is still public.

Therefore the method implemented in your Java8InterfaceTest class must have public visibility:

```<code>public void printHello() {
    ...
}
</code>```

Body:
I have a class (Say FOO) and it has a method with default visibility,
like below :

void sayHi() {}

Now, If a override this method in extending class I cannot decrease it's visibility. So I can only use default or public.

public class MyClassTest extends FOO {
    @Override
    // Or I can use public void sayHi()
    void sayHi() {
        System.out.println("Overriden sayHi");
    }
}

Now if I write an Interface in Java 8 with a default method like below :

public interface InterfaceX {

    // Java-8 defalu method
    default String printName() {
        System.out.println("Interface1 default metod");
        return "Interface1 default metod";
    }
}

Now, if I override this method in a class It should compile if a keep overridden method's visibility default.

public class Java8InterfaceTest implements InterfaceX{
    @Override
     void printHello() {
        System.out.println("Printing..!");
        Interface1.super.printName();
    }
 }

It says

Cannot reduce the visibility of the inherited method from InterfaceX

I already know that every method in interface in public by default, but in the above example we are using default which I think is one of the access modifier in java.

I have following questions:

Is default in interface different from default visibility which is provide when no access modifier applied?

If it's different then how it's different?

Body:
default has nothing to do with default visibility. A default method in an interface is a method that has a default implementation within the interface.

The visibility of that method is still public.

Therefore the method implemented in your Java8InterfaceTest class must have public visibility:

public void printHello() {
    ...
}


来源: stackexchange

答:
Just put it in forward-slashes:

```<code>var re = /^(((0?[1-9]|1[012])\/(0?[1-9]|1\d|2[0-8])|(0?[13456789]|1[012])/(29|30)|(0?[13578]|1[02])/31)\/(19|[2-9]\d)\d{2}|0?2/29/((19|[2-9]\d)(0[48]|[2468][048]|[13579][26])|(([2468][048]|[3579][26])00)))$/
</code>```

Now, while that'll get you a regular expression to use, I have to say that this may be one of the silliest applications of a regex ever. You'd be way better off just instantiating a JavaScript "Date" object and using it's surprisingly friendly API to check what you need to check.

If you instantiate a JavaScript "Date" object with a bogus date (like Februrary 30), it'll just roll to the actual date that sort-of corresponds to the bogus date; in other words, it carries over the bogus days into the next month.  Thus, if you just hold on to the month and day, and create a "Date" instance, you can know that if the month and day that the "Date" instance gives you when you ask are different from the ones you fed it, then the original date must have been unreal.

ContentLicense: CC BY-SA 2.5

Title: How to use this regular expression in JavaScript?

Body:
I am trying to use the following regular expression to test for a valid date.

^(((0?[1-9]|1[012])/(0?[1-9]|1\d|2[0-8])|(0?[13456789]|1[012])/(29|30)|(0?[13578]|1[02])/31)/(19|[2-9]\d)\d{2}|0?2/29/((19|[2-9]\d)(0[48]|[2468][048]|[13579][26])|(([2468][048]|[3579][26])00)))$

which I got from

http://regexlib.com/REDetails.aspx?regexp_id=1071

My JavaScript test code is:

var date='1/1/1965';
var re = new RegExp('^(((0?[1-9]|1[012])/(0?[1-9]|1\d|2[0-8])|(0?[13456789]|1[012])/(29|30)|(0?[13578]|1[02])/31)/(19|[2-9]\d)\d{2}|0?2/29/((19|[2-9]\d)(0[48]|[2468][048]|[13579][26])|(([2468][048]|[3579][26])00)))$');
alert(re.test(date));

I keep getting "false" rather than "true" for this valid test date.

Body:
Just put it in forward-slashes:

var re = /^(((0?[1-9]|1[012])\/(0?[1-9]|1\d|2[0-8])|(0?[13456789]|1[012])/(29|30)|(0?[13578]|1[02])/31)\/(19|[2-9]\d)\d{2}|0?2/29/((19|[2-9]\d)(0[48]|[2468][048]|[13579][26])|(([2468][048]|[3579][26])00)))$/

Now, while that'll get you a regular expression to use, I have to say that this may be one of the silliest applications of a regex ever. You'd be way better off just instantiating a JavaScript "Date" object and using it's surprisingly friendly API to check what you need to check.

If you instantiate a JavaScript "Date" object with a bogus date (like Februrary 30), it'll just roll to the actual date that sort-of corresponds to the bogus date; in other words, it carries over the bogus days into the next month.  Thus, if you just hold on to the month and day, and create a "Date" instance, you can know that if the month and day that the "Date" instance gives you when you ask are different from the ones you fed it, then the original date must have been unreal.


问:
How to use Count SQL Server Query
i write this post to ask for help on a query on the following schema:

Imagine having two formats, for example, PDF and EBOOK. My goal is to get the following result:

```<code>PushiblerName  |  Number_PDF   |  Numerber_BOOK  |
--------------------------------------------------
ExampleName1   |    2          |   0
ExampleName2   |    3          |   1
</code>```

Would anyone help me write this query?
Thanks in advance.

答:
Here you go:

```<code>CREATE TABLE Author (
    AuthorID INT IDENTITY (1,1) PRIMARY KEY NOT NULL,
    AuthorName VARCHAR (25) NOT NULL
    );
CREATE TABLE Books (
    BookID INT IDENTITY (1,1) PRIMARY KEY NOT NULL,
    BookName VARCHAR (25) NOT NULL,
    BookAothor INT NOT NULL,
    CONSTRAINT PK_AuthorOfBook FOREIGN KEY (BookAothor) REFERENCES Author (AuthorID)
    );
CREATE TABLE Formats (
    FormatID INT IDENTITY (1,1) PRIMARY KEY NOT NULL,
    FormatName VARCHAR (10) NOT NULL
    );
CREATE TABLE BookFormat (
    BookID INT NOT NULL,
    FormatID INT NOT NULL,
    CONSTRAINT PK_BookFormats PRIMARY KEY (BookID, FormatID),
    CONSTRAINT FK_BookRef FOREIGN KEY (BookID) REFERENCES Books (BookID),
    CONSTRAINT FK_FormatRef FOREIGN KEY (FormatID) REFERENCES Formats (FormatID)
    );
INSERT INTO Author VALUES
('Author1'), ('Author2'), ('Author3');
INSERT INTO Books VALUES
('Book1', 1), ('Book2', 1),
('Book3', 2), ('Book4', 2),
('Book5', 2), ('Book6', 2);
INSERT INTO Formats VALUES
('PDF'), ('E-Book');
INSERT INTO BookFormat VALUES
(1, 1), (2,1),
(3,1), (4,1), (5,1), (6,2);

SELECT A.AuthorName,
       ISNULL(Pdf.PdfBooks, 0) AS PdfBooks,
       ISNULL(EBook.EBooks, 0) AS EBooks
FROM
Author A  LEFT JOIN
    (
        SELECT A.AuthorID, COUNT(B.BookID) AS PdfBooks
        FROM Author A JOIN Books B ON A.AuthorID = B.BookAothor
             INNER JOIN BookFormat BF ON B.BookID = BF.BookID
        WHERE BF.FormatID =1
        GROUP BY A.AuthorID
    ) Pdf ON A.AuthorID = Pdf.AuthorID
     FULL JOIN
    (
        SELECT A.AuthorID, COUNT(B.BookID) AS EBooks
        FROM Author A JOIN Books B ON A.AuthorID = B.BookAothor
             INNER JOIN BookFormat BF ON B.BookID = BF.BookID
        WHERE BF.FormatID =2
        GROUP BY A.AuthorID
    ) EBook
    ON Pdf.AuthorID = EBook.AuthorID;
</code>```

Results:

```<code>+------------+----------+--------+
| AuthorName | PdfBooks | EBooks |
+------------+----------+--------+
| Author1    |        2 |      0 |
| Author2    |        3 |      1 |
| Author3    |        0 |      0 |
+------------+----------+--------+
</code>```

Here is a demo

ContentLicense: CC BY-SA 3.0

Title: How to use Count SQL Server Query

Body:
i write this post to ask for help on a query on the following schema:

Imagine having two formats, for example, PDF and EBOOK. My goal is to get the following result:

PushiblerName  |  Number_PDF   |  Numerber_BOOK  |
--------------------------------------------------
ExampleName1   |    2          |   0
ExampleName2   |    3          |   1

Would anyone help me write this query?
Thanks in advance.

Body:
Here you go:

CREATE TABLE Author (
    AuthorID INT IDENTITY (1,1) PRIMARY KEY NOT NULL,
    AuthorName VARCHAR (25) NOT NULL
    );
CREATE TABLE Books (
    BookID INT IDENTITY (1,1) PRIMARY KEY NOT NULL,
    BookName VARCHAR (25) NOT NULL,
    BookAothor INT NOT NULL,
    CONSTRAINT PK_AuthorOfBook FOREIGN KEY (BookAothor) REFERENCES Author (AuthorID)
    );
CREATE TABLE Formats (
    FormatID INT IDENTITY (1,1) PRIMARY KEY NOT NULL,
    FormatName VARCHAR (10) NOT NULL
    );
CREATE TABLE BookFormat (
    BookID INT NOT NULL,
    FormatID INT NOT NULL,
    CONSTRAINT PK_BookFormats PRIMARY KEY (BookID, FormatID),
    CONSTRAINT FK_BookRef FOREIGN KEY (BookID) REFERENCES Books (BookID),
    CONSTRAINT FK_FormatRef FOREIGN KEY (FormatID) REFERENCES Formats (FormatID)
    );
INSERT INTO Author VALUES
('Author1'), ('Author2'), ('Author3');
INSERT INTO Books VALUES
('Book1', 1), ('Book2', 1),
('Book3', 2), ('Book4', 2),
('Book5', 2), ('Book6', 2);
INSERT INTO Formats VALUES
('PDF'), ('E-Book');
INSERT INTO BookFormat VALUES
(1, 1), (2,1),
(3,1), (4,1), (5,1), (6,2);

SELECT A.AuthorName,
       ISNULL(Pdf.PdfBooks, 0) AS PdfBooks,
       ISNULL(EBook.EBooks, 0) AS EBooks
FROM
Author A  LEFT JOIN
    (
        SELECT A.AuthorID, COUNT(B.BookID) AS PdfBooks
        FROM Author A JOIN Books B ON A.AuthorID = B.BookAothor
             INNER JOIN BookFormat BF ON B.BookID = BF.BookID
        WHERE BF.FormatID =1
        GROUP BY A.AuthorID
    ) Pdf ON A.AuthorID = Pdf.AuthorID
     FULL JOIN
    (
        SELECT A.AuthorID, COUNT(B.BookID) AS EBooks
        FROM Author A JOIN Books B ON A.AuthorID = B.BookAothor
             INNER JOIN BookFormat BF ON B.BookID = BF.BookID
        WHERE BF.FormatID =2
        GROUP BY A.AuthorID
    ) EBook
    ON Pdf.AuthorID = EBook.AuthorID;

Results:

+------------+----------+--------+
| AuthorName | PdfBooks | EBooks |
+------------+----------+--------+
| Author1    |        2 |      0 |
| Author2    |        3 |      1 |
| Author3    |        0 |      0 |
+------------+----------+--------+

Here is a demo


问:
Data Binding in UWP doesn't refresh
I'm trying to bind the 'Text' property of my TextBlock in xaml to a global string, but when I change the string the TextBlock's content doesn't change. What is that I'm missing?

My xaml:

```<code><StackPanel>
        <Button Content="Change!" Click="Button_Click" />
        <TextBlock Text="{x:Bind text}" />
</StackPanel>
</code>```

My C#:

```<code>    string text;
    public MainPage()
    {
        this.InitializeComponent();
        text = "This is the original text.";
    }

    private void Button_Click(object sender, RoutedEventArgs e)
    {
        text = "This is the changed text!";
    }
</code>```

答: When databinding via Itemsource not refresh even source is modified this may solve refresh problem</p>

Title: Data Binding in UWP doesn't refresh

Body:
I'm trying to bind the 'Text' property of my TextBlock in xaml to a global string, but when I change the string the TextBlock's content doesn't change. What is that I'm missing?

My xaml:

<StackPanel>
        <Button Content="Change!" Click="Button_Click" />
        <TextBlock Text="{x:Bind text}" />
</StackPanel>

My C#:

    string text;
    public MainPage()
    {
        this.InitializeComponent();
        text = "This is the original text.";
    }

    private void Button_Click(object sender, RoutedEventArgs e)
    {
        text = "This is the changed text!";
    }

ContentLicense: CC BY-SA 4.0


问:
Troubles creating assembly in MS SQL Server
I had intentions to import the .NET assembly with SQL functions to MS SQL Server.

I've been trying to import it like this:

```<code>CREATE ASSEMBLY [AssemblyName]
AUTHORIZATION [dbo]
FROM 0x4D5A9000030...
</code>```

It was generated by my SQL project in Visual Studio

After that I needed to also create the referenced assemblies, like 'Microsoft.CSharp'

```<code>CREATE ASSEMBLY [Microsoft.CSharp]
FROM 'path to dll'
WITH PERMISSION_SET = UNSAFE
</code>```

And then I've got the error like this:

Assembly 'Microsoft.CSharp' references assembly 'system.dynamic, version=4.0.0.0, culture=neutral, publickeytoken=b03f5f7f11d50a3a.', which is not present in the current database. SQL Server attempted to locate and automatically load the referenced assembly from the same location where referring assembly came from, but that operation has failed (reason: 2(The system cannot find the file specified.)). Please load the referenced assembly into the current database and retry your request.'

And now I really don't understand. As far as I know, System.Dynamic is not an assembly, but a namespace in System.Core.dll. And the System.Core is supported by MS SQL Server and imported by default. Is there any way to resolve such issue and successfully import such assembly?

答:
That (System.Dynamic.dll) really is an assembly - you can find it in the GAC and on disk; it has lots of the implementation details that C# uses to implement dynamic. You don't normally see it because all the types are internal, but it uses:

```<code>[assembly: InternalsVisibleTo("Microsoft.CSharp, PublicKey =002400000480000094000000060200000024000052534131000400000100010007d1fa57c4aed9f0a32e84aa0faefd0de9e8fd6aec8f87fb03766c834c99921eb23be79ad9d5dcc1dd9ad236132102900b723cf980957fc4e177108fc607774f29e8320e92ea05ece4e821c0a5efe8f1645c4c0c93c1ab99285d622caa652c1dfad63d745d6f2de5f17e5eaf0fc4963d261c8a12436518206dc093344d5ad293")]
</code>```

so those implementation details are available to Micrsoft.CSharp.dll

The database is 100% correct here.

Body:
I had intentions to import the .NET assembly with SQL functions to MS SQL Server.

I've been trying to import it like this:

CREATE ASSEMBLY [AssemblyName]
AUTHORIZATION [dbo]
FROM 0x4D5A9000030...

It was generated by my SQL project in Visual Studio

After that I needed to also create the referenced assemblies, like 'Microsoft.CSharp'

CREATE ASSEMBLY [Microsoft.CSharp]
FROM 'path to dll'
WITH PERMISSION_SET = UNSAFE

And then I've got the error like this:

Assembly 'Microsoft.CSharp' references assembly 'system.dynamic, version=4.0.0.0, culture=neutral, publickeytoken=b03f5f7f11d50a3a.', which is not present in the current database. SQL Server attempted to locate and automatically load the referenced assembly from the same location where referring assembly came from, but that operation has failed (reason: 2(The system cannot find the file specified.)). Please load the referenced assembly into the current database and retry your request.'

And now I really don't understand. As far as I know, System.Dynamic is not an assembly, but a namespace in System.Core.dll. And the System.Core is supported by MS SQL Server and imported by default. Is there any way to resolve such issue and successfully import such assembly?

Body:
That (System.Dynamic.dll) really is an assembly - you can find it in the GAC and on disk; it has lots of the implementation details that C# uses to implement dynamic. You don't normally see it because all the types are internal, but it uses:

[assembly: InternalsVisibleTo("Microsoft.CSharp, PublicKey =002400000480000094000000060200000024000052534131000400000100010007d1fa57c4aed9f0a32e84aa0faefd0de9e8fd6aec8f87fb03766c834c99921eb23be79ad9d5dcc1dd9ad236132102900b723cf980957fc4e177108fc607774f29e8320e92ea05ece4e821c0a5efe8f1645c4c0c93c1ab99285d622caa652c1dfad63d745d6f2de5f17e5eaf0fc4963d261c8a12436518206dc093344d5ad293")]

so those implementation details are available to Micrsoft.CSharp.dll

The database is 100% correct here.


问:
Multi threading in Dataset api
TL;DR: how to ensure that data is loaded in multi threaded manner when using Dataset api in tensorflow 0.1.4?

Previously I did something like this with my images in disk:

```<code>filename_queue = tf.train.string_input_producer(filenames)
image_reader = tf.WholeFileReader()
_, image_file = image_reader.read(filename_queue)
imsize = 120
image = tf.image.decode_jpeg(image_file, channels=3)
image = tf.image.convert_image_dtype(image, dtype=tf.float32)
image_r = tf.image.resize_images(image, [imsize, imsize])
images = tf.train.shuffle_batch([image_r],
    batch_size=20,
    num_threads=30,
    capacity=200,
    min_after_dequeue=0)
</code>```

This ensures that there will be 20 threads getting data ready for next learning iterations.

Now with the Dataset api I do something like:

```<code>dataset = tf.data.Dataset.from_tensor_slices((filenames, filenames_up, filenames_blacked))
dataset = dataset.map(parse_upscaler_corrector_batch)
</code>```

After this I create an iterator:

```<code>sess = tf.Session();
iterator = dataset.make_initializable_iterator();
next_element = iterator.get_next();
sess.run(iterator.initializer);
value = sess.run(next_element)
</code>```

Variable value will be passed for further processing.

So how do I ensure that data is being prepared in multui-threading manner here? Where could I read about Dataset api and multi threading data read?

答:
So it appears that the way to achieve this is as follows:

```<code>dataset = dataset.map(parse_upscaler_corrector_batch, num_parallel_calls=12).prefetch(32).batch(self.ex_config.batch_size)
</code>```

If one changes num_parallel_calls=12 one can see that both network/hdd load and cpu load either spike or decrease.

Title: Multi threading in Dataset api

Body:
TL;DR: how to ensure that data is loaded in multi threaded manner when using Dataset api in tensorflow 0.1.4?

Previously I did something like this with my images in disk:

filename_queue = tf.train.string_input_producer(filenames)
image_reader = tf.WholeFileReader()
_, image_file = image_reader.read(filename_queue)
imsize = 120
image = tf.image.decode_jpeg(image_file, channels=3)
image = tf.image.convert_image_dtype(image, dtype=tf.float32)
image_r = tf.image.resize_images(image, [imsize, imsize])
images = tf.train.shuffle_batch([image_r],
    batch_size=20,
    num_threads=30,
    capacity=200,
    min_after_dequeue=0)

This ensures that there will be 20 threads getting data ready for next learning iterations.

Now with the Dataset api I do something like:

dataset = tf.data.Dataset.from_tensor_slices((filenames, filenames_up, filenames_blacked))
dataset = dataset.map(parse_upscaler_corrector_batch)

After this I create an iterator:

sess = tf.Session();
iterator = dataset.make_initializable_iterator();
next_element = iterator.get_next();
sess.run(iterator.initializer);
value = sess.run(next_element)

Variable value will be passed for further processing.

So how do I ensure that data is being prepared in multui-threading manner here? Where could I read about Dataset api and multi threading data read?

Body:
So it appears that the way to achieve this is as follows:

dataset = dataset.map(parse_upscaler_corrector_batch, num_parallel_calls=12).prefetch(32).batch(self.ex_config.batch_size)

If one changes num_parallel_calls=12 one can see that both network/hdd load and cpu load either spike or decrease.


问:
boost process running() and exit_code() thread safety
I am using boost::process::child and boost::process::async_pipe to start an application and read asynchronously (through the means of boost::asio) everything that app outputs on screen whenever this happens.

I want to check also if the application is alive by using child::running() method; if not running I'd like to read the exit code using child::exit_code.

This is very useful ESPECIALLY as it is a way to be notified about an application crashing or exiting unexpectedly (I could not find a better way); when the app exits the callback is called with boost::system::error_code set.

Do you know if I can use these two methods inside the callback called by async_pipe::async_read_some ?

In general the much more simple question would be if child::running() and child::exit_code() are thread safe (in both Windows and Linux).

```<code> namespace bp = boost::process;

 char my_buffer[1024];

 boost::asio::io_service io;
 bp::async_pipe in_pipe(io);

 void handle_pipe_read(const boost::system::error_code &ec, std::size_t bytes_transferred);

 void schedule_read()  {
     in_pipe.async_read_some(
         boost::asio::buffer(my_buffer),
         boost::bind(&handle_pipe_read,
                  boost::asio::placeholders::error,
                  boost::asio::placeholders::bytes_transferred));
 }

 void handle_pipe_read(
    const boost::system::error_code &ec,
    std::size_t bytes_transferred
    )
 {
     // Q: Is this call possible? 'handle_pipe_read' can run in any thread
     if(c->running())
        std::cout << "I am alive" << std::endl;
     else
        std::cout << "EXIT CODE:" << c->exit_code() << std::endl;

     if(ec) return; //app probably exit

     // Do something with buffer and re-schedule

     schedule_read();
 }

 int main() {
   bp::child c("my_program_url", bp::std_out > in_pipe);
   any_c = &c;

   schedule_read();
   io.run();
 }
</code>```

答:
Since you only run the io_service::run() on the main thread, all completion handlers also run there. There's no threading.

Remember to pass the io_service to the child, and use the on_exit handler:

Live On Coliru

```<code>#include <boost/process.hpp>
//#include <boost/asio.hpp>
#include <boost/bind.hpp>
#include <system_error>
#include <utility>
#include <iostream>

namespace bp = boost::process;

char my_buffer[1024];

boost::asio::io_service io;
bp::async_pipe in_pipe(io);

void handle_pipe_read(const boost::system::error_code &ec, std::size_t bytes_transferred);

void schedule_read() {
    in_pipe.async_read_some(
        boost::asio::buffer(my_buffer),
        boost::bind(&handle_pipe_read, _1, _2));
}

void handle_pipe_read(const boost::system::error_code &ec, std::size_t bytes_transferred) {
    if (ec)
        return; // app probably exit

    // Do something with buffer and re-schedule
    std::cout.write(my_buffer, bytes_transferred);

    if (in_pipe.is_open())
        schedule_read();
}

int main() {
    bp::child c("/bin/ls", bp::std_out > in_pipe,
            bp::on_exit([](int code, std::error_code ec) {
                std::cout << "Child exited (" << code << "): " << ec.message() << std::endl;
                in_pipe.close();
            }), io);

    schedule_read();
    io.run();

    std::cout << "Service done (" << c.exit_code() << ")" << std::endl;
}
</code>```

Prints:

```<code>a.out
main.cpp
Child exited (0): Success
Service done (0)
</code>```

Body:
I am using boost::process::child and boost::process::async_pipe to start an application and read asynchronously (through the means of boost::asio) everything that app outputs on screen whenever this happens.

I want to check also if the application is alive by using child::running() method; if not running I'd like to read the exit code using child::exit_code.

This is very useful ESPECIALLY as it is a way to be notified about an application crashing or exiting unexpectedly (I could not find a better way); when the app exits the callback is called with boost::system::error_code set.

Do you know if I can use these two methods inside the callback called by async_pipe::async_read_some ?

In general the much more simple question would be if child::running() and child::exit_code() are thread safe (in both Windows and Linux).

 namespace bp = boost::process;

 char my_buffer[1024];

 boost::asio::io_service io;
 bp::async_pipe in_pipe(io);

 void handle_pipe_read(const boost::system::error_code &ec, std::size_t bytes_transferred);

 void schedule_read()  {
     in_pipe.async_read_some(
         boost::asio::buffer(my_buffer),
         boost::bind(&handle_pipe_read,
                  boost::asio::placeholders::error,
                  boost::asio::placeholders::bytes_transferred));
 }

 void handle_pipe_read(
    const boost::system::error_code &ec,
    std::size_t bytes_transferred
    )
 {
     // Q: Is this call possible? 'handle_pipe_read' can run in any thread
     if(c->running())
        std::cout << "I am alive" << std::endl;
     else
        std::cout << "EXIT CODE:" << c->exit_code() << std::endl;

     if(ec) return; //app probably exit

     // Do something with buffer and re-schedule

     schedule_read();
 }

 int main() {
   bp::child c("my_program_url", bp::std_out > in_pipe);
   any_c = &c;

   schedule_read();
   io.run();
 }

Body:
Since you only run the io_service::run() on the main thread, all completion handlers also run there. There's no threading.

Remember to pass the io_service to the child, and use the on_exit handler:

Live On Coliru

#include <boost/process.hpp>
//#include <boost/asio.hpp>
#include <boost/bind.hpp>
#include <system_error>
#include <utility>
#include <iostream>

namespace bp = boost::process;

char my_buffer[1024];

boost::asio::io_service io;
bp::async_pipe in_pipe(io);

void handle_pipe_read(const boost::system::error_code &ec, std::size_t bytes_transferred);

void schedule_read() {
    in_pipe.async_read_some(
        boost::asio::buffer(my_buffer),
        boost::bind(&handle_pipe_read, _1, _2));
}

void handle_pipe_read(const boost::system::error_code &ec, std::size_t bytes_transferred) {
    if (ec)
        return; // app probably exit

    // Do something with buffer and re-schedule
    std::cout.write(my_buffer, bytes_transferred);

    if (in_pipe.is_open())
        schedule_read();
}

int main() {
    bp::child c("/bin/ls", bp::std_out > in_pipe,
            bp::on_exit([](int code, std::error_code ec) {
                std::cout << "Child exited (" << code << "): " << ec.message() << std::endl;
                in_pipe.close();
            }), io);

    schedule_read();
    io.run();

    std::cout << "Service done (" << c.exit_code() << ")" << std::endl;
}

Prints:

a.out
main.cpp
Child exited (0): Success
Service done (0)


答:
Your problem might be escaping of the slashes.

There are 2 ways you can insert a regexp in javascript. 1st way is just put it in forward slashes, and the second way, which is the way you are doing it is with RegExp object, which means that you then have to include the regexp string itself in the JavaScript code as a string.

And as every other string in Javascript which contains special characters like backward slashes (which your regexp does), you have to escape them with yet another backslash.

So basically just replace every backslash in your code with double backslash (\\) and you should be fine.


问:
why the height of the out div is affected by vertical-align

in chrome, I thought the height of .wrap should be 24px.

it is 25px when the vertial-align is set to middle. can someone explain why?

answer in this article

body {
  line-height: 1.5;
}

.wrap {
  font-size:16px;  /* 16*1.5= 24 */
}

.btn {
  font-size: 14px;
  padding: 4px;
  line-height: 1;
  box-sizing: border-box;
  border: 1px solid blue;
  vertical-align: middle;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="wrap">
  <button class="btn">
    OK
  </button>
</div></code>```

答:
Solving the problem:

Simply you're getting the extra pixel because of this:

```<code>body {
    line-height: 1.5;
}
</code>```

All your HTML elements are inheriting this attribute from the body.

Answering the question:

why the height of the out div is affected by vertical-align

The <button> default display attribute is "inline-block", which gets affects by white-spaces, line-height, font-size, and other text-related CSS attributes. vertical-align is one of these text-related attributes. For example, if you change the button's display to "block" you can see that it no longer affects the .wrap's height.

Body:
in chrome, I thought the height of .wrap should be 24px.

it is 25px when the vertial-align is set to middle. can someone explain why?

answer in this article

body {
  line-height: 1.5;
}

.wrap {
  font-size:16px;  /* 16*1.5= 24 */
}

.btn {
  font-size: 14px;
  padding: 4px;
  line-height: 1;
  box-sizing: border-box;
  border: 1px solid blue;
  vertical-align: middle;
}

  <button class="btn">
    OK
  </button>

Body:
Solving the problem:

Simply you're getting the extra pixel because of this:

body {
    line-height: 1.5;
}

All your HTML elements are inheriting this attribute from the body.

Answering the question:

why the height of the out div is affected by vertical-align

The <button> default display attribute is "inline-block", which gets affects by white-spaces, line-height, font-size, and other text-related CSS attributes. vertical-align is one of these text-related attributes. For example, if you change the button's display to "block" you can see that it no longer affects the .wrap's height.


问:
Trigger two Javascript actions with onclick
I have a button that need to trigger a div and a Google Analytics event. I can't get this to work. Right now, the div triggers fine, but the GA event does not trigger.

This is the HTML:

```<code><a class="knappmedium knappfeedbackyes" href="#" onclick="showFeedback('yes');ga('send', 'event', 'Feedback', 'Feedback positive', 'PAGEURL');">YES</a>
</code>```

Edit:
This button will be on multiple pages, with the GA tacking parameters unique for each instance it is used.

Help would be very much appreciated!

Kind regards,
Pete

答:
It does work. Check the snippet below.

function showFeedback(){
  console.log('showFeedback');
}

function ga(){
  console.log('ga');
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code>YES</code>```

Body:
I have a button that need to trigger a div and a Google Analytics event. I can't get this to work. Right now, the div triggers fine, but the GA event does not trigger.

This is the HTML:

YES

Edit:
This button will be on multiple pages, with the GA tacking parameters unique for each instance it is used.

Help would be very much appreciated!

Kind regards,
Pete

Body:
It does work. Check the snippet below.

function showFeedback(){
  console.log('showFeedback');
}

function ga(){
  console.log('ga');
}

<a href="#" onclick="showFeedback();ga();">YES</a>


答:
Why don't you try querySelector ?</p>

```<code>document.querySelector('.knappmedium.knappfeedbackyes').addEventListener('click', function(){
    showFeedback('yes');
    ga('send', 'event', 'Feedback', 'Feedback positive', 'PAGEURL');
});
</code>```

Title: Trigger two Javascript actions with onclick

Body:
Why don't you try querySelector ?

document.querySelector('.knappmedium.knappfeedbackyes').addEventListener('click', function(){
    showFeedback('yes');
    ga('send', 'event', 'Feedback', 'Feedback positive', 'PAGEURL');
});


问:
DB or XML Question
XML seems to be another way to store information in a much smaller scale? While DB can handle all sorts. I'm interested in knowing what are the pro's and con's to the each. Is one of them better in a scenario? I'm sure each has there best case scenario.

Thank you in advance.

答: Well XML vs DB has been covered a lot by all the smart people you care to name including the Man himself. Read http://www.joelonsoftware.com/articles/fog0000000319.html things will become clearer.</p>

Title: DB or XML Question


问:
Acumatica Customization MS SQL MySql
We have faced the following problem.
We were developing customization package under system on MySQL database.
All the database changes were added to customization from Customization Page.

Now when we are publishing this customization under system on MS SQL database we are getting errors associated with the differences between MySQL and MS SQL.
I have reviewed the xml's which Acumatica is generating for database changes and there are some differences, for example:

timestamp is set to have default value when xml is generated from MySQL database.

Primary key constraint has name PRIMARY when xml is generated from MySQL.

How can we solve this problem so that we have not to have two different packages, one for MySQL and the other for MS SQL?

Here is how Acumatica Generates Script for CS Attribute in case of MySql:

```<code>  <Sql TableName="csattribute" TableSchemaXml="#CDATA">
  <CDATA name="TableSchemaXml"><![CDATA[<table name="csattribute">
  <col name="CompanyID" type="Int" default="Zero" />
  <col name="AttributeID" type="NVarChar(30)" />
  <col name="Description" type="NVarChar(60)" />
  <col name="ControlType" type="Int" />
  <col name="EntryMask" type="VarChar(60)" nullable="true" />
  <col name="RegExp" type="NVarChar(60)" nullable="true" />
  <col name="List" type="NVarChar(MAX)" nullable="true" />
  <col name="IsInternal" type="Bit" nullable="true" />
  <col name="tstamp" type="Timestamp" default="CurrentDateTime" />
  <col name="CreatedByID" type="UniqueIdentifier" />
  <col name="CreatedByScreenID" type="Char(8)" />
  <col name="CreatedDateTime" type="DateTime" />
  <col name="LastModifiedByID" type="UniqueIdentifier" />
  <col name="LastModifiedByScreenID" type="Char(8)" />
  <col name="LastModifiedDateTime" type="DateTime" />
  <col name="NoteID" type="UniqueIdentifier" />
  <index name="CSAttribute_NoteID">
    <col name="NoteID" />
    <col name="CompanyID" />
  </index>
  <index name="PRIMARY" clustered="true" primary="true" unique="true">
    <col name="AttributeID" />
    <col name="CompanyID" />
  </index>
</table>]]></CDATA>
</Sql>
</code>```

And the same table in case of MS SQL:

```<code>    <Sql TableName="csattribute" TableSchemaXml="#CDATA">
        <CDATA name="TableSchemaXml"><![CDATA[<table name="csattribute">
  <col name="CompanyID" type="Int" default="Zero" />
  <col name="AttributeID" type="NVarChar(30)" />
  <col name="Description" type="NVarChar(60)" />
  <col name="ControlType" type="Int" />
  <col name="EntryMask" type="VarChar(60)" nullable="true" />
  <col name="RegExp" type="NVarChar(60)" nullable="true" />
  <col name="List" type="NVarChar(MAX)" nullable="true" />
  <col name="IsInternal" type="Bit" nullable="true" />
  <col name="tstamp" type="Timestamp"/>
  <col name="CreatedByID" type="UniqueIdentifier" />
  <col name="CreatedByScreenID" type="Char(8)" />
  <col name="CreatedDateTime" type="DateTime" />
  <col name="LastModifiedByID" type="UniqueIdentifier" />
  <col name="LastModifiedByScreenID" type="Char(8)" />
  <col name="LastModifiedDateTime" type="DateTime" />
  <col name="NoteID" type="UniqueIdentifier" />
  <index name="CSAttribute_NoteID">
    <col name="NoteID" />
    <col name="CompanyID" />
  </index>
  <index name="CSAttribute_PK" clustered="true" primary="true" unique="true">
    <col name="CompanyID" />
    <col name="AttributeID" />
  </index>
</table>]]></CDATA>
    </Sql>
</code>```

答:
You can indicate if the script should run specifically for MySQL or MS SQL in a custom SQL script in your project if you use the following key words...

for a MySQL statement use the following:

```<code>--[mssql: Skip]
--[mysql: Native]
-- include your MySQL Code here...
</code>```

for a MS SQL statement use the following:

```<code>--[mssql: Native]
--[mysql: Skip]
-- include your MS SQL Code here...
</code>```

These sql script attributes are available in the help within an Acumatica site under:
Customization Guide > Managing Items in a Project > Database Scripts > To Add a Custom SQL Script to a Project (Public help article)

This information is based on 2017R2. You would have to test and confirm its use in 6.1.

Below is an example I currently use in 2017R2. Note the importance of needing to run the scripts in an order in 6.1 you might have to name the script something to make it run in a specific order (Ex: use "Upgrade..." to run last or "AUpgrade..." to run first). In 2017R2 you can set priority values which control the order of execution and even in the edit script window you have a "Specify Database Engine" button which will add the attributes for you.

Title: Acumatica Customization MS SQL MySql

Body:
We have faced the following problem.
We were developing customization package under system on MySQL database.
All the database changes were added to customization from Customization Page.

Now when we are publishing this customization under system on MS SQL database we are getting errors associated with the differences between MySQL and MS SQL.
I have reviewed the xml's which Acumatica is generating for database changes and there are some differences, for example:

timestamp is set to have default value when xml is generated from MySQL database.

Primary key constraint has name PRIMARY when xml is generated from MySQL.

How can we solve this problem so that we have not to have two different packages, one for MySQL and the other for MS SQL?

Here is how Acumatica Generates Script for CS Attribute in case of MySql:

  <Sql TableName="csattribute" TableSchemaXml="#CDATA">
  <CDATA name="TableSchemaXml"><![CDATA[

  <col name="CompanyID" type="Int" default="Zero" />
  <col name="AttributeID" type="NVarChar(30)" />
  <col name="Description" type="NVarChar(60)" />
  <col name="ControlType" type="Int" />
  <col name="EntryMask" type="VarChar(60)" nullable="true" />
  <col name="RegExp" type="NVarChar(60)" nullable="true" />
  <col name="List" type="NVarChar(MAX)" nullable="true" />
  <col name="IsInternal" type="Bit" nullable="true" />
  <col name="tstamp" type="Timestamp" default="CurrentDateTime" />
  <col name="CreatedByID" type="UniqueIdentifier" />
  <col name="CreatedByScreenID" type="Char(8)" />
  <col name="CreatedDateTime" type="DateTime" />
  <col name="LastModifiedByID" type="UniqueIdentifier" />
  <col name="LastModifiedByScreenID" type="Char(8)" />
  <col name="LastModifiedDateTime" type="DateTime" />
  <col name="NoteID" type="UniqueIdentifier" />
  <index name="CSAttribute_NoteID">
    <col name="NoteID" />
    <col name="CompanyID" />
  </index>
  <index name="PRIMARY" clustered="true" primary="true" unique="true">
    <col name="AttributeID" />
    <col name="CompanyID" />
  </index>

]]></CDATA>
</Sql>

And the same table in case of MS SQL:

    <Sql TableName="csattribute" TableSchemaXml="#CDATA">
        <CDATA name="TableSchemaXml"><![CDATA[

  <col name="CompanyID" type="Int" default="Zero" />
  <col name="AttributeID" type="NVarChar(30)" />
  <col name="Description" type="NVarChar(60)" />
  <col name="ControlType" type="Int" />
  <col name="EntryMask" type="VarChar(60)" nullable="true" />
  <col name="RegExp" type="NVarChar(60)" nullable="true" />
  <col name="List" type="NVarChar(MAX)" nullable="true" />
  <col name="IsInternal" type="Bit" nullable="true" />
  <col name="tstamp" type="Timestamp"/>
  <col name="CreatedByID" type="UniqueIdentifier" />
  <col name="CreatedByScreenID" type="Char(8)" />
  <col name="CreatedDateTime" type="DateTime" />
  <col name="LastModifiedByID" type="UniqueIdentifier" />
  <col name="LastModifiedByScreenID" type="Char(8)" />
  <col name="LastModifiedDateTime" type="DateTime" />
  <col name="NoteID" type="UniqueIdentifier" />
  <index name="CSAttribute_NoteID">
    <col name="NoteID" />
    <col name="CompanyID" />
  </index>
  <index name="CSAttribute_PK" clustered="true" primary="true" unique="true">
    <col name="CompanyID" />
    <col name="AttributeID" />
  </index>

]]></CDATA>
    </Sql>

Body:
You can indicate if the script should run specifically for MySQL or MS SQL in a custom SQL script in your project if you use the following key words...

for a MySQL statement use the following:

--[mssql: Skip]
--[mysql: Native]
-- include your MySQL Code here...

for a MS SQL statement use the following:

--[mssql: Native]
--[mysql: Skip]
-- include your MS SQL Code here...

These sql script attributes are available in the help within an Acumatica site under:
Customization Guide > Managing Items in a Project > Database Scripts > To Add a Custom SQL Script to a Project (Public help article)

This information is based on 2017R2. You would have to test and confirm its use in 6.1.

Below is an example I currently use in 2017R2. Note the importance of needing to run the scripts in an order in 6.1 you might have to name the script something to make it run in a specific order (Ex: use "Upgrade..." to run last or "AUpgrade..." to run first). In 2017R2 you can set priority values which control the order of execution and even in the edit script window you have a "Specify Database Engine" button which will add the attributes for you.


问:
awk : extracting a data which is on several lines
so I have a file that looks like this :

```<code>/translation="MDGVTQQNAALVQEATTAAASLEEQARNLTAAVAAFDLGDKQTV
                 LITPRAAVPALKRPALKASLPASSSHGNWETF"
                 /product="Methyl-accepting chemotaxis protein I (serine
                 chemoreceptor protein)"
 CDS             complement(471..590)
                 /db_xref="SEED:fig|1240086.14.peg.2"
                 /translation="MHQYQSAILAKICRYGGIEKPEITPASVYKLDSHWRYVI"
                 /product="hypothetical protein"
 CDS             717..2354
                 /db_xref="SEED:fig|1240086.14.peg.3"
                 /translation="MGFFVVLWGGASGFSLYSLKQVTTLLHDNSTQGRTYTYLVYGND
                 QYFRSVTRMARVMDYSQFSDAAIASLEEQAQQLTKAVEVFHLGSEYQTAAS
                 RTRPAGNMALKRPALSGMAPALPPARTASDEGSWEKF"
                 /product="Methyl-accepting chemotaxis protein I (serine
                 chemoreceptor protein)"
                 /product="macromolecule metabolism; macromolecule
                 degradation; degradation of proteins, peptides,
                 glycopeptides"
</code>```

I need to extract the text that is between quotes after a "/product=", so I need this :

```<code>Methyl-accepting chemotaxis protein I (serine chemoreceptor protein)
hypothetical protein
Methyl-accepting chemotaxis protein I (serine chemoreceptor protein)
macromolecule metabolism; macromolecule degradation; degradation of proteins, peptides, glycopeptides
</code>```

I have to use awk, so I wrote this :

```<code>awk '/\/product/ {split($0, a, "\""); printf a[2] "\n"}'
</code>```

but this only takes the info on the same line as "/product", and some times the info is on two or three lines.. I'm out of ideas as to how to get the entire info between the quotes, anyone can help?

答:
Awk solution:

```<code>awk -v RS='"' '!(NR%2) && f{ gsub(/[[:space:]]+/," "); print }
               /\/[[:alnum:]_-]+=$/{ f=(/product=/? 1:0) }' file
</code>```

-v RS='"' - treat double quote " as record separator

!(NR%2) - on each even line

gsub(/[[:space:]]+/," ") - remove extra whitespaces(s)

f=(/product=/? 1:0) - set the flag f in active state 1 on /product= ... lines

The output:

```<code>Methyl-accepting chemotaxis protein I (serine chemoreceptor protein)
hypothetical protein
Methyl-accepting chemotaxis protein I (serine chemoreceptor protein)
macromolecule metabolism; macromolecule degradation; degradation of proteins, peptides, glycopeptides
</code>```

Body:
so I have a file that looks like this :

/translation="MDGVTQQNAALVQEATTAAASLEEQARNLTAAVAAFDLGDKQTV
                 LITPRAAVPALKRPALKASLPASSSHGNWETF"
                 /product="Methyl-accepting chemotaxis protein I (serine
                 chemoreceptor protein)"
 CDS             complement(471..590)
                 /db_xref="SEED:fig|1240086.14.peg.2"
                 /translation="MHQYQSAILAKICRYGGIEKPEITPASVYKLDSHWRYVI"
                 /product="hypothetical protein"
 CDS             717..2354
                 /db_xref="SEED:fig|1240086.14.peg.3"
                 /translation="MGFFVVLWGGASGFSLYSLKQVTTLLHDNSTQGRTYTYLVYGND
                 QYFRSVTRMARVMDYSQFSDAAIASLEEQAQQLTKAVEVFHLGSEYQTAAS
                 RTRPAGNMALKRPALSGMAPALPPARTASDEGSWEKF"
                 /product="Methyl-accepting chemotaxis protein I (serine
                 chemoreceptor protein)"
                 /product="macromolecule metabolism; macromolecule
                 degradation; degradation of proteins, peptides,
                 glycopeptides"

I need to extract the text that is between quotes after a "/product=", so I need this :

Methyl-accepting chemotaxis protein I (serine chemoreceptor protein)
hypothetical protein
Methyl-accepting chemotaxis protein I (serine chemoreceptor protein)
macromolecule metabolism; macromolecule degradation; degradation of proteins, peptides, glycopeptides

I have to use awk, so I wrote this :

awk '/\/product/ {split($0, a, "\""); printf a[2] "\n"}'

but this only takes the info on the same line as "/product", and some times the info is on two or three lines.. I'm out of ideas as to how to get the entire info between the quotes, anyone can help?

Body:
Awk solution:

awk -v RS='"' '!(NR%2) && f{ gsub(/[[:space:]]+/," "); print }
               /\/[[:alnum:]_-]+=$/{ f=(/product=/? 1:0) }' file

-v RS='"' - treat double quote " as record separator

!(NR%2) - on each even line

gsub(/[[:space:]]+/," ") - remove extra whitespaces(s)

f=(/product=/? 1:0) - set the flag f in active state 1 on /product= ... lines

The output:

Methyl-accepting chemotaxis protein I (serine chemoreceptor protein)
hypothetical protein
Methyl-accepting chemotaxis protein I (serine chemoreceptor protein)
macromolecule metabolism; macromolecule degradation; degradation of proteins, peptides, glycopeptides


问:
Labelling with "factor" change variable values
I am currently moving from Stata to R, trying to do on R what I did on Stata, starting from scratch.
I imported raw data from Stata and had to dump my labels to avoid them overwriting the variable values, and I'm now trying to generate them back in R, as well as generating my dummy variables again from multilevel variables.

SO I did that:

```<code>newvar<-basevar
newvar<-mapvalues(newvar, c(1, 2, 3, 4, 5), c(1, 0, 0, 0, 0 ))

newvar <- factor(newvar,
                    levels = c(0,1),
                    labels = c("Bad", "Good"))

describe(newvar)
</code>```

This worked perfectly, and I got what I expected, a normal describe result with frequency and proportions, correctly labelled.

Then I realized my 0/1 values had been overwritten with 1 instead of 0 and 2 instead of 1.

Is that a normal part of how labelling works in R?
Is there a way to add labels while conserving the initial values of the variable?

I'm used to working with 0 and 1,  for coding efficiency (and since Stata tends to interpret 1/2 as numerical which added extra steps to go back to dummy variables, but since I set the variable as factor in R, I should not have this kind of problem), and labels to get perfectly understandable results (tables and graphs).

Should I learn to work differently with R?

答:
As far as I know, the first level of an factor is always represented with 1.
It is how R works.

In other functions such as lm() R treats the first level (1) as the reference and will make dummies in the background.

Small example:

```<code>set.seed(314)
newvar <- c(1, 0, 0, 0, 0 )
outcome <- newvar + rnorm(5)/5

newvar <- factor(newvar,
                 levels = c(0,1),
                 labels = c("Bad", "Good"))

summary(lm(outcome ~ newvar))
</code>```

result:

```<code>    Call:
  lm(formula = outcome ~ newvar)

Residuals:
  1        2        3        4        5
0.00000  0.17959 -0.13249 -0.10664  0.05954

Coefficients:
  Estimate Std. Error t value Pr(>|t|)
(Intercept) -0.03409    0.07344  -0.464   0.6741
newvarGood   0.77645    0.16422   4.728   0.0179 *
  ---
  Signif. codes:  0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1

Residual standard error: 0.1469 on 3 degrees of freedom
Multiple R-squared:  0.8817,    Adjusted R-squared:  0.8422
F-statistic: 22.36 on 1 and 3 DF,  p-value: 0.01793
</code>```

Body:
I am currently moving from Stata to R, trying to do on R what I did on Stata, starting from scratch.
I imported raw data from Stata and had to dump my labels to avoid them overwriting the variable values, and I'm now trying to generate them back in R, as well as generating my dummy variables again from multilevel variables.

SO I did that:

newvar<-basevar
newvar<-mapvalues(newvar, c(1, 2, 3, 4, 5), c(1, 0, 0, 0, 0 ))

newvar <- factor(newvar,
                    levels = c(0,1),
                    labels = c("Bad", "Good"))

describe(newvar)

This worked perfectly, and I got what I expected, a normal describe result with frequency and proportions, correctly labelled.

Then I realized my 0/1 values had been overwritten with 1 instead of 0 and 2 instead of 1.

Is that a normal part of how labelling works in R?
Is there a way to add labels while conserving the initial values of the variable?

I'm used to working with 0 and 1,  for coding efficiency (and since Stata tends to interpret 1/2 as numerical which added extra steps to go back to dummy variables, but since I set the variable as factor in R, I should not have this kind of problem), and labels to get perfectly understandable results (tables and graphs).

Should I learn to work differently with R?

Body:
As far as I know, the first level of an factor is always represented with 1.
It is how R works.

In other functions such as lm() R treats the first level (1) as the reference and will make dummies in the background.

Small example:

set.seed(314)
newvar <- c(1, 0, 0, 0, 0 )
outcome <- newvar + rnorm(5)/5

newvar <- factor(newvar,
                 levels = c(0,1),
                 labels = c("Bad", "Good"))

summary(lm(outcome ~ newvar))

result:

    Call:
  lm(formula = outcome ~ newvar)

Residuals:
  1        2        3        4        5
0.00000  0.17959 -0.13249 -0.10664  0.05954

Coefficients:
  Estimate Std. Error t value Pr(>|t|)
(Intercept) -0.03409    0.07344  -0.464   0.6741
newvarGood   0.77645    0.16422   4.728   0.0179 *
  ---
  Signif. codes:  0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1

Residual standard error: 0.1469 on 3 degrees of freedom
Multiple R-squared:  0.8817,    Adjusted R-squared:  0.8422
F-statistic: 22.36 on 1 and 3 DF,  p-value: 0.01793


问:
How to use caching in ASP.NET Boilerplate?
I have some master data in DB which I need throughout my application. So What is the best way to define this data in the application? and Where should I define in the application so that every time applications starts I will initialize this master data in my application. And Where should I define the method which will fetch data from DB?

```<code>using System.Linq;
using System.Threading.Tasks;
using Abp.Application.Services.Dto;
using Abp.Authorization;
using Abp.Runtime.Caching;
using Test.Authorization;
using Test.Caching.Dto;

namespace Test.Caching
{
    [AbpAuthorize(AppPermissions.Pages_Administration_Host_Maintenance)]
    public class CachingAppService : TestAppServiceBase, ICachingAppService
    {
        private readonly ICacheManager _cacheManager;

        public CachingAppService(ICacheManager cacheManager)
        {
            _cacheManager = cacheManager;
        }

        public ListResultDto<CacheDto> GetAllCaches()
        {
            var caches = _cacheManager.GetAllCaches()
                                        .Select(cache => new CacheDto
                                        {
                                            Name = cache.Name
                                        })
                                        .ToList();

            return new ListResultDto<CacheDto>(caches);
        }

        public async Task ClearCache(EntityDto<string> input)
        {
            var cache = _cacheManager.GetCache(input.Id);
            await cache.ClearAsync();
        }

        public async Task ClearAllCaches()
        {
            var caches = _cacheManager.GetAllCaches();
            foreach (var cache in caches)
            {
                await cache.ClearAsync();
            }
        }
    }
}
</code>```

Startup.cs code:

```<code>public IServiceProvider ConfigureServices(IServiceCollection services)
{
   services.AddMemoryCache();
}
</code>```

答:
This answer is based on the documentation for Entity Caching.

What is the best way to define this data in the application?

As a cache item:

[AutoMapFrom(typeof(Person))]
public class PersonCacheItem
{
    public string Name { get; set; }
}
```

<blockquote>
  <p>Where should I define in the application so that every time applications starts I will initialize this master data in my application? How to add my data to cache? Where do I need to add data to cache?</p>
</blockquote>

<p>You don't initialize the master data (nor add data to <code>IEntityCache</code>). It's lazy-loaded.</p>

<p><em>Default cache expire time is 60 minutes. It's sliding. So, if you don't use an item in the cache for 60 minutes, it's automatically removed from the cache. You can configure it for all caches or for a specific cache.</em></p>

<pre class="lang-cs prettyprint-override"><code>// Configuration for a specific cache
Configuration.Caching.Configure("MyCache", cache =>
{
    cache.DefaultSlidingExpireTime = TimeSpan.FromHours(8);
});
</code>```

This code should be placed PreInitialize method of your module.

Where should I define the method which will fetch data from DB?

You don't define the method. Just inject an IRepository. Specify cacheName if configured above.

public class PersonCache : EntityCache<Person, PersonCacheItem>, IPersonCache, ITransientDependency
{
    public PersonCache(ICacheManager cacheManager, IRepository<Person> repository)
        : base(cacheManager, repository, "MyCache") // "MyCache" is optional
    {
    }
}

public interface IPersonCache : IEntityCache<PersonCacheItem>
{
}
```

<blockquote>
  <p>How will I get data from cache?</p>
</blockquote>

<p><em>An example class that uses the Person cache:</em></p>

<pre class="lang-cs prettyprint-override"><code>public class MyPersonService : ITransientDependency
{
    private readonly IPersonCache _personCache;

    public MyPersonService(IPersonCache personCache)
    {
        _personCache = personCache;
    }

    public string GetPersonNameById(int id)
    {
        return _personCache[id].Name; // alternative: _personCache.Get(id).Name;
    }
}
</code>```

Body:
I have some master data in DB which I need throughout my application. So What is the best way to define this data in the application? and Where should I define in the application so that every time applications starts I will initialize this master data in my application. And Where should I define the method which will fetch data from DB?

using System.Linq;
using System.Threading.Tasks;
using Abp.Application.Services.Dto;
using Abp.Authorization;
using Abp.Runtime.Caching;
using Test.Authorization;
using Test.Caching.Dto;

namespace Test.Caching
{
    [AbpAuthorize(AppPermissions.Pages_Administration_Host_Maintenance)]
    public class CachingAppService : TestAppServiceBase, ICachingAppService
    {
        private readonly ICacheManager _cacheManager;

        public CachingAppService(ICacheManager cacheManager)
        {
            _cacheManager = cacheManager;
        }

        public ListResultDto<CacheDto> GetAllCaches()
        {
            var caches = _cacheManager.GetAllCaches()
                                        .Select(cache => new CacheDto
                                        {
                                            Name = cache.Name
                                        })
                                        .ToList();

            return new ListResultDto<CacheDto>(caches);
        }

        public async Task ClearCache(EntityDto<string> input)
        {
            var cache = _cacheManager.GetCache(input.Id);
            await cache.ClearAsync();
        }

        public async Task ClearAllCaches()
        {
            var caches = _cacheManager.GetAllCaches();
            foreach (var cache in caches)
            {
                await cache.ClearAsync();
            }
        }
    }
}

Startup.cs code:

public IServiceProvider ConfigureServices(IServiceCollection services)
{
   services.AddMemoryCache();
}

Body:
This answer is based on the documentation for Entity Caching.

What is the best way to define this data in the application?

As a cache item:

[AutoMapFrom(typeof(Person))]
public class PersonCacheItem
{
    public string Name { get; set; }
}

Where should I define in the application so that every time applications starts I will initialize this master data in my application? How to add my data to cache? Where do I need to add data to cache?

You don't initialize the master data (nor add data to IEntityCache). It's lazy-loaded.

Default cache expire time is 60 minutes. It's sliding. So, if you don't use an item in the cache for 60 minutes, it's automatically removed from the cache. You can configure it for all caches or for a specific cache.

// Configuration for a specific cache
Configuration.Caching.Configure("MyCache", cache =>
{
    cache.DefaultSlidingExpireTime = TimeSpan.FromHours(8);
});

This code should be placed PreInitialize method of your module.

Where should I define the method which will fetch data from DB?

You don't define the method. Just inject an IRepository. Specify cacheName if configured above.

public class PersonCache : EntityCache<Person, PersonCacheItem>, IPersonCache, ITransientDependency
{
    public PersonCache(ICacheManager cacheManager, IRepository<Person> repository)
        : base(cacheManager, repository, "MyCache") // "MyCache" is optional
    {
    }
}

public interface IPersonCache : IEntityCache<PersonCacheItem>
{
}

How will I get data from cache?

An example class that uses the Person cache:

public class MyPersonService : ITransientDependency
{
    private readonly IPersonCache _personCache;

    public MyPersonService(IPersonCache personCache)
    {
        _personCache = personCache;
    }

    public string GetPersonNameById(int id)
    {
        return _personCache[id].Name; // alternative: _personCache.Get(id).Name;
    }
}


问:
How can I rotate a 3D array?
Currently, if I want to compare pressure under each of the paws of a dog, I only compare the pressure underneath each of the toes. But I want to try and compare the pressures underneath the entire paw.

But to do so I have to rotate them, so the toes overlap (better). Because most of the times the left and right paws are slightly rotated externally, so if you can't simply project one on top of the other. Therefore, I want to rotate the paws, so they are all aligned the same way.

Currently, I calculate the angle of rotation, by looking up the two middle toes and the rear one using the toe detection then I calculate the the angle between the yellow line (axis between toe green and red) and the green line (neutral axis).

Now I want to rotate the array would rotate around the rear toe, such that the yellow and green lines are aligned. But how do I do this?

Note that while this image is just 2D (only the maximal values of each sensor), I want to calculate this on a 3D array (10x10x50 on average). Also a downside of my angle calculation is that its very sensitive to the toe detection, so if somebody has a more mathematically correct proposal for calculating this, I'm all ears.

I have seen one study with pressure measurements on humans, where they used the local geometric inertial axis method, which at least was very reliable. But that still doesn't help me explain how to rotate the array!

 If someone feels the need to experiment, here's a file with all the sliced arrays that contain the pressure data of each paw. To clarfiy: walk_sliced_data is a dictionary that contains ['ser_3', 'ser_2', 'sel_1', 'sel_2', 'ser_1', 'sel_3'], which are the names of the measurements. Each measurement contains another dictionary, [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10] (example from 'sel_1') which represent the impacts that were extracted.

答:
Why would you do it that way? Why not simply integrate the whole region and compare? In this case you'll get a magnitude of the force and you can simply compare scalars which would be much easier.

If you need to somehow compare regions(and hence that's why you need to align them) then maybe attempt a feature extraction and alignment. But this would seem to fail if the pressure maps are not similar(say someone is not putting much wait on one foot).

I suppose you can get really complex but it sounds like simply calculating the force is what you want?

BTW, you can use a simple correlation test to find the optimal angle and translation if the images are similar.

To do this you simply compute the correlation between the two different images for various translations and rotations.

Title: How can I rotate a 3D array?


问:
Mercurial - cannot commit merge with missing files error
I have done a 'hg merge' however when I attempt to do a 'hg commit -m "my msg.." I get the following error message :

```<code>abort: cannot commit merge with missing files
</code>```

Can anyone explain how to fix this to allow the commit go through?

答:
If you are using TortoiseHG, click in View/Commit. It will show you files in state ! (missing).

Right click on the file and choose Revert (undelete the file) and commit.

Body:
I have done a 'hg merge' however when I attempt to do a 'hg commit -m "my msg.." I get the following error message :

abort: cannot commit merge with missing files

Can anyone explain how to fix this to allow the commit go through?


问:
Place an image/icon in the upper right corner of a div
I would like to place an image in the upper right corner of a div that always stays in that place and always moves (at different viewport sizes).

Here is the current status of my less code and the associated HTML:

LESS:

```<code>.selling,
.price,
.cta {
    float: left;
    width: 33.33%; min-height: @height;
    padding: 0 1%;
    .font-size(18px);

    & > div,
    & > a {
        // min-height: @height;
        height: @height;
        padding: 14px 22px;
        background-color: @black;
        color: #fff;
    }

    &.rabattaktion {
        div::after {
            position: absolute; z-index: 1;
            width: 68px; height: 65px;
            background: transparent url('../img/santa_hat.png') center top no-repeat;
            content: "";
            margin-top: -170px;
            margin-left: 351px;
            }
            div:hover:before { z-index: 4; }
        }
}
</code>```

HTML:

```<code><div class="offer">
   ...
    <div class="price sh <?php if($entry->field('rabattaktion')->value()): ?> rabattaktion<?php endif ?>">
        <div>
            <h3>Gesamtpreis:</h3>
            <p><span><?php echo $new_price_formatted; ?> € *</span></p>
            <?php if(isset($rate)): ?>
               <p>
                    <b>Ratenzahlung:</b>
            <?php echo $raten; ?> Monatsraten á <?php echo $rate_formatted; ?> € *
                </p>
            <?php endif; ?>
        </div>
    </div>
    ...
</div>
</code>```

In this way I get the picture in the upper right corner. But as soon as the viewport size changes, the position is no longer correct.

What am I doing wrong?

答:
You'll need to set position: relative on the container, this tells the absolute positioned child what to position itself against.

On the child, you can get rid of the margin-left and margin-top values and position it with top and right

```<code>.parent {
  position: relative;
}
.child {
  position: absolute;
  top: 0;
  right: 0;
}
</code>```

Body:
I would like to place an image in the upper right corner of a div that always stays in that place and always moves (at different viewport sizes).

Here is the current status of my less code and the associated HTML:

LESS:

.selling,
.price,
.cta {
    float: left;
    width: 33.33%; min-height: @height;
    padding: 0 1%;
    .font-size(18px);

    & > div,
    & > a {
        // min-height: @height;
        height: @height;
        padding: 14px 22px;
        background-color: @black;
        color: #fff;
    }

    &.rabattaktion {
        div::after {
            position: absolute; z-index: 1;
            width: 68px; height: 65px;
            background: transparent url('../img/santa_hat.png') center top no-repeat;
            content: "";
            margin-top: -170px;
            margin-left: 351px;
            }
            div:hover:before { z-index: 4; }
        }
}

HTML:

   ...
    <div class="price sh <?php if($entry->field('rabattaktion')->value()): ?> rabattaktion<?php endif ?>">

Gesamtpreis:

<?php echo $new_price_formatted; ?> € *

            <?php if(isset($rate)): ?>

                    Ratenzahlung:
            <?php echo $raten; ?> Monatsraten á <?php echo $rate_formatted; ?> € *

            <?php endif; ?>

    ...

In this way I get the picture in the upper right corner. But as soon as the viewport size changes, the position is no longer correct.

What am I doing wrong?

Body:
You'll need to set position: relative on the container, this tells the absolute positioned child what to position itself against.

On the child, you can get rid of the margin-left and margin-top values and position it with top and right

.parent {
  position: relative;
}
.child {
  position: absolute;
  top: 0;
  right: 0;
}


问:
How to update customer data faster and more efficiently

I am writing a script to add values to a custom attribute for 10 thousand customers. I have two questions here.

when we update custom attribute values for product, we can use:

```<code>$resource = $product->getResource();
$product->setData($attribute, $value);
$resource->saveAttribute($product,$attribute);
</code>```

which is very fast. But as for customer, it does not have getResource() method. The only way I know is: $this->_customerRepository->save($customer); which is very very slow. so how can I update the customers values faster?

when I update these values in bulk, I wrote the script as followings, it was running fine at the first hundreds of customers data updating, but then throws exception:

```<code>(/chroot/home/.../html/vendor/magento/framework/Exception/FileSystemException.php): failed to open stream: Too many open files in /chroot/home/.../html/vendor/composer/ClassLoader.php on line 444
</code>```

I Googled this problem and someone says it is relevant to the settings of sever. However, since we rent the server and have no authorization to change it, how should I modify my code and make it use less resources?

```<code>protected function updateAttributes($customersListData,$output) {
  $time_start = microtime(true);
  $totalLength = sizeof($customersListData);
  foreach ($customersListData as $customerIndex => $singleCustomerData) {
    try {
      $id = $singleCustomerData['id'];
      $customer = $this->_customerRepository->getById($id);

      $arrayKeys = array_keys($singleCustomerData);
      array_shift($arrayKeys);
      foreach ($arrayKeys as $singleKey) {
        if (empty($singleCustomerData[$singleKey])) {
          $singleCustomerData[$singleKey] = "";
        }
        $time_now = microtime(true);
        $time_used = $time_now - $time_start;
        $finished_records = (int)$customerIndex + 1;
        $output->writeln("Updating attribute: ".$singleCustomerData[$singleKey].". " .$finished_records ."/".$totalLength." done. will finsih in: ". round($time_used / $finished_records * ($totalLength - $finished_records), 0). "s.");
        $customer->setData($singleKey, $singleCustomerData[$singleKey]);
      }
      $this->_customerRepository->save($customer);
      unset($customer);
    } catch (\Exception $e) {
      $output->writeln($e->getMessage());
      continue;
    }
  }
}
</code>```

答:
get All Customers before the "foreach" into a variable as array

afterwards, you can pick your customer from the array instead of the repository

make a $toUpdate[] array, where you put all your $customer objects

at the end, outside of the foreach, you can bulk save all customers.

in this case you have 2 Database requests per iteration in the foreach. this is like 20'000 requests within a minute or somewhat.

Here an idea in pseudo-code:

```<code>$allCustomers = $this->_customerRepository()->getAll();
$bulkSave[];

foreach($customersListData as $customerIndex => $singleCustomerData)
{
    $myCustomer = $allCustomers->find($singleCustomerData['id']);
    $bulkSave[] = $myCustomer;
}

$this->_customerRepository()->save($bulkSave);
</code>```

Body:
I am writing a script to add values to a custom attribute for 10 thousand customers. I have two questions here.

when we update custom attribute values for product, we can use:

$resource = $product->getResource();
$product->setData($attribute, $value);
$resource->saveAttribute($product,$attribute);

which is very fast. But as for customer, it does not have getResource() method. The only way I know is: $this->_customerRepository->save($customer); which is very very slow. so how can I update the customers values faster?

when I update these values in bulk, I wrote the script as followings, it was running fine at the first hundreds of customers data updating, but then throws exception:

(/chroot/home/.../html/vendor/magento/framework/Exception/FileSystemException.php): failed to open stream: Too many open files in /chroot/home/.../html/vendor/composer/ClassLoader.php on line 444

I Googled this problem and someone says it is relevant to the settings of sever. However, since we rent the server and have no authorization to change it, how should I modify my code and make it use less resources?

protected function updateAttributes($customersListData,$output) {
  $time_start = microtime(true);
  $totalLength = sizeof($customersListData);
  foreach ($customersListData as $customerIndex => $singleCustomerData) {
    try {
      $id = $singleCustomerData['id'];
      $customer = $this->_customerRepository->getById($id);

      $arrayKeys = array_keys($singleCustomerData);
      array_shift($arrayKeys);
      foreach ($arrayKeys as $singleKey) {
        if (empty($singleCustomerData[$singleKey])) {
          $singleCustomerData[$singleKey] = "";
        }
        $time_now = microtime(true);
        $time_used = $time_now - $time_start;
        $finished_records = (int)$customerIndex + 1;
        $output->writeln("Updating attribute: ".$singleCustomerData[$singleKey].". " .$finished_records ."/".$totalLength." done. will finsih in: ". round($time_used / $finished_records * ($totalLength - $finished_records), 0). "s.");
        $customer->setData($singleKey, $singleCustomerData[$singleKey]);
      }
      $this->_customerRepository->save($customer);
      unset($customer);
    } catch (\Exception $e) {
      $output->writeln($e->getMessage());
      continue;
    }
  }
}

Body:
get All Customers before the "foreach" into a variable as array

afterwards, you can pick your customer from the array instead of the repository

make a $toUpdate[] array, where you put all your $customer objects

at the end, outside of the foreach, you can bulk save all customers.

in this case you have 2 Database requests per iteration in the foreach. this is like 20'000 requests within a minute or somewhat.

Here an idea in pseudo-code:

$allCustomers = $this->_customerRepository()->getAll();
$bulkSave[];

foreach($customersListData as $customerIndex => $singleCustomerData)
{
    $myCustomer = $allCustomers->find($singleCustomerData['id']);
    $bulkSave[] = $myCustomer;
}

$this->_customerRepository()->save($bulkSave);


问:
create restful apis with Event driven architecture node js?
Hi I'm a newbie in nodejs as far as I'm concerned nodejs is event-driven which is a powerful feature in it.

I have been learning nodejs from last few days and try to build restful apis in it with mongodb, but I'm not able to use its event-driven architecture in apis below is my sudo code

```<code>//routes

   app.get('/someUrl', SomeClass.executeSomeController);

//controller

  class SomeClass {
    async executeSomeController(req, res){
       let response = awaitSomeHelper.executeQueryAndBusinessLogic(req.body);
       res.send(response)
  }

}
</code>```

As per my understanding I have written normal code as I used to write using Ror or PHP The only difference I found that the controller is running asynchronous which does not happens in Ror or Php.

How can I use event-driven architecture to build  restful apis

答:
Hope I can cover your question. Basically in some cases 'event-driven architecture' term can be explained differently. In one case it's a basic core NodeJS flow that explains all the async functions. In another case, the root of the question can be related to events, event emitter etc.

But the main idea that you have to wait for all the asynchronous actions. In order to avoid thread blocking it goes further and handles the rest of your code without waiting for heavy requests. And there we have to know how to handle this async functionality.

Basic Async Flow

As I understand, you've got questions related to async operations in NodeJS. That's a root of the technology - all the heavy operations will be handled asynchronously. It's all about V8 and Event Loop.

So in order to work with asynchronous operations, you may use callback functions, promises or async-await syntax.

Callback Functions

```<code>function asyncFunction(params, callback) {
  //do async stuff
  callback(err, result);
}

function callbackFunction(err, result) {

}

asyncFunction(params, callbackFunction);
</code>```

Promises

```<code>promiseFunction()
  .then(anotherPromiseFunction)
  .then((result) => {
    //handle result
  })
  .catch((err) => {
    //handle error
  });
</code>```

async-await

```<code>function anotherAsyncFunction() {
  //do async stuff
}

const asycnFunction = async (params) => {
  const result = await anotherAsyncFunction();
  return result;
};
</code>```

Events/Event Emitter

```<code>const fs = require('fs');

const filePath = './path/to/your/file';
const stream = fs.createReadStream(filePath);

stream.on('data', (data) => {
  //do something
});

stream.on('end', () => {
  //do something;
});

stream.on('error', (err) => {
  //do something;
});
</code>```

You may use these methods depends on the situation and your needs. I recommend skipping callback functions as we have modern ways to work in async flow (promises and async-await). By the way, 'async-await' returns promises as well.

Here is the example of a simple Express JS Server (pretty old syntax), but still valid. Please feel free to check and write questions:

https://github.com/roman-sachenko/express-entity-based

Here is a list of articles I'd recommend you:

https://blog.risingstack.com/node-js-at-scale-understanding-node-js-event-loop/
https://blog.risingstack.com/mastering-async-await-in-nodejs/

Body:
Hi I'm a newbie in nodejs as far as I'm concerned nodejs is event-driven which is a powerful feature in it.

I have been learning nodejs from last few days and try to build restful apis in it with mongodb, but I'm not able to use its event-driven architecture in apis below is my sudo code

//routes

   app.get('/someUrl', SomeClass.executeSomeController);

//controller

  class SomeClass {
    async executeSomeController(req, res){
       let response = awaitSomeHelper.executeQueryAndBusinessLogic(req.body);
       res.send(response)
  }

}

As per my understanding I have written normal code as I used to write using Ror or PHP The only difference I found that the controller is running asynchronous which does not happens in Ror or Php.

How can I use event-driven architecture to build  restful apis

Body:
Hope I can cover your question. Basically in some cases 'event-driven architecture' term can be explained differently. In one case it's a basic core NodeJS flow that explains all the async functions. In another case, the root of the question can be related to events, event emitter etc.

But the main idea that you have to wait for all the asynchronous actions. In order to avoid thread blocking it goes further and handles the rest of your code without waiting for heavy requests. And there we have to know how to handle this async functionality.

Basic Async Flow

As I understand, you've got questions related to async operations in NodeJS. That's a root of the technology - all the heavy operations will be handled asynchronously. It's all about V8 and Event Loop.

So in order to work with asynchronous operations, you may use callback functions, promises or async-await syntax.

Callback Functions

function asyncFunction(params, callback) {
  //do async stuff
  callback(err, result);
}

function callbackFunction(err, result) {

}

asyncFunction(params, callbackFunction);

Promises

promiseFunction()
  .then(anotherPromiseFunction)
  .then((result) => {
    //handle result
  })
  .catch((err) => {
    //handle error
  });

async-await

function anotherAsyncFunction() {
  //do async stuff
}

const asycnFunction = async (params) => {
  const result = await anotherAsyncFunction();
  return result;
};

Events/Event Emitter

const fs = require('fs');

const filePath = './path/to/your/file';
const stream = fs.createReadStream(filePath);

stream.on('data', (data) => {
  //do something
});

stream.on('end', () => {
  //do something;
});

stream.on('error', (err) => {
  //do something;
});

You may use these methods depends on the situation and your needs. I recommend skipping callback functions as we have modern ways to work in async flow (promises and async-await). By the way, 'async-await' returns promises as well.

Here is the example of a simple Express JS Server (pretty old syntax), but still valid. Please feel free to check and write questions:

https://github.com/roman-sachenko/express-entity-based

Here is a list of articles I'd recommend you:

https://blog.risingstack.com/node-js-at-scale-understanding-node-js-event-loop/
https://blog.risingstack.com/mastering-async-await-in-nodejs/


问:
github pages Can't find variable: $
I just created a SPA using github pages.
It is pretty clear, as contains one .html with two .js files
I mostly use d3.js

I have no problem launching on local host, but have problems, when I deployed it on github pages

I have two errors:

Can't find variable: $

and

Failed to load resource: the server responded with a status of 404
  (HTTP/2.0 404)

Although in my index.html contains jquery

```<code><script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script type="text/javascript" src="script.js"></script>
</code>```

https://zkid18.github.io/data_visualization_project/
https://github.com/zkid18/data_visualization_project
What's wrong?

答:
If you open up the dev tool console on that link you've shared, here's the error:

```<code>Mixed Content: The page at 'https://zkid18.github.io/data_visualization_project/' was loaded over HTTPS, but requested an insecure script 'http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js'.

This request has been blocked; the content must be served over HTTPS.
</code>```

So in this case, the solution is to just load your external resources over HTTPS, because this is what GitHub is hosted on. For example:

```<code><script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
</code>```

If a page is loaded over HTTPS then every resource it uses should also be loaded over HTTPS.

Reason behind this is, that otherwise a man-in-the-middle could replace resources (or ones that exploit buffer overflow issues in browsers to execute code) and scripts with ones that do different things (such as leak data to the third party).

You can read more about this in this article on the Mozilla site.

Title: github pages Can't find variable: $

Body:
I just created a SPA using github pages.
It is pretty clear, as contains one .html with two .js files
I mostly use d3.js

I have no problem launching on local host, but have problems, when I deployed it on github pages

I have two errors:

Can't find variable: $

and

Failed to load resource: the server responded with a status of 404
  (HTTP/2.0 404)

Although in my index.html contains jquery

https://zkid18.github.io/data_visualization_project/
https://github.com/zkid18/data_visualization_project
What's wrong?

Body:
If you open up the dev tool console on that link you've shared, here's the error:

Mixed Content: The page at 'https://zkid18.github.io/data_visualization_project/' was loaded over HTTPS, but requested an insecure script 'http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js'.

This request has been blocked; the content must be served over HTTPS.

So in this case, the solution is to just load your external resources over HTTPS, because this is what GitHub is hosted on. For example:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

If a page is loaded over HTTPS then every resource it uses should also be loaded over HTTPS.

Reason behind this is, that otherwise a man-in-the-middle could replace resources (or ones that exploit buffer overflow issues in browsers to execute code) and scripts with ones that do different things (such as leak data to the third party).

You can read more about this in this article on the Mozilla site.