问:
COMMTIMEOUT and Thread not timming out on serial port Read function
I am calling a function that operates an I/o board through a serial port to check that it is communicating in an instance of my main class.

I know that this is risky but unfortunately this is an old section of code that has been used for a while so I am unable to alter the functionality while I have been asked to improve it.

If there is no communication issue the application will start up, use the function and continue with no issue.

The problem arises when there is a communication fault with the I/o board, I have found that the read function is hanging and stopping the app from starting for the majority of the time. On occasion the app will load and will report that there is a communication fault.

What I am trying to achieve is for the application to load successfully every time when there is a communication fault.

The comport is set up with COMMTIMEOUTs originally which I expected would timeout the port when there has been nothing to read. I have attempted to alter the timings but with no avail.

I have also attempted to use a thread for the read function so that it would not block the start up but still it hangs.

Currently the port is set up synchronously.

Has anybody got any suggestions? I can put some code examples up if required.

Main.cpp

```<code>extern COMPort comPort;
BOOL Main::InitInstance()
{
 int i = comPort.DoorLatchOff();
 If(i<0) printf("Error checksum. COM port?\n");
 else printf("checksum ok.\n");
}
</code>```

COMPort.h

```<code>class CCOMPort
{
  public:
   CCOMPort (COM_PORT port = NULL_COM, DCB * state = NULL);
   BOOL SetPortNumber (COM_PORT port = NULL_COM, DCB * state = NULL);
   void Read(BYTE* buff, int count);
   int DoorLatchOff(void);
  protected:
   HANDLE    m_hPort;
};
static HANDLE    m_hPortThreaded;
typedef struct readParam{BYTE* readBuff;int readCount;}RP, *PRP;

DWORD WINAPI ThreadedRead( LPVOID lpParam );
</code>```

COMPort.cpp

```<code>CCOMPort::CCOMPort (COM_PORT port, DCB * state) : m_portNum (port), m_hPort(INVALID_HANDLE_VALUE)
{
 SetPortNumber (port, state);
}
BOOL CCOMPort::SetPortNumber (COM_PORT port, DCB * state)
{
  if (m_hPort != INVALID_HANDLE_VALUE){
    ::CloseHandle (m_hPort);
    m_hPort = INVALID_HANDLE_VALUE;
  }

   m_portNum     = port;
   m_currState   = m_defState;
   m_originState = m_defState;

  if (m_portNum != NULL_COM){
  stringstream ssPortName;
  ssPortName << "COM" << (m_portNum + 1) << ":" << flush;

  m_hPort = ::CreateFile (ssPortName.str().c_str(),
                         GENERIC_READ | GENERIC_WRITE,
                         FILE_SHARE_READ | FILE_SHARE_WRITE,
                          NULL,
                          OPEN_EXISTING,
                          FILE_ATTRIBUTE_NORMAL | FILE_FLAG_WRITE_THROUGH,
                          NULL);

  if (m_hPort == INVALID_HANDLE_VALUE)
    return FALSE;
  else
    {
      GetState (& m_originState);

     if (state)
      m_currState = * state;
     SetState (& m_currState);

     GetCommTimeouts(m_hPort, &timeouts);

     timeouts.ReadIntervalTimeout = 75; //15
     timeouts.ReadTotalTimeoutMultiplier = 5;       //1
     timeouts.ReadTotalTimeoutConstant = 1250;      //250
     timeouts.WriteTotalTimeoutMultiplier = 5;      //1
     timeouts.WriteTotalTimeoutConstant = 1250;     //250
     SetCommTimeouts(m_hPort, &timeouts);
     FlushOutput ();
     FlushInput ();
     PurgeOutput ();
     PurgeInput ();
    }
  }

  return TRUE;
}
void CCOMPort::Read(BYTE* buff, int count)
{
  PRP pReadArray[1];
  DWORD dwThreadArray[1];
  HANDLE hThreadArray[1];
  m_hPortThreaded = m_hPort;

  pReadArray[0] = (PRP) HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(RP));

  if(pReadArray[0] == NULL){
    ExitProcess(2);
  }

  pReadArray[0]->readBuff = buff;
  pReadArray[0]->readCount = count;
  hThreadArray[0] = CreateThread(NULL,
                                    0,
                         ThreadedRead,
                        pReadArray[0],
                                    0,
                   &dwThreadArray[0]);

  if(hThreadArray[0] == NULL){
    ExitProcess(3);
  }

  WaitForSingleObject(hThreadArray[0],500/*INFINITE*/);
  CloseHandle(hThreadArray[0]);

  if(pReadArray[0] != NULL){
    HeapFree(GetProcessHeap(), 0, pReadArray[0]);
    pReadArray[0] = NULL;
  }
}

DWORD WINAPI ThreadedRead(LPVOID lpParam)
{
  BOOL bDone = FALSE, bResult;
  //int buff_idx = 0;
  DWORD dwCommModemStatus;
  DWORD dwBytesTransfered;

  PRP pReadArray;
  pReadArray = (PRP)lpParam;
  SetCommMask(m_hPortThreaded, EV_RXCHAR);
  while(!bDone){
    WaitCommEvent(m_hPortThreaded, &dwCommModemStatus, 0);
    if(dwCommModemStatus == 0){
    bDone = TRUE;
    break;
    }
    if(dwCommModemStatus & EV_RXCHAR){
      bResult = ReadFile(m_hPortThreaded, pReadArray[0].readBuff, pReadArray[0].readCount, &dwBytesTransfered, 0);
      bDone = TRUE;
    }
  }
  return(bResult);

}
int COMPort::DoorLatchOff(void)
{
  unsigned char comm_str[10];
  int chksum, chksum1;
  DWORD count = 6;

  WriteComm(21, 7, 0);
  comm.Read(comm_str, count);

  chksum = comm_str[0] + comm_str[2] + comm_str[3];
  chksum1 = comm_str[4];
  chksum1 = (chksum1 << 8) | comm_str[5];

  if(chksum == chksum1)
   return(0);
  else
   return(-1);
}
</code>```

答:
When dealing with hw I/O it is a best practice to decouple the Application (GUI) thread from the command-execution thread.

If you are developing a C++ Win32 app you could use SerialLib. It is an old but stable Win32 event-driven serial library.

Body:
I am calling a function that operates an I/o board through a serial port to check that it is communicating in an instance of my main class.

I know that this is risky but unfortunately this is an old section of code that has been used for a while so I am unable to alter the functionality while I have been asked to improve it.

If there is no communication issue the application will start up, use the function and continue with no issue.

The problem arises when there is a communication fault with the I/o board, I have found that the read function is hanging and stopping the app from starting for the majority of the time. On occasion the app will load and will report that there is a communication fault.

What I am trying to achieve is for the application to load successfully every time when there is a communication fault.

The comport is set up with COMMTIMEOUTs originally which I expected would timeout the port when there has been nothing to read. I have attempted to alter the timings but with no avail.

I have also attempted to use a thread for the read function so that it would not block the start up but still it hangs.

Currently the port is set up synchronously.

Has anybody got any suggestions? I can put some code examples up if required.

Main.cpp

extern COMPort comPort;
BOOL Main::InitInstance()
{
 int i = comPort.DoorLatchOff();
 If(i<0) printf("Error checksum. COM port?\n");
 else printf("checksum ok.\n");
}

COMPort.h

class CCOMPort
{
  public:
   CCOMPort (COM_PORT port = NULL_COM, DCB * state = NULL);
   BOOL SetPortNumber (COM_PORT port = NULL_COM, DCB * state = NULL);
   void Read(BYTE* buff, int count);
   int DoorLatchOff(void);
  protected:
   HANDLE    m_hPort;
};
static HANDLE    m_hPortThreaded;
typedef struct readParam{BYTE* readBuff;int readCount;}RP, *PRP;

DWORD WINAPI ThreadedRead( LPVOID lpParam );

COMPort.cpp

CCOMPort::CCOMPort (COM_PORT port, DCB * state) : m_portNum (port), m_hPort(INVALID_HANDLE_VALUE)
{
 SetPortNumber (port, state);
}
BOOL CCOMPort::SetPortNumber (COM_PORT port, DCB * state)
{
  if (m_hPort != INVALID_HANDLE_VALUE){
    ::CloseHandle (m_hPort);
    m_hPort = INVALID_HANDLE_VALUE;
  }

   m_portNum     = port;
   m_currState   = m_defState;
   m_originState = m_defState;

  if (m_portNum != NULL_COM){
  stringstream ssPortName;
  ssPortName << "COM" << (m_portNum + 1) << ":" << flush;

  m_hPort = ::CreateFile (ssPortName.str().c_str(),
                         GENERIC_READ | GENERIC_WRITE,
                         FILE_SHARE_READ | FILE_SHARE_WRITE,
                          NULL,
                          OPEN_EXISTING,
                          FILE_ATTRIBUTE_NORMAL | FILE_FLAG_WRITE_THROUGH,
                          NULL);

  if (m_hPort == INVALID_HANDLE_VALUE)
    return FALSE;
  else
    {
      GetState (& m_originState);

     if (state)
      m_currState = * state;
     SetState (& m_currState);

     GetCommTimeouts(m_hPort, &timeouts);

     timeouts.ReadIntervalTimeout = 75; //15
     timeouts.ReadTotalTimeoutMultiplier = 5;       //1
     timeouts.ReadTotalTimeoutConstant = 1250;      //250
     timeouts.WriteTotalTimeoutMultiplier = 5;      //1
     timeouts.WriteTotalTimeoutConstant = 1250;     //250
     SetCommTimeouts(m_hPort, &timeouts);
     FlushOutput ();
     FlushInput ();
     PurgeOutput ();
     PurgeInput ();
    }
  }

  return TRUE;
}
void CCOMPort::Read(BYTE* buff, int count)
{
  PRP pReadArray[1];
  DWORD dwThreadArray[1];
  HANDLE hThreadArray[1];
  m_hPortThreaded = m_hPort;

  pReadArray[0] = (PRP) HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(RP));

  if(pReadArray[0] == NULL){
    ExitProcess(2);
  }

  pReadArray[0]->readBuff = buff;
  pReadArray[0]->readCount = count;
  hThreadArray[0] = CreateThread(NULL,
                                    0,
                         ThreadedRead,
                        pReadArray[0],
                                    0,
                   &dwThreadArray[0]);

  if(hThreadArray[0] == NULL){
    ExitProcess(3);
  }

  WaitForSingleObject(hThreadArray[0],500/*INFINITE*/);
  CloseHandle(hThreadArray[0]);

  if(pReadArray[0] != NULL){
    HeapFree(GetProcessHeap(), 0, pReadArray[0]);
    pReadArray[0] = NULL;
  }
}

DWORD WINAPI ThreadedRead(LPVOID lpParam)
{
  BOOL bDone = FALSE, bResult;
  //int buff_idx = 0;
  DWORD dwCommModemStatus;
  DWORD dwBytesTransfered;

  PRP pReadArray;
  pReadArray = (PRP)lpParam;
  SetCommMask(m_hPortThreaded, EV_RXCHAR);
  while(!bDone){
    WaitCommEvent(m_hPortThreaded, &dwCommModemStatus, 0);
    if(dwCommModemStatus == 0){
    bDone = TRUE;
    break;
    }
    if(dwCommModemStatus & EV_RXCHAR){
      bResult = ReadFile(m_hPortThreaded, pReadArray[0].readBuff, pReadArray[0].readCount, &dwBytesTransfered, 0);
      bDone = TRUE;
    }
  }
  return(bResult);

}
int COMPort::DoorLatchOff(void)
{
  unsigned char comm_str[10];
  int chksum, chksum1;
  DWORD count = 6;

  WriteComm(21, 7, 0);
  comm.Read(comm_str, count);

  chksum = comm_str[0] + comm_str[2] + comm_str[3];
  chksum1 = comm_str[4];
  chksum1 = (chksum1 << 8) | comm_str[5];

  if(chksum == chksum1)
   return(0);
  else
   return(-1);
}


来源: stackexchange

问:
Should nuget .props and .targets files be part of the source code repository?
Those files are created during package restore that's why I assume they don't have to be in the repository. Is there further documentation of the purpose of those files which might help to answer the question?</p>

答:
For a .NET Core project the nuget.g.targets and nuget.g.props are generated by a NuGet restore. They are created in the obj folder. So you do not need to have these in version control. Typically files in the obj folder are not included in version control.

Visual Studio will automatically restore these files on opening a solution if they are missing.

If you are using a build server then you can run dotnet restore to restore these files. MSBuild 15 when installed with Visual Studio 2017 can also be used to restore these files by running msbuild /t:Restore for the solution.

The nuget.g.targets and nuget.g.props files define various properties, such as the path to where the packages cache is on your machine. They also include any MSBuild imports that NuGet packages referenced by your project need.

For example, if you have the Microsoft.Net.Test.Sdk NuGet package referenced, the nuget.g.targets and nuget.g.props import MSBuild files that are included in that NuGet package. When using a packages.config file these imports would be added directly into your project file (.csproj).

ContentLicense: CC BY-SA 3.0


问:
search mysql for multiple tables

<?php
    mysql_connect("localhost", "dbl", "pass") or die("Error connecting to database: ".mysql_error());
    /*
        localhost - it's location of the mysql server, usually localhost
        root - your username
        third is your password

        if connection fails it will stop loading the page and display an error
    */

    mysql_select_db("trackerp_excl") or die(mysql_error());
    /* tutorial_search is the name of database we've created */
?>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <title>Search results</title>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

<?php
    $query = $_GET['query'];
    // gets value sent over search form

    $min_length = 3;
    // you can set minimum length of the query if you want

    if(strlen($query) >= $min_length){ // if query length is more or equal minimum length then

        $query = htmlspecialchars($query);
        // changes characters used in html to their equivalents, for example: < to >

        $query = mysql_real_escape_string($query);
        // makes sure nobody uses SQL injection

      $raw_results = mysql_query("SELECT * FROM june2016
            WHERE (`CUSTOMER_NAME` LIKE '%".$query."%') OR (`PHONE_NO` LIKE '%".$query."%')") or die(mysql_error());

        // * means that it selects all fields, you can also write: `id`, `title`, `text`
        // articles is the name of our table

        // '%$query%' is what we're looking for, % means anything, for example if $query is Hello
        // it will match "hello", "Hello man", "gogohello", if you want exact match use `title`='$query'
        // or if you want to match just full word so "gogohello" is out use '% $query %' ...OR ... '$query %' ... OR ... '% $query'
   echo "

Date
Name
PHONE NO
ALT NO
EMAIL
AMOUNT
PAYMENT STATUS
SALES AGENT
MODE OF PAYMENT
PLAN
INVOICE NO

";
        if(mysql_num_rows($raw_results) > 0){ // if one or more rows are returned do following

            while($results = mysql_fetch_array($raw_results)){
            // $results = mysql_fetch_array($raw_results) puts data from database into array, while it's valid it does the loop

                echo "
".$results['DATE']."	".$results['CUSTOMER_NAME']."	".$results['PHONE_NO']."	".$results['ALT_NO']."	".$results['EMAIL']."	".$results['AMOUNT']."	".$results['PAYMENT_STATUS']."	".$results['SALES_AGENT']."	".$results['MODE_OF_PAYMENT']."	".$results['PLAN']."	".$results['INVOICE_NO']."	";

                // posts results gotten from database(title and text) you can also show id ($results['id'])
            }

        }
        else{ // if there is no matching rows do following
            echo "No results";
        }

    }
    else{ // if query length is less than minimum
        echo "Minimum length is ".$min_length;
    }echo "
";
?>

```

I have the above code to search for customer name or phone no itto showup the customer details. Here I am facing a issue I have total 9 tables like aug2016,sep206. I tried joins union none works for me always giving me error. Can some one tell me how I can search all the tables at a time? Thanks

答:
the only way I could think of is that you need to query on all tables using union </p>

<p>try something like that </p>

```<code>select * from table1 where username="user1"
union
(select * from table2 where username="user1")
union
(select * from table3 where username="user1")
...
</code>```

Title: search mysql for multiple tables

Body:
<?php
    mysql_connect("localhost", "dbl", "pass") or die("Error connecting to database: ".mysql_error());
    /*
        localhost - it's location of the mysql server, usually localhost
        root - your username
        third is your password

        if connection fails it will stop loading the page and display an error
    */

    mysql_select_db("trackerp_excl") or die(mysql_error());
    /* tutorial_search is the name of database we've created */
?>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <title>Search results</title>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

<?php
    $query = $_GET['query'];
    // gets value sent over search form

    $min_length = 3;
    // you can set minimum length of the query if you want

    if(strlen($query) >= $min_length){ // if query length is more or equal minimum length then

        $query = htmlspecialchars($query);
        // changes characters used in html to their equivalents, for example: < to >

        $query = mysql_real_escape_string($query);
        // makes sure nobody uses SQL injection

      $raw_results = mysql_query("SELECT * FROM june2016
            WHERE (`CUSTOMER_NAME` LIKE '%".$query."%') OR (`PHONE_NO` LIKE '%".$query."%')") or die(mysql_error());

        // * means that it selects all fields, you can also write: `id`, `title`, `text`
        // articles is the name of our table

        // '%$query%' is what we're looking for, % means anything, for example if $query is Hello
        // it will match "hello", "Hello man", "gogohello", if you want exact match use `title`='$query'
        // or if you want to match just full word so "gogohello" is out use '% $query %' ...OR ... '$query %' ... OR ... '% $query'
   echo "

Date
Name
PHONE NO
ALT NO
EMAIL
AMOUNT
PAYMENT STATUS
SALES AGENT
MODE OF PAYMENT
PLAN
INVOICE NO

";
        if(mysql_num_rows($raw_results) > 0){ // if one or more rows are returned do following

            while($results = mysql_fetch_array($raw_results)){
            // $results = mysql_fetch_array($raw_results) puts data from database into array, while it's valid it does the loop

                echo "
".$results['DATE']."	".$results['CUSTOMER_NAME']."	".$results['PHONE_NO']."	".$results['ALT_NO']."	".$results['EMAIL']."	".$results['AMOUNT']."	".$results['PAYMENT_STATUS']."	".$results['SALES_AGENT']."	".$results['MODE_OF_PAYMENT']."	".$results['PLAN']."	".$results['INVOICE_NO']."	";

                // posts results gotten from database(title and text) you can also show id ($results['id'])
            }

        }
        else{ // if there is no matching rows do following
            echo "No results";
        }

    }
    else{ // if query length is less than minimum
        echo "Minimum length is ".$min_length;
    }echo "
";
?>

I have the above code to search for customer name or phone no itto showup the customer details. Here I am facing a issue I have total 9 tables like aug2016,sep206. I tried joins union none works for me always giving me error. Can some one tell me how I can search all the tables at a time? Thanks

Body:
the only way I could think of is that you need to query on all tables using union

try something like that

select * from table1 where username="user1"
union
(select * from table2 where username="user1")
union
(select * from table3 where username="user1")
...


问:
How to add a diagonal line to a plot?
I want to add a diagonal line to the plot. It is not a linear regression line. I just want a diagnol line.
Can anyone help me with this? Thanks a lot!</p>

答:
If you want to add the 1:1 diagonal line:</p>

```<code>qplot(1,1) + geom_abline(intercept = 0, slope = 1)
</code>```

Title: How to add a diagonal line to a plot?

Body:
If you want to add the 1:1 diagonal line:

qplot(1,1) + geom_abline(intercept = 0, slope = 1)


问:
Covert "back" to textile markup when editing post via RedCloth and Acts-as-Textiled?
Question: How can I "convert" my textile generated HTML back to textile markup in my app?

Here's the situtation. I managed to piece together a poor man's blog editor in my Rails 3 app by implementing RedCloth and acts-as-textiled in my "posts" model. I use acts-as-textiled to take the pain out of writing content in the body of my "posts".

It works great. However, when I edit the post I see the generated HTML in the post body. What I would like to see is the original textile markup. Is this possible?

Thanks in advance for your help!

Here is my post model:

```<code>class Post < ActiveRecord::Base
  has_many :tags
  acts_as_taggable_on :tags
  acts_as_textiled :title, :body
  attr_accessible :tag_list, :tags, :title, :body, :post, :comments
  validates :title, :presence => true
  validates :body, :presence => true
  default_scope :order => 'posts.created_at DESC'
</code>```

Here is my Posts view for the "Show" method:

```<code><%= @post.title.html_safe %>
<%= @post.body.html_safe %>
</code>```

答:
Try this:

```<code>html = <<HTML
<h1>This is a heading</h1>
<strong>bold text</strong>
<i>italic</i>
HTML

textile = ClothRed.new(html).to_textile

puts textile
</code>```

Output:

```<code>h1. This is a heading

*bold text*
__italic__
</code>```

In your case, I think you should do:

```<code><%= ClothRed.new(@post.body).to_textile.html_safe %>
# instead of
<%= @post.body.html_safe %>
</code>```

I don't know if this is considered best practice, though.

Documentation: http://clothred.rubyforge.org/doc/html/index.html

ContentLicense: CC BY-SA 2.5

Body:
Question: How can I "convert" my textile generated HTML back to textile markup in my app?

Here's the situtation. I managed to piece together a poor man's blog editor in my Rails 3 app by implementing RedCloth and acts-as-textiled in my "posts" model. I use acts-as-textiled to take the pain out of writing content in the body of my "posts".

It works great. However, when I edit the post I see the generated HTML in the post body. What I would like to see is the original textile markup. Is this possible?

Thanks in advance for your help!

Here is my post model:

class Post < ActiveRecord::Base
  has_many :tags
  acts_as_taggable_on :tags
  acts_as_textiled :title, :body
  attr_accessible :tag_list, :tags, :title, :body, :post, :comments
  validates :title, :presence => true
  validates :body, :presence => true
  default_scope :order => 'posts.created_at DESC'

Here is my Posts view for the "Show" method:

<%= @post.title.html_safe %>
<%= @post.body.html_safe %>

Body:
Try this:

html = <<HTML
<h1>This is a heading</h1>
<strong>bold text</strong>
<i>italic</i>
HTML

textile = ClothRed.new(html).to_textile

puts textile

Output:

h1. This is a heading

*bold text*
__italic__

In your case, I think you should do:

<%= ClothRed.new(@post.body).to_textile.html_safe %>
# instead of
<%= @post.body.html_safe %>

I don't know if this is considered best practice, though.

Documentation: http://clothred.rubyforge.org/doc/html/index.html


问:
How to inverse a conditional in JavaScript
I have a function that changes the case of some text and returns it, based on the value of capitalisation. I would like to pass another parameter called inverse, which if true, basically performs the opposite; so if capitalisation is lowercase, it will make the text lower case instead of uppercase.

It's important that the value of capitalisation does not change, because it's used by other parts of the application.

I'm looking for a really succinct way to do this with minimal code.

```<code>       capitalisation = "lowercase";

       function switchCase(text, inverse) {
            if (capitalisation === "lowercase") {
                text = text.toLowerCase();
            } else {
                text = text.toUpperCase();
            }
            return text;
        }
</code>```

答:
I think this can be useful for you. I can show you two ways: with two functions or on only one function:

2 functions

```<code>   capitalisation = "lowercase";

   function switchCase(text, inverse) {
        if(inverse) {
            return switchInverseCase(text);
        }
        if (capitalisation === "lowercase") {
            text = text.toLowerCase();
        } else {
            text = text.toUpperCase();
        }
        return text;
    }

   function switchInverseCase(text) {
        if (capitalisation === "lowercase") {
            text = text.toUpperCase();
        } else {
            text = text.toLowerCase();
        }
        return text;
    }
</code>```

1 function

```<code>   capitalisation = "lowercase";

   function switchCase(text, inverse) {

        if (capitalisation === "lowercase") {
            if(inverse) {
                text = text.toUpperCase();
            } else {
                text = text.toLowerCase();
            }
        } else {
            if(inverse) {
                text = text.toLowerCase();
            } else {
                text = text.toUpperCase();
            }
        }
        return text;
    }
</code>```

Hope this helps you.

Body:
I have a function that changes the case of some text and returns it, based on the value of capitalisation. I would like to pass another parameter called inverse, which if true, basically performs the opposite; so if capitalisation is lowercase, it will make the text lower case instead of uppercase.

It's important that the value of capitalisation does not change, because it's used by other parts of the application.

I'm looking for a really succinct way to do this with minimal code.

       capitalisation = "lowercase";

       function switchCase(text, inverse) {
            if (capitalisation === "lowercase") {
                text = text.toLowerCase();
            } else {
                text = text.toUpperCase();
            }
            return text;
        }

Body:
I think this can be useful for you. I can show you two ways: with two functions or on only one function:

2 functions

   capitalisation = "lowercase";

   function switchCase(text, inverse) {
        if(inverse) {
            return switchInverseCase(text);
        }
        if (capitalisation === "lowercase") {
            text = text.toLowerCase();
        } else {
            text = text.toUpperCase();
        }
        return text;
    }

   function switchInverseCase(text) {
        if (capitalisation === "lowercase") {
            text = text.toUpperCase();
        } else {
            text = text.toLowerCase();
        }
        return text;
    }

1 function

   capitalisation = "lowercase";

   function switchCase(text, inverse) {

        if (capitalisation === "lowercase") {
            if(inverse) {
                text = text.toUpperCase();
            } else {
                text = text.toLowerCase();
            }
        } else {
            if(inverse) {
                text = text.toLowerCase();
            } else {
                text = text.toUpperCase();
            }
        }
        return text;
    }

Hope this helps you.


问:
Why laravel homestead is not running Apache
Obviously, I've Laravel project that really needs the .htaccess rules and Nginx doesn't seem to be the best solution for me,

1- my question is why Laravel didn't provide homestead with Apache!
After a small research that I made I found online tool for converting the rules but the output didn't work (was too short), whereas, Apache is more likely known and usable, plus it's easier to define rules for security and pretty URLs ..etc. ( at least for me )

2- Please give me answers explaining why they choose Nginx!, more importantly I need to know what Seniors and Experts will use ( Nginx, Apache )

3- Do you advise me to install Apache on Homestead?

答:
Laravel homestead is currently able to install apache using your Homestead.yaml file.

Add a key to your sites called type. Set it to apache. like so:

```<code>sites:
    - map: laravel.local
      to: "/home/vagrant/laravel"
      type: apache
</code>```

Make sure you don't mix up apache and nginx, that won't work.

Then run vagrant up and to install apache and provision the right config files.

If it doesn't work, then first make sure to update to the latest version of homestead.

Here is an interesting article on the matter: https://www.nginx.com/blog/nginx-vs-apache-our-view/. TLDR: Nginx is faster.

Only when you have an existing project and you really need to use apache. Or in case your application is going to run on an apache server. Starting fresh? Use nginx.

Body:
Laravel homestead is currently able to install apache using your Homestead.yaml file.

Add a key to your sites called type. Set it to apache. like so:

sites:
    - map: laravel.local
      to: "/home/vagrant/laravel"
      type: apache

Make sure you don't mix up apache and nginx, that won't work.

Then run vagrant up and to install apache and provision the right config files.

If it doesn't work, then first make sure to update to the latest version of homestead.

Here is an interesting article on the matter: https://www.nginx.com/blog/nginx-vs-apache-our-view/. TLDR: Nginx is faster.

Only when you have an existing project and you really need to use apache. Or in case your application is going to run on an apache server. Starting fresh? Use nginx.

ContentLicense: CC BY-SA 4.0


问:
Merging two sorted singly linked list
I came across this problem on Leetcode while looking for some exam practice, and I came up with the following solution:

```<code>public class ListNode {
    int val;
    ListNode next;
    ListNode(int x) { val = x; }
}

public class Solution {
    public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
        // base case: if any one of the lists are empty then we are done.
        if (l1 == null) return l2;
        else if (l2 == null) return l1;

        ListNode head = new ListNode(-1);
        // dummy head node

        ListNode prev = head; // pointer to do the modifications on the list
        while ((l1 != null) && (l2 != null)) {
            // while both lists arent empty
            int val;
            if (l1.val < l2.val) {
                val = l1.val;
                l1 = l1.next;
            } else {
                val = l2.val;
                l2 = l2.next;
            }
            ListNode curr = new ListNode(val); // creates a new node with the chosen value
            prev.next = curr; // update pointers
            prev = curr;
        }

        // one of the list is finished. we add the rest onto the list ln
        if (l1 == null) prev.next = l2;
        else prev.next = l1;

        return head.next;
    }
}
</code>```

It appears to pass all the tests - however the problem I have is that it is slower than 90% of the solutions submitted. I've recently leanred about linkedlists and I'm still not completely comfortable with the concept, which is why there is probably some lapses in understanding resulting in inefficient code here. I'd be grateful if someone could explain how my implementation can be improved.

答:
There are two issues with your code.

First, it works inconsistently with input data. If one of the input lists is empty, the routine returns the other input list as a result. On the other hand, if both input lists are non-empty, the routine creates new items to build a result list. However, when one of input lists gets exhausted during the merging process, the remaining part of the other one is appended to the result list. Eventually the result list is built partially with new nodes and a trailing part of one of the input lists.

That causes unnecessary overhead for creating duplicates of nodes and for destroying original nodes, which got replaced with their copies.

To avoid that, buid the result list directly with nodes taken from input lists. No creation of new nodes then, no recycling of old nodes, no intermediate variable to keep val before it is copied, no risk you'll forget copying some other data members if the ListNode class is ever extended...

The other one is ordering the output nodes. You use the 'less than' operator to decide whether to get the next node from l1 or from l2. That's wrong. You should use 'less than or equal', so for equal keys you get nodes from l1 first, then from l2. This way nodes which have equal key values val, but are otherwise distinguishabe (say, they have other data members), maintain the original order. We call it a stable sorting.

Implementation:

```<code>public ListNode mergeTwoLists(ListNode l1, ListNode l2) {

    ListNode head = new ListNode(-1);  // temporary head node
    ListNode last = head; // the last item of the list; we append here

    while ((l1 != null) && (l2 != null)) { // while both lists arent empty
        if (l1.val <= l2.val) {            // 'or equal' for stable merging
            last.next = l1;                // append the chosen node to result list
            l1 = l1.next;                  // skip (effectively remove) it in input list
        } else {
            last.next = l2;
            l2 = l2.next;
        }
        last = last.next;                  // the appended node becomes last
    }

    // one of the lists is finished - append the rest of the other one
    if (l1 == null) last.next = l2;
    else last.next = l1;

    return head.next;
}
</code>```

Additionally we don't need testing whether any of input lists is empty – if so, the while loop is skipped with no iteration and the last if appends the non-empty input list to the result. The gain here is one if less at the cost of creating a temporary head node.

We can also get rid of the temporary ListNode variable at the cost of additional conditional branch. This may be useful when the node class becomes more complicated, as we would potentially have to give more parameters to constructor, which may be unavailable inside the merging routine.

```<code>public ListNode mergeTwoLists(ListNode l1, ListNode l2) {

    if (l1 == null) return l2;
    else if (l2 == null) return l1;    // make sure both lists aren't empty

    ListNode head = null;                  // the resulting list's head

    if (l1.val <= l2.val) {                // choose the head node
        head = l1;
        l1 = l1.next;
    } else {
        head = l2;
        l2 = l2.next;
    }

    ListNode last = head;  // the last item of the list; we append here

    while ((l1 != null) && (l2 != null)) { // while both lists arent empty
        if (l1.val <= l2.val) {            // 'or equal' for stable merging
            last.next = l1;                // append the chosen node to result list
            l1 = l1.next;                  // skip (effectively remove) it in input list
        } else {
            last.next = l2;
            l2 = l2.next;
        }
        last = last.next;                  // the appended node becomes last
    }

    // one of the lists is finished - append the rest of the other one
    if (l1 == null) last.next = l2;
    else last.next = l1;

    return head;
}
</code>```

Title: Merging two sorted singly linked list

Body:
I came across this problem on Leetcode while looking for some exam practice, and I came up with the following solution:

public class ListNode {
    int val;
    ListNode next;
    ListNode(int x) { val = x; }
}

public class Solution {
    public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
        // base case: if any one of the lists are empty then we are done.
        if (l1 == null) return l2;
        else if (l2 == null) return l1;

        ListNode head = new ListNode(-1);
        // dummy head node

        ListNode prev = head; // pointer to do the modifications on the list
        while ((l1 != null) && (l2 != null)) {
            // while both lists arent empty
            int val;
            if (l1.val < l2.val) {
                val = l1.val;
                l1 = l1.next;
            } else {
                val = l2.val;
                l2 = l2.next;
            }
            ListNode curr = new ListNode(val); // creates a new node with the chosen value
            prev.next = curr; // update pointers
            prev = curr;
        }

        // one of the list is finished. we add the rest onto the list ln
        if (l1 == null) prev.next = l2;
        else prev.next = l1;

        return head.next;
    }
}

It appears to pass all the tests - however the problem I have is that it is slower than 90% of the solutions submitted. I've recently leanred about linkedlists and I'm still not completely comfortable with the concept, which is why there is probably some lapses in understanding resulting in inefficient code here. I'd be grateful if someone could explain how my implementation can be improved.

Body:
There are two issues with your code.

First, it works inconsistently with input data. If one of the input lists is empty, the routine returns the other input list as a result. On the other hand, if both input lists are non-empty, the routine creates new items to build a result list. However, when one of input lists gets exhausted during the merging process, the remaining part of the other one is appended to the result list. Eventually the result list is built partially with new nodes and a trailing part of one of the input lists.

That causes unnecessary overhead for creating duplicates of nodes and for destroying original nodes, which got replaced with their copies.

To avoid that, buid the result list directly with nodes taken from input lists. No creation of new nodes then, no recycling of old nodes, no intermediate variable to keep val before it is copied, no risk you'll forget copying some other data members if the ListNode class is ever extended...

The other one is ordering the output nodes. You use the 'less than' operator to decide whether to get the next node from l1 or from l2. That's wrong. You should use 'less than or equal', so for equal keys you get nodes from l1 first, then from l2. This way nodes which have equal key values val, but are otherwise distinguishabe (say, they have other data members), maintain the original order. We call it a stable sorting.

Implementation:

public ListNode mergeTwoLists(ListNode l1, ListNode l2) {

    ListNode head = new ListNode(-1);  // temporary head node
    ListNode last = head; // the last item of the list; we append here

    while ((l1 != null) && (l2 != null)) { // while both lists arent empty
        if (l1.val <= l2.val) {            // 'or equal' for stable merging
            last.next = l1;                // append the chosen node to result list
            l1 = l1.next;                  // skip (effectively remove) it in input list
        } else {
            last.next = l2;
            l2 = l2.next;
        }
        last = last.next;                  // the appended node becomes last
    }

    // one of the lists is finished - append the rest of the other one
    if (l1 == null) last.next = l2;
    else last.next = l1;

    return head.next;
}

Additionally we don't need testing whether any of input lists is empty – if so, the while loop is skipped with no iteration and the last if appends the non-empty input list to the result. The gain here is one if less at the cost of creating a temporary head node.

We can also get rid of the temporary ListNode variable at the cost of additional conditional branch. This may be useful when the node class becomes more complicated, as we would potentially have to give more parameters to constructor, which may be unavailable inside the merging routine.

public ListNode mergeTwoLists(ListNode l1, ListNode l2) {

    if (l1 == null) return l2;
    else if (l2 == null) return l1;    // make sure both lists aren't empty

    ListNode head = null;                  // the resulting list's head

    if (l1.val <= l2.val) {                // choose the head node
        head = l1;
        l1 = l1.next;
    } else {
        head = l2;
        l2 = l2.next;
    }

    ListNode last = head;  // the last item of the list; we append here

    while ((l1 != null) && (l2 != null)) { // while both lists arent empty
        if (l1.val <= l2.val) {            // 'or equal' for stable merging
            last.next = l1;                // append the chosen node to result list
            l1 = l1.next;                  // skip (effectively remove) it in input list
        } else {
            last.next = l2;
            l2 = l2.next;
        }
        last = last.next;                  // the appended node becomes last
    }

    // one of the lists is finished - append the rest of the other one
    if (l1 == null) last.next = l2;
    else last.next = l1;

    return head;
}


问:
"No space left on device" error while fitting Sklearn model
I'm fitting a LDA model with lots of data using scikit-learn. Relevant code piece looks like this:

```<code>lda = LatentDirichletAllocation(n_topics = n_topics,
                                max_iter = iters,
                                learning_method = 'online',
                                learning_offset = offset,
                                random_state = 0,
                                evaluate_every = 5,
                                n_jobs = 3,
                                verbose = 0)
lda.fit(X)
</code>```

(I guess the only possibly relevant detail here is that I'm using multiple jobs.)

After some time I'm getting "No space left on device" error, even though there is plenty of space on the disk and plenty of free memory. I tried the same code several times, on two different computers (on my local machine and on a remote server), first using python3, then using python2, and each time I ended up with the same error.

If I run the same code on a smaller sample of data everything works fine.

The entire stack trace:

```<code>Failed to save <type 'numpy.ndarray'> to .npy file:
Traceback (most recent call last):
  File "/home/ubuntu/anaconda2/lib/python2.7/site-packages/sklearn/externals/joblib/numpy_pickle.py", line 271, in save
    obj, filename = self._write_array(obj, filename)
  File "/home/ubuntu/anaconda2/lib/python2.7/site-packages/sklearn/externals/joblib/numpy_pickle.py", line 231, in _write_array
    self.np.save(filename, array)
  File "/home/ubuntu/anaconda2/lib/python2.7/site-packages/numpy/lib/npyio.py", line 491, in save
    pickle_kwargs=pickle_kwargs)
  File "/home/ubuntu/anaconda2/lib/python2.7/site-packages/numpy/lib/format.py", line 584, in write_array
    array.tofile(fp)
IOError: 275500 requested and 210934 written

IOErrorTraceback (most recent call last)
<ipython-input-7-6af7e7c9845f> in <module>()
      7                                 n_jobs = 3,
      8                                 verbose = 0)
----> 9 lda.fit(X)

/home/ubuntu/anaconda2/lib/python2.7/site-packages/sklearn/decomposition/online_lda.pyc in fit(self, X, y)
    509                     for idx_slice in gen_batches(n_samples, batch_size):
    510                         self._em_step(X[idx_slice, :], total_samples=n_samples,
--> 511                                       batch_update=False, parallel=parallel)
    512                 else:
    513                     # batch update

/home/ubuntu/anaconda2/lib/python2.7/site-packages/sklearn/decomposition/online_lda.pyc in _em_step(self, X, total_samples, batch_update, parallel)
    403         # E-step
    404         _, suff_stats = self._e_step(X, cal_sstats=True, random_init=True,
--> 405                                      parallel=parallel)
    406
    407         # M-step

/home/ubuntu/anaconda2/lib/python2.7/site-packages/sklearn/decomposition/online_lda.pyc in _e_step(self, X, cal_sstats, random_init, parallel)
    356                                               self.mean_change_tol, cal_sstats,
    357                                               random_state)
--> 358             for idx_slice in gen_even_slices(X.shape[0], n_jobs))
    359
    360         # merge result

/home/ubuntu/anaconda2/lib/python2.7/site-packages/sklearn/externals/joblib/parallel.pyc in __call__(self, iterable)
    808                 # consumption.
    809                 self._iterating = False
--> 810             self.retrieve()
    811             # Make sure that we get a last message telling us we are done
    812             elapsed_time = time.time() - self._start_time

/home/ubuntu/anaconda2/lib/python2.7/site-packages/sklearn/externals/joblib/parallel.pyc in retrieve(self)
    725                 job = self._jobs.pop(0)
    726             try:
--> 727                 self._output.extend(job.get())
    728             except tuple(self.exceptions) as exception:
    729                 # Stop dispatching any new job in the async callback thread

/home/ubuntu/anaconda2/lib/python2.7/multiprocessing/pool.pyc in get(self, timeout)
    565             return self._value
    566         else:
--> 567             raise self._value
    568
    569     def _set(self, i, obj):

IOError: [Errno 28] No space left on device
</code>```

答:
Had the same problem with LatentDirichletAllocation. It seems, that your are running out of shared memory (/dev/shm when you run df -h). Try setting JOBLIB_TEMP_FOLDER environment variable to something different: e.g., to /tmp. In my case it has solved the problem.

Or just increase the size of the shared memory, if you have the appropriate rights for the machine you are training the LDA on.

Body:
I'm fitting a LDA model with lots of data using scikit-learn. Relevant code piece looks like this:

lda = LatentDirichletAllocation(n_topics = n_topics,
                                max_iter = iters,
                                learning_method = 'online',
                                learning_offset = offset,
                                random_state = 0,
                                evaluate_every = 5,
                                n_jobs = 3,
                                verbose = 0)
lda.fit(X)

(I guess the only possibly relevant detail here is that I'm using multiple jobs.)

After some time I'm getting "No space left on device" error, even though there is plenty of space on the disk and plenty of free memory. I tried the same code several times, on two different computers (on my local machine and on a remote server), first using python3, then using python2, and each time I ended up with the same error.

If I run the same code on a smaller sample of data everything works fine.

The entire stack trace:

Failed to save <type 'numpy.ndarray'> to .npy file:
Traceback (most recent call last):
  File "/home/ubuntu/anaconda2/lib/python2.7/site-packages/sklearn/externals/joblib/numpy_pickle.py", line 271, in save
    obj, filename = self._write_array(obj, filename)
  File "/home/ubuntu/anaconda2/lib/python2.7/site-packages/sklearn/externals/joblib/numpy_pickle.py", line 231, in _write_array
    self.np.save(filename, array)
  File "/home/ubuntu/anaconda2/lib/python2.7/site-packages/numpy/lib/npyio.py", line 491, in save
    pickle_kwargs=pickle_kwargs)
  File "/home/ubuntu/anaconda2/lib/python2.7/site-packages/numpy/lib/format.py", line 584, in write_array
    array.tofile(fp)
IOError: 275500 requested and 210934 written

IOErrorTraceback (most recent call last)
<ipython-input-7-6af7e7c9845f> in <module>()
      7                                 n_jobs = 3,
      8                                 verbose = 0)
----> 9 lda.fit(X)

/home/ubuntu/anaconda2/lib/python2.7/site-packages/sklearn/decomposition/online_lda.pyc in fit(self, X, y)
    509                     for idx_slice in gen_batches(n_samples, batch_size):
    510                         self._em_step(X[idx_slice, :], total_samples=n_samples,
--> 511                                       batch_update=False, parallel=parallel)
    512                 else:
    513                     # batch update

/home/ubuntu/anaconda2/lib/python2.7/site-packages/sklearn/decomposition/online_lda.pyc in _em_step(self, X, total_samples, batch_update, parallel)
    403         # E-step
    404         _, suff_stats = self._e_step(X, cal_sstats=True, random_init=True,
--> 405                                      parallel=parallel)
    406
    407         # M-step

/home/ubuntu/anaconda2/lib/python2.7/site-packages/sklearn/decomposition/online_lda.pyc in _e_step(self, X, cal_sstats, random_init, parallel)
    356                                               self.mean_change_tol, cal_sstats,
    357                                               random_state)
--> 358             for idx_slice in gen_even_slices(X.shape[0], n_jobs))
    359
    360         # merge result

/home/ubuntu/anaconda2/lib/python2.7/site-packages/sklearn/externals/joblib/parallel.pyc in __call__(self, iterable)
    808                 # consumption.
    809                 self._iterating = False
--> 810             self.retrieve()
    811             # Make sure that we get a last message telling us we are done
    812             elapsed_time = time.time() - self._start_time

/home/ubuntu/anaconda2/lib/python2.7/site-packages/sklearn/externals/joblib/parallel.pyc in retrieve(self)
    725                 job = self._jobs.pop(0)
    726             try:
--> 727                 self._output.extend(job.get())
    728             except tuple(self.exceptions) as exception:
    729                 # Stop dispatching any new job in the async callback thread

/home/ubuntu/anaconda2/lib/python2.7/multiprocessing/pool.pyc in get(self, timeout)
    565             return self._value
    566         else:
--> 567             raise self._value
    568
    569     def _set(self, i, obj):

IOError: [Errno 28] No space left on device


问:
How do I plot an energy ranking figure using Python?
This is a typical energy ranking that is used in a few published papers and I am struggling to reproduce one for my data using Python (anything matplotlib, sns etc.). I have my data constructed in Pandas dataframe like below:

```<code>System  Color_id  Data1  Data2
Form I     1      0.0    0.6
Form II    2      0.8    0.0
Form III   3      2.1    2.7
Form IV    4      2.2    0.3
Form V     5      1.7    1.2
</code>```

I added "Color_id" column to enable specific_column_values coloring as in matplotlib and I think I am half-way using simply plt.scatter. What I am struggling mostly is plotting elongated lines instead of typical markers, and how to automatically connect those dash lines between similar systems across different data? Any help or suggestions is much appreciated.

答:
I implemented an example of what I suggested in the comments. This doesn't automatically scale the axes (I hardcoded it), or add the tick labels, but those are all things you should be able to find on other questions.</p>

```<code>import matplotlib.pyplot as plt
import numpy as np

def energy_rank(data, marker_width=.5, color='blue'):
    y_data = np.repeat(data, 2)
    x_data = np.empty_like(y_data)
    x_data[0::2] = np.arange(1, len(data)+1) - (marker_width/2)
    x_data[1::2] = np.arange(1, len(data)+1) + (marker_width/2)
    lines = []
    lines.append(plt.Line2D(x_data, y_data, lw=1, linestyle='dashed', color=color))
    for x in range(0,len(data)*2, 2):
        lines.append(plt.Line2D(x_data[x:x+2], y_data[x:x+2], lw=2, linestyle='solid', color=color))
    return lines

data = np.random.rand(4,8) * 4 # 4 lines with 8 datapoints from 0 - 4

artists = []
for row, color in zip(data, ('red','blue','green','magenta')):
    artists.extend(energy_rank(row, color=color))

fig, ax = plt.subplots()

for artist in artists:
    ax.add_artist(artist)
ax.set_ybound([0,4])
ax.set_xbound([.5,8.5])
</code>```

Body:
This is a typical energy ranking that is used in a few published papers and I am struggling to reproduce one for my data using Python (anything matplotlib, sns etc.). I have my data constructed in Pandas dataframe like below:

System  Color_id  Data1  Data2
Form I     1      0.0    0.6
Form II    2      0.8    0.0
Form III   3      2.1    2.7
Form IV    4      2.2    0.3
Form V     5      1.7    1.2

I added "Color_id" column to enable specific_column_values coloring as in matplotlib and I think I am half-way using simply plt.scatter. What I am struggling mostly is plotting elongated lines instead of typical markers, and how to automatically connect those dash lines between similar systems across different data? Any help or suggestions is much appreciated.

Body:
I implemented an example of what I suggested in the comments. This doesn't automatically scale the axes (I hardcoded it), or add the tick labels, but those are all things you should be able to find on other questions.

import matplotlib.pyplot as plt
import numpy as np

def energy_rank(data, marker_width=.5, color='blue'):
    y_data = np.repeat(data, 2)
    x_data = np.empty_like(y_data)
    x_data[0::2] = np.arange(1, len(data)+1) - (marker_width/2)
    x_data[1::2] = np.arange(1, len(data)+1) + (marker_width/2)
    lines = []
    lines.append(plt.Line2D(x_data, y_data, lw=1, linestyle='dashed', color=color))
    for x in range(0,len(data)*2, 2):
        lines.append(plt.Line2D(x_data[x:x+2], y_data[x:x+2], lw=2, linestyle='solid', color=color))
    return lines

data = np.random.rand(4,8) * 4 # 4 lines with 8 datapoints from 0 - 4

artists = []
for row, color in zip(data, ('red','blue','green','magenta')):
    artists.extend(energy_rank(row, color=color))

fig, ax = plt.subplots()

for artist in artists:
    ax.add_artist(artist)
ax.set_ybound([0,4])
ax.set_xbound([.5,8.5])


问:
Inserting into a single table from multiple table
I have defined multiple aliases in my query and I want to write the result of each alias into table tab_1. But when I run the following query I get error

missing EOF at 'INSERT' near 'tab_1'

Have I written it correctly? Can someone verify the syntax or tell me how to write it? Please verify that I have put commas at right place. Appreciate for the help.

```<code>func_1 as
( .....),

func_2 as
(.....),

func_3 as
(....),

INSERT INTO TABLE tab_1 select * from func_1,

INSERT INTO TABLE tab_1 select * from func_2,

INSERT INTO TABLE tab_1 select * from func_3;
</code>```

答:
Use this template:

```<code>with
func_1 as ( .....),
func_2 as (.....),
func_3 as (....)
INSERT INTO TABLE tab_1
select * from func_1
   union all
select * from func_2
   union all
select * from func_3;
</code>```

Subqueries in union all will be executed in parallel.

Checked explain plan on this sentence, it seems to work ok:

```<code>with func_1 as
( select * from default.dual),
func_2 as
(select * from default.dual)
insert into table default.dual
select * from func_1
union all
select * from func_2
</code>```

Body:
I have defined multiple aliases in my query and I want to write the result of each alias into table tab_1. But when I run the following query I get error

missing EOF at 'INSERT' near 'tab_1'

Have I written it correctly? Can someone verify the syntax or tell me how to write it? Please verify that I have put commas at right place. Appreciate for the help.

func_1 as
( .....),

func_2 as
(.....),

func_3 as
(....),

INSERT INTO TABLE tab_1 select * from func_1,

INSERT INTO TABLE tab_1 select * from func_2,

INSERT INTO TABLE tab_1 select * from func_3;

Body:
Use this template:

with
func_1 as ( .....),
func_2 as (.....),
func_3 as (....)
INSERT INTO TABLE tab_1
select * from func_1
   union all
select * from func_2
   union all
select * from func_3;

Subqueries in union all will be executed in parallel.

Checked explain plan on this sentence, it seems to work ok:

with func_1 as
( select * from default.dual),
func_2 as
(select * from default.dual)
insert into table default.dual
select * from func_1
union all
select * from func_2


问:
Spark Dataframe Scala: groupby doesn't work after UnionAll
I used unionAll to combine the source DF (with negative weights) and the target DF (with positive weights) into a node DF. Then I perform groupby to sum all the weights of the same nodes, but i don't know why groupby didn't work for the unioned DF at all. Did anyone face the same problem ?:

```<code>val src    = file.map(_.split("\t")).map(p => node(p(0), (0-p(2).trim.toInt))).toDF()
val target = file.map(_.split("\t")).map(p => node(p(1), p(2).trim.toInt)).toDF()

val srcfl = src.filter(src("weight") != -1)
val targetfl = target.filter(target("weight") != 1)

val nodes = srcfl.unionAll(targetfl)

nodes.groupBy("name").sum()

nodes.map(x => x.mkString("\t")).saveAsTextFile("hdfs://localhost:8020" + args(1))
</code>```

答:
You're simply ignoring the result of the groupBy operation: just like all DataFrame transformations, .groupBy(...).sum() doesn't mutate the original DataFrame (nodes), it produces a new one. I suspect that if you actually use the return value from sum() you'll see the result you're looking for:

```<code>val result = nodes.groupBy("name").sum()

result.map(x => x.mkString("\t")).saveAsTextFile("hdfs://localhost:8020" + args(1))
</code>```

Body:
I used unionAll to combine the source DF (with negative weights) and the target DF (with positive weights) into a node DF. Then I perform groupby to sum all the weights of the same nodes, but i don't know why groupby didn't work for the unioned DF at all. Did anyone face the same problem ?:

val src    = file.map(_.split("\t")).map(p => node(p(0), (0-p(2).trim.toInt))).toDF()
val target = file.map(_.split("\t")).map(p => node(p(1), p(2).trim.toInt)).toDF()

val srcfl = src.filter(src("weight") != -1)
val targetfl = target.filter(target("weight") != 1)

val nodes = srcfl.unionAll(targetfl)

nodes.groupBy("name").sum()

nodes.map(x => x.mkString("\t")).saveAsTextFile("hdfs://localhost:8020" + args(1))

Body:
You're simply ignoring the result of the groupBy operation: just like all DataFrame transformations, .groupBy(...).sum() doesn't mutate the original DataFrame (nodes), it produces a new one. I suspect that if you actually use the return value from sum() you'll see the result you're looking for:

val result = nodes.groupBy("name").sum()

result.map(x => x.mkString("\t")).saveAsTextFile("hdfs://localhost:8020" + args(1))


问:
How to get rid of white space in palindrome (Java)
```<code>public class reverserapp {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
      Scanner scan = new Scanner(System.in);
      System.out.println("Please Enter a word");
      String str = scan.nextLine();

      String reverse = "";
      for( int i = str.length() - 1; i >= 0; i--)
          reverse += str.charAt(i);

      if(reverse.equalsIgnoreCase(str))
          System.out.println("Palindrome");
      else System.out.println("Not Palindrome");

    }

}
</code>```

This is my palindrome code. I'm doing this for a small assignment. I can get single words to work but if I write a something like "Don’t nod" it shows up as not palindrome. How can I achieve this? I'd like for my code to ignore punctuation's and white space.

So in the end result should be like "dontnod"

Thanks in advance for any help, complete noob at this.

答:
You can define a regex to remove punctuation and space, and perform a String replace on input, e.g.:

```<code>String regex = "[\\p{Punct}\\s]";
String input = "don't nod";
System.out.println(input.replaceAll(regex, ""));
</code>```

Body:
public class reverserapp {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
      Scanner scan = new Scanner(System.in);
      System.out.println("Please Enter a word");
      String str = scan.nextLine();

      String reverse = "";
      for( int i = str.length() - 1; i >= 0; i--)
          reverse += str.charAt(i);

      if(reverse.equalsIgnoreCase(str))
          System.out.println("Palindrome");
      else System.out.println("Not Palindrome");

    }

}

This is my palindrome code. I'm doing this for a small assignment. I can get single words to work but if I write a something like "Don’t nod" it shows up as not palindrome. How can I achieve this? I'd like for my code to ignore punctuation's and white space.

So in the end result should be like "dontnod"

Thanks in advance for any help, complete noob at this.

Body:
You can define a regex to remove punctuation and space, and perform a String replace on input, e.g.:

String regex = "[\\p{Punct}\\s]";
String input = "don't nod";
System.out.println(input.replaceAll(regex, ""));


问:
List sorting - two lists into one
I have to make two list. One with names (str) and second one with wage (int). And then, i have to sort the wages with the names. The problem is that, always when I do this, only wages are sorted.

```<code>names = ["Asia","Łukasz","Aneta","Ola","Mikołaj"]
wages = [15000,1500,200,14500,2600]

print("Here(should) be sorted list")
wages.sort()
for i in range (len(wages)) :
    print(wages[i],names[i])
</code>```

To be clear, I want to set on hold these two lists into one and sort both of them. With the simple method as it can be. Without functions, sets, zips etc. Just with loops.

答:
I think one way is to build a dictionary to store the name and wage. </p>

```<code> names = ["Asia","Łukasz","Aneta","Ola","Mikołaj"]
 wages = [15000,1500,200,14500,2600]
 the_dict = {}
 for i in range(len(names)):
      the_dict[wages[i]] = names[i]

 wages.sort()
 sorted_names = [the_dict[i] for i in wages]
 #now, both names and wages are sorted, and you can print them

 for i in range(len(wages)):
      print(sorted_names[i], wages[i])
</code>```

Title: List sorting - two lists into one

Body:
I have to make two list. One with names (str) and second one with wage (int). And then, i have to sort the wages with the names. The problem is that, always when I do this, only wages are sorted.

names = ["Asia","Łukasz","Aneta","Ola","Mikołaj"]
wages = [15000,1500,200,14500,2600]

print("Here(should) be sorted list")
wages.sort()
for i in range (len(wages)) :
    print(wages[i],names[i])

To be clear, I want to set on hold these two lists into one and sort both of them. With the simple method as it can be. Without functions, sets, zips etc. Just with loops.

Body:
I think one way is to build a dictionary to store the name and wage.

 names = ["Asia","Łukasz","Aneta","Ola","Mikołaj"]
 wages = [15000,1500,200,14500,2600]
 the_dict = {}
 for i in range(len(names)):
      the_dict[wages[i]] = names[i]

 wages.sort()
 sorted_names = [the_dict[i] for i in wages]
 #now, both names and wages are sorted, and you can print them

 for i in range(len(wages)):
      print(sorted_names[i], wages[i])


问:
UITextView - Setting max lines hides the cursor
This is what I am doing to set max number of lines :

```<code>self.text_description.textContainer.maximumNumberOfLines = 2
self.text_description.layoutManager.textContainerChangedGeometry(self.text_description.textContainer)
</code>```

When 3rd line is about to get started, the cursor disappears. To put it back I have to tap backspace.

答:
I don't quite sure what you are expecting. If you want two lines max, there should be no 3rd line.

Use this:

```<code>self.text_description.textContainer.maximumNumberOfLines = 2
self.text_description.textContainer.lineBreakMode = .byTruncatingTail
</code>```

Limit the number of lines for UITextview

It seems what you actually want is a textview with two lines height? If that is true, try this in you view controller.

```<code>self.text_description = UITextView(frame: CGRect(x: 100.0, y: 100.0, width: 200.0, height: 28.0))
self.text_description.backgroundColor = #colorLiteral(red: 0.8039215803, green: 0.8039215803, blue: 0.8039215803, alpha: 1)
self.view.addSubview(self.text_description)
</code>```

Body:
This is what I am doing to set max number of lines :

self.text_description.textContainer.maximumNumberOfLines = 2
self.text_description.layoutManager.textContainerChangedGeometry(self.text_description.textContainer)

When 3rd line is about to get started, the cursor disappears. To put it back I have to tap backspace.

Body:
I don't quite sure what you are expecting. If you want two lines max, there should be no 3rd line.

Use this:

self.text_description.textContainer.maximumNumberOfLines = 2
self.text_description.textContainer.lineBreakMode = .byTruncatingTail

Limit the number of lines for UITextview

It seems what you actually want is a textview with two lines height? If that is true, try this in you view controller.

self.text_description = UITextView(frame: CGRect(x: 100.0, y: 100.0, width: 200.0, height: 28.0))
self.text_description.backgroundColor = #colorLiteral(red: 0.8039215803, green: 0.8039215803, blue: 0.8039215803, alpha: 1)
self.view.addSubview(self.text_description)


问:
How to get python list first element id
I have a list

```<code>MENU_Items = [ {  "ID":0x3B08, "Description":"Read Levelling Status\t\t"},
                { "ID":0x3B39, "Description":"Read Air system control module state"},
                { "ID":0x3B3A, "Description":"Read Movement inhibit state\t"},
                { "ID":0x3B3B, "Description":"Read Target height status\t\t"}]
</code>```

Input = 1

MENU_Items[Input - 1]

I am getting the result as below:

```<code>{'ID': 15112, 'Description': 'Read Levelling Status\t\t'}
</code>```

I want to extract only 'ID' as a output

```<code>I am trying something like this MENU_Items[Input - 1].ID
</code>```

Its not working.

答:
So why not do something like this:

```<code>MENU_Items = [ {  "ID":0x3B08, "Description":"Read Levelling Status\t\t"},
            { "ID":0x3B39, "Description":"Read Air system control module state"},
            { "ID":0x3B3A, "Description":"Read Movement inhibit state\t"},
            { "ID":0x3B3B, "Description":"Read Target height status\t\t"}]

print(MENU_Items[0]["ID"])
</code>```

The output would be

```<code>15112
</code>```

To do this with user input, you can simply do:

```<code>info = int(input("Please enter which ID you wish to access: "))

x = info - 1

print(MENU_Items[x]["ID"])
</code>```

Your output would be determined based on what they selected. I really wouldn't go this route though as there is no error handling, and you are not guaranteed they are entering an int which will cause an error as well. I'm just showing you a down and dirty quick example of how it could be done.

Title: How to get python list first element id

Body:
I have a list

MENU_Items = [ {  "ID":0x3B08, "Description":"Read Levelling Status\t\t"},
                { "ID":0x3B39, "Description":"Read Air system control module state"},
                { "ID":0x3B3A, "Description":"Read Movement inhibit state\t"},
                { "ID":0x3B3B, "Description":"Read Target height status\t\t"}]

Input = 1

MENU_Items[Input - 1]

I am getting the result as below:

{'ID': 15112, 'Description': 'Read Levelling Status\t\t'}

I want to extract only 'ID' as a output

I am trying something like this MENU_Items[Input - 1].ID

Its not working.

Body:
So why not do something like this:

MENU_Items = [ {  "ID":0x3B08, "Description":"Read Levelling Status\t\t"},
            { "ID":0x3B39, "Description":"Read Air system control module state"},
            { "ID":0x3B3A, "Description":"Read Movement inhibit state\t"},
            { "ID":0x3B3B, "Description":"Read Target height status\t\t"}]

print(MENU_Items[0]["ID"])

The output would be

15112

To do this with user input, you can simply do:

info = int(input("Please enter which ID you wish to access: "))

x = info - 1

print(MENU_Items[x]["ID"])

Your output would be determined based on what they selected. I really wouldn't go this route though as there is no error handling, and you are not guaranteed they are entering an int which will cause an error as well. I'm just showing you a down and dirty quick example of how it could be done.


问:
Worpdress meta query not working if value is array of strings
i'm facing wordpress meta_query problem, from this simple query i am not able to output values :

```<code>(
[post_type] => offres
[meta_query] => Array
    (
        [0] => Array
            (
                [key] => topics
                [value] => Array
                    (
                        [0] => PADINE
                        [1] => ALKEKENGE
                    )

                [compare] => IN
            )

    )
)
</code>```

This is the php code :

```<code>$args = array(
    'post_type' => 'offres',
    'meta_query' => array(
        array(
             'key' => 'topics',
              'value' => array('PADINE','ALKEKENGE'),
               'compare' => 'IN'
         )
    )
);
</code>```

On my wordpress admin i have a post assigned with 'topics' meta key and  'PADINE' as value, i wonder why is it not working ?

Thank you for your helps.

答:
Sometimes, it is hard to get the meta value due to the serialize structure of the data.

```<code>$args = array(
    'post_type' => 'offres',
    'meta_query'    => array(
       'relation' => 'OR',
        array(
            'key'       => 'topics',
            'value'     => 'PADINE',
            'compare'   => 'LIKE',
        ),
        array(
            'key'       => 'topics',
            'value'     => 'ALKEKENGE',
            'compare'   => 'LIKE',
        )
    )
);
</code>```

Hope it works,

Thanks

Body:
i'm facing wordpress meta_query problem, from this simple query i am not able to output values :

(
[post_type] => offres
[meta_query] => Array
    (
        [0] => Array
            (
                [key] => topics
                [value] => Array
                    (
                        [0] => PADINE
                        [1] => ALKEKENGE
                    )

                [compare] => IN
            )

    )
)

This is the php code :

$args = array(
    'post_type' => 'offres',
    'meta_query' => array(
        array(
             'key' => 'topics',
              'value' => array('PADINE','ALKEKENGE'),
               'compare' => 'IN'
         )
    )
);

On my wordpress admin i have a post assigned with 'topics' meta key and  'PADINE' as value, i wonder why is it not working ?

Thank you for your helps.

Body:
Sometimes, it is hard to get the meta value due to the serialize structure of the data.

$args = array(
    'post_type' => 'offres',
    'meta_query'    => array(
       'relation' => 'OR',
        array(
            'key'       => 'topics',
            'value'     => 'PADINE',
            'compare'   => 'LIKE',
        ),
        array(
            'key'       => 'topics',
            'value'     => 'ALKEKENGE',
            'compare'   => 'LIKE',
        )
    )
);

Hope it works,

Thanks


问:
Use CSS to affect an outer element
This is hard to sum up in a title, so forgive me.

Basically, here is what I have:

```<code>a img {
/ * style * /
}
</code>```

However, I want to affect the a tag in this instance. Is there any way to do so in CSS without resorting to JavaScript wizardry?

答:
Unfortunately the cascading in CSS only goes one way.  From your example, I'm guessing you are trying to do something like this:

```<code><a><img src="icon.gif">Hello</a> <!-- This A has a taller line height for the icon -->

<a>Hello</a> <!-- This A is normal -->
</code>```

Most developers would accomplish it by simply adding a class.

```<code><a class="icon"><img src="icon.gif">Hello</a> <!-- This A has a taller line height for the icon -->
</code>```

Even better, use that class to make the icon a background image and add padding.

```<code><style type="text/css">
a.icon { background:18px left center no-repeat; line-height:18px; }
</style>

<a class="icon" style="background-image:url('icon.gif');">Hello with icon</a>
</code>```

Put all your icon images into classes too and you have some pretty clean HTML!

Title: Use CSS to affect an outer element

Body:
This is hard to sum up in a title, so forgive me.

Basically, here is what I have:

a img {
/ * style * /
}

However, I want to affect the a tag in this instance. Is there any way to do so in CSS without resorting to JavaScript wizardry?

Body:
Unfortunately the cascading in CSS only goes one way.  From your example, I'm guessing you are trying to do something like this:

<a><img src="icon.gif">Hello</a> <!-- This A has a taller line height for the icon -->

<a>Hello</a> <!-- This A is normal -->

Most developers would accomplish it by simply adding a class.

<a class="icon"><img src="icon.gif">Hello</a> <!-- This A has a taller line height for the icon -->

Even better, use that class to make the icon a background image and add padding.

<style type="text/css">
a.icon { background:18px left center no-repeat; line-height:18px; }
</style>

<a class="icon" style="background-image:url('icon.gif');">Hello with icon</a>

Put all your icon images into classes too and you have some pretty clean HTML!


问:
How to fix the distance between horizontal points (x-axis) in chartJS
Problem: Hi all! i am using chart.js to draw the charts. chart is a dynamic sometimes shows 10 points and sometimes can be more than thousand i have applied a panel successfully so that my points can be shown at some distance to read them easily.

Right now i want to know if there is any option to set the distance between points in x-axis grid. right now it automatically adjust the points.

What i tried:
i tried to do the stepsize and scalewidth by searching other stackoverflow answers but did not succeed. Any kind of help would be much appreciated.

P.S:  i m using chart.js2

This is my chartjs dataset

```<code>var data = {
    labels: data.graph_date,
    datasets: [
        {
            label: 'Assay Values',
            fill: false,
            lineTension: 0,
            backgroundColor: "rgba(255, 0, 0,1)",
            borderColor: "rgba(255, 0, 0,1)",
            borderCapStyle: 'butt',
            borderDash: [],
            borderDashOffset: 0.0,
            borderWidth: 1,
            borderJoinStyle: 'miter',
            pointBorderColor: "rgba(255, 0, 0,1)",
            pointBackgroundColor: "#fff",
            pointBorderWidth: 1,
            pointHoverRadius: 5,
            pointHoverBackgroundColor: "rgba(255, 0, 0,1)",
            pointHoverBorderColor: "rgba(255, 0, 0,1)",
            pointHoverBorderWidth: 2,
            pointRadius: 1,
            pointHitRadius: 10,
            data: data.assay_value,
            spanGaps: false
        },var options = {
    responsive: false,
    title: {
        display: true,
        position: "top",
        text: label,
        fontSize: 18,
        fontColor: "#111"
    },
    legend: {
        display: true,
        position: "bottom",
        labels: {
            fontColor: "#333",
            fontSize: 16
        }
    },
    tooltips: {
        enabled: true,
        mode: 'single',
        callbacks: {
            label: function(tooltipItems, data) {
                var multistringText = ['Assay Value: '+tooltipItems.yLabel];
                multistringText.push('Assigned Value: '+assigned_value[tooltipItems.index]);
                multistringText.push('Sample ID: '+sample_id[tooltipItems.index]);
                return multistringText;
            }
        }
    },
    scales:{
        yAxes:[{
            ticks:{
                min:graph_min
            }
        }],
        xAxes: [{
            gridLines: {
                display:false
            }
        }]
    }
};
if(new_chart[ctx.canvas.id] != null)
    new_chart[ctx.canvas.id].destroy();

new_chart[ctx.canvas.id] =new Chart(ctx, {
    type: 'line',
    data: data,
    options: options
});
</code>```

In x-axis there is data like this

```<code>[19-Aug-2015,21-Aug-2015,21-Aug-2015,21-Aug-2015,21-Aug-2015,22-Aug-2015,27-Aug-2015,29-Aug-2015,1-Sep-2015,2-Sep-2015,3-Sep-2015,]
</code>```

in y-axis data is like this

```<code>[0.1,0.05,0.89,0.89,0.79,0.58,0.68,0.25,0.98]
</code>```

答:
The way to control distance between points it to set the X and Y axis with a min, max, and step size so that they never change regardless of the number of points that are in the chart.

Here is an example that sets the scales so that they will never change.  Regardless of how many points appear on the chart everything will stay the same.

```<code>var ctx = document.getElementById("myChart");
var myChart = new Chart(ctx, {
  type: 'line',
  data: {
    datasets: [{
      label: 'Points',
      data: [
        {x: 0, y: 2},
        {x: 1, y: 3},
        {x: 2, y: 2},
        {x: 1.02, y: 0.4},
        {x: 0, y: -1}
      ],
      backgroundColor: 'rgba(123, 83, 252, 0.8)',
      borderColor: 'rgba(33, 232, 234, 1)',
      borderWidth: 1,
      fill: false,
      showLine: false,
    }],
  },
  options: {
    title: {
      display: true,
      text: 'Chart.js - Fixed X and Y Axis',
    },
    scales: {
      xAxes: [{
        type: 'linear',
        position: 'bottom',
        ticks: {
          min: -1,
          max: 8,
          stepSize: 1,
          fixedStepSize: 1,
        }
      }],
      yAxes: [{
        ticks: {
          min: -2,
          max: 4,
          stepSize: 1,
          fixedStepSize: 1,
        }
      }]
    }
  }
});
</code>```

Here is a codepen example that demonstrates what this looks like

Body:
Problem: Hi all! i am using chart.js to draw the charts. chart is a dynamic sometimes shows 10 points and sometimes can be more than thousand i have applied a panel successfully so that my points can be shown at some distance to read them easily.

Right now i want to know if there is any option to set the distance between points in x-axis grid. right now it automatically adjust the points.

What i tried:
i tried to do the stepsize and scalewidth by searching other stackoverflow answers but did not succeed. Any kind of help would be much appreciated.

P.S:  i m using chart.js2

This is my chartjs dataset

var data = {
    labels: data.graph_date,
    datasets: [
        {
            label: 'Assay Values',
            fill: false,
            lineTension: 0,
            backgroundColor: "rgba(255, 0, 0,1)",
            borderColor: "rgba(255, 0, 0,1)",
            borderCapStyle: 'butt',
            borderDash: [],
            borderDashOffset: 0.0,
            borderWidth: 1,
            borderJoinStyle: 'miter',
            pointBorderColor: "rgba(255, 0, 0,1)",
            pointBackgroundColor: "#fff",
            pointBorderWidth: 1,
            pointHoverRadius: 5,
            pointHoverBackgroundColor: "rgba(255, 0, 0,1)",
            pointHoverBorderColor: "rgba(255, 0, 0,1)",
            pointHoverBorderWidth: 2,
            pointRadius: 1,
            pointHitRadius: 10,
            data: data.assay_value,
            spanGaps: false
        },var options = {
    responsive: false,
    title: {
        display: true,
        position: "top",
        text: label,
        fontSize: 18,
        fontColor: "#111"
    },
    legend: {
        display: true,
        position: "bottom",
        labels: {
            fontColor: "#333",
            fontSize: 16
        }
    },
    tooltips: {
        enabled: true,
        mode: 'single',
        callbacks: {
            label: function(tooltipItems, data) {
                var multistringText = ['Assay Value: '+tooltipItems.yLabel];
                multistringText.push('Assigned Value: '+assigned_value[tooltipItems.index]);
                multistringText.push('Sample ID: '+sample_id[tooltipItems.index]);
                return multistringText;
            }
        }
    },
    scales:{
        yAxes:[{
            ticks:{
                min:graph_min
            }
        }],
        xAxes: [{
            gridLines: {
                display:false
            }
        }]
    }
};
if(new_chart[ctx.canvas.id] != null)
    new_chart[ctx.canvas.id].destroy();

new_chart[ctx.canvas.id] =new Chart(ctx, {
    type: 'line',
    data: data,
    options: options
});

In x-axis there is data like this

[19-Aug-2015,21-Aug-2015,21-Aug-2015,21-Aug-2015,21-Aug-2015,22-Aug-2015,27-Aug-2015,29-Aug-2015,1-Sep-2015,2-Sep-2015,3-Sep-2015,]

in y-axis data is like this

[0.1,0.05,0.89,0.89,0.79,0.58,0.68,0.25,0.98]

Body:
The way to control distance between points it to set the X and Y axis with a min, max, and step size so that they never change regardless of the number of points that are in the chart.

Here is an example that sets the scales so that they will never change.  Regardless of how many points appear on the chart everything will stay the same.

var ctx = document.getElementById("myChart");
var myChart = new Chart(ctx, {
  type: 'line',
  data: {
    datasets: [{
      label: 'Points',
      data: [
        {x: 0, y: 2},
        {x: 1, y: 3},
        {x: 2, y: 2},
        {x: 1.02, y: 0.4},
        {x: 0, y: -1}
      ],
      backgroundColor: 'rgba(123, 83, 252, 0.8)',
      borderColor: 'rgba(33, 232, 234, 1)',
      borderWidth: 1,
      fill: false,
      showLine: false,
    }],
  },
  options: {
    title: {
      display: true,
      text: 'Chart.js - Fixed X and Y Axis',
    },
    scales: {
      xAxes: [{
        type: 'linear',
        position: 'bottom',
        ticks: {
          min: -1,
          max: 8,
          stepSize: 1,
          fixedStepSize: 1,
        }
      }],
      yAxes: [{
        ticks: {
          min: -2,
          max: 4,
          stepSize: 1,
          fixedStepSize: 1,
        }
      }]
    }
  }
});

Here is a codepen example that demonstrates what this looks like


问:
How to combine models using Mongoose Population
At the moment I'm defining different models in different files depending on where I use them but there are relations between them and I find myself constantly fetching one, then the other using an ID from the first. E.g.:

File 'models/users.js'

```<code>var mongoose = require('mongoose');
var db = mongoose.connection;
var UserSchema = mongoose.Schema({
    // fields
    companyId: {
        type: String
    }
});

var User = module.exports = mongoose.model('User', UserSchema);

module.exports.getUserById = function(id, callback){
    User.findById(id, callback);
}
</code>```

File 'models/company.js'

```<code>var mongoose = require('mongoose');
var db = mongoose.connection;
var CompanySchema = mongoose.Schema({
    // fields
});
// module export and functions etc.
</code>```

So in that example the User companyId is the ID of one of the companies. Then in my routes I'll import both models, get a User, find the company ID and then fetch that company data:

```<code>var Promise = require('bluebird');
var User = Promise.promisifyAll(require('../models/user'));
var Company = Promise.promisifyAll(require('../models/company'));

User.getUserByIdAsync()
.then(function(user){
    return [user, Company.getCompanyByIdAsync(user.companyId)];
}).spread(function(user,company){
    // Do stuff
}).catch(function(err)... etc });
</code>```

I've been reading about population on the Mongoose docs here: http://mongoosejs.com/docs/populate.html but in the examples everything is in one file. I'm trying to keep models separate for maintainability (and my sanity) so any calls to other models will throw errors.

Is there a way to join the models or reference other external models so I can do this? Is the schema even right?...

I'm using Express and Mongoose.

答:
You can save company reference in Users Model and hence While fetching details you can get company details as well : </p>

```<code>var getUserWithPopulate = function (criteria, projection, options, callback) {
  Models.Users.find(criteria, projection, options).populate([
    {path: 'company', select:'companyId, companyName'}
  ]).exec(callback);
};
</code>```

Body:
At the moment I'm defining different models in different files depending on where I use them but there are relations between them and I find myself constantly fetching one, then the other using an ID from the first. E.g.:

File 'models/users.js'

var mongoose = require('mongoose');
var db = mongoose.connection;
var UserSchema = mongoose.Schema({
    // fields
    companyId: {
        type: String
    }
});

var User = module.exports = mongoose.model('User', UserSchema);

module.exports.getUserById = function(id, callback){
    User.findById(id, callback);
}

File 'models/company.js'

var mongoose = require('mongoose');
var db = mongoose.connection;
var CompanySchema = mongoose.Schema({
    // fields
});
// module export and functions etc.

So in that example the User companyId is the ID of one of the companies. Then in my routes I'll import both models, get a User, find the company ID and then fetch that company data:

var Promise = require('bluebird');
var User = Promise.promisifyAll(require('../models/user'));
var Company = Promise.promisifyAll(require('../models/company'));

User.getUserByIdAsync()
.then(function(user){
    return [user, Company.getCompanyByIdAsync(user.companyId)];
}).spread(function(user,company){
    // Do stuff
}).catch(function(err)... etc });

I've been reading about population on the Mongoose docs here: http://mongoosejs.com/docs/populate.html but in the examples everything is in one file. I'm trying to keep models separate for maintainability (and my sanity) so any calls to other models will throw errors.

Is there a way to join the models or reference other external models so I can do this? Is the schema even right?...

I'm using Express and Mongoose.

Body:
You can save company reference in Users Model and hence While fetching details you can get company details as well :

var getUserWithPopulate = function (criteria, projection, options, callback) {
  Models.Users.find(criteria, projection, options).populate([
    {path: 'company', select:'companyId, companyName'}
  ]).exec(callback);
};


问:
How to force an element above another
I have two slightly overlapping (breadcrumb) elements, side-by-side, and I want to make the one on the left to clip the one on the right. Setting z-index didn't appear to work. Is there a better way?

DEMO:https://plnkr.co/edit/5RCH9hswONT16QJeK3KE?p=preview

    .arrow-point {
        display: inline-block;
        border-top: 12px solid transparent;
        border-bottom: 12px solid transparent;
        border-left: 15px solid #777;
        /* z-index:10; */
    }
    .arrow-body {
        font-family: verdana;
        font-size:15px;
        display: inline-block;
        background-color: #777;
        color:white;
        padding:2px 6px 2px 20px;
        height:20px;
        vertical-align:top;
        /* z-index:-3; */
    }
    .arrow-tail {
        position: absolute;
        display: inline-block;
        border-top: 12px solid transparent;
        border-bottom: 12px solid transparent;
        border-left: 15px solid #FFF;
        /* z-index:-2; */
        /* margin-left:-6px; */
    }```
<pre class="snippet-code-html lang-html prettyprint-override"><code>    <div style="font-size:0;display:inline-block">
        <div class="arrow-tail"></div>
        <div class="arrow-body">Submenu A</div>
        <div class="arrow-point"></div>
    </div>
    <div style="font-size:0;float:left;margin-right:-6px;display:inline-block">
        <div class="arrow-body">Main Menu</div>
        <div class="arrow-point"></div>
    </div></code>```

答:
Assuming that all these menus are inside a container div, set the parent style to float:left; and have the children float:right. Please ensure that the order must be reversed.  Take a look.

.container{
    position:relative;
    float:left;
}
.container > div{
    position: relative;
    margin-left: -15px;
    z-index: 10;
    font-size: 0;
    display: inline-block;
    float: right;
}
.container > div:last-child{
  margin-left:0;
}
.arrow-point {
        display: inline-block;
        border-top: 12px solid transparent;
        border-bottom: 12px solid transparent;
        border-left: 15px solid #777;
        /* z-index:10; */
    }
    .arrow-body {
        font-family: verdana;
        font-size:15px;
        display: inline-block;
        background-color: #777;
        color:white;
        padding:2px 6px 2px 20px;
        height:20px;
        vertical-align:top;
        /* z-index:-3; */
    }
    .arrow-tail {
        position: absolute;
        display: inline-block;
        border-top: 12px solid transparent;
        border-bottom: 12px solid transparent;
        border-left: 15px solid #FFF;
        /* z-index:-2; */
        /* margin-left:-6px; */
    }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">
    <div>
        <div class="arrow-tail"></div>
        <div class="arrow-body">Submenu B</div>
        <div class="arrow-point"></div>
    </div>
    <div>
        <div class="arrow-tail"></div>
        <div class="arrow-body">Submenu A</div>
        <div class="arrow-point"></div>
    </div>
    <div>
        <div class="arrow-body">Main Menu</div>
        <div class="arrow-point"></div>
    </div>
</div></code>```

Title: How to force an element above another

Body:
I have two slightly overlapping (breadcrumb) elements, side-by-side, and I want to make the one on the left to clip the one on the right. Setting z-index didn't appear to work. Is there a better way?

DEMO:https://plnkr.co/edit/5RCH9hswONT16QJeK3KE?p=preview

    .arrow-point {
        display: inline-block;
        border-top: 12px solid transparent;
        border-bottom: 12px solid transparent;
        border-left: 15px solid #777;
        /* z-index:10; */
    }
    .arrow-body {
        font-family: verdana;
        font-size:15px;
        display: inline-block;
        background-color: #777;
        color:white;
        padding:2px 6px 2px 20px;
        height:20px;
        vertical-align:top;
        /* z-index:-3; */
    }
    .arrow-tail {
        position: absolute;
        display: inline-block;
        border-top: 12px solid transparent;
        border-bottom: 12px solid transparent;
        border-left: 15px solid #FFF;
        /* z-index:-2; */
        /* margin-left:-6px; */
    }

Submenu A

Main Menu

Body:
Assuming that all these menus are inside a container div, set the parent style to float:left; and have the children float:right. Please ensure that the order must be reversed.  Take a look.

.container{
    position:relative;
    float:left;
}
.container > div{
    position: relative;
    margin-left: -15px;
    z-index: 10;
    font-size: 0;
    display: inline-block;
    float: right;
}
.container > div:last-child{
  margin-left:0;
}
.arrow-point {
        display: inline-block;
        border-top: 12px solid transparent;
        border-bottom: 12px solid transparent;
        border-left: 15px solid #777;
        /* z-index:10; */
    }
    .arrow-body {
        font-family: verdana;
        font-size:15px;
        display: inline-block;
        background-color: #777;
        color:white;
        padding:2px 6px 2px 20px;
        height:20px;
        vertical-align:top;
        /* z-index:-3; */
    }
    .arrow-tail {
        position: absolute;
        display: inline-block;
        border-top: 12px solid transparent;
        border-bottom: 12px solid transparent;
        border-left: 15px solid #FFF;
        /* z-index:-2; */
        /* margin-left:-6px; */
    }

<div class="container">
    <div>
        <div class="arrow-tail"></div>
        <div class="arrow-body">Submenu B</div>
        <div class="arrow-point"></div>
    </div>
    <div>
        <div class="arrow-tail"></div>
        <div class="arrow-body">Submenu A</div>
        <div class="arrow-point"></div>
    </div>
    <div>
        <div class="arrow-body">Main Menu</div>
        <div class="arrow-point"></div>
    </div>
</div>


答:
```<code> >>> MENU_Items = [ {  "ID":0x3B08, "Description":"Read Levelling Status\t\t"},
...                 { "ID":0x3B39, "Description":"Read Air system control module state"},
...                 { "ID":0x3B3A, "Description":"Read Movement inhibit state\t"},
...                 { "ID":0x3B3B, "Description":"Read Target height status\t\t"}]
</code>```

for input  = 1,search for index = 0

```<code>>>> MENU_Items[0]
{'ID': 15112, 'Description': 'Read Levelling Status\t\t'}
>>> MENU_Items[0]['ID']
15112
</code>```

Title: How to get python list first element id

Body:
 >>> MENU_Items = [ {  "ID":0x3B08, "Description":"Read Levelling Status\t\t"},
...                 { "ID":0x3B39, "Description":"Read Air system control module state"},
...                 { "ID":0x3B3A, "Description":"Read Movement inhibit state\t"},
...                 { "ID":0x3B3B, "Description":"Read Target height status\t\t"}]

for input  = 1,search for index = 0

>>> MENU_Items[0]
{'ID': 15112, 'Description': 'Read Levelling Status\t\t'}
>>> MENU_Items[0]['ID']
15112


问:
Kubernetes and flannel network setup
I hope someone can enlighten me on Kubernetes network setup. I want to use flannel as the Kubernetes network layer.

I'm on Kubernetes: 1.5.5 btw.

The problem is, there are so many places you can(should?) define a cidr, I'm not seeing the woods for the trees anymore.

To give you some info about my setup:

my hosts are deployed in the 10.9.0.0/24 range.

I want to use 10.254.0.0/16 as the flannel range

at the moment, docker on the worker nodes uses the 172.17.0.0/16 range

kube-apiserver has the following options for cidr's:

```<code>--service-cluster-ip-range
</code>```

kube-controller-manager has the following options for cidr's:

```<code>--cluster-cidr
--service-cluster-ip-range
</code>```

what's the difference between those two?

kube-proxy has this one:

```<code>--cluster-cidr={{ kubernetes_cluster_cidr }}
</code>```

what ip range goes where exactly?

答:
Actually, you have 2 different network layers there:

Cluster-cidr: the pods layer (where you want to use 10.254.0.0/16):
Once you have your flannel network up and running, you will have to configure Docker to use it (via systemd drop-in or with something like:
echo "DOCKER_OPTS="--bip=${FLANNEL_SUBNET} --mtu=${FLANNEL_MTU}"" >> /etc/default/docker). This way all the "docker0" interfaces in your cluster will be connected within the flannel network.

Service-cluster-ip-range: the service layer. Services are used to abstract a logical set of pods. As long as you don't know where a pod is going to be located, or the IP that is going to be assigned to it... You need some kind of abstraction to reach a pod/set of pods, wherever they are.

A Kubernetes Service is an abstraction which defines a logical set of Pods and a policy by which to access them - sometimes called a micro-service. The set of Pods targeted by a Service is (usually) determined by a Label Selector (see below for why you might want a Service without a selector).
  As an example, consider an image-processing backend which is running with 3 replicas. Those replicas are fungible - frontends do not care which backend they use. While the actual Pods that compose the backend set may change, the frontend clients should not need to be aware of that or keep track of the list of backends themselves. The Service abstraction enables this decoupling.

NOTE: The service layer must not overlap with your cluster pods network (flannel) or any other existing network infrastructure.

Title: Kubernetes and flannel network setup

Body:
I hope someone can enlighten me on Kubernetes network setup. I want to use flannel as the Kubernetes network layer.

I'm on Kubernetes: 1.5.5 btw.

The problem is, there are so many places you can(should?) define a cidr, I'm not seeing the woods for the trees anymore.

To give you some info about my setup:

my hosts are deployed in the 10.9.0.0/24 range.

I want to use 10.254.0.0/16 as the flannel range

at the moment, docker on the worker nodes uses the 172.17.0.0/16 range

kube-apiserver has the following options for cidr's:

--service-cluster-ip-range

kube-controller-manager has the following options for cidr's:

--cluster-cidr
--service-cluster-ip-range

what's the difference between those two?

kube-proxy has this one:

--cluster-cidr={{ kubernetes_cluster_cidr }}

what ip range goes where exactly?


问:
How to retrieve shell output from within i_CTRL_R in vim?
When in insert mode in vim, I often do CTRL-R and retrieve a register content.

I like to be able to retrieve text that's not currently in a buffer, like the output of the shell command, pwd.

I was under the impression I could hit i_CTRL_R ! pwd sequence, but  i_CTRL_R can only takes a register.

The expression register = seems to be the only way to compute things dynamically, but I don't know what is the minimum number of key-strokes to get the = register to be populated with a shell output, or env variables.

Vimmers?

答:
You can insert environment variables directly with:

```<code><C-r>=$PATH
</code>```

For inserting the output of shell commands you will need :help system() if you absolutely need to stay in insert mode:

```<code><C-r>=system('ls')
</code>```

If you don't mind leaving insert mode temporarily, you can use :help :read:

```<code><C-o>:r!ls<CR>
</code>```

Body:
You can insert environment variables directly with:

<C-r>=$PATH

For inserting the output of shell commands you will need :help system() if you absolutely need to stay in insert mode:

<C-r>=system('ls')

If you don't mind leaving insert mode temporarily, you can use :help :read:

<C-o>:r!ls<CR>


问:
WebGL cuts part of the 3D image (works fine in RGL viewer)
I am trying to export a 3D plot from the plot3D() function as so:

```<code>library(maptools)
library(raster)
srtm <- getData("SRTM", lon=-15.59972, lat=27.965)

library(rgdal)
library(rasterVis)
library(rgl)
library(htmlwidgets)

open3d() # Open a new RGL device
plot3D(srtm)
</code>```

When I run the code in R, everything works fine. The plot is rendered correctly in the RGL device window.

However, when I want to either export to html or embed it in a RMarkdown, part of the 3D plot gets cut.

By following the link below, you can see the html from

```<code>writeWebGL(dir = "webGL", filename = file.path(getwd(), "index.html"), width = 1000, height = 1000)
</code>```

or

```<code>browseURL(paste("file://", writeWebGL(dir=file.path(getwd(), "webGL"), width=1000), sep=""))
</code>```

html from writeWebGL

I also tried the following to embed the plot in an RMarkdown:

```<code>library(knitr)
knit_hooks$set(webgl = hook_webgl)
options(rgl.printRglwidget = TRUE)

open3d()
plot3D(srtm)
rglscene <- scene3d()
# render the saved rgl scene as widget in the markdown page
rglwidget(rglscene,webGLoptions = list(preserveDrawingBuffer = FALSE))
</code>```

Here is the RMarkdown that got produced

Does somebody know why the plot gets cut in the html? I see the same if I plot other countries, btw. Thank you!

答: As the docs say in ?writeWebGL, there's a limit of 65536 vertices in objects in WebGL in many browsers.  Your surface object is 316 by 316, which gives it about 100000 vertices.  You'll need to break it up into two or more pieces, or plot it with lower resolution.

Body:
I am trying to export a 3D plot from the plot3D() function as so:

library(maptools)
library(raster)
srtm <- getData("SRTM", lon=-15.59972, lat=27.965)

library(rgdal)
library(rasterVis)
library(rgl)
library(htmlwidgets)

open3d() # Open a new RGL device
plot3D(srtm)

When I run the code in R, everything works fine. The plot is rendered correctly in the RGL device window.

However, when I want to either export to html or embed it in a RMarkdown, part of the 3D plot gets cut.

By following the link below, you can see the html from

writeWebGL(dir = "webGL", filename = file.path(getwd(), "index.html"), width = 1000, height = 1000)

or

browseURL(paste("file://", writeWebGL(dir=file.path(getwd(), "webGL"), width=1000), sep=""))

html from writeWebGL

I also tried the following to embed the plot in an RMarkdown:

library(knitr)
knit_hooks$set(webgl = hook_webgl)
options(rgl.printRglwidget = TRUE)

open3d()
plot3D(srtm)
rglscene <- scene3d()
# render the saved rgl scene as widget in the markdown page
rglwidget(rglscene,webGLoptions = list(preserveDrawingBuffer = FALSE))

Here is the RMarkdown that got produced

Does somebody know why the plot gets cut in the html? I see the same if I plot other countries, btw. Thank you!