问:
Tuple error with class and object
I'm currently working on this,

Design a class Car.
This class has the following attributes: maker, model, and price
The Car class should have methods to return the current values of these attributes. In addition, this class has a method update_price to change the price attribute value.

Design a class called Dealer.
This class has the following attributes: address and inventory. The inventory attribute is a list of Car objects.
The Dealer class should have methods to add a car object to the inventory, remove a car object from the inventory (car removal should be done based on car model), and update the price of a certain car model. This class also has a method that shows the entire inventory and a method that calculates the total value of all cars in the inventory.

In the main function, the program creates a Dealer object, adds multiple cars to the inventory, and shows the current inventory. Then the program removes a car model from the inventory and updates the price for a given car model. At the end, the program displays the entire inventory and the total value of all cars currently in the inventory.

But when I run my code I get

TypeError: descriptor 'append' requires a 'list' object but received a 'tuple'

And I have no idea how to fix this

```<code>class Car:
    def __init__(self, maker, model, price):
        self.__maker=maker
        self.__model=model
        self.__price=price
    def get_model(self):
        return self.__model
    def get_maker(self):
        return self.__maker
    def get_price(self):
        return self.__price

    def create_list(list):
        maker=input('Enter Car maker: ')
        model=input('Enter Car model: ')
        price=float(input('Enter Car price: $'))
        account=(maker, model, price)
        list.append(account)

    def update_price(self):
        self.__price=price
        return self.__update_price

class Dealer():
    def __init__(address, inventory):
        self.__inventory=inventory
        self.__address=address
    def update_price(list):
        model=input('Enter car model: ')
        account=Car(maker, model, price)
        found='false'
        for model in list:
            if account.get_model() == model:
                account.append(price)
                found=='true'
            if found == 'false':
                print('Model Not Found')
        return account
def show_inventory(list):
    show_inventory=print(account)

def calculate_total_value(list):
    print(sum(self.__account.price))

def remove_car(list):
    model=input('Model for removal')
    found = 'false'
    for model in list:
        if account.get_model() ==model:
            account.remove(model)
            found =='true'
    if found =='false':
        print('Model Not Found')
def get_address(address):

    self.__address=address
    return self.__address
def main():
    address=input('Enter address: ')

    account_list=[]
    counter=1
    manytimes=float(input('How many cars to add? '))
    while counter<=manytimes:
        counter=counter+1
        create_list(list)
    show_inventory(account_list)
    remove_car(account_list)
    show_inventory(list)
    update_price(account_list)
    show_inventory(account_list)
    calculate_total_value(account_list)

main()
</code>```

答: Looks like wherever that error is occuring, you're trying to append something to a tuple which is immutable, meaning it can't be changed (in this case, you can't append something to it). A tuple is very similar to a list in that in can store values and be accessed through an index (starting at 0). Wherever you're trying to append something, make sure you're using a list and not a tuple. If it is a tuple, you can convert it to a list using list(tuple_name) and then you should be able to append to it.

Title: Tuple error with class and object

Body:
I'm currently working on this,

Design a class Car.
This class has the following attributes: maker, model, and price
The Car class should have methods to return the current values of these attributes. In addition, this class has a method update_price to change the price attribute value.

Design a class called Dealer.
This class has the following attributes: address and inventory. The inventory attribute is a list of Car objects.
The Dealer class should have methods to add a car object to the inventory, remove a car object from the inventory (car removal should be done based on car model), and update the price of a certain car model. This class also has a method that shows the entire inventory and a method that calculates the total value of all cars in the inventory.

In the main function, the program creates a Dealer object, adds multiple cars to the inventory, and shows the current inventory. Then the program removes a car model from the inventory and updates the price for a given car model. At the end, the program displays the entire inventory and the total value of all cars currently in the inventory.

But when I run my code I get

TypeError: descriptor 'append' requires a 'list' object but received a 'tuple'

And I have no idea how to fix this

class Car:
    def __init__(self, maker, model, price):
        self.__maker=maker
        self.__model=model
        self.__price=price
    def get_model(self):
        return self.__model
    def get_maker(self):
        return self.__maker
    def get_price(self):
        return self.__price

    def create_list(list):
        maker=input('Enter Car maker: ')
        model=input('Enter Car model: ')
        price=float(input('Enter Car price: $'))
        account=(maker, model, price)
        list.append(account)

    def update_price(self):
        self.__price=price
        return self.__update_price

class Dealer():
    def __init__(address, inventory):
        self.__inventory=inventory
        self.__address=address
    def update_price(list):
        model=input('Enter car model: ')
        account=Car(maker, model, price)
        found='false'
        for model in list:
            if account.get_model() == model:
                account.append(price)
                found=='true'
            if found == 'false':
                print('Model Not Found')
        return account
def show_inventory(list):
    show_inventory=print(account)

def calculate_total_value(list):
    print(sum(self.__account.price))

def remove_car(list):
    model=input('Model for removal')
    found = 'false'
    for model in list:
        if account.get_model() ==model:
            account.remove(model)
            found =='true'
    if found =='false':
        print('Model Not Found')
def get_address(address):

    self.__address=address
    return self.__address
def main():
    address=input('Enter address: ')

    account_list=[]
    counter=1
    manytimes=float(input('How many cars to add? '))
    while counter<=manytimes:
        counter=counter+1
        create_list(list)
    show_inventory(account_list)
    remove_car(account_list)
    show_inventory(list)
    update_price(account_list)
    show_inventory(account_list)
    calculate_total_value(account_list)

main()


来源: stackexchange

问:
Excel - Function to use in CHOOSE - Return list of values from range
Which excel function can I use in this CHOOSE formula to convert the range to a list and allow the return of the below CHOOSE function to be b

Example this problem to get value 'b'. Where range B2:F2 is equal to a,b,c,d,e.

```<code>CHOOSE(2, B2:F2)
</code>```

This will fail as we have supplied a range to choose not a list.

答:
To do this with CHOOSE you have to split the range in to individual cells, i.e.

=CHOOSE(2,B2,C2,D2,E2,F2)

ContentLicense: CC BY-SA 3.0

Body:
Which excel function can I use in this CHOOSE formula to convert the range to a list and allow the return of the below CHOOSE function to be b

Example this problem to get value 'b'. Where range B2:F2 is equal to a,b,c,d,e.

CHOOSE(2, B2:F2)

This will fail as we have supplied a range to choose not a list.


问:
Div above another one JQuery script didn't work !
I have two divs, and I just want the second one to be under [in z-index] the first one, I read about it here and I figured out that I have to use the following JQuery script:

```<code><script type="text/javascript">
    $('#secondDiv').insertBefore('#firstDiv');
</script>
</code>```

I tried it, but it didn't work with me, Any help!!

```<code><DetailedTemplate>
<div id="firstDiv" style="background-color:Black">
    <asp:ImageButton ID="SelectButton" Visible='<%# org.SelectedValue == null || Container.DataElement("ID").ToString() != org.SelectedValue.ToString() %>' runat="server" CommandName="Select" CommandArgument='<%# Container.DataElement("ID") %>'
      OnPreRender="SelectButton_PreRender" style="border-style:none; Height:58px; width:113px; cursor:hand"  ImageUrl="~/Contents/Images/item-background.png"/>
</div>

<div id="secondDiv" style="background-color:Red" >
    <center style=" margin: 5px; padding-top: 5px; padding-right: 5px; padding-left: 5px;">
        <asp:LinkButton ID="lnkTitle" ForeColor="#6c1b24" Font-Bold="true" runat="server"
            Text='<%# Container.DataElement("Name") %>' NavigateUrl="http://google.com">
        </asp:LinkButton>
        <div runat="server" visible='<%# Convert.ToInt32(Container.DataElement("NumOfChildren")) > 0 %>'
            style="border: 1px solid #6c1b24; width: 15px; text-align: center; height: 15px;
            margin-top: 25px; background-color: #fddb73; font-size: larger; font-family: Courier New;">
            <asp:LinkButton ID="btnExpand" runat="server" ForeColor="#6c1b24" CommandArgument='<%# Container.DataElement("ID")%>'
                CommandName="Expand" Font-Underline="false" Text='<%# Container.NumberOfChildren > 0 ? "-" : "+" %>' />
        </div>
    </center>
</div>

<script type="text/javascript">
    $('#secondDiv').insertBefore('#firstDiv');
</script>
</DetailedTemplate>
</code>```

Note: I can't put my divs as absolute in my situation.

答:
insertBefore() has nothing to do with z-index. It adds it to the DOM tree before the element specified.

Use

```<code>$("#myId").css("z-index", "-10");
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I have two divs, and I just want the second one to be under [in z-index] the first one, I read about it here and I figured out that I have to use the following JQuery script:

I tried it, but it didn't work with me, Any help!!

<DetailedTemplate>

    <asp:ImageButton ID="SelectButton" Visible='<%# org.SelectedValue == null || Container.DataElement("ID").ToString() != org.SelectedValue.ToString() %>' runat="server" CommandName="Select" CommandArgument='<%# Container.DataElement("ID") %>'
      OnPreRender="SelectButton_PreRender" style="border-style:none; Height:58px; width:113px; cursor:hand"  ImageUrl="~/Contents/Images/item-background.png"/>

        <asp:LinkButton ID="lnkTitle" ForeColor="#6c1b24" Font-Bold="true" runat="server"
            Text='<%# Container.DataElement("Name") %>' NavigateUrl="http://google.com">
        </asp:LinkButton>
        <div runat="server" visible='<%# Convert.ToInt32(Container.DataElement("NumOfChildren")) > 0 %>'
            style="border: 1px solid #6c1b24; width: 15px; text-align: center; height: 15px;
            margin-top: 25px; background-color: #fddb73; font-size: larger; font-family: Courier New;">
            <asp:LinkButton ID="btnExpand" runat="server" ForeColor="#6c1b24" CommandArgument='<%# Container.DataElement("ID")%>'
                CommandName="Expand" Font-Underline="false" Text='<%# Container.NumberOfChildren > 0 ? "-" : "+" %>' />

</DetailedTemplate>

Note: I can't put my divs as absolute in my situation.

Body:
insertBefore() has nothing to do with z-index. It adds it to the DOM tree before the element specified.

Use

$("#myId").css("z-index", "-10");


问:
Async/Await with Request-Promise returns Undefined
I have two files; server.js and scrape.js, below are the code snippets as they currently stand.

server.js:

```<code>const scrape = require("./scrape");

async function start() {
    const response = await scrape.start();
    console.log(response);
}

start();
</code>```

and scrape.js:

```<code>const cheerio = require("cheerio");
const request = require("request-promise");

go = async () => {

const options = {
  uri: "http://www.somewebsite.com/something",
  transform: function(body) {
    return cheerio.load(body);
  }
};

request(options)
  .then($ => {
    let scrapeTitleArray = [];
    $(".some-class-in-html").each(function(i, obj) {
      const data = $(this)
        .text()
        .trim();
      scrapeTitleArray.push(data);
    });
    return scrapeTitleArray;
  })
  .catch(err => {
    console.log(err);
  });
};

module.exports = {
  start: go
};
</code>```

So when I spin up server.js, I return undefined to the console.log(response), when I actually want to return the array i've been pushing to, can you see where I'm going wrong?

答:
You need to return something from your async function (a return inside a then does not return from the main function). Either a promise or something you await-ed.

Also, make sure to declare your go variable to avoid leaking it into the global space.

```<code>const go = async () => {

  const options = {
    uri: "http://www.somewebsite.com/something",
    transform: function(body) {
      return cheerio.load(body);
    }
  };

  return request(options)
    .then($ => {
      let scrapeTitleArray = [];
      $(".some-class-in-html").each(function(i, obj) {
        const data = $(this)
          .text()
          .trim();
        scrapeTitleArray.push(data);
      });
      return scrapeTitleArray;
    })
    .catch(err => {
      console.log(err);
    });
};
</code>```

Since you are using an async function, you might want to take advantage of the await syntax also.

```<code>const go = async () => {

  const options = {
    uri: "http://www.somewebsite.com/something",
    transform: function(body) {
      return cheerio.load(body);
    }
  };

  try {
    const $ = await request(options);
    $(".some-class-in-html").each(function(i, obj) {
      const data = $(this)
        .text()
        .trim();
      scrapeTitleArray.push(data);
    });
    return scrapeTitleArray;
  }
  catch (err) {
    console.log(err);
  }
};
</code>```

Body:
I have two files; server.js and scrape.js, below are the code snippets as they currently stand.

server.js:

const scrape = require("./scrape");

async function start() {
    const response = await scrape.start();
    console.log(response);
}

start();

and scrape.js:

const cheerio = require("cheerio");
const request = require("request-promise");

go = async () => {

const options = {
  uri: "http://www.somewebsite.com/something",
  transform: function(body) {
    return cheerio.load(body);
  }
};

request(options)
  .then($ => {
    let scrapeTitleArray = [];
    $(".some-class-in-html").each(function(i, obj) {
      const data = $(this)
        .text()
        .trim();
      scrapeTitleArray.push(data);
    });
    return scrapeTitleArray;
  })
  .catch(err => {
    console.log(err);
  });
};

module.exports = {
  start: go
};

So when I spin up server.js, I return undefined to the console.log(response), when I actually want to return the array i've been pushing to, can you see where I'm going wrong?

Body:
You need to return something from your async function (a return inside a then does not return from the main function). Either a promise or something you await-ed.

Also, make sure to declare your go variable to avoid leaking it into the global space.

const go = async () => {

  const options = {
    uri: "http://www.somewebsite.com/something",
    transform: function(body) {
      return cheerio.load(body);
    }
  };

  return request(options)
    .then($ => {
      let scrapeTitleArray = [];
      $(".some-class-in-html").each(function(i, obj) {
        const data = $(this)
          .text()
          .trim();
        scrapeTitleArray.push(data);
      });
      return scrapeTitleArray;
    })
    .catch(err => {
      console.log(err);
    });
};

Since you are using an async function, you might want to take advantage of the await syntax also.

const go = async () => {

  const options = {
    uri: "http://www.somewebsite.com/something",
    transform: function(body) {
      return cheerio.load(body);
    }
  };

  try {
    const $ = await request(options);
    $(".some-class-in-html").each(function(i, obj) {
      const data = $(this)
        .text()
        .trim();
      scrapeTitleArray.push(data);
    });
    return scrapeTitleArray;
  }
  catch (err) {
    console.log(err);
  }
};


答:
I believe your go function isn't returning any value.

You're calling request(options).then(...), but what follows from that promise is never returned by go. I recommend you add a return statement:

```<code>go = async () => {

  const options = {
    uri: "http://www.somewebsite.com/something",
    transform: function(body) {
      return cheerio.load(body);
    }
  };

  // The only difference is that it says "return" here:
  return request(options)
    .then($ => {
      let scrapeTitleArray = [];
      $(".some-class-in-html").each(function(i, obj) {
        const data = $(this)
          .text()
          .trim();
        scrapeTitleArray.push(data);
      });
      return scrapeTitleArray;
    })
    .catch(err => {
      console.log(err);
    });
};
</code>```

Title: Async/Await with Request-Promise returns Undefined

Body:
I believe your go function isn't returning any value.

You're calling request(options).then(...), but what follows from that promise is never returned by go. I recommend you add a return statement:

go = async () => {

  const options = {
    uri: "http://www.somewebsite.com/something",
    transform: function(body) {
      return cheerio.load(body);
    }
  };

  // The only difference is that it says "return" here:
  return request(options)
    .then($ => {
      let scrapeTitleArray = [];
      $(".some-class-in-html").each(function(i, obj) {
        const data = $(this)
          .text()
          .trim();
        scrapeTitleArray.push(data);
      });
      return scrapeTitleArray;
    })
    .catch(err => {
      console.log(err);
    });
};


问:
C++ - Overwrite Multiple Lines that were Previously Output to Console
If I have a grid of characters displayed in the console, is there any practical way to re-write those multiple lines in order to output an altered grid on those same lines of the console.

e.g, I would like this code:

```<code>#include <iostream>

using namespace std;

int main() {
        for (int i=0; i<5; i++) {
                for (int j=0; j<5; j++) {
                        cout << "-";
                }
                cout << endl;
        }

        getchar();

        for (int i=0; i<5; i++) {
                cout << '\r';
                for (int j=0; j<5; j++) {
                        cout << "x";
                }
                cout.flush();
        }

        return 0;
}
</code>```

to output:

```<code>-----
-----
-----
-----
-----
</code>```

then, upon user input, overwrite that with;

```<code>xxxxx
xxxxx
xxxxx
xxxxx
xxxxx
</code>```

I see other examples of people displaying loading bar type displays by outputting '\r' to re-write a single line, but I'm not sure if there is any straightforward way to accomplish that for multiple lines?

I'm using MinGW.

One Solution:

```<code>#include <iostream>
#include <stdio.h>
#include <windows.h>

using namespace std;

void gotoxy( int column, int line )
  {
  COORD coord;
  coord.X = column;
  coord.Y = line;
  SetConsoleCursorPosition(
    GetStdHandle( STD_OUTPUT_HANDLE ),
    coord
    );
  }

int main() {
        for (int i=0; i<5; i++) {
                for (int j=0; j<5; j++) {
                        cout << "-";
                }
                cout << endl;
        }

        getchar();

        gotoxy(0,0);

        for (int i=0; i<5; i++) {
                for (int j=0; j<5; j++) {
                        cout << "x";
                }
                cout << endl;
        }

        return 0;
}
</code>```

答:
is any straightforward way to accomplish that for multiple lines?

Yes.  Ansi terminals are a straight forward and portable solution.  Every PC I have ever worked with has Ansi terminal emulations.  On ubuntu, gnome-terminal works fine.  I have long used ansi escape sequences.

For this effort, you probably only need goto and clear screen, but there are many more ansi terminal functions.

Since you have marked this post as C++, consider the following.

```<code>#include <chrono>
// 'compressed' chrono access --------------vvvvvvv
typedef std::chrono::high_resolution_clock  HRClk_t; // std-chrono-hi-res-clk
typedef HRClk_t::time_point                 Time_t;  // std-chrono-hi-res-clk-time-point
typedef std::chrono::milliseconds           MS_t;    // std-chrono-milliseconds
typedef std::chrono::microseconds           US_t;    // std-chrono-microseconds
typedef std::chrono::nanoseconds            NS_t;    // std-chrono-nanoseconds
using   namespace std::chrono_literals;  // support suffixes like 100ms, 2s, 30us
#include <iostream>
#include <iomanip>
#include <thread>

class Ansi_t   // use ansi features of gnome-terminal,
{              // or any ansi terminal
   // note: Ubuntu 15.10 gnome-terminal ansi term cursor locations
   //       are 1-based, with origin 1,1 at top left corner

   enum ANSI : int { ESC = 27 }; // escape

public:

   static std::string clrscr(void)
      {
         std::stringstream ss;
         ss << static_cast<char>(ESC)<< "[H"   // home
            << static_cast<char>(ESC)<< "[2J"; // clrbos
         return(ss.str());
      }

   //       r/c are 0 based------v------v------0 based from C++
   static std::string gotoRC(int r, int c)
      {
         std::stringstream ss;
         // Note: row/col of my apps are 0 based (as in C++)
         // here I fix xy to 1 based, by adding 1 while forming output
         ss << static_cast<char>(ESC)<< "["
            << (r+1) << ';' << (c+1) << 'H';
         return(ss.str());
      }

   // tbr - add more ansi functions when needed

}; // Ansi_t
</code>```

Note: I have, on occasion, added asserts to enforce that r and c are >= 0.

Usage example:

```<code>int main(int, char**)
{
   int retVal = -1;
   {
      Time_t start_us = HRClk_t::now();

      {
         std::cout << Ansi_t::clrscr() << std::flush;  // leaves cursor at top left of screen

         for (int i=0; i<10; ++i)
         {

            for (int r=0; r<5; ++r) // 0 based
            {
               std::cout << Ansi_t::gotoRC(r+5, 5)  // set cursor location
                         << "-----" << std::flush;
            }

            std::this_thread::sleep_for(500ms);

            // to overwrite
            for (int r=0; r<5; ++r)
            {
               std::cout << Ansi_t::gotoRC(r+5, 5)  // set cursor location
                         << "xxxxx" << std::flush;
            }

            std::this_thread::sleep_for(500ms);

            std::cout << Ansi_t::gotoRC(11,5) << 9-i << std::flush;

         }// for i

         std::cout << "\n\n" << std::endl;

         return 0;
      }

      auto  duration_us = std::chrono::duration_cast<US_t>(HRClk_t::now() - start_us);

      std::cout << "\n\n  duration  " << duration_us.count() << " us" << std::endl;
   }

   return(retVal);
}
</code>```

Memoization is straight forward using these Ansi_t methods.  Example snippets from working code:

add a data attribute to the class

```<code>std::string     m_toRowCol;  // cursor position string
</code>```

pre-fill the string in ctor

```<code> FOO_t::FOO_t( ... )
 : m_seqId     (a_gb.gBoardSz())
 , m_toRowCol  (a_gb.gotoRC(aRow, aCol)) // pre-compute
 // other data attribute init
 {
    // ctor body
 }
</code>```

use the pre-filled string to position cursor prior to state output

```<code>m_gb.termUpdate(m_toRowCol + // position cursor
                <output string>); // provide state info
</code>```

Body:
If I have a grid of characters displayed in the console, is there any practical way to re-write those multiple lines in order to output an altered grid on those same lines of the console.

e.g, I would like this code:

#include <iostream>

using namespace std;

int main() {
        for (int i=0; i<5; i++) {
                for (int j=0; j<5; j++) {
                        cout << "-";
                }
                cout << endl;
        }

        getchar();

        for (int i=0; i<5; i++) {
                cout << '\r';
                for (int j=0; j<5; j++) {
                        cout << "x";
                }
                cout.flush();
        }

        return 0;
}

to output:

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

then, upon user input, overwrite that with;

xxxxx
xxxxx
xxxxx
xxxxx
xxxxx

I see other examples of people displaying loading bar type displays by outputting '\r' to re-write a single line, but I'm not sure if there is any straightforward way to accomplish that for multiple lines?

I'm using MinGW.

One Solution:

#include <iostream>
#include <stdio.h>
#include <windows.h>

using namespace std;

void gotoxy( int column, int line )
  {
  COORD coord;
  coord.X = column;
  coord.Y = line;
  SetConsoleCursorPosition(
    GetStdHandle( STD_OUTPUT_HANDLE ),
    coord
    );
  }

int main() {
        for (int i=0; i<5; i++) {
                for (int j=0; j<5; j++) {
                        cout << "-";
                }
                cout << endl;
        }

        getchar();

        gotoxy(0,0);

        for (int i=0; i<5; i++) {
                for (int j=0; j<5; j++) {
                        cout << "x";
                }
                cout << endl;
        }

        return 0;
}

Body:
is any straightforward way to accomplish that for multiple lines?

Yes.  Ansi terminals are a straight forward and portable solution.  Every PC I have ever worked with has Ansi terminal emulations.  On ubuntu, gnome-terminal works fine.  I have long used ansi escape sequences.

For this effort, you probably only need goto and clear screen, but there are many more ansi terminal functions.

Since you have marked this post as C++, consider the following.

#include <chrono>
// 'compressed' chrono access --------------vvvvvvv
typedef std::chrono::high_resolution_clock  HRClk_t; // std-chrono-hi-res-clk
typedef HRClk_t::time_point                 Time_t;  // std-chrono-hi-res-clk-time-point
typedef std::chrono::milliseconds           MS_t;    // std-chrono-milliseconds
typedef std::chrono::microseconds           US_t;    // std-chrono-microseconds
typedef std::chrono::nanoseconds            NS_t;    // std-chrono-nanoseconds
using   namespace std::chrono_literals;  // support suffixes like 100ms, 2s, 30us
#include <iostream>
#include <iomanip>
#include <thread>

class Ansi_t   // use ansi features of gnome-terminal,
{              // or any ansi terminal
   // note: Ubuntu 15.10 gnome-terminal ansi term cursor locations
   //       are 1-based, with origin 1,1 at top left corner

   enum ANSI : int { ESC = 27 }; // escape

public:

   static std::string clrscr(void)
      {
         std::stringstream ss;
         ss << static_cast<char>(ESC)<< "[H"   // home
            << static_cast<char>(ESC)<< "[2J"; // clrbos
         return(ss.str());
      }

   //       r/c are 0 based------v------v------0 based from C++
   static std::string gotoRC(int r, int c)
      {
         std::stringstream ss;
         // Note: row/col of my apps are 0 based (as in C++)
         // here I fix xy to 1 based, by adding 1 while forming output
         ss << static_cast<char>(ESC)<< "["
            << (r+1) << ';' << (c+1) << 'H';
         return(ss.str());
      }

   // tbr - add more ansi functions when needed

}; // Ansi_t

Note: I have, on occasion, added asserts to enforce that r and c are >= 0.

Usage example:

int main(int, char**)
{
   int retVal = -1;
   {
      Time_t start_us = HRClk_t::now();

      {
         std::cout << Ansi_t::clrscr() << std::flush;  // leaves cursor at top left of screen

         for (int i=0; i<10; ++i)
         {

            for (int r=0; r<5; ++r) // 0 based
            {
               std::cout << Ansi_t::gotoRC(r+5, 5)  // set cursor location
                         << "-----" << std::flush;
            }

            std::this_thread::sleep_for(500ms);

            // to overwrite
            for (int r=0; r<5; ++r)
            {
               std::cout << Ansi_t::gotoRC(r+5, 5)  // set cursor location
                         << "xxxxx" << std::flush;
            }

            std::this_thread::sleep_for(500ms);

            std::cout << Ansi_t::gotoRC(11,5) << 9-i << std::flush;

         }// for i

         std::cout << "\n\n" << std::endl;

         return 0;
      }

      auto  duration_us = std::chrono::duration_cast<US_t>(HRClk_t::now() - start_us);

      std::cout << "\n\n  duration  " << duration_us.count() << " us" << std::endl;
   }

   return(retVal);
}

Memoization is straight forward using these Ansi_t methods.  Example snippets from working code:

add a data attribute to the class

std::string     m_toRowCol;  // cursor position string

pre-fill the string in ctor

 FOO_t::FOO_t( ... )
 : m_seqId     (a_gb.gBoardSz())
 , m_toRowCol  (a_gb.gotoRC(aRow, aCol)) // pre-compute
 // other data attribute init
 {
    // ctor body
 }

use the pre-filled string to position cursor prior to state output

m_gb.termUpdate(m_toRowCol + // position cursor
                <output string>); // provide state info


问:
Why are these .then() occurring out of order?
I've got a node application that spawns a child_process. When the child_process is finished running, I'd like to resolve a promise. The following code works, but the .then() statements occur out of order:

```<code>const storage = require('./storage');
const logging = require('./logging');
const process = require('child_process').spawn;

function convertIncomingFile(pathToFile) {
  logging.info(`Converting ${pathToFile}`);
  const convert = process(`cat`, [pathToFile], {});

  return Promise.resolve(
    convert.stdout.on('data', (data) => {
      logging.info(data.toString('utf8'));
    }),
    convert.stderr.on('data', (err) => {
      logging.error(err);
    }),
    convert.on('close', (code) => {
      logging.info(`Conversion finished with status code ${code}`);
    })
  );
}

module.exports = {
  convertFile: (filename) => {
    storage.downloadFile(filename).
      then((localFilename) => {
        logging.info(`File saved to: ${localFilename}`);
      }).
      then(() => convertIncomingFile(`./files/${filename}`)).
      then(() => {
        logging.info(`Coversion of ${filename} complete.`);
      }).
      catch((apiErr) => {
        logging.error(apiErr);
      });
  }
};
</code>```

The output I get is:

```<code>info: File saved to: ./files/package.json
info: Converting ./files/package.json
info: Coversion of package.json complete.
info: {
 <file contents>
}

info: Conversion finished with status code 0
</code>```

As you can see the Conversion of package.json complete. statement occurs before the file contents are logged and the conversion status code statement. Why is this the case and how do I get the 'Conversion complete' statement to come after the 'status code' statement?

答:
You have to pass the convertFile promise further to let next then know that it has to wait:

```<code>then(() => {
  return convertFile(`./files/${filename}`);
})
</code>```

and shorter equivalent:

```<code>then(() => convertFile(`./files/${filename}`))
</code>```

Body:
I've got a node application that spawns a child_process. When the child_process is finished running, I'd like to resolve a promise. The following code works, but the .then() statements occur out of order:

const storage = require('./storage');
const logging = require('./logging');
const process = require('child_process').spawn;

function convertIncomingFile(pathToFile) {
  logging.info(`Converting ${pathToFile}`);
  const convert = process(`cat`, [pathToFile], {});

  return Promise.resolve(
    convert.stdout.on('data', (data) => {
      logging.info(data.toString('utf8'));
    }),
    convert.stderr.on('data', (err) => {
      logging.error(err);
    }),
    convert.on('close', (code) => {
      logging.info(`Conversion finished with status code ${code}`);
    })
  );
}

module.exports = {
  convertFile: (filename) => {
    storage.downloadFile(filename).
      then((localFilename) => {
        logging.info(`File saved to: ${localFilename}`);
      }).
      then(() => convertIncomingFile(`./files/${filename}`)).
      then(() => {
        logging.info(`Coversion of ${filename} complete.`);
      }).
      catch((apiErr) => {
        logging.error(apiErr);
      });
  }
};

The output I get is:

info: File saved to: ./files/package.json
info: Converting ./files/package.json
info: Coversion of package.json complete.
info: {
 <file contents>
}

info: Conversion finished with status code 0

As you can see the Conversion of package.json complete. statement occurs before the file contents are logged and the conversion status code statement. Why is this the case and how do I get the 'Conversion complete' statement to come after the 'status code' statement?

Body:
You have to pass the convertFile promise further to let next then know that it has to wait:

then(() => {
  return convertFile(`./files/${filename}`);
})

and shorter equivalent:

then(() => convertFile(`./files/${filename}`))


问:
Strange Rails console behaviour
When I run a multi-line statement in the Rails 3.0.1 console, pressing enter doesn't actually run the statement. Instead, it goes to a new console line, and the cursor has been tabbed to the right. Then I have to run a basic line (like p "hey"), and then the multi-line statement will run.

```<code>ruby-1.9.2-p0 > images = Image.all;images.each do |im|; if im.imagestore_width.blank?;im.save;end;
ruby-1.9.2-p0 >     p "hey"
</code>```

I've been doing it like this for awhile and it's been working okay. But now I've got a problem in the console and it might be related. When I ran the above code, instead of it working like it normally does, it just went to a new console line with a ? added

```<code>ruby-1.9.2-p0 > images = Image.all;images.each do |im|; if im.imagestore_width.blank?;im.save;end;
ruby-1.9.2-p0 >     p "hey"
ruby-1.9.2-p0 ?>
</code>```

When it does this, I can't exit the console

```<code>ruby-1.9.2-p0 ?>  exit
ruby-1.9.2-p0 ?>  ^C
</code>```

Are these problems related? How can I fix them?

答:
In the line:

```<code>images = Image.all;images.each do |im|; if im.imagestore_width.blank?;im.save;end;
</code>```

You have an end to close the if but not an end to close the do block of the each.

This is why the console is redisplaying the prompt asking for more input before executing your statements.

Try:

```<code>images = Image.all;images.each do |im|; if im.imagestore_width.blank?;im.save;end;end
</code>```

Notice, you will see the same behaviour with brackets. irb or console won't execute until the brackets balance e.g.

```<code>irb(main):010:0> (3 *
irb(main):011:1* (2 + 1)
irb(main):012:1> )
=> 9
</code>```

Title: Strange Rails console behaviour

Body:
When I run a multi-line statement in the Rails 3.0.1 console, pressing enter doesn't actually run the statement. Instead, it goes to a new console line, and the cursor has been tabbed to the right. Then I have to run a basic line (like p "hey"), and then the multi-line statement will run.

ruby-1.9.2-p0 > images = Image.all;images.each do |im|; if im.imagestore_width.blank?;im.save;end;
ruby-1.9.2-p0 >     p "hey"

I've been doing it like this for awhile and it's been working okay. But now I've got a problem in the console and it might be related. When I ran the above code, instead of it working like it normally does, it just went to a new console line with a ? added

ruby-1.9.2-p0 > images = Image.all;images.each do |im|; if im.imagestore_width.blank?;im.save;end;
ruby-1.9.2-p0 >     p "hey"
ruby-1.9.2-p0 ?>

When it does this, I can't exit the console

ruby-1.9.2-p0 ?>  exit
ruby-1.9.2-p0 ?>  ^C

Are these problems related? How can I fix them?

Body:
In the line:

images = Image.all;images.each do |im|; if im.imagestore_width.blank?;im.save;end;

You have an end to close the if but not an end to close the do block of the each.

This is why the console is redisplaying the prompt asking for more input before executing your statements.

Try:

images = Image.all;images.each do |im|; if im.imagestore_width.blank?;im.save;end;end

Notice, you will see the same behaviour with brackets. irb or console won't execute until the brackets balance e.g.

irb(main):010:0> (3 *
irb(main):011:1* (2 + 1)
irb(main):012:1> )
=> 9


问:
Executing Multiple Scripts
I've been working on some scripts that pull data from the web in JSON format and convert to CSV files. There are roughly 20 scripts and I'm looking for the best way to run them at once. Right now I just type python script1.py into Windows PowerShell and then repeat. Is there an easy way to go about this?</p>

答:
A way you could do this is by making another script that runs the different programs.

For example what you would do is:

```<code>exec(open("[where ever the file is located]").read())
</code>```

Then you could have it run a certain amount of times in a for loop and take the file names out of an array!

```<code>Files = ['C:\\filename.py', 'C:\\filename2.py']
</code>```

and so on.

Title: Executing Multiple Scripts

Body:
A way you could do this is by making another script that runs the different programs.

For example what you would do is:

exec(open("[where ever the file is located]").read())

Then you could have it run a certain amount of times in a for loop and take the file names out of an array!

Files = ['C:\\filename.py', 'C:\\filename2.py']

and so on.


问:
removing all duplicates of max numbers in a correlation table
I need code for taking a .csv of a correlation table, sample of the table is posted here:

```<code>     AA bb  cc  dd  ff
AA  100 87  71  71  78
bb  87  100 73  74  81
cc  71  73  100 96  69
dd  71  74  96  100 71
ee  78  81  69  100 100
ff  72  73  68  68  71
Pg  68  69  62  62  64
Ph  68  69  69  62  64
Pi  68  69  62  62  64
Pj  68  69  63  63  64
Pk  70  71  65  65  67
</code>```

I currently have read the .csv file with python's .csv module as a list of lists. I then removed the first column and row. And am now trying to take these int values and find the max values of each row. If there are multiple max values in a row, I want those values as well.

Then I intend to place that output into a table

```<code>file1values col row %
group1      AA   AA 100
...
group1      dd   ee 100
group1      ff   ee 100
</code>```

The issue I have so far is getting the max values for each row. Also I think I would be a bit confused on how to get the address (the col and row) for each max value.

Here is code so far:

```<code>from io import StringIO
import csv
import numpy as np

with open('/home/group1.csv', newline='') as csvfile:
    reader = csv.reader(csvfile)
    data_as_list = list(reader)

    a = np.array(data_as_list)

    a = np.delete(a, (0), axis=0)

    a = np.delete(a, (0), axis=1)

    np.set_printoptions(threshold=np.nan)
    print (a)
    print ('')

    count = 0
    b = (a.astype(int))

    maxArr = []
    while (count < b.shape[0]):
        print (b[count])
        count = count + 1
        maxArr.append(max(b[count - 1]))
    print (maxArr)
</code>```

Body:
I need code for taking a .csv of a correlation table, sample of the table is posted here:

     AA bb  cc  dd  ff
AA  100 87  71  71  78
bb  87  100 73  74  81
cc  71  73  100 96  69
dd  71  74  96  100 71
ee  78  81  69  100 100
ff  72  73  68  68  71
Pg  68  69  62  62  64
Ph  68  69  69  62  64
Pi  68  69  62  62  64
Pj  68  69  63  63  64
Pk  70  71  65  65  67

I currently have read the .csv file with python's .csv module as a list of lists. I then removed the first column and row. And am now trying to take these int values and find the max values of each row. If there are multiple max values in a row, I want those values as well.

Then I intend to place that output into a table

file1values col row %
group1      AA   AA 100
...
group1      dd   ee 100
group1      ff   ee 100

The issue I have so far is getting the max values for each row. Also I think I would be a bit confused on how to get the address (the col and row) for each max value.

Here is code so far:

from io import StringIO
import csv
import numpy as np

with open('/home/group1.csv', newline='') as csvfile:
    reader = csv.reader(csvfile)
    data_as_list = list(reader)

    a = np.array(data_as_list)

    a = np.delete(a, (0), axis=0)

    a = np.delete(a, (0), axis=1)

    np.set_printoptions(threshold=np.nan)
    print (a)
    print ('')

    count = 0
    b = (a.astype(int))

    maxArr = []
    while (count < b.shape[0]):
        print (b[count])
        count = count + 1
        maxArr.append(max(b[count - 1]))
    print (maxArr)

Body:
there are easier ways...

create a random matrix for tests

> import numpy as np
> m=np.random.randint(100,size=(10,10))

set diagonal to zero (or set to an out of range negative number)

> np.fill_diagonal(m,0)

array([[ 0, 35, 52, 40, 54,  1, 20, 41, 62, 92],
       [45,  0, 75, 71, 85, 86, 83, 39, 52, 69],
       [29, 21,  0, 78, 32, 14, 13, 27, 31, 26],
       [99, 90, 16,  0, 28, 36, 30, 45, 85, 41],
       [29, 21, 48, 31,  0, 86, 18,  7, 70, 76],
       [96, 97, 34, 82, 51,  0, 69, 22, 27, 85],
       [71, 58, 98, 42,  3, 51,  0, 19, 41, 93],
       [54, 97, 86, 75, 62, 91, 78,  0, 55, 89],
       [87, 44, 44, 54, 94, 94, 57, 24,  0, 81],
       [94, 32,  1, 92, 34, 46, 96, 38, 75,  0]])

find the maximum values per column/row (since your matrix is symmetric doesn't matter)

> cm=np.argmax(m,1)

array([9, 5, 3, 0, 5, 1, 2, 1, 4, 6])

You will need to map the row/column indices to your labels.

> for r in range(10):
      print(r,cm[r],m[r,cm[r]])

0 9 92
1 5 86
2 3 78
3 0 99
4 5 86
5 1 97
6 2 98
7 1 97
8 4 94
9 6 96


问:
Are there any other ways to run two different loops in VBA?
I have two loops, i loop I am counting rows in the first sheet, ii loops counting rows in the second sheet, but in my second sheet, my condition doesn't meet the requirement I need, it just goes back to i loop.  I am want to find an empty cell in the second loop, but it doesn't go through the whole condition. Any Idea...</p>

```<code>For i = 3 To lastrow
 ' condition to check number
 If IsNumeric(ws1.Cells(i, 1)) Then
    If ws1.Cells(i, 1) <> "" Then
    cName = ws1.Cells(i, 1)
    'This one is for second loop
      For ii = 3 To lastroww
           If ws2.Cells(ii, 3) = "" Then
            ws2.Cells(ii, 3) = "Name" + cName + "City"
           End If
      Next ii
  End If
  End If
Next i
</code>```

答:
```<code>   For ii = 3 To lastroww
        lastroww = ws2.UsedRange.Rows.Count
          If ws2.Cells(ii, 3) = "" Then
          ws2.Cells(ii, 3) = "Name" + cName + "City"
       End If
  Next ii
</code>```

Body:
I have two loops, i loop I am counting rows in the first sheet, ii loops counting rows in the second sheet, but in my second sheet, my condition doesn't meet the requirement I need, it just goes back to i loop.  I am want to find an empty cell in the second loop, but it doesn't go through the whole condition. Any Idea...

For i = 3 To lastrow
 ' condition to check number
 If IsNumeric(ws1.Cells(i, 1)) Then
    If ws1.Cells(i, 1) <> "" Then
    cName = ws1.Cells(i, 1)
    'This one is for second loop
      For ii = 3 To lastroww
           If ws2.Cells(ii, 3) = "" Then
            ws2.Cells(ii, 3) = "Name" + cName + "City"
           End If
      Next ii
  End If
  End If
Next i


问:
AIDL implementation on Custom Object in separate module
I have a custom Employee object in one module which doesn't implement Parcelable(module doesn't allow android components)

How can i implement AIDL in separate android module which returns Employee object in one of the methods?

One way i can achieve this is my extending parent object but while creating constructor with Parcel object input how can i call super method??

答:
I don't say this is perfect solution but just a small work around,

create a class in aidl module and extend Employee class and implement parcelable. Implement aidl using this new class


问:
returning an iterator from a function
I have the following example:

```<code>#include <stdio.h>
#include <map>
#include <conio.h>

typedef std::map<int,int> mi;
typedef std::map<int,int>::iterator mit;

mit myfind(mi mymap)
{
    mit it = mymap.find(1);
    printf("in function: %d\n",it->second);

    return it;
}

void main()
{
    mi a;
    a.insert(std::pair<int,int>(1,2));
    a.insert(std::pair<int,int>(3,4));

    mit it = myfind(a);

    printf("out of function: %d\n",it->second);

    _getch();

}
</code>```

The output is:

in function: 2

out of function: -17891602

Why? Does the iterator become invalid? Why? Thanks in advance.

答:
Your returned iterator is pointing somewhere into the local copy of mymap that was passed into myfind() (which is deallocated when the function returns). Try:

```<code>mit myfind(mi &mymap) { ...
</code>```

This will pass a reference to mymap and no copy is made.

Title: returning an iterator from a function

Body:
I have the following example:

#include <stdio.h>
#include <map>
#include <conio.h>

typedef std::map<int,int> mi;
typedef std::map<int,int>::iterator mit;

mit myfind(mi mymap)
{
    mit it = mymap.find(1);
    printf("in function: %d\n",it->second);

    return it;
}

void main()
{
    mi a;
    a.insert(std::pair<int,int>(1,2));
    a.insert(std::pair<int,int>(3,4));

    mit it = myfind(a);

    printf("out of function: %d\n",it->second);

    _getch();

}

The output is:

in function: 2

out of function: -17891602

Why? Does the iterator become invalid? Why? Thanks in advance.

Body:
Your returned iterator is pointing somewhere into the local copy of mymap that was passed into myfind() (which is deallocated when the function returns). Try:

mit myfind(mi &mymap) { ...

This will pass a reference to mymap and no copy is made.


问:
How to add jekyll build command in gulp watch task?
I need to run jekyll build during gulp watch task and I did that as per the following code.

```<code>var gulp = require('gulp-help')(require('gulp')),
    sass = require('gulp-sass');

gulp.task('sass', function(){
    return gulp.src(sassFiles)
        .pipe(sass().on('error', sass.logError))
        .pipe(gulp.dest(cssDest));
});

gulp.task('jekyll-build', function (done) {
    return cp.spawn(jekyll, ['build'], {stdio: 'inherit'})
        .on('close', done);
});

gulp.task('default', ['sass'], function(){
    gulp.watch(['_includes/**/*.js', '_includes/**/*._', 'assets/styles/**/*.scss'], ['jekyll-build', 'sass']);
});
</code>```

When I make some changes in any file and try to save at once, command runs in terminal but it is not getting reflected in UI. I need to save twice or thrice to get the changes reflected. Not sure what's the issue or whether its the issue of the gulp watch code added here. Any help is appreciated.

答:
When you say the changes are not reflected do you mean the browser is not refreshing?

The line to launch jekyll build is different for mac vs Windows, your looks like it is for a Mac, on Windows I use jekyll.bat on this line (jekyll, ['build'].

In your watch step you are not watching very much. Rather than try to tell gulp to watch every different thing I do the opposite and tell gulp to watch everything **/*.* and then tell it what not to watch like !_site/**/*. This also lets you watch the config file for changes.

Also, it doesn't look like you are live-reloading with browser sync, that is half the fun of using gulp with jekyll (other half is having gulp do sass processing as it is much faster than jekyll).

Here is a gulp file that I use and a link to a write up I did about it:

https://rdyar.github.io/2017/10/01/speed-up-jekyll-by-using-gulp-for-sass-and-other-assets/

```<code>var gulp        = require('gulp');
var browserSync = require('browser-sync');
var cp          = require('child_process');
var sass = require('gulp-sass');
var postcss    = require('gulp-postcss');
var sourcemaps = require('gulp-sourcemaps');
var autoprefixer = require('autoprefixer');
var watch = require('gulp-watch');
var uglify = require('gulp-uglify');
var cssnano = require('cssnano');
var imagemin = require('gulp-imagemin');
var htmlhint = require("gulp-htmlhint");

var messages = {
    jekyllBuild: '<span style="color: grey">Running:</span> $ jekyll build'
};
// Gulp as asset manager for jekyll. Please note that the assets folder is never cleaned
//so you might want to manually delete the _site/assets folder once in a while.
// this is because gulp will move files from the assets directory to _site/assets,
// but it will not remove them from _site/assets if you remove them from assets.

/**
 * Build the Jekyll Site - for windos. If you are on a Mac/linux change jekyll.bat to just jekyll
 */
gulp.task('jekyll-build', function (done) {
    browserSync.notify(messages.jekyllBuild);
    return cp.spawn('jekyll.bat', ['build'], {stdio: 'inherit'})
        .on('close', done);
});

/**
 * Rebuild Jekyll & do page reload when watched files change
 */
gulp.task('jekyll-rebuild', ['jekyll-build'], function () {
    browserSync.reload();
});

/**
 * Wait for jekyll-build, then launch the Server
 */

gulp.task('serve', ['jekyll-build'], function() {
    browserSync.init({
        server: "_site/"
    });
});

/**
 * Watch jekyll source files for changes, don't watch assets
 */
gulp.task('watch', function () {
    gulp.watch(['**/*.*', '!_site/**/*','!_assets/**/*','!node_modules/**/*','!.sass-cache/**/*' ], ['jekyll-rebuild']);
});

//watch just the sass files - no need to rebuild jekyll
gulp.task('watch-sass', ['sass-rebuild'], function() {
     gulp.watch(['_assets/sass/**/*.scss'], ['sass-rebuild']);
});

// watch just the js files
gulp.task('watch-js', ['js-rebuild'], function() {
     gulp.watch(['_assets/js/**/*.js'], ['js-rebuild']);
});

// watch just the image files
gulp.task('watch-images', ['images-rebuild'], function() {
     gulp.watch(['_assets/img/**/*.*'], ['images-rebuild']);
});

//if sass files change just rebuild them with gulp-sass and what not
gulp.task('sass-rebuild', function() {
     var plugins = [
        autoprefixer({browsers: ['last 2 version']}),
        cssnano()
    ];
     return gulp.src('_assets/sass/**/*.scss')
    .pipe(sourcemaps.init())
    .pipe(sass())
    .pipe(sourcemaps.init())
    .pipe(postcss(plugins))
    .pipe(sourcemaps.write('.'))
    .pipe( gulp.dest('_site/assets/css/') )
    .pipe(browserSync.reload({
      stream: true
    }))
});

gulp.task('js-rebuild', function(cb) {
    return gulp.src('_assets/js/**/*.js')
      .pipe(uglify())
      .pipe( gulp.dest('_site/assets/js/') )
      .pipe(browserSync.reload({
      stream: true
    }))
});

gulp.task('images-rebuild', function(cb) {

     return gulp.src('_assets/img/**/*.*')
      .pipe( gulp.dest('_site/assets/img/') )
      .pipe(browserSync.reload({
      stream: true
    }))
});

/**
 * Default task, running just `gulp` will
 * compile the jekyll site, launch BrowserSync & watch files.
 */
gulp.task('default', ['serve', 'watch','watch-sass','watch-js','watch-images']);

//build and deploy stuff
gulp.task('imagemin', function() {
    console.log('Minimizing images in source!!');
 return gulp.src('_assets/img/**/*')
    .pipe(imagemin())
    .pipe(gulp.dest(function (file) {
        return file.base;
    }));
});

gulp.task('w3', function() {
gulp.src("_site/**/*.html")
    .pipe(htmlhint())
    .pipe(htmlhint.reporter())
})
// validate from the command line instead, works better
// npm install htmlhint -g
// htmlhint _site/**/*.html
</code>```

Body:
I need to run jekyll build during gulp watch task and I did that as per the following code.

var gulp = require('gulp-help')(require('gulp')),
    sass = require('gulp-sass');

gulp.task('sass', function(){
    return gulp.src(sassFiles)
        .pipe(sass().on('error', sass.logError))
        .pipe(gulp.dest(cssDest));
});

gulp.task('jekyll-build', function (done) {
    return cp.spawn(jekyll, ['build'], {stdio: 'inherit'})
        .on('close', done);
});

gulp.task('default', ['sass'], function(){
    gulp.watch(['_includes/**/*.js', '_includes/**/*._', 'assets/styles/**/*.scss'], ['jekyll-build', 'sass']);
});

When I make some changes in any file and try to save at once, command runs in terminal but it is not getting reflected in UI. I need to save twice or thrice to get the changes reflected. Not sure what's the issue or whether its the issue of the gulp watch code added here. Any help is appreciated.

Body:
When you say the changes are not reflected do you mean the browser is not refreshing?

The line to launch jekyll build is different for mac vs Windows, your looks like it is for a Mac, on Windows I use jekyll.bat on this line (jekyll, ['build'].

In your watch step you are not watching very much. Rather than try to tell gulp to watch every different thing I do the opposite and tell gulp to watch everything **/*.* and then tell it what not to watch like !_site/**/*. This also lets you watch the config file for changes.

Also, it doesn't look like you are live-reloading with browser sync, that is half the fun of using gulp with jekyll (other half is having gulp do sass processing as it is much faster than jekyll).

Here is a gulp file that I use and a link to a write up I did about it:

https://rdyar.github.io/2017/10/01/speed-up-jekyll-by-using-gulp-for-sass-and-other-assets/

var gulp        = require('gulp');
var browserSync = require('browser-sync');
var cp          = require('child_process');
var sass = require('gulp-sass');
var postcss    = require('gulp-postcss');
var sourcemaps = require('gulp-sourcemaps');
var autoprefixer = require('autoprefixer');
var watch = require('gulp-watch');
var uglify = require('gulp-uglify');
var cssnano = require('cssnano');
var imagemin = require('gulp-imagemin');
var htmlhint = require("gulp-htmlhint");

var messages = {
    jekyllBuild: '<span style="color: grey">Running:</span> $ jekyll build'
};
// Gulp as asset manager for jekyll. Please note that the assets folder is never cleaned
//so you might want to manually delete the _site/assets folder once in a while.
// this is because gulp will move files from the assets directory to _site/assets,
// but it will not remove them from _site/assets if you remove them from assets.

/**
 * Build the Jekyll Site - for windos. If you are on a Mac/linux change jekyll.bat to just jekyll
 */
gulp.task('jekyll-build', function (done) {
    browserSync.notify(messages.jekyllBuild);
    return cp.spawn('jekyll.bat', ['build'], {stdio: 'inherit'})
        .on('close', done);
});

/**
 * Rebuild Jekyll & do page reload when watched files change
 */
gulp.task('jekyll-rebuild', ['jekyll-build'], function () {
    browserSync.reload();
});

/**
 * Wait for jekyll-build, then launch the Server
 */

gulp.task('serve', ['jekyll-build'], function() {
    browserSync.init({
        server: "_site/"
    });
});

/**
 * Watch jekyll source files for changes, don't watch assets
 */
gulp.task('watch', function () {
    gulp.watch(['**/*.*', '!_site/**/*','!_assets/**/*','!node_modules/**/*','!.sass-cache/**/*' ], ['jekyll-rebuild']);
});

//watch just the sass files - no need to rebuild jekyll
gulp.task('watch-sass', ['sass-rebuild'], function() {
     gulp.watch(['_assets/sass/**/*.scss'], ['sass-rebuild']);
});

// watch just the js files
gulp.task('watch-js', ['js-rebuild'], function() {
     gulp.watch(['_assets/js/**/*.js'], ['js-rebuild']);
});

// watch just the image files
gulp.task('watch-images', ['images-rebuild'], function() {
     gulp.watch(['_assets/img/**/*.*'], ['images-rebuild']);
});

//if sass files change just rebuild them with gulp-sass and what not
gulp.task('sass-rebuild', function() {
     var plugins = [
        autoprefixer({browsers: ['last 2 version']}),
        cssnano()
    ];
     return gulp.src('_assets/sass/**/*.scss')
    .pipe(sourcemaps.init())
    .pipe(sass())
    .pipe(sourcemaps.init())
    .pipe(postcss(plugins))
    .pipe(sourcemaps.write('.'))
    .pipe( gulp.dest('_site/assets/css/') )
    .pipe(browserSync.reload({
      stream: true
    }))
});

gulp.task('js-rebuild', function(cb) {
    return gulp.src('_assets/js/**/*.js')
      .pipe(uglify())
      .pipe( gulp.dest('_site/assets/js/') )
      .pipe(browserSync.reload({
      stream: true
    }))
});

gulp.task('images-rebuild', function(cb) {

     return gulp.src('_assets/img/**/*.*')
      .pipe( gulp.dest('_site/assets/img/') )
      .pipe(browserSync.reload({
      stream: true
    }))
});

/**
 * Default task, running just `gulp` will
 * compile the jekyll site, launch BrowserSync & watch files.
 */
gulp.task('default', ['serve', 'watch','watch-sass','watch-js','watch-images']);

//build and deploy stuff
gulp.task('imagemin', function() {
    console.log('Minimizing images in source!!');
 return gulp.src('_assets/img/**/*')
    .pipe(imagemin())
    .pipe(gulp.dest(function (file) {
        return file.base;
    }));
});

gulp.task('w3', function() {
gulp.src("_site/**/*.html")
    .pipe(htmlhint())
    .pipe(htmlhint.reporter())
})
// validate from the command line instead, works better
// npm install htmlhint -g
// htmlhint _site/**/*.html


问:
How to list a specific data with *ngFor
hi guys i am trying to make a simple friendrequests page with ionic3 and firebase

i succesfully listed usernames with ngfor. but i cannot list users FirstName from my data.

list html:

```<code> <ion-item *ngFor="let friendrequest of friendRequestArray; let name of requesterName; let i = index" (click)="getFirstName(i)">
    <h2>{{friendrequest.$key}}</h2>
    <p> {{name}} </p>
  </ion-item>
</code>```

constructor:

```<code>  friendRequestArray = [];
  requesterName =[];

  constructor(public navCtrl: NavController, public navParams: NavParams,
    public alertCtrl: AlertController, private afDatabase: AngularFireDatabase, private afAuth: AngularFireAuth) {

      this.myUid = this.afAuth.auth.currentUser.uid;

      this.afDatabase.list(`users/${this.myUid}/friendrequests/`).subscribe(data => {
        this.friendRequestArray = data;
        console.log(this.friendRequestArray);

      });

  }
</code>```

now, usernames (friendrequest) works fine but {{name}} doesnt work because of specific parents. as you see there is a function for getting first name by click, it works fine and returns me the name of user as i want in console. but i want it in constructor, like username, for each request.

getting firstname function is this, and its not working in constructor;

```<code>      getFirstName(i) {

    this.afDatabase.object(`users/${this.friendRequestArray[i].$value}/profile`).subscribe(data => {

        this.requesterName = data.firstName;
        console.log(this.requesterName);
    });
  }
</code>```

thanks for reading please assist me

答:
Why don't you call it inside the constructor?

```<code>this.afDatabase.list(`users/${this.myUid}/friendrequests/`).subscribe(data =>{
    this.friendRequestArray = data;
    console.log(this.friendRequestArray);

    this.friendRequestArray.forEach((item, i) => {
       getFirstName(i);
    })

  });
</code>```

Add one line to your getFirstName function to store firstName in friendRequestArray:

```<code>getFirstName(i) {

this.afDatabase.object(`users/${this.friendRequestArray[i].$value}/profile`).subscribe(data => {

    this.requesterName = data.firstName;
    console.log(this.requesterName);
    friendRequestArray[i]["firstName"] = data.firstName;
});
</code>```

}

Now your html, can be:

```<code><ion-item *ngFor="let friendrequest of friendRequestArray; let i = index">
    <h2>{{friendrequest.$key}}</h2>
    <p> {{friendrequest.firstName}} </p>
  </ion-item>
</code>```

Title: How to list a specific data with *ngFor

Body:
hi guys i am trying to make a simple friendrequests page with ionic3 and firebase

i succesfully listed usernames with ngfor. but i cannot list users FirstName from my data.

list html:

 <ion-item *ngFor="let friendrequest of friendRequestArray; let name of requesterName; let i = index" (click)="getFirstName(i)">

{{friendrequest.$key}}

 {{name}}

  </ion-item>

constructor:

  friendRequestArray = [];
  requesterName =[];

  constructor(public navCtrl: NavController, public navParams: NavParams,
    public alertCtrl: AlertController, private afDatabase: AngularFireDatabase, private afAuth: AngularFireAuth) {

      this.myUid = this.afAuth.auth.currentUser.uid;

      this.afDatabase.list(`users/${this.myUid}/friendrequests/`).subscribe(data => {
        this.friendRequestArray = data;
        console.log(this.friendRequestArray);

      });

  }

now, usernames (friendrequest) works fine but {{name}} doesnt work because of specific parents. as you see there is a function for getting first name by click, it works fine and returns me the name of user as i want in console. but i want it in constructor, like username, for each request.

getting firstname function is this, and its not working in constructor;

      getFirstName(i) {

    this.afDatabase.object(`users/${this.friendRequestArray[i].$value}/profile`).subscribe(data => {

        this.requesterName = data.firstName;
        console.log(this.requesterName);
    });
  }

thanks for reading please assist me

Body:
Why don't you call it inside the constructor?

this.afDatabase.list(`users/${this.myUid}/friendrequests/`).subscribe(data =>{
    this.friendRequestArray = data;
    console.log(this.friendRequestArray);

    this.friendRequestArray.forEach((item, i) => {
       getFirstName(i);
    })

  });

Add one line to your getFirstName function to store firstName in friendRequestArray:

getFirstName(i) {

this.afDatabase.object(`users/${this.friendRequestArray[i].$value}/profile`).subscribe(data => {

    this.requesterName = data.firstName;
    console.log(this.requesterName);
    friendRequestArray[i]["firstName"] = data.firstName;
});

}

Now your html, can be:

<ion-item *ngFor="let friendrequest of friendRequestArray; let i = index">
    <h2>{{friendrequest.$key}}</h2>
    <p> {{friendrequest.firstName}} </p>
  </ion-item>


问:
ggplotly and geom_area : display informations when hovering over an area (not a point)
When it comes to a ggplotly graph, it's easy to display informations when hovering over specific point. This code do the job :

```<code>toy_df=data.frame("t"=c(seq(1,10),seq(1,10)),
                  "value"=c(runif(10,0,10),2*runif(10,0,10)),
                  "event"=c(rep("A",10),rep("B",10)))

p <- ggplot() + geom_area(aes(y = value, x = t, fill=event), data = toy_df)
ggplotly(p)
</code>```

But I would like to display informations when hovering over one of the area. Because in my case, area is an event that I want to be able to describe deeply.

答:
Polygons in ggplot2 (geom_polygon) provide a possible solutions.

Below you can find a rather raw code that should clarify the main idea:

```<code>library(ggplot2)
library(plotly)
set.seed(1)
toy_df=data.frame("t"=c(seq(1,10),seq(1,10)),
                  "value"=c(runif(10,0,10),2*runif(10,0,10)),
                  "event"=c(rep("A",10),rep("B",10)))

# In order to create polygons like in geom_areas,
# two points on the x-axis must be added: one at t=1 and one at t=10
toy_df2 <- toy_df[NULL,]
for (k in unique(toy_df$event)) {
 subdf <- subset(toy_df, toy_df$event==k)
 nr <- nrow(subdf)
 row1 <- subdf[1,]
 row1$value <- 0
 row2 <- subdf[nr,]
 row2$value <- 0
 toy_df2 <- rbind(toy_df2, row1, subdf, row2)
}
# Stack polygons
toy_df2$value[toy_df2$event=="A"] <- toy_df2$value[toy_df2$event=="A"] +
                                     toy_df2$value[toy_df2$event=="B"]

# Calculate mean values for the two events: they will be displayed in the tooltip
toy_df2 <- toy_df2 %>% group_by(event) %>% mutate(mn=round(mean(value),3))

p <- ggplot(data = toy_df2, aes(y = value, x = t, fill=event,
            text=paste0("Value:", mn,"<br>Event:", event))) +
     geom_polygon()
ggplotly(p, tooltip="text")
</code>```

Body:
When it comes to a ggplotly graph, it's easy to display informations when hovering over specific point. This code do the job :

toy_df=data.frame("t"=c(seq(1,10),seq(1,10)),
                  "value"=c(runif(10,0,10),2*runif(10,0,10)),
                  "event"=c(rep("A",10),rep("B",10)))

p <- ggplot() + geom_area(aes(y = value, x = t, fill=event), data = toy_df)
ggplotly(p)

But I would like to display informations when hovering over one of the area. Because in my case, area is an event that I want to be able to describe deeply.

Body:
Polygons in ggplot2 (geom_polygon) provide a possible solutions.

Below you can find a rather raw code that should clarify the main idea:

library(ggplot2)
library(plotly)
set.seed(1)
toy_df=data.frame("t"=c(seq(1,10),seq(1,10)),
                  "value"=c(runif(10,0,10),2*runif(10,0,10)),
                  "event"=c(rep("A",10),rep("B",10)))

# In order to create polygons like in geom_areas,
# two points on the x-axis must be added: one at t=1 and one at t=10
toy_df2 <- toy_df[NULL,]
for (k in unique(toy_df$event)) {
 subdf <- subset(toy_df, toy_df$event==k)
 nr <- nrow(subdf)
 row1 <- subdf[1,]
 row1$value <- 0
 row2 <- subdf[nr,]
 row2$value <- 0
 toy_df2 <- rbind(toy_df2, row1, subdf, row2)
}
# Stack polygons
toy_df2$value[toy_df2$event=="A"] <- toy_df2$value[toy_df2$event=="A"] +
                                     toy_df2$value[toy_df2$event=="B"]

# Calculate mean values for the two events: they will be displayed in the tooltip
toy_df2 <- toy_df2 %>% group_by(event) %>% mutate(mn=round(mean(value),3))

p <- ggplot(data = toy_df2, aes(y = value, x = t, fill=event,
            text=paste0("Value:", mn,"<br>Event:", event))) +
     geom_polygon()
ggplotly(p, tooltip="text")


问:
Avoid global functions when compiling typescript
How can I avoid the creation of global functions when compiling typescript into javascript.

Benefit: obfuscator won't have to provide a public API

Foo.ts:

```<code>class Foo {}
</code>```

Foo.js:

```<code>var Foo = (function () {
    function Foo() {
    }
    return Foo;
}());
</code>```

Foo.obfuscated.js (using npm jsobfuscator):

```<code>var _0xcd14=[];var _0x12e2=[];var Foo=(function(){function Foo(){}return Foo}())
</code>```

Foo is still visible. I understand why (public API). Solution would be:

Foo.isolated.js:

```<code>(function() { /* code from Foo.js */ })();
</code>```

Foo.isolated.obfuscated.js (what I want):

```<code>var _0xe1f1=[];var _0xa6a8=[];(function(){var _0x64f8x2=(function(){function _0x64f8x2(){}return _0x64f8x2}())})()
</code>```

Is there a typescript setup for tsconfig.js / compiler options like isolation: true or something?

答:
nested (private) class ?</p>

```<code>module MyModule {
    export class MyPublicClass {
        private myPrivateClass: PrivateClass;
        constructor() {
            this.myPrivateClass = new PrivateClass;
        }
        public test() {
            this.myPrivateClass.test();
        }
    }

    class PrivateClass {
        public test() {
            console.log('it works');
        }
    }
}
</code>```

Body:
How can I avoid the creation of global functions when compiling typescript into javascript.

Benefit: obfuscator won't have to provide a public API

Foo.ts:

class Foo {}

Foo.js:

var Foo = (function () {
    function Foo() {
    }
    return Foo;
}());

Foo.obfuscated.js (using npm jsobfuscator):

var _0xcd14=[];var _0x12e2=[];var Foo=(function(){function Foo(){}return Foo}())

Foo is still visible. I understand why (public API). Solution would be:

Foo.isolated.js:

(function() { /* code from Foo.js */ })();

Foo.isolated.obfuscated.js (what I want):

var _0xe1f1=[];var _0xa6a8=[];(function(){var _0x64f8x2=(function(){function _0x64f8x2(){}return _0x64f8x2}())})()

Is there a typescript setup for tsconfig.js / compiler options like isolation: true or something?

Body:
nested (private) class ?

module MyModule {
    export class MyPublicClass {
        private myPrivateClass: PrivateClass;
        constructor() {
            this.myPrivateClass = new PrivateClass;
        }
        public test() {
            this.myPrivateClass.test();
        }
    }

    class PrivateClass {
        public test() {
            console.log('it works');
        }
    }
}


问:
CGFloat *f= accelerometer.x;
I have used this but it is not working?How can i store accelerometer.x value in a int or float or CGFloat?</p>

答: CGFloat is just a typedef for float, so it is not an object. Try CGFloat f= accelerometer.x;

Title: CGFloat *f= accelerometer.x;


问:
Using window.print() in angular 2 print only one page
I put the html for print in a div with class forPrint which is in a material dialog page and call the window.print() when the print button is clicked in the angular component.

However, it shows/prints only the page in the current screen and the rest is cut off when the button is clicked.

How to print the whole content in the div with class forPrint?

I think the reason is material dialog because when I print something in a normal page it works fine.

CSS:

```<code>@media print {
    /deep/ body * { visibility: hidden; }
    /deep/ .forPrint * { visibility: visible; display:block;}
    /deep/ .forPrint { display:block;position: absolute; top: 40px; left: 30px; }

}
</code>```

答: I had such a problem when used material sidenav. Try create forPrint div beyond sidenav container.</p>

Body:
I put the html for print in a div with class forPrint which is in a material dialog page and call the window.print() when the print button is clicked in the angular component.

However, it shows/prints only the page in the current screen and the rest is cut off when the button is clicked.

How to print the whole content in the div with class forPrint?

I think the reason is material dialog because when I print something in a normal page it works fine.

CSS:

@media print {
    /deep/ body * { visibility: hidden; }
    /deep/ .forPrint * { visibility: visible; display:block;}
    /deep/ .forPrint { display:block;position: absolute; top: 40px; left: 30px; }

}


问:
ES6 JavaScript classes
Is there a way to create a class and in that classes constructor method pass in two different objects from other classes, along with some other information. For example, say I have three classes, a Statistics class, an Attributes class, and a Character class. They look kind of like this:

```<code>class Statistics {
    constructor(stren, dex, wis, cha, armorClass, hitPoints) {
        this._stren = stren;
        this._dex = dex;
        this._wis = wis;
        this._cha = cha;
        this._armorClass = armorClass;
        this._hitPoints = hitPoints;
    }
}

class Attributes {
    constructor(name, race, sex, level, height, weight, speed) {
        this._name = name;
        this._race = race;
        this._sex = sex;
        this._level = level;
        this._height = height;
        this._weight = weight;
        this._speed = speed;
    }
}
</code>```

Since the Character class' constructor would have 13+ arguments, I figured separating them into other classes was better than writing a constructor with 13+ arguments. So is there a way to do something similar to:

```<code>class Character {
    constructor(Statistics statistic, Attributes attributes) {
        .....
    }
}
</code>```

EDIT: No, this is not a duplicate of that question, do people even actually read what is being asked before saying that questions are duplicates?

答:
Remember that classes are just syntactic sugar, so you can add to the Character prototype with Object.defineProperty and make your own getter.

edit: DRYd it up with a loop.

class Statistics {
    constructor(stren, dex, wis, cha, armorClass, hitPoints) {
        this._stren = stren;
        this._dex = dex;
        this._wis = wis;
        this._cha = cha;
        this._armorClass = armorClass;
        this._hitPoints = hitPoints;
    }
}

class Attributes {
    constructor(name, race, sex, level, height, weight, speed) {
        this._name = name;
        this._race = race;
        this._sex = sex;
        this._level = level;
        this._height = height;
        this._weight = weight;
        this._speed = speed;
    }
}

class Character {
    constructor(statistics, attributes) {
        this.buildGetters(attributes)
        this.buildGetters(statistics)
      }

      buildGetters(obj) {
        for (let attr in obj){
          Object.defineProperty(Character.prototype, attr.replace("_", ""), {
            get: function() {
              return obj[attr]
            }
          })
        }
      }
}

const stats = new Statistics()
const attr = new Attributes("Mike")
const mike = new Character(stats, attr)
console.log(mike.name);```

Title: ES6 JavaScript classes

Body:
Is there a way to create a class and in that classes constructor method pass in two different objects from other classes, along with some other information. For example, say I have three classes, a Statistics class, an Attributes class, and a Character class. They look kind of like this:

class Statistics {
    constructor(stren, dex, wis, cha, armorClass, hitPoints) {
        this._stren = stren;
        this._dex = dex;
        this._wis = wis;
        this._cha = cha;
        this._armorClass = armorClass;
        this._hitPoints = hitPoints;
    }
}

class Attributes {
    constructor(name, race, sex, level, height, weight, speed) {
        this._name = name;
        this._race = race;
        this._sex = sex;
        this._level = level;
        this._height = height;
        this._weight = weight;
        this._speed = speed;
    }
}

Since the Character class' constructor would have 13+ arguments, I figured separating them into other classes was better than writing a constructor with 13+ arguments. So is there a way to do something similar to:

class Character {
    constructor(Statistics statistic, Attributes attributes) {
        .....
    }
}

EDIT: No, this is not a duplicate of that question, do people even actually read what is being asked before saying that questions are duplicates?


问:
Merge multiple CSV into one DataFrame with filename as column name
I have a number of txt files in a directory that I'd like to combine.The following is an example of three files named df_A, df_B and df_c:

```<code>df_A
       0  1    2
0  James  1  yes
1   Jake  3   No
2   Jane  2  Yes

df_B
       0  1    2
0   Jane  2   No
1    Job  6   No
2  James  1  Yes

df_C
       0  1    2
0   Jack  4   No
1  Jenny  7  Yes
2  James  1   No
3   John  9  Yes
</code>```

AndI'd like the final dataframe to look like this:

```<code>ID  Name    df_A    df_B    df_C

1   James   Yes     Yes     No
3   Jake    No      NA      NA
2   Jane    Yes     No      NA
6   Job     NA      Yes     NA
4   Jack    NA      NA      No
7   Jenny   NA      NA      Yes
9   John    NA      NA      Yes
</code>```

this is the code I have thus far...

```<code>new_df = pd.DataFrame(columns = ['Name', 'ID'])

for filename in os.listdir('/path'):
    if filename.endswith('.txt'):
        course = os.path.splitext(filename)[0]

        new_df = pd.concat([combined_df,pd.DataFrame(columns=[course])])
        data = pd.read_csv(filename, sep="\t", header=None)

        for i in data[data.columns[1]]:
            if i not in new_df['ID']:
                new_df['ID'].append(i)
</code>```

答:
For these three dataframes, just assign column names. The last column should be unique. Then, call pd.concat + groupby for your output.

```<code>dfA.columns = ['Name', 'ID', 'df_A']
dfB.columns = ['Name', 'ID', 'df_B']
dfC.columns = ['Name', 'ID', 'df_C']

pd.concat([dfA, dfB, df3])\
      .groupby('Name', as_index=False, sort=False).first()\
      .set_index('ID').fillna('')

     Name df_A df_B df_C
ID
1   James  yes  Yes   No
3    Jake   No
2    Jane  Yes   No
6     Job        No
4    Jack             No
7   Jenny            Yes
9    John            Yes
</code>```

In a general case, say you have df_list. You can then assign column names in a loop.

```<code>df_list = [dfA, dfB, dfC, ...]
for i, df in enumerate(df_list):
    df.columns = ['Name', 'ID', 'df_{}'.format(chr(ord('A') + i))]

pd.concat(df_list).groupby('Name',
        as_index=False, sort=False).first().set_index('ID')
</code>```

Body:
I have a number of txt files in a directory that I'd like to combine.The following is an example of three files named df_A, df_B and df_c:

df_A
       0  1    2
0  James  1  yes
1   Jake  3   No
2   Jane  2  Yes

df_B
       0  1    2
0   Jane  2   No
1    Job  6   No
2  James  1  Yes

df_C
       0  1    2
0   Jack  4   No
1  Jenny  7  Yes
2  James  1   No
3   John  9  Yes

AndI'd like the final dataframe to look like this:

ID  Name    df_A    df_B    df_C

1   James   Yes     Yes     No
3   Jake    No      NA      NA
2   Jane    Yes     No      NA
6   Job     NA      Yes     NA
4   Jack    NA      NA      No
7   Jenny   NA      NA      Yes
9   John    NA      NA      Yes

this is the code I have thus far...

new_df = pd.DataFrame(columns = ['Name', 'ID'])

for filename in os.listdir('/path'):
    if filename.endswith('.txt'):
        course = os.path.splitext(filename)[0]

        new_df = pd.concat([combined_df,pd.DataFrame(columns=[course])])
        data = pd.read_csv(filename, sep="\t", header=None)

        for i in data[data.columns[1]]:
            if i not in new_df['ID']:
                new_df['ID'].append(i)

Body:
For these three dataframes, just assign column names. The last column should be unique. Then, call pd.concat + groupby for your output.

dfA.columns = ['Name', 'ID', 'df_A']
dfB.columns = ['Name', 'ID', 'df_B']
dfC.columns = ['Name', 'ID', 'df_C']

pd.concat([dfA, dfB, df3])\
      .groupby('Name', as_index=False, sort=False).first()\
      .set_index('ID').fillna('')

     Name df_A df_B df_C
ID
1   James  yes  Yes   No
3    Jake   No
2    Jane  Yes   No
6     Job        No
4    Jack             No
7   Jenny            Yes
9    John            Yes

In a general case, say you have df_list. You can then assign column names in a loop.

df_list = [dfA, dfB, dfC, ...]
for i, df in enumerate(df_list):
    df.columns = ['Name', 'ID', 'df_{}'.format(chr(ord('A') + i))]

pd.concat(df_list).groupby('Name',
        as_index=False, sort=False).first().set_index('ID')


问:
How define named native query in xml with spring boot
I am using spring boot, I would like to define the native query in xml files.
Here is the entity:

```<code>@NamedNativeQuery(name = "findAllUsers",query = "select * from user")
@Entity
@Table(name="user")
public class User implements Serializable {
    @Id
    @GeneratedValue
    @Column(name = "UserId")
    private Integer userId;
}
</code>```

And the Repository:

```<code>@Repository
public interface UserDao extends CrudRepository<User, Integer>, JpaSpecificationExecutor<User> {
    @Query(name="findAllUsers")
    List<User> findAllUsers();
}
</code>```

I want to switch native sql quickly between native-sql-oracle.xml and native-sql-mysql.xml.

答:
Just add a .hbm.xml file in the resources directory, it will be auto scanned by spring。

A sample xml:

```<code><?xml version="1.0" encoding="UTF-8"?>
<entity-mappings xmlns="http://java.sun.com/xml/ns/persistence/orm" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/persistence/orm http://java.sun.com/xml/ns/persistence/orm_1_0.xsd" version="1.0">
    <package>com.xxx.auth</package>
    <entity class="User">
        <named-native-query name="searchUser" result-class="User">
            <query>
                <![CDATA[
                SELECT * FROM User
                ]]>
            </query>
        </named-native-query>
    </entity>
</entity-mappings>
</code>```

Body:
I am using spring boot, I would like to define the native query in xml files.
Here is the entity:

@NamedNativeQuery(name = "findAllUsers",query = "select * from user")
@Entity
@Table(name="user")
public class User implements Serializable {
    @Id
    @GeneratedValue
    @Column(name = "UserId")
    private Integer userId;
}

And the Repository:

@Repository
public interface UserDao extends CrudRepository<User, Integer>, JpaSpecificationExecutor<User> {
    @Query(name="findAllUsers")
    List<User> findAllUsers();
}

I want to switch native sql quickly between native-sql-oracle.xml and native-sql-mysql.xml.

Body:
Just add a .hbm.xml file in the resources directory, it will be auto scanned by spring。

A sample xml:

<?xml version="1.0" encoding="UTF-8"?>
<entity-mappings xmlns="http://java.sun.com/xml/ns/persistence/orm" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/persistence/orm http://java.sun.com/xml/ns/persistence/orm_1_0.xsd" version="1.0">
    <package>com.xxx.auth</package>
    <entity class="User">
        <named-native-query name="searchUser" result-class="User">
            <query>
                <![CDATA[
                SELECT * FROM User
                ]]>
            </query>
        </named-native-query>
    </entity>
</entity-mappings>


问:
Saving bool to NSUserDefaults and using it in a if statement using Swift
I am struggling to figure out how to do an if statement with a bool saved to NSUserDefaults using Swift. I believe I know how to save the bool to NSUserDefaults but a confirmation in that would be greatly appreciated. This is the Objective-C code I am trying to figure out how to use with swift.

```<code>if(![[NSUserDefaults standardUserDefaults] boolForKey:@"onoroff"]) {
    [[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"onoroff"];
}
</code>```

this is what I have so far in Swift...

```<code>if  NSUserDefaults.standardUserDefaults().objectForKey("onoroff") != nil{
    NSUserDefaults.standardUserDefaults().setBool(false, forKey: "onoroff")
}
</code>```

I think I might have figure it out. Can anyone confirm this is the correct way to save a bool to NSUserDefaults and use a if statement with it. Here it is:

```<code>if  !NSUserDefaults.standardUserDefaults().boolForKey("onoroff"){
     NSUserDefaults.standardUserDefaults().setBool(true, forKey: "onoroff")
}else{ NSUserDefaults.standardUserDefaults().setBool(false, forKey: "onoroff")
     }
</code>```

答:
Swift 3

This is code for the switch, that will save true or false to UserDefaults.

```<code>let defaults = UserDefaults.standard
@IBOutlet weak var mySwitch: UISwitch!

@IBAction func switchValueChanged(_ sender: Any) {
    self.defaults.set(mySwitch.isOn, forKey: "mySwitch")
}
</code>```

Then to show the switch's saved state... on/off:

```<code>override func viewDidLoad() {
    super.viewDidLoad()
    mySwitch.isOn = self.defaults.bool(forKey: "mySwitch")
}
</code>```

So really 1 line to set the switch's state, and 1 line to get the users saved state and set the switch properly!

ContentLicense: CC BY-SA 4.0

Body:
I am struggling to figure out how to do an if statement with a bool saved to NSUserDefaults using Swift. I believe I know how to save the bool to NSUserDefaults but a confirmation in that would be greatly appreciated. This is the Objective-C code I am trying to figure out how to use with swift.

if(![[NSUserDefaults standardUserDefaults] boolForKey:@"onoroff"]) {
    [[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"onoroff"];
}

this is what I have so far in Swift...

if  NSUserDefaults.standardUserDefaults().objectForKey("onoroff") != nil{
    NSUserDefaults.standardUserDefaults().setBool(false, forKey: "onoroff")
}

I think I might have figure it out. Can anyone confirm this is the correct way to save a bool to NSUserDefaults and use a if statement with it. Here it is:

if  !NSUserDefaults.standardUserDefaults().boolForKey("onoroff"){
     NSUserDefaults.standardUserDefaults().setBool(true, forKey: "onoroff")
}else{ NSUserDefaults.standardUserDefaults().setBool(false, forKey: "onoroff")
     }

Body:
Swift 3

This is code for the switch, that will save true or false to UserDefaults.

let defaults = UserDefaults.standard
@IBOutlet weak var mySwitch: UISwitch!

@IBAction func switchValueChanged(_ sender: Any) {
    self.defaults.set(mySwitch.isOn, forKey: "mySwitch")
}

Then to show the switch's saved state... on/off:

override func viewDidLoad() {
    super.viewDidLoad()
    mySwitch.isOn = self.defaults.bool(forKey: "mySwitch")
}

So really 1 line to set the switch's state, and 1 line to get the users saved state and set the switch properly!


问:
for loop to concatenate strings
I need to concatenate strings in the list and add the integers to a sum; of course, I intend to change it to other data types later - thanks so much for all your kind responses

```<code>l = ['magical unicorns', 19, 'hello', 98.98, 'world']

comb_str = ''
comb_int = 0

for i in l:
    if type(i) is 'str':
        comb_str = comb_str + 'i'
    elif type(i) is 'int':
        comb_int += i
    else:
        pass

print comb_str
print comb_int
</code>```

I am just getting the '0' output that was initialized in the beginning as if it skipped over the for loop :)

答:
Taking your statements literally (that you only want integers, not numerics) the entire program comes down to two function calls with filtered versions of the list</p>

```<code>>>> l = ['magical unicorns', 19, 'hello', 98.98, 'world']
>>> ''.join([s for s in l if isinstance(s,str)])
'magical unicornshelloworld'
>>> sum([i for i in l if isinstance(i,int)])
19
>>
</code>```

Title: for loop to concatenate strings

Body:
I need to concatenate strings in the list and add the integers to a sum; of course, I intend to change it to other data types later - thanks so much for all your kind responses

l = ['magical unicorns', 19, 'hello', 98.98, 'world']

comb_str = ''
comb_int = 0

for i in l:
    if type(i) is 'str':
        comb_str = comb_str + 'i'
    elif type(i) is 'int':
        comb_int += i
    else:
        pass

print comb_str
print comb_int

I am just getting the '0' output that was initialized in the beginning as if it skipped over the for loop :)

Body:
Taking your statements literally (that you only want integers, not numerics) the entire program comes down to two function calls with filtered versions of the list

>>> l = ['magical unicorns', 19, 'hello', 98.98, 'world']
>>> ''.join([s for s in l if isinstance(s,str)])
'magical unicornshelloworld'
>>> sum([i for i in l if isinstance(i,int)])
19
>>


问:
Get all possible part-of-speech tags for a word using NLTK
Some words can have more than one possible part of speech (pos) tag.
E.g. 'Stick' is both a noun and a verb.

The pos taggers in NLTK try to guess the correct tag based on context and return only the 1 guess. How can I instead get a list of all possible tags for any given word?

答:
TL;DR

No, not for the default pos_tag function.

In Long

For the default pos_tag function it's not possible.

The default pos_tag function is from the AveragedPerceptron object that uses the predict() function to get the most probable tag: https://github.com/nltk/nltk/blob/develop/nltk/tag/perceptron.py#L48

The function returns the argmax from the list of probable tags:

```<code>def predict(self, features):
    '''Dot-product the features and current weights and return the best label.'''
    scores = defaultdict(float)
    for feat, value in features.items():
        if feat not in self.weights or value == 0:
            continue
        weights = self.weights[feat]
        for label, weight in weights.items():
            scores[label] += value * weight
    # Do a secondary alphabetic sort, for stability
    return max(self.classes, key=lambda label: (scores[label], label))
</code>```

Effectively, if you change the code you code get the score of every possible tag by letting it return self.classes.

But because the features used in tag() requires the previous two tags as features https://github.com/nltk/nltk/blob/develop/nltk/tag/perceptron.py#L156

```<code>def tag(self, tokens):
    '''
    Tag tokenized sentences.
    :params tokens: list of word
    :type tokens: list(str)
    '''
    prev, prev2 = self.START
    output = []

    context = self.START + [self.normalize(w) for w in tokens] + self.END
    for i, word in enumerate(tokens):
        tag = self.tagdict.get(word)
        if not tag:
            features = self._get_features(i, word, context, prev, prev2)
            tag = self.model.predict(features)
        output.append((word, tag))
        prev2 = prev
        prev = tag

    return output
</code>```

The task of returning n-best tags would have to change the simple one-best "greedy" nature of the tagger to something that requires a beam.

Body:
TL;DR

No, not for the default pos_tag function.

In Long

For the default pos_tag function it's not possible.

The default pos_tag function is from the AveragedPerceptron object that uses the predict() function to get the most probable tag: https://github.com/nltk/nltk/blob/develop/nltk/tag/perceptron.py#L48

The function returns the argmax from the list of probable tags:

def predict(self, features):
    '''Dot-product the features and current weights and return the best label.'''
    scores = defaultdict(float)
    for feat, value in features.items():
        if feat not in self.weights or value == 0:
            continue
        weights = self.weights[feat]
        for label, weight in weights.items():
            scores[label] += value * weight
    # Do a secondary alphabetic sort, for stability
    return max(self.classes, key=lambda label: (scores[label], label))

Effectively, if you change the code you code get the score of every possible tag by letting it return self.classes.

But because the features used in tag() requires the previous two tags as features https://github.com/nltk/nltk/blob/develop/nltk/tag/perceptron.py#L156

def tag(self, tokens):
    '''
    Tag tokenized sentences.
    :params tokens: list of word
    :type tokens: list(str)
    '''
    prev, prev2 = self.START
    output = []

    context = self.START + [self.normalize(w) for w in tokens] + self.END
    for i, word in enumerate(tokens):
        tag = self.tagdict.get(word)
        if not tag:
            features = self._get_features(i, word, context, prev, prev2)
            tag = self.model.predict(features)
        output.append((word, tag))
        prev2 = prev
        prev = tag

    return output

The task of returning n-best tags would have to change the simple one-best "greedy" nature of the tagger to something that requires a beam.


问:
Generalization vs Specialization of DB table
When I want to design database tables that model a finite parent-child relationship, for e.g., computer as parent, and the components inside as the child; or a simple organizational hierarchy, I am usually torn at which approach to use -

A 'specialized table' approach, in which I create a table for each of the possible entity. In the computer component example, I would have a Computer table and a Component table, with the ComputerID as FK in the Component table referencing back to Computer.ComputerID.
or

A 'generalized table approach, in which I have one table table called Component, with ComponentID as PK, and a ParentComponentID as FK referencing to its parent's ComponentID.

答:
There's a great danger in relational design when you try to create generalisations that aren't actually true, but look elegant. If you have a general table with a type field, that introduces a form of indirection that has to be resolved in your code instead, which can hurt both performance and the clarity of the code.

On the other hand, such indirection can have its uses, and for certain purposes I use it quite a lot. The question you have to ask is whether Computer and Component really are aspects of the same thing, or whether you're just fudging them together because it sounds good.

OwnerDisplayName: Marcus Downing


问:
Find and extract a number from a string
I have a requirement to find and extract a number contained within a string.

For example, from these strings:

```<code>string test = "1 test"
string test1 = " 1 test"
string test2 = "test 99"
</code>```

How can I do this?

答:
Just use a RegEx to match the string, then convert:</p>

```<code>Match match = Regex.Match(test , @"(\d+)");
if (match.Success) {
   return int.Parse(match.Groups[1].Value);
}
</code>```

Title: Find and extract a number from a string

Body:
I have a requirement to find and extract a number contained within a string.

For example, from these strings:

string test = "1 test"
string test1 = " 1 test"
string test2 = "test 99"

How can I do this?

Body:
Just use a RegEx to match the string, then convert:

Match match = Regex.Match(test , @"(\d+)");
if (match.Success) {
   return int.Parse(match.Groups[1].Value);
}


问:
Why does Swift not allow a type conforming to a protocol to be used in an argument taking the protocol?
Given this example code:

```<code>private protocol P {}
final private class X {
    private func j(j: (P) -> Void) -> Void {}
    private func jj<Z: P>(jj: (Z) -> Void) -> Void {
        j(j: jj)
    }
}
</code>```

Swift 4 in XCode 9.1 gives this compiler error on the line j(j: jj):

Cannot convert value of type ‘(Z) -> Void’ to expected argument type
  ‘(P) -> Void’.

Why?

Note, it seems to me that it should not give this error, because the type constraint <Z: P> requires that Z absolutely must conform to protocol P. So, there should be absolutely no reason to convert from Z to P, since Z already conforms to P.

Seems like a compiler bug to me...

答:
The compiler is correct – a (Z) -> Void is not a (P) -> Void. To illustrate why this is the case, let's define the following conformances:

```<code>extension String : P {}
extension Int : P {}
</code>```

Now let's substitute Int for Z:

```<code>final private class X {

  func j(j: (P) -> Void) {
    j("foob")
  }

  func jj(jj: (Int) -> Void) {
    // error: Cannot convert value of type '(Int) -> Void' to expected argument
    // type '(P) -> Void'
    j(j: jj)
  }
}
</code>```

We cannot pass an (Int) -> Void to a (P) -> Void. Why? Well a (P) -> Void accepts anything that conforms to P – for example, we could pass in a String. But the function that we're passing to j is actually an (Int) -> Void, so we're trying to pass a String to an Int parameter, which is clearly unsound.

If we put the generics back in, it should still be fairly clear why this cannot work:

```<code>final private class X {

  func j(j: (P) -> Void) {
    j("foob")
  }

  func jj<Z : P>(jj: (Z) -> Void) {
    // error: Cannot convert value of type '(Z) -> Void' to expected argument
    // type '(P) -> Void'
    j(j: jj)
  }
}

X().jj { (i: Int) in
  print(i) // What are we printing here? A String gets passed in the above implementation..
}
</code>```

(P) -> Void is a function can deal with any P conforming argument. However (Z) -> Void is a function that can only deal with one specific concrete typed argument that conforms to P (e.g Int in our above example). Typing it as a function that can deal with any P conforming argument would be a lie.

Put in more technical manner, (Z) -> Void is not a subtype of (P) -> Void. Functions are contravariant with respect to their parameter types, meaning that (U) -> Void is a subtype of
 (V) -> Void if and only if V is a subtype of U. But P is not a subtype of Z : P – Z is a placeholder that is replaced at runtime with a concrete type that conforms to (so is a subtype of) P.

The more interesting part comes when we consider the opposite; that is, passing a (P) -> Void to a (Z) -> Void. Although the placeholder Z : P can only be satisfied by a concrete subtype of P, we cannot substitute P for Z because protocols don't conform to themselves.

Body:
Given this example code:

private protocol P {}
final private class X {
    private func j(j: (P) -> Void) -> Void {}
    private func jj<Z: P>(jj: (Z) -> Void) -> Void {
        j(j: jj)
    }
}

Swift 4 in XCode 9.1 gives this compiler error on the line j(j: jj):

Cannot convert value of type ‘(Z) -> Void’ to expected argument type
  ‘(P) -> Void’.

Why?

Note, it seems to me that it should not give this error, because the type constraint <Z: P> requires that Z absolutely must conform to protocol P. So, there should be absolutely no reason to convert from Z to P, since Z already conforms to P.

Seems like a compiler bug to me...

Body:
The compiler is correct – a (Z) -> Void is not a (P) -> Void. To illustrate why this is the case, let's define the following conformances:

extension String : P {}
extension Int : P {}

Now let's substitute Int for Z:

final private class X {

  func j(j: (P) -> Void) {
    j("foob")
  }

  func jj(jj: (Int) -> Void) {
    // error: Cannot convert value of type '(Int) -> Void' to expected argument
    // type '(P) -> Void'
    j(j: jj)
  }
}

We cannot pass an (Int) -> Void to a (P) -> Void. Why? Well a (P) -> Void accepts anything that conforms to P – for example, we could pass in a String. But the function that we're passing to j is actually an (Int) -> Void, so we're trying to pass a String to an Int parameter, which is clearly unsound.

If we put the generics back in, it should still be fairly clear why this cannot work:

final private class X {

  func j(j: (P) -> Void) {
    j("foob")
  }

  func jj<Z : P>(jj: (Z) -> Void) {
    // error: Cannot convert value of type '(Z) -> Void' to expected argument
    // type '(P) -> Void'
    j(j: jj)
  }
}

X().jj { (i: Int) in
  print(i) // What are we printing here? A String gets passed in the above implementation..
}

(P) -> Void is a function can deal with any P conforming argument. However (Z) -> Void is a function that can only deal with one specific concrete typed argument that conforms to P (e.g Int in our above example). Typing it as a function that can deal with any P conforming argument would be a lie.

Put in more technical manner, (Z) -> Void is not a subtype of (P) -> Void. Functions are contravariant with respect to their parameter types, meaning that (U) -> Void is a subtype of
 (V) -> Void if and only if V is a subtype of U. But P is not a subtype of Z : P – Z is a placeholder that is replaced at runtime with a concrete type that conforms to (so is a subtype of) P.

The more interesting part comes when we consider the opposite; that is, passing a (P) -> Void to a (Z) -> Void. Although the placeholder Z : P can only be satisfied by a concrete subtype of P, we cannot substitute P for Z because protocols don't conform to themselves.