问:
Accessing private members via reference accessor
What is the appropriate way to access private members of a referenced class instance? For example, accessing the initialNumberOfColumns from an instance of Cookie? Then have that value be used in another classes member function, such at Game::Game() after the reference accessor has retrieved the member of the Cookie class.

first.h:

```<code>class Cookie {
    public:
        Cookie();
        ~Cookie();
        void takeABite (int column, int row);
        int getNumberOfRows();
        int getNumberOfRows(int colNum);
        int getNumberOfColumns();
        int getNumberOfColumns(int rowNum);
        void display (std::ostream& output);

    private:
        int initialNumberOfRows;
        int numberOfRows;
        int numberOfColumns
        int* cookie;
};
</code>```

second.h:

```<code>class Game {
    public:
        Game();
        bool gameEnded();
        bool biteIsLegal (int column, int row);
        Cookie& getCookie();

    private:
        Cookie cookie;
};
</code>```

second.cpp is where I am having difficult. I know I need to use Cookie& Game::getCookie() but I am not sure how to return the private members of the Cookie class such that they can be accessed in the member function Game() below.:

```<code>Cookie& Game::getCookie() {
    return //not sure how to access;
}

Game::Game() {
    initialNumberOfRows = numberOfRows = 4 + rand() % (MAXROWS - 4);
    numberOfColumns = numberOfRows;

    while (numberOfColumns == numberOfRows) {
        numberOfColumns = 4 + rand() % (MAXROWS - 4);
    }

    cout << "The cookie has " << numberOfRows << " rows of "
         << numberOfColumns << " columns" << endl;

    for (int row = 0; row < numberOfRows; ++row) {
        cookie[row] = numberOfColumns;
    }
}
</code>```

答:
The Game class has a cookie member.  That is what the Game::getCookie() method should return:

```<code>Cookie& Game::getCookie() {
    return cookie;
}
</code>```

Now, inside of the Game constructor, you have direct access to the cookie member, so you don't need to use getCookie() to access it.  And the Cookie class has public methods for reading most of the values you are trying to use, but it DOES NOT provide any access to set those member values, or any access to its private initialNumberOfRows member at all.

The things you are trying to do in the Game constructor should be done in the Cookie constructor instead:

```<code>Cookie::Cookie() {
    initialNumberOfRows = numberOfRows = 4 + rand() % (MAXROWS - 4);

    numberOfColumns = numberOfRows;
    while (numberOfColumns == numberOfRows) {
        numberOfColumns = 4 + rand() % (MAXROWS - 4);
    }

    cookie = new int[numberofRows];

    for (int row = 0; row < numberOfRows; ++row) {
        cookie[row] = numberOfColumns;
    }
}
</code>```

Then the Game constructor can log the values as needed:

```<code>Game::Game() {
    cout << "The cookie has " << cookie.getNumberOfRows() << " rows of "
         << cookie.getNumberOfColumns() << " columns" << endl;
}
</code>```

Now, that being said, the Cookie class is violating the Rule of Three.  It needs to implement a copy constructor and copy assignment operator to ensure the integrity of its int *cookie field:

```<code>class Cookie {
public:
    Cookie();
    Cookie(const Cookie &src);
    ~Cookie();

    Cookie& operator=(const Cookie &rhs);
    void swap(Cookie &other);

    ...

private:
    int initialNumberOfRows;
    int numberOfRows;
    int numberOfColumns
    int* cookie;
};
</code>```

```<code>#include <algorithm>

Cookie::Cookie() {
    initialNumberOfRows = numberOfRows = 4 + rand() % (MAXROWS - 4);

    numberOfColumns = numberOfRows;
    while (numberOfColumns == numberOfRows) {
        numberOfColumns = 4 + rand() % (MAXROWS - 4);
    }

    cookie = new int[numberOfRows];
    std::fill(cookie, cookie + numberOfRows, numberOfColumns);
}

Cookie::Cookie(const Cookie &src) :
    initialNumberOfRows(src.initialNumberOfRows),
    numberOfRows(src.numberOfRows),
    numberOfColumns(src.numberOfColumns),
    cookie(new int[numberOfRows])
{
    std::copy(src.cookie, src.cookie + numberOfRows, cookie);
}

Cookie::~Cookie()
{
    delete[] cookie;
}

Cookie& Cookie::operator=(const Cookie &rhs)
{
    if (this != &rhs)
        Cookie(rhs).swap(*this);
    return *this;
}

void Cookie::swap(Cookie &other)
{
    std::swap(initialNumberOfRows, other.initialNumberOfRows);
    std::swap(numberOfRows, other.numberOfRows);
    std::swap(numberOfColumns, other.numberOfColumns);
    std::swap(cookie, other.cookie);
}
</code>```

Otherwise, change the int *cookie member to a std::vector instead, and let the compiler and STL handle the hard work of memory management for you:

```<code>#include <vector>

class Cookie {
public:
    Cookie();

    ...

private:
    int initialNumberOfRows;
    int numberOfRows;
    int numberOfColumns
    std::vector<int> cookie;
};
</code>```

```<code>Cookie::Cookie() {
    initialNumberOfRows = numberOfRows = 4 + rand() % (MAXROWS - 4);

    numberOfColumns = numberOfRows;
    while (numberOfColumns == numberOfRows) {
        numberOfColumns = 4 + rand() % (MAXROWS - 4);
    }

    cookie.resize(numberOfRows);
    std::fill(cookie.begin(), cookie.end(), numberOfColumns);
}
</code>```

Body:
What is the appropriate way to access private members of a referenced class instance? For example, accessing the initialNumberOfColumns from an instance of Cookie? Then have that value be used in another classes member function, such at Game::Game() after the reference accessor has retrieved the member of the Cookie class.

first.h:

class Cookie {
    public:
        Cookie();
        ~Cookie();
        void takeABite (int column, int row);
        int getNumberOfRows();
        int getNumberOfRows(int colNum);
        int getNumberOfColumns();
        int getNumberOfColumns(int rowNum);
        void display (std::ostream& output);

    private:
        int initialNumberOfRows;
        int numberOfRows;
        int numberOfColumns
        int* cookie;
};

second.h:

class Game {
    public:
        Game();
        bool gameEnded();
        bool biteIsLegal (int column, int row);
        Cookie& getCookie();

    private:
        Cookie cookie;
};

second.cpp is where I am having difficult. I know I need to use Cookie& Game::getCookie() but I am not sure how to return the private members of the Cookie class such that they can be accessed in the member function Game() below.:

Cookie& Game::getCookie() {
    return //not sure how to access;
}

Game::Game() {
    initialNumberOfRows = numberOfRows = 4 + rand() % (MAXROWS - 4);
    numberOfColumns = numberOfRows;

    while (numberOfColumns == numberOfRows) {
        numberOfColumns = 4 + rand() % (MAXROWS - 4);
    }

    cout << "The cookie has " << numberOfRows << " rows of "
         << numberOfColumns << " columns" << endl;

    for (int row = 0; row < numberOfRows; ++row) {
        cookie[row] = numberOfColumns;
    }
}

Body:
The Game class has a cookie member.  That is what the Game::getCookie() method should return:

Cookie& Game::getCookie() {
    return cookie;
}

Now, inside of the Game constructor, you have direct access to the cookie member, so you don't need to use getCookie() to access it.  And the Cookie class has public methods for reading most of the values you are trying to use, but it DOES NOT provide any access to set those member values, or any access to its private initialNumberOfRows member at all.

The things you are trying to do in the Game constructor should be done in the Cookie constructor instead:

Cookie::Cookie() {
    initialNumberOfRows = numberOfRows = 4 + rand() % (MAXROWS - 4);

    numberOfColumns = numberOfRows;
    while (numberOfColumns == numberOfRows) {
        numberOfColumns = 4 + rand() % (MAXROWS - 4);
    }

    cookie = new int[numberofRows];

    for (int row = 0; row < numberOfRows; ++row) {
        cookie[row] = numberOfColumns;
    }
}

Then the Game constructor can log the values as needed:

Game::Game() {
    cout << "The cookie has " << cookie.getNumberOfRows() << " rows of "
         << cookie.getNumberOfColumns() << " columns" << endl;
}

Now, that being said, the Cookie class is violating the Rule of Three.  It needs to implement a copy constructor and copy assignment operator to ensure the integrity of its int *cookie field:

class Cookie {
public:
    Cookie();
    Cookie(const Cookie &src);
    ~Cookie();

    Cookie& operator=(const Cookie &rhs);
    void swap(Cookie &other);

    ...

private:
    int initialNumberOfRows;
    int numberOfRows;
    int numberOfColumns
    int* cookie;
};

#include <algorithm>

Cookie::Cookie() {
    initialNumberOfRows = numberOfRows = 4 + rand() % (MAXROWS - 4);

    numberOfColumns = numberOfRows;
    while (numberOfColumns == numberOfRows) {
        numberOfColumns = 4 + rand() % (MAXROWS - 4);
    }

    cookie = new int[numberOfRows];
    std::fill(cookie, cookie + numberOfRows, numberOfColumns);
}

Cookie::Cookie(const Cookie &src) :
    initialNumberOfRows(src.initialNumberOfRows),
    numberOfRows(src.numberOfRows),
    numberOfColumns(src.numberOfColumns),
    cookie(new int[numberOfRows])
{
    std::copy(src.cookie, src.cookie + numberOfRows, cookie);
}

Cookie::~Cookie()
{
    delete[] cookie;
}

Cookie& Cookie::operator=(const Cookie &rhs)
{
    if (this != &rhs)
        Cookie(rhs).swap(*this);
    return *this;
}

void Cookie::swap(Cookie &other)
{
    std::swap(initialNumberOfRows, other.initialNumberOfRows);
    std::swap(numberOfRows, other.numberOfRows);
    std::swap(numberOfColumns, other.numberOfColumns);
    std::swap(cookie, other.cookie);
}

Otherwise, change the int *cookie member to a std::vector instead, and let the compiler and STL handle the hard work of memory management for you:

#include <vector>

class Cookie {
public:
    Cookie();

    ...

private:
    int initialNumberOfRows;
    int numberOfRows;
    int numberOfColumns
    std::vector<int> cookie;
};

Cookie::Cookie() {
    initialNumberOfRows = numberOfRows = 4 + rand() % (MAXROWS - 4);

    numberOfColumns = numberOfRows;
    while (numberOfColumns == numberOfRows) {
        numberOfColumns = 4 + rand() % (MAXROWS - 4);
    }

    cookie.resize(numberOfRows);
    std::fill(cookie.begin(), cookie.end(), numberOfColumns);
}


来源: stackexchange

问:
DRY initialization in Vues.js components
When a component is initialized I run the data callback like:

```<code>data(){
    return {
        name: myNameGetter(),
        age: myAgeGetter(),
        // etc...
    }
},
</code>```

and then warn some parent component about logic from this component:

```<code>created(){
    this.$emit('personFullName', this.getFullName());
},
</code>```

and then I also have the same logic inside my watchers:

```<code>watch: {
    person: function(){
        this.name = myNameGetter();
        this.age = myAgeGetter();
        this.$emit('personFullName', this.getFullName());
    }
}
</code>```

Is there a way to DRY this?

The only idea I came up with was:

```<code>watch: {
    person: function(){
        const data = this.data();
        for (let key in data) this[key] = data[key];
        this.$emit('personFullName', this.getFullName());
    }
}
</code>```

but feels a bit unDRY still. How does the community solved this?

答:
so that was a example, the real life app is a calendar. In the container I have the calendar header. Then I have child components for month, week and day view. The title in the container is set by the child component. So if its month view the child will $emit "march 2017", if its the day view the other child component will $emit "31st march". And so on. The problem is that I have to call that getter function in data when the component initialises, also on watch and emit that to parent when created. This is what I want to DRY.

I've made a date/time picker in Vue before, which is kind of similar to your Calendar component in that there is a container component (DateTimePicker) which has 2 child components (DatePicker and TimePicker). Only one of the child components is visible at a time depending on whether the date or time is being edited.

I think it would be better to restructure how your components share data. It sounds to me like the child components are tightly coupled to the Calendar component (which is fine). I'm not sure if your Calendar component is meant for user input (can the user choose a date?), or only to display a particular date.

Why is it the responsibility of the child component to determine the title? The same Date is shared across each child component, so the Calendar component can easily determine the title depending on which child component is visible, something like:

```<code><div class="calendar">
  <div class="cal-title">{{ title }}</div>
  <day v-if="view === 'day'" :value="date" @input="onInput"></day>
  <week v-if="view === 'week'" :value="date" @input="onInput"></week>
  <month v-if="view === 'month'" :value="date" @input="onInput"></month>
</div>
</code>```

```<code>{
  props: ['date'],

  data() {
    return {
      view: 'day',
      // This component has no internal state for the date
    };
  },

  computed: {
    title() {
      switch (this.view) {
        case 'day': return this.date.format('day'); break;
        case 'week': return this.date.format('week'); break;
        case 'month': return this.date.format('month'); break;
      }
    },
  },

  methods: {
    onInput(date) {
      this.$emit('input', date);
    },
  },
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
When a component is initialized I run the data callback like:

data(){
    return {
        name: myNameGetter(),
        age: myAgeGetter(),
        // etc...
    }
},

and then warn some parent component about logic from this component:

created(){
    this.$emit('personFullName', this.getFullName());
},

and then I also have the same logic inside my watchers:

watch: {
    person: function(){
        this.name = myNameGetter();
        this.age = myAgeGetter();
        this.$emit('personFullName', this.getFullName());
    }
}

Is there a way to DRY this?

The only idea I came up with was:

watch: {
    person: function(){
        const data = this.data();
        for (let key in data) this[key] = data[key];
        this.$emit('personFullName', this.getFullName());
    }
}

but feels a bit unDRY still. How does the community solved this?

Body:
so that was a example, the real life app is a calendar. In the container I have the calendar header. Then I have child components for month, week and day view. The title in the container is set by the child component. So if its month view the child will $emit "march 2017", if its the day view the other child component will $emit "31st march". And so on. The problem is that I have to call that getter function in data when the component initialises, also on watch and emit that to parent when created. This is what I want to DRY.

I've made a date/time picker in Vue before, which is kind of similar to your Calendar component in that there is a container component (DateTimePicker) which has 2 child components (DatePicker and TimePicker). Only one of the child components is visible at a time depending on whether the date or time is being edited.

I think it would be better to restructure how your components share data. It sounds to me like the child components are tightly coupled to the Calendar component (which is fine). I'm not sure if your Calendar component is meant for user input (can the user choose a date?), or only to display a particular date.

Why is it the responsibility of the child component to determine the title? The same Date is shared across each child component, so the Calendar component can easily determine the title depending on which child component is visible, something like:

<div class="calendar">
  <div class="cal-title">{{ title }}</div>
  <day v-if="view === 'day'" :value="date" @input="onInput"></day>
  <week v-if="view === 'week'" :value="date" @input="onInput"></week>
  <month v-if="view === 'month'" :value="date" @input="onInput"></month>
</div>

{
  props: ['date'],

  data() {
    return {
      view: 'day',
      // This component has no internal state for the date
    };
  },

  computed: {
    title() {
      switch (this.view) {
        case 'day': return this.date.format('day'); break;
        case 'week': return this.date.format('week'); break;
        case 'month': return this.date.format('month'); break;
      }
    },
  },

  methods: {
    onInput(date) {
      this.$emit('input', date);
    },
  },
}


问:
Convert row to column when data are not numbers
I have a Question table, which has a unknown number of questions.(first table in the figure)

I also have an AnswerSheet table, which records student's answer to question.(second table in the figure)

```<code>Create table Question
(
    Id int,
    Text nvarchar(50),

    PRIMARY KEY (Id)
)

Create table AnswerSheet
(
    StudentId int,
    QuestionId int,
    Answer nvarchar(50),

    PRIMARY KEY (StudentId,QuestionId),
    FOREIGN KEY (QuestionId) REFERENCES Question (Id)
)

insert into Question
values(1,'What''s your age'),
      (2,'What''s your gender'),
      (3,'When do you go home'),
      ....

insert into AnswerSheet
values(500,1,'20'),
      (500,2,'Male'),
      (500,3,'5:00pm'),
      (501,1,'50'),
      (502,2,'I don''t know@@'),
      ....
</code>```

How do I write a SQL to generate a table like this?

```<code>StudentId    What's your age    What's your gender    When do you go home ...
---------    ----------------   -------------------   -------------------
500          20                 Male                  5:00pm              ...
501          50                 NULL                  NULL
502          NULL               I don''t know@@       NULL                ...
</code>```

I feel Pivot is promising but I'm not sure how to use it especially PIVOT requires an aggreation function but my data are not numbers.

答:
Assuming you wanted to go Dynamic

Example

```<code>Declare @SQL varchar(max) = Stuff((Select ',' + QuoteName(Text) From Question  Order by ID For XML Path('')),1,1,'')

Select  @SQL = '
Select *
From (
        Select StudentID
              ,Col       = B.Text
              ,Value     = A.Answer
         From AnswerSheet A
         Join Question B on A.QuestionID=B.ID
     ) A
 Pivot (max(Value) For [Col] in (' + @SQL + ') ) p'
Exec(@SQL);
</code>```

Returns

```<code>StudentID   What's your age What's your gender  When do you go home
500         20              Male               5:00pm
501         50              NULL               NULL
502         NULL            I don't know@@     NULL
</code>```

If it Helps, the Generated SQL Looks Like This

```<code>Select *
From (
        Select StudentID
              ,Col       = B.Text
              ,Value     = A.Answer
         From AnswerSheet A
         Join Question B on A.QuestionID=B.ID
     ) A
 Pivot (max(Value) For [Col] in ([What's your age],[What's your gender],[When do you go home]) ) p
</code>```

Body:
I have a Question table, which has a unknown number of questions.(first table in the figure)

I also have an AnswerSheet table, which records student's answer to question.(second table in the figure)

Create table Question
(
    Id int,
    Text nvarchar(50),

    PRIMARY KEY (Id)
)

Create table AnswerSheet
(
    StudentId int,
    QuestionId int,
    Answer nvarchar(50),

    PRIMARY KEY (StudentId,QuestionId),
    FOREIGN KEY (QuestionId) REFERENCES Question (Id)
)

insert into Question
values(1,'What''s your age'),
      (2,'What''s your gender'),
      (3,'When do you go home'),
      ....

insert into AnswerSheet
values(500,1,'20'),
      (500,2,'Male'),
      (500,3,'5:00pm'),
      (501,1,'50'),
      (502,2,'I don''t know@@'),
      ....

How do I write a SQL to generate a table like this?

StudentId    What's your age    What's your gender    When do you go home ...
---------    ----------------   -------------------   -------------------
500          20                 Male                  5:00pm              ...
501          50                 NULL                  NULL
502          NULL               I don''t know@@       NULL                ...

I feel Pivot is promising but I'm not sure how to use it especially PIVOT requires an aggreation function but my data are not numbers.

Body:
Assuming you wanted to go Dynamic

Example

Declare @SQL varchar(max) = Stuff((Select ',' + QuoteName(Text) From Question  Order by ID For XML Path('')),1,1,'')

Select  @SQL = '
Select *
From (
        Select StudentID
              ,Col       = B.Text
              ,Value     = A.Answer
         From AnswerSheet A
         Join Question B on A.QuestionID=B.ID
     ) A
 Pivot (max(Value) For [Col] in (' + @SQL + ') ) p'
Exec(@SQL);

Returns

StudentID   What's your age What's your gender  When do you go home
500         20              Male               5:00pm
501         50              NULL               NULL
502         NULL            I don't know@@     NULL

If it Helps, the Generated SQL Looks Like This

Select *
From (
        Select StudentID
              ,Col       = B.Text
              ,Value     = A.Answer
         From AnswerSheet A
         Join Question B on A.QuestionID=B.ID
     ) A
 Pivot (max(Value) For [Col] in ([What's your age],[What's your gender],[When do you go home]) ) p


问:
QwtPlot mouse click event
I need to get x and y coordinates of mouse click on QwtPlot drawing area (not the whole widget!). The problem is that there's only method bool event(QEvent*) that is called on every event. I've found some solutions (http://www.qtcentre.org/archive/index.php/t-9502.html), using QwtPlotPicker but that doesn't work for me, I'm using Qwt 6 and there are no such methods like setSelectionState().

What is other methods for achieving mouse click events on drawing area in QwtPlot?

答:
I'm capturing the mouse events using the mouse event methods in a subclass of QwtPlotCanvas, and using the conversion methods in QwtPlot to map the mouse event x and y coordinates to the values they represent in the plot.

Create a subclass of QwtPlotCanvas and override the mousePressEvent method like this.

```<code>void SpecialMapPlotCanvas::mousePressEvent (QMouseEvent* event) {
    QWidget::mousePressEvent (event);
    double x = plot() -> invTransform (plot() -> xBottom, event -> pos().x());
    double y = plot() -> invTransform (plot() -> yLeft, event -> pos().y());
    std::cout << "Values " << x << " " << y << "\n";
}
</code>```

Then set the canvas on the QwtPlot by instantiating an object of this class and passing it to QwtPlot::setCanvas. Then SpecialMapPlotCanvas::plot() gives you a reference to the owning QwtPlot, and its invTransform methods can be used to convert the click coordinates to plot values. If you use the mouse events on QwtPlot itself you get the wrong answers because the mouse event coordinates here relate to the whole QwtPlot widget area (as you say), not just the canvas.

Title: QwtPlot mouse click event

Body:
I'm capturing the mouse events using the mouse event methods in a subclass of QwtPlotCanvas, and using the conversion methods in QwtPlot to map the mouse event x and y coordinates to the values they represent in the plot.

Create a subclass of QwtPlotCanvas and override the mousePressEvent method like this.

void SpecialMapPlotCanvas::mousePressEvent (QMouseEvent* event) {
    QWidget::mousePressEvent (event);
    double x = plot() -> invTransform (plot() -> xBottom, event -> pos().x());
    double y = plot() -> invTransform (plot() -> yLeft, event -> pos().y());
    std::cout << "Values " << x << " " << y << "\n";
}

Then set the canvas on the QwtPlot by instantiating an object of this class and passing it to QwtPlot::setCanvas. Then SpecialMapPlotCanvas::plot() gives you a reference to the owning QwtPlot, and its invTransform methods can be used to convert the click coordinates to plot values. If you use the mouse events on QwtPlot itself you get the wrong answers because the mouse event coordinates here relate to the whole QwtPlot widget area (as you say), not just the canvas.


问:
How to extract a string from a cell from right to left using a specific character that occurs more than once?
Normally I would just use the RIGHT function in excel to split it by finding a specific character such as / and outputting the string that I want.

However, I am finding trouble extracting THISSTRING.txt from d/aaa/THISSTRING.txt. With only one instance of / I would just use a function such as =RIGHT(B17,LEN(B17) - FIND("/",B17))

答:
Here's another way.....

=REPLACE(B17,1,LOOKUP(2^15,FIND("/",B17,ROW(INDIRECT("1:"&LEN(B17))))),"")

FIND generates an array of values, indicating the first position of a "/" in B17, but with the start point incrementing by 1 each time, which means that the last numeric value in that array is the positon of the last "/".

LOOKUP extracts that value from the array and we can use it in REPLACE function to replace all characters before and at that position with nothing, just leaving you with all characters after the last "/"

You'll get an error if there is no "/" in B17


问:
Multi-instance XML file to CSV with Headers and Column Mappings
I am trying to convert an multi-instance XML file, where a parent node, could have 2 or more child nodes of the same kind.

Essentially, I have this type of XML file:

```<code><?xml version='1.0' encoding='UTF-8'?>
<Report_Data>
   <Report_Entry>
      <field1>Record1_field1</field1>
      <field2>Record1_field2</field2>
      <field3>Record1_field3</field3>
      <Report_SubEntry>
         <subField1>Record_1subfield1</subField1>
         <subField2>Record_1subfield2</subField2>
         <subField3>Record_1subfield3</subField3>
      </Report_SubEntry>
      <Report_SubEntry>
         <subField1>Record1_subfield1_subEntry2</subField1>
         <subField2>Record1_subfield2_subEntry2</subField2>
         <subField3>Record1_subfield3_subEntry2</subField3>
      </Report_SubEntry>
   </Report_Entry>
      <Report_Entry>
      <field1>Record2_field1</field1>
      <field2>Record2_field2</field2>
      <field3>Record2_field3</field3>
      <Report_SubEntry>
         <subField1>Record2_subfield1</subField1>
         <subField2>Record2_subfield2</subField2>
         <subField3>Record2_subfield3</subField3>
      </Report_SubEntry>
   </Report_Entry>
 </Report_Data>
</code>```

The XSLT function has to be re-usable for similarly structured XML files, without having to hard-code loops or conditions for all the possible sub-entry types.

This is my XSLT:

```<code><xsl:stylesheet version="1.0"
    xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    exclude-result-prefixes="xs this ws">

    <xsl:output method="text" encoding="UTF-8" media-type="text/plain"/>
    <xsl:strip-space elements="*"/>

    <xsl:param name="delimiter" select="'§'" />
    <xsl:param name="quote" select="''" />
    <xsl:param name="break" select="'\n'" />

    <!--
        List of Fields to be included in final CSV.
        !! Use only XPATH node names with prefixes. !!
               If prefixes are to be removed from the header, update the
    -->

    <xsl:variable name="fieldArray">
        <field>field1</field>
        <field>field2</field>
        <field>field3</field>
        <field>subField1</field>
        <field>subField2</field>
        <field>subField3</field>
    </xsl:variable>

    <xsl:param name="fields" select="document('')/*/xsl:variable[@name='fieldArray']/*" />

    <xsl:template match="//Report_Entry">

        <!-- output the header row -->
        <xsl:for-each select="$fields">
            <xsl:if test="position() != 1">
                <xsl:value-of select="$delimiter"/>
            </xsl:if>
            <xsl:value-of select="." />
        </xsl:for-each>

        <!-- output newline -->
        <xsl:text>
</xsl:text>
        <xsl:apply-templates select="Report_Entry"/>

    </xsl:template>

    <xsl:template match="//Report_Entry">
        <xsl:variable name="currNode" select="." />

        <!-- output the data row -->
        <!-- loop over the field names and find the value of each one in the xml -->

        <xsl:for-each select="$fields">

            <xsl:if test="position() != 1">
                <xsl:value-of select="$delimiter"/>
            </xsl:if>

            <xsl:value-of select="$quote" />

            <xsl:variable name="child" select="$currNode[*]/*/*[name() = current()]" />
            <xsl:variable name="childSecondLevel" select="$currNode[*]/*/*/*[name() = current()]" />
            <xsl:variable name="childThirdLevel" select="$currNode[*]/*/*/*/*[name() = current()]" />

            <xsl:choose>

                <xsl:when test="count($child) > 0">
                    <xsl:value-of select="$child"/>
                </xsl:when>

                <xsl:when test="count($childSecondLevel) > 0">
                    <xsl:value-of select="$childSecondLevel"/>
                </xsl:when>

                <xsl:when test="count($childThirdLevel) > 0">
                    <xsl:value-of select="$childThirdLevel"/>
                </xsl:when>

                <xsl:otherwise>
                    <xsl:value-of select="$currNode/*[name() = current()]" />
                </xsl:otherwise>

            </xsl:choose>

            <xsl:value-of select="$quote" />

        </xsl:for-each>

        <!-- output newline -->
        <xsl:value-of select="$break" />
    </xsl:template>

</xsl:stylesheet>
</code>```

The Output that I get is:

```<code>field1,field2,field3,subField1,subField2,subField3
Record1_field1,Record1_field2,Record1_field3,Record_1subfield1,Record_1subfield2,Record_1subfield3
Record2_field1,Record2_field2,Record2_field3,Record2_subfield1,Record2_subfield2,Record2_subfield3
</code>```

But the output I need is:

```<code>field1,field2,field3,subField1,subField2,subField3
Record1_field1,Record1_field2,Record1_field3,Record_1subfield1,Record_1subfield2,Record_1subfield3
Record1_field1,Record1_field2,Record1_field3,Record_1subfield1_subEntry2,Record_1subfield2_subEntry2,Record_1subfield3_subEntry3
Record2_field1,Record2_field2,Record2_field3,Record2_subfield1,Record2_subfield2,Record2_subfield3
</code>```

Does anyone have suggestions on approaching this?

答:
How about the below.

I am looping through the Report_SubEntry instead of the Report_Entry, meaning for each Report_SubEntry you will get one row.

```<code><xsl:template match="/">
    <!-- Output header -->
    <xsl:text>f1,f2,f3,sf1,sf2,sf3
</xsl:text>

    <!-- Loop through all children of Report_Entry that have childen themselves -->
    <xsl:for-each select="/Report_Data/*/*[*]">
        <xsl:variable name="strCurrentNode" select="name()" />

        <!-- Output parent values -->
        <xsl:for-each select="../*">
            <xsl:if test="name() != $strCurrentNode">
                <xsl:value-of select="." />
                <xsl:text>,</xsl:text>
            </xsl:if>
        </xsl:for-each>

        <!-- Output child values -->
        <xsl:for-each select="./*">
            <xsl:if test="name() != $strCurrentNode">
                <xsl:value-of select="." />

                <xsl:if test="position() != last()">
                    <xsl:text>,</xsl:text>
                </xsl:if>
            </xsl:if>
        </xsl:for-each>

        <!-- output newline -->
        <xsl:text>
</xsl:text>
    </xsl:for-each>
</xsl:template>
</code>```

Body:
I am trying to convert an multi-instance XML file, where a parent node, could have 2 or more child nodes of the same kind.

Essentially, I have this type of XML file:

<?xml version='1.0' encoding='UTF-8'?>
<Report_Data>
   <Report_Entry>
      <field1>Record1_field1</field1>
      <field2>Record1_field2</field2>
      <field3>Record1_field3</field3>
      <Report_SubEntry>
         <subField1>Record_1subfield1</subField1>
         <subField2>Record_1subfield2</subField2>
         <subField3>Record_1subfield3</subField3>
      </Report_SubEntry>
      <Report_SubEntry>
         <subField1>Record1_subfield1_subEntry2</subField1>
         <subField2>Record1_subfield2_subEntry2</subField2>
         <subField3>Record1_subfield3_subEntry2</subField3>
      </Report_SubEntry>
   </Report_Entry>
      <Report_Entry>
      <field1>Record2_field1</field1>
      <field2>Record2_field2</field2>
      <field3>Record2_field3</field3>
      <Report_SubEntry>
         <subField1>Record2_subfield1</subField1>
         <subField2>Record2_subfield2</subField2>
         <subField3>Record2_subfield3</subField3>
      </Report_SubEntry>
   </Report_Entry>
 </Report_Data>

The XSLT function has to be re-usable for similarly structured XML files, without having to hard-code loops or conditions for all the possible sub-entry types.

This is my XSLT:

<xsl:stylesheet version="1.0"
    xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    exclude-result-prefixes="xs this ws">

    <xsl:output method="text" encoding="UTF-8" media-type="text/plain"/>
    <xsl:strip-space elements="*"/>

    <xsl:param name="delimiter" select="'§'" />
    <xsl:param name="quote" select="''" />
    <xsl:param name="break" select="'
'" />

    <xsl:variable name="fieldArray">
        <field>field1</field>
        <field>field2</field>
        <field>field3</field>
        <field>subField1</field>
        <field>subField2</field>
        <field>subField3</field>
    </xsl:variable>

    <xsl:param name="fields" select="document('')/*/xsl:variable[@name='fieldArray']/*" />

    <xsl:template match="//Report_Entry">

        <xsl:for-each select="$fields">
            <xsl:if test="position() != 1">
                <xsl:value-of select="$delimiter"/>
            </xsl:if>
            <xsl:value-of select="." />
        </xsl:for-each>

        <xsl:text>
</xsl:text>
        <xsl:apply-templates select="Report_Entry"/>

    </xsl:template>

    <xsl:template match="//Report_Entry">
        <xsl:variable name="currNode" select="." />

        <xsl:for-each select="$fields">

            <xsl:if test="position() != 1">
                <xsl:value-of select="$delimiter"/>
            </xsl:if>

            <xsl:value-of select="$quote" />

            <xsl:variable name="child" select="$currNode[*]/*/*[name() = current()]" />
            <xsl:variable name="childSecondLevel" select="$currNode[*]/*/*/*[name() = current()]" />
            <xsl:variable name="childThirdLevel" select="$currNode[*]/*/*/*/*[name() = current()]" />

            <xsl:choose>

                <xsl:when test="count($child) > 0">
                    <xsl:value-of select="$child"/>
                </xsl:when>

                <xsl:when test="count($childSecondLevel) > 0">
                    <xsl:value-of select="$childSecondLevel"/>
                </xsl:when>

                <xsl:when test="count($childThirdLevel) > 0">
                    <xsl:value-of select="$childThirdLevel"/>
                </xsl:when>

                <xsl:otherwise>
                    <xsl:value-of select="$currNode/*[name() = current()]" />
                </xsl:otherwise>

            </xsl:choose>

            <xsl:value-of select="$quote" />

        </xsl:for-each>

        <xsl:value-of select="$break" />
    </xsl:template>

</xsl:stylesheet>

The Output that I get is:

field1,field2,field3,subField1,subField2,subField3
Record1_field1,Record1_field2,Record1_field3,Record_1subfield1,Record_1subfield2,Record_1subfield3
Record2_field1,Record2_field2,Record2_field3,Record2_subfield1,Record2_subfield2,Record2_subfield3

But the output I need is:

field1,field2,field3,subField1,subField2,subField3
Record1_field1,Record1_field2,Record1_field3,Record_1subfield1,Record_1subfield2,Record_1subfield3
Record1_field1,Record1_field2,Record1_field3,Record_1subfield1_subEntry2,Record_1subfield2_subEntry2,Record_1subfield3_subEntry3
Record2_field1,Record2_field2,Record2_field3,Record2_subfield1,Record2_subfield2,Record2_subfield3

Does anyone have suggestions on approaching this?

Body:
How about the below.

I am looping through the Report_SubEntry instead of the Report_Entry, meaning for each Report_SubEntry you will get one row.

<xsl:template match="/">
    <!-- Output header -->
    <xsl:text>f1,f2,f3,sf1,sf2,sf3&#xa;</xsl:text>

    <!-- Loop through all children of Report_Entry that have childen themselves -->
    <xsl:for-each select="/Report_Data/*/*[*]">
        <xsl:variable name="strCurrentNode" select="name()" />

        <!-- Output parent values -->
        <xsl:for-each select="../*">
            <xsl:if test="name() != $strCurrentNode">
                <xsl:value-of select="." />
                <xsl:text>,</xsl:text>
            </xsl:if>
        </xsl:for-each>

        <!-- Output child values -->
        <xsl:for-each select="./*">
            <xsl:if test="name() != $strCurrentNode">
                <xsl:value-of select="." />

                <xsl:if test="position() != last()">
                    <xsl:text>,</xsl:text>
                </xsl:if>
            </xsl:if>
        </xsl:for-each>

        <!-- output newline -->
        <xsl:text>&#xa;</xsl:text>
    </xsl:for-each>
</xsl:template>


问:
Elasticsearch highlighter number of tokens before and after
I'm using the plain highlighter (Elasticsearch 5.2). Here is an example

```<code>PUT bookstore
{
  "mappings": {
    "books": {
      "properties": {
        "list": {
          "properties": {
            "summary": {
              "type": "text"
            },
            "title": {
              "type": "text"
            }
          }
        }
      }
    }
  }
}
</code>```

```<code>POST bookstore/books/1
{
  "list": [
    {
      "summary": "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.",
      "title": "Elasticsearch"
    }
  ]
}
</code>```

```<code>GET bookstore/books/_search
{
  "query": {
    "simple_query_string": {
      "query": "scrambled"
    }
  },
  "highlight": {
    "fields": {
      "*": {
        "require_field_match": false,
        "number_of_fragments": 1,
        "fragment_size": 70
      }
    }
  }
}
</code>```

```<code>"highlight": {
  "list.summary": [
    " <em>scrambled</em> it to make a type specimen book. It has survived not only five"
  ]
}
</code>```

My question is, how can I make it to center the highlighted word? In this case the highlighted word is at the beginning, on other cases is at the end. How can I make sure that is in the middle?

Ideally what I want is to specify number of tokens before and after the highlighted text, instead of fragment size.

答:
In the end this is not supported. A workaround is to set number_of_fragments:0. This will return the full field with highlighting. After that, it's easy to apply any custom logic on application level.

http://elasticsearch-users.115913.n3.nabble.com/Controlling-highlight-fragments-td1563243.html

Body:
I'm using the plain highlighter (Elasticsearch 5.2). Here is an example

PUT bookstore
{
  "mappings": {
    "books": {
      "properties": {
        "list": {
          "properties": {
            "summary": {
              "type": "text"
            },
            "title": {
              "type": "text"
            }
          }
        }
      }
    }
  }
}

POST bookstore/books/1
{
  "list": [
    {
      "summary": "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.",
      "title": "Elasticsearch"
    }
  ]
}

GET bookstore/books/_search
{
  "query": {
    "simple_query_string": {
      "query": "scrambled"
    }
  },
  "highlight": {
    "fields": {
      "*": {
        "require_field_match": false,
        "number_of_fragments": 1,
        "fragment_size": 70
      }
    }
  }
}

"highlight": {
  "list.summary": [
    " scrambled it to make a type specimen book. It has survived not only five"
  ]
}

My question is, how can I make it to center the highlighted word? In this case the highlighted word is at the beginning, on other cases is at the end. How can I make sure that is in the middle?

Ideally what I want is to specify number of tokens before and after the highlighted text, instead of fragment size.


问:
Error in eval(expr, envir, enclos) : object 'V2' not found
Why am I attaining this error?
It appears my svm classifier worked based on the output, however the rest does not work. I have attempted this with the given iris dataset from R, and the code below worked perfectly. However, when trying to run with the loaded data set it does not.

error:

```<code>Error in eval(expr, envir, enclos) : object 'V2' not found
</code>```

Code:

```<code>balance_data = read.table(file.choose(), sep=",")
str(balance_data)
x <- balance_data[, c(2,3,4,5)]
y <- balance_data[,1]
X_train <-head(x,500)
Y_train <- head(y,100)
X_test <-tail(x,122)

decisionTree_Learnruntime = c()
svm_Learnruntime = c()
naivebayes_Learnruntime = c()
knn_Learnruntime = c()

decisionTree_Predictruntime = c()
svm_Predictruntime = c()
naivebayes_Predictruntime =c()
knn_Predictruntime = c()

for (i in 1:20){
  library(e1071)
  library(caret)
  #SVM Model
  start.time <- Sys.time()
  svm_model <- svm(X_train,Y_train)
  end.time <- Sys.time()
  time.taken <- end.time - start.time
  svm_Learnruntime [i]<- time.taken

  #Prediction Time
  start.time <- Sys.time()
  pred <- predict(svm_model,X_test)
  end.time <- Sys.time()
  time.taken <- end.time - start.time
  svm_Predictruntime [i]<- time.taken

  library(rpart)
  #Decision Tree
  #Learn Time
  start.time <- Sys.time()
  tree_model <- rpart(X_train,Y_train)
  end.time <- Sys.time()
  time.taken <- end.time - start.time
  decisionTree_Learnruntime [i]<- time.taken

  #Prediction Time
  start.time <- Sys.time()
  pred = predict(tree_model,X_test)
  end.time <- Sys.time()
  time.taken <- end.time - start.time
  decisionTree_Predictruntime[i] <- time.taken

  #Naive Bayes
  #Learn Time
  start.time <- Sys.time()
  naive_model <-naiveBayes(X_train,Y_train)
  end.time <- Sys.time()
  time.taken <- end.time - start.time
  naivebayes_Learnruntime [i]<- time.taken

  #Prediction Time
  start.time <- Sys.time()
  pred <- predict(naive_model,X_test)
  end.time <- Sys.time()
  time.taken <- end.time - start.time
  naivebayes_Predictruntime [i]<- time.taken

}

mean(svm_Learnruntime)
mean(svm_Predictruntime)
decisionTree_Learnruntime
decisionTree_Predictruntime
naivebayes_Learnruntime
naivebayes_Predictruntime
</code>```

output

```<code>> mean(svm_Learnruntime)
[1] 0.01403713
> mean(svm_Predictruntime)
[1] 0.001003027
> decisionTree_Learnruntime
NULL
> decisionTree_Predictruntime
NULL
> naivebayes_Learnruntime
NULL
> naivebayes_Predictruntime
NULL
</code>```

structure

```<code>> str(balance_data)
'data.frame':   625 obs. of  5 variables:
 $ V1: Factor w/ 3 levels "B","L","R": 1 3 3 3 3 3 3 3 3 3 ...
 $ V2: int  1 1 1 1 1 1 1 1 1 1 ...
 $ V3: int  1 1 1 1 1 1 1 1 1 1 ...
 $ V4: int  1 1 1 1 1 2 2 2 2 2 ...
 $ V5: int  1 2 3 4 5 1 2 3 4 5 ...
> str(X_train)
'data.frame':   500 obs. of  4 variables:
 $ V2: int  1 1 1 1 1 1 1 1 1 1 ...
 $ V3: int  1 1 1 1 1 1 1 1 1 1 ...
 $ V4: int  1 1 1 1 1 2 2 2 2 2 ...
 $ V5: int  1 2 3 4 5 1 2 3 4 5 ...
> str(X_test)
'data.frame':   122 obs. of  4 variables:
 $ V2: int  5 5 5 5 5 5 5 5 5 5 ...
 $ V3: int  1 1 1 1 1 1 1 1 1 1 ...
 $ V4: int  1 1 2 2 2 2 2 3 3 3 ...
 $ V5: int  4 5 1 2 3 4 5 1 2 3 ...
> str(Y_train)
 Factor w/ 3 levels "B","L","R": 1 3 3 3 3 3 3 3 3 3 ...
</code>```

答:
Your error comes from the rpart function.

From the rpart documentation:

Usage

```<code>rpart(formula, data, weights, subset, na.action = na.rpart, method,
  model = FALSE, x = FALSE, y = TRUE, parms, control, cost, ...)
</code>```

Arguments

formula:
     a formula, with a response but no interaction terms. If this a a
  data frome, that is taken as the model frame (see model.frame).

So you need something like:

```<code>data_train <- head(balance_data,100)
...
tree_model <- rpart(V1 ~ V2 + V3 + V4, data_train)
</code>```

Depending on what are your model.

Body:
Why am I attaining this error?
It appears my svm classifier worked based on the output, however the rest does not work. I have attempted this with the given iris dataset from R, and the code below worked perfectly. However, when trying to run with the loaded data set it does not.

error:

Error in eval(expr, envir, enclos) : object 'V2' not found

Code:

balance_data = read.table(file.choose(), sep=",")
str(balance_data)
x <- balance_data[, c(2,3,4,5)]
y <- balance_data[,1]
X_train <-head(x,500)
Y_train <- head(y,100)
X_test <-tail(x,122)

decisionTree_Learnruntime = c()
svm_Learnruntime = c()
naivebayes_Learnruntime = c()
knn_Learnruntime = c()

decisionTree_Predictruntime = c()
svm_Predictruntime = c()
naivebayes_Predictruntime =c()
knn_Predictruntime = c()

for (i in 1:20){
  library(e1071)
  library(caret)
  #SVM Model
  start.time <- Sys.time()
  svm_model <- svm(X_train,Y_train)
  end.time <- Sys.time()
  time.taken <- end.time - start.time
  svm_Learnruntime [i]<- time.taken

  #Prediction Time
  start.time <- Sys.time()
  pred <- predict(svm_model,X_test)
  end.time <- Sys.time()
  time.taken <- end.time - start.time
  svm_Predictruntime [i]<- time.taken

  library(rpart)
  #Decision Tree
  #Learn Time
  start.time <- Sys.time()
  tree_model <- rpart(X_train,Y_train)
  end.time <- Sys.time()
  time.taken <- end.time - start.time
  decisionTree_Learnruntime [i]<- time.taken

  #Prediction Time
  start.time <- Sys.time()
  pred = predict(tree_model,X_test)
  end.time <- Sys.time()
  time.taken <- end.time - start.time
  decisionTree_Predictruntime[i] <- time.taken

  #Naive Bayes
  #Learn Time
  start.time <- Sys.time()
  naive_model <-naiveBayes(X_train,Y_train)
  end.time <- Sys.time()
  time.taken <- end.time - start.time
  naivebayes_Learnruntime [i]<- time.taken

  #Prediction Time
  start.time <- Sys.time()
  pred <- predict(naive_model,X_test)
  end.time <- Sys.time()
  time.taken <- end.time - start.time
  naivebayes_Predictruntime [i]<- time.taken

}

mean(svm_Learnruntime)
mean(svm_Predictruntime)
decisionTree_Learnruntime
decisionTree_Predictruntime
naivebayes_Learnruntime
naivebayes_Predictruntime

output

> mean(svm_Learnruntime)
[1] 0.01403713
> mean(svm_Predictruntime)
[1] 0.001003027
> decisionTree_Learnruntime
NULL
> decisionTree_Predictruntime
NULL
> naivebayes_Learnruntime
NULL
> naivebayes_Predictruntime
NULL

structure

> str(balance_data)
'data.frame':   625 obs. of  5 variables:
 $ V1: Factor w/ 3 levels "B","L","R": 1 3 3 3 3 3 3 3 3 3 ...
 $ V2: int  1 1 1 1 1 1 1 1 1 1 ...
 $ V3: int  1 1 1 1 1 1 1 1 1 1 ...
 $ V4: int  1 1 1 1 1 2 2 2 2 2 ...
 $ V5: int  1 2 3 4 5 1 2 3 4 5 ...
> str(X_train)
'data.frame':   500 obs. of  4 variables:
 $ V2: int  1 1 1 1 1 1 1 1 1 1 ...
 $ V3: int  1 1 1 1 1 1 1 1 1 1 ...
 $ V4: int  1 1 1 1 1 2 2 2 2 2 ...
 $ V5: int  1 2 3 4 5 1 2 3 4 5 ...
> str(X_test)
'data.frame':   122 obs. of  4 variables:
 $ V2: int  5 5 5 5 5 5 5 5 5 5 ...
 $ V3: int  1 1 1 1 1 1 1 1 1 1 ...
 $ V4: int  1 1 2 2 2 2 2 3 3 3 ...
 $ V5: int  4 5 1 2 3 4 5 1 2 3 ...
> str(Y_train)
 Factor w/ 3 levels "B","L","R": 1 3 3 3 3 3 3 3 3 3 ...

Body:
Your error comes from the rpart function.

From the rpart documentation:

Usage

rpart(formula, data, weights, subset, na.action = na.rpart, method,
  model = FALSE, x = FALSE, y = TRUE, parms, control, cost, ...)

Arguments

formula:
     a formula, with a response but no interaction terms. If this a a
  data frome, that is taken as the model frame (see model.frame).

So you need something like:

data_train <- head(balance_data,100)
...
tree_model <- rpart(V1 ~ V2 + V3 + V4, data_train)

Depending on what are your model.


问:
Using Azure Application Insights REST API (https://dev.applicationinsights.io) to read custom events/metrics
Our service writes a lot of custom events and metrics to App Insights.
Using the AI portal we can make complex queries and see nice charts, but I would like to access the data from outside the portal.
The Azure Application Insights REST API page (https://dev.applicationinsights.io) claims that those API can be used to perform such task, but I am unable to make them work - again I want to query custom events and metrics, not the standard ones.
Does anyone have any examples?
Here is for example one our queries: </p>

```<code>customEvents
| where name startswith "Monitor.Xxxxxxx"
| summarize count() by bin(timestamp, 1min)
| order by timestamp desc
</code>```

答: It turned out I was using the wrong AppId/Key; once I plugged the correct ones I am able to use the API Explorer.</p>

Body:
Our service writes a lot of custom events and metrics to App Insights.
Using the AI portal we can make complex queries and see nice charts, but I would like to access the data from outside the portal.
The Azure Application Insights REST API page (https://dev.applicationinsights.io) claims that those API can be used to perform such task, but I am unable to make them work - again I want to query custom events and metrics, not the standard ones.
Does anyone have any examples?
Here is for example one our queries:

customEvents
| where name startswith "Monitor.Xxxxxxx"
| summarize count() by bin(timestamp, 1min)
| order by timestamp desc


问:
div is not fading in when button is pressed
So basically I have some javascript that should fadein a page whenever a user clicks a button. But it isn't working for some reason. It is also supposed to fade out when you click anywhere on the div. Any ideas on what is wrong?

//Menu
function expand(){
  $(this).toggleClass("on");
  $(".menu").toggleClass("active");
};
$(".button").on('click', expand);

//Page transition
$(function() {

  $('#about').click(function() {
    var bodyContent = $('#aboutContent')
    bodyContent.fadeIn(400);

    bodyContent.click(function(e) {
      if($(e.target).hasClass('fa-times')) {
        $(this).fadeOut(400);
      } else if(!$(e.target).hasClass('fa')) {
        $(this).fadeOut(400);
      }
    })
  });

  $('#projects').click(function() {
    var bodyContent = $('#projectsContent')
    bodyContent.fadeIn(400);

    bodyContent.click(function(e) {
      if($(e.target).hasClass('fa-times')) {
        $(this).fadeOut(400);
      } else if(!$(e.target).hasClass('fa')) {
        $(this).fadeOut(400);
      }
    })
  });

  $('#contact').click(function() {
    var bodyContent = $('#contactContent')
    bodyContent.fadeIn(400);

    bodyContent.click(function(e) {
      if($(e.target).hasClass('fa-times')) {
        $(this).fadeOut(400);
      } else if(!$(e.target).hasClass('fa')) {
        $(this).fadeOut(400);
      }
    })
  });

});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body {
  background-color: black;
  font-family: "Source Sans Pro", sans-serif;
  color: #ccc;
  z-index: -100;
  background-color:black;
  overflow: hidden;
}

#aboutContent {
    width: 100%;
    height: 100%;
    background-color: #393939;
    z-index: 1000;
}

#projectsContent {
    width: 100%;
    height: 100%;
    background-color: #393939;
    z-index: 100;
}

#contactContent {
    width: 100%;
    height: 100%;
    background-color: #393939;
    z-index: 100;
}

.menu {
  position: absolute;
  top: 0;
  left: 0;
  bottom: 0;
  padding: 0;
  overflow: hidden;
  background: rgba(25, 25, 25, .5);
  width: 18%;
  box-sizing: border-box;
  transition: all 250ms;
  -webkit-transform: translateZ(0) translateX(-100%);
  transform: translateZ(0) translateX(-100%);
  text-align:center;
  box-shadow: 0 0 20px #000000;
}

.active {
  transform: translateZ(0) translateX(0);
  transform: translateZ(0) translateX(0);
  -webkit-transition: 0.4s;
  transition: 0.4s;
}

h1 {
  margin-top:60%;
  font-size: 2.5em;
  cursor: default;
}

ul {
  padding:0;
  list-style:none;
  font-size:14px;
}

li {
  padding:10px 10px;
}

a {
  text-decoration:none;
  padding:10px 15px;
  color:#fff;
  font-family:"Roboto";
  font-size: 1.5em;
  font-weight: 300;
}

a:hover {
  text-decoration: line-through;
  color: aqua;
}

.content {
  position:relative;
  width:300px;
}

.button {
  width:50px;
  height:50px;
  margin:24% 36%;
  padding: 10px;
  cursor:pointer;
}

.line {
 width: 40px;
 height: 2px;
    background-color:#fff;
 transition: transform 0.3s ease, background 0.3s ease, opacity 0.3s ease, top 0.3s ease;
}

.line.first {
  transform: translateX(-10px) translateY(22px) rotate(-90deg);
}

.line.second {
  transform: translateX(-10px) translateY(19px) rotate(0deg);
}

.button.on .line.top {
 width: 40px;
 transform: translateX(-10px) translateY(20px) rotate(45deg);
}

.button.on .line.bottom {
 width: 40px;
 transform: translateX(-10px) translateY(17px)rotate(-45deg);
}

@keyframes fadein {
    from {
        opacity:0;
    }
    to {
        opacity:1;
    }
}
@-webkit-keyframes fadein { /* Safari and Chrome */
    from {
        opacity:0;
    }
    to {
        opacity:1;
    }
}</code>```

<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <title>Home</title>

    <link href="https://fonts.googleapis.com/css?family=Source+Sans+Pro|Play|Raleway" rel="stylesheet">

    <link rel='stylesheet prefetch' href='http://maxcdn.bootstrapcdn.com/font-awesome/4.5.0/css/font-awesome.min.css'>

    <link rel="stylesheet" type="text/css" href="css/style.css">

AL-SABA

 home

 about

 projects

 contact

```

答:
First of all your content elements have width and height set to 100%, you need a parent element with fixed dimensions to grab percentage values from.

Another mistake which you made is adding click handlers when you open your menu. It leads to memory leaks as you will add new handlers over and over when your menu is opened.

To fade in, your element has to be invisible first.

I fixed the about button for you, the rest of them you can do in the same way.

//Menu
function expand() {
  $(this).toggleClass("on");
  $(".menu").toggleClass("active");
};
$(".button").on('click', expand);

//Page transition
$(function() {

  var bodyContent = $('#aboutContent')

  bodyContent.click(function(e) {
    if ($(e.target).hasClass('fa-times')) {
      $(this).fadeOut(400);
    } else if (!$(e.target).hasClass('fa')) {
      $(this).fadeOut(400);
    }
  });

  $('#about').click(function(ev) {
    bodyContent.fadeIn(400);
  });

});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body {
  background-color: black;
  font-family: "Source Sans Pro", sans-serif;
  color: #ccc;
  z-index: -100;
  background-color: black;
  overflow: hidden;
}

#aboutContent {
  width: 1000px;
  height: 1000px;
  background-color: #393939;
  z-index: 1000;
  display: none;
}

#projectsContent {
  width: 100%;
  height: 100%;
  background-color: #393939;
  z-index: 100;
}

#contactContent {
  width: 100%;
  height: 100%;
  background-color: #393939;
  z-index: 100;
}

.menu {
  position: absolute;
  top: 0;
  left: 0;
  bottom: 0;
  padding: 0;
  overflow: hidden;
  background: rgba(25, 25, 25, .5);
  width: 18%;
  box-sizing: border-box;
  transition: all 250ms;
  -webkit-transform: translateZ(0) translateX(-100%);
  transform: translateZ(0) translateX(-100%);
  text-align: center;
  box-shadow: 0 0 20px #000000;
}

.active {
  transform: translateZ(0) translateX(0);
  transform: translateZ(0) translateX(0);
  -webkit-transition: 0.4s;
  transition: 0.4s;
}

h1 {
  margin-top: 60%;
  font-size: 2.5em;
  cursor: default;
}

ul {
  padding: 0;
  list-style: none;
  font-size: 14px;
}

li {
  padding: 10px 10px;
}

a {
  text-decoration: none;
  padding: 10px 15px;
  color: #fff;
  font-family: "Roboto";
  font-size: 1.5em;
  font-weight: 300;
}

a:hover {
  text-decoration: line-through;
  color: aqua;
}

.content {
  position: relative;
  width: 300px;
}

.button {
  width: 50px;
  height: 50px;
  margin: 24% 36%;
  padding: 10px;
  cursor: pointer;
}

.line {
  width: 40px;
  height: 2px;
  background-color: #fff;
  transition: transform 0.3s ease, background 0.3s ease, opacity 0.3s ease, top 0.3s ease;
}

.line.first {
  transform: translateX(-10px) translateY(22px) rotate(-90deg);
}

.line.second {
  transform: translateX(-10px) translateY(19px) rotate(0deg);
}

.button.on .line.top {
  width: 40px;
  transform: translateX(-10px) translateY(20px) rotate(45deg);
}

.button.on .line.bottom {
  width: 40px;
  transform: translateX(-10px) translateY(17px)rotate(-45deg);
}

@keyframes fadein {
  from {
    opacity: 0;
  }
  to {
    opacity: 1;
  }
}

@-webkit-keyframes fadein {
  /* Safari and Chrome */
  from {
    opacity: 0;
  }
  to {
    opacity: 1;
  }
}</code>```

<!DOCTYPE html>

  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">

  <title>Home</title>

  <link href="https://fonts.googleapis.com/css?family=Source+Sans+Pro|Play|Raleway" rel="stylesheet">

  <link rel='stylesheet prefetch' href='http://maxcdn.bootstrapcdn.com/font-awesome/4.5.0/css/font-awesome.min.css'>

  <link rel="stylesheet" type="text/css" href="css/style.css">

AL-SABA

 home

 about

 projects

 contact

```

Body:
So basically I have some javascript that should fadein a page whenever a user clicks a button. But it isn't working for some reason. It is also supposed to fade out when you click anywhere on the div. Any ideas on what is wrong?

//Menu
function expand(){
  $(this).toggleClass("on");
  $(".menu").toggleClass("active");
};
$(".button").on('click', expand);

//Page transition
$(function() {

  $('#about').click(function() {
    var bodyContent = $('#aboutContent')
    bodyContent.fadeIn(400);

    bodyContent.click(function(e) {
      if($(e.target).hasClass('fa-times')) {
        $(this).fadeOut(400);
      } else if(!$(e.target).hasClass('fa')) {
        $(this).fadeOut(400);
      }
    })
  });

  $('#projects').click(function() {
    var bodyContent = $('#projectsContent')
    bodyContent.fadeIn(400);

    bodyContent.click(function(e) {
      if($(e.target).hasClass('fa-times')) {
        $(this).fadeOut(400);
      } else if(!$(e.target).hasClass('fa')) {
        $(this).fadeOut(400);
      }
    })
  });

  $('#contact').click(function() {
    var bodyContent = $('#contactContent')
    bodyContent.fadeIn(400);

    bodyContent.click(function(e) {
      if($(e.target).hasClass('fa-times')) {
        $(this).fadeOut(400);
      } else if(!$(e.target).hasClass('fa')) {
        $(this).fadeOut(400);
      }
    })
  });

});

body {
  background-color: black;
  font-family: "Source Sans Pro", sans-serif;
  color: #ccc;
  z-index: -100;
  background-color:black;
  overflow: hidden;
}

#aboutContent {
    width: 100%;
    height: 100%;
    background-color: #393939;
    z-index: 1000;
}

#projectsContent {
    width: 100%;
    height: 100%;
    background-color: #393939;
    z-index: 100;
}

#contactContent {
    width: 100%;
    height: 100%;
    background-color: #393939;
    z-index: 100;
}

.menu {
  position: absolute;
  top: 0;
  left: 0;
  bottom: 0;
  padding: 0;
  overflow: hidden;
  background: rgba(25, 25, 25, .5);
  width: 18%;
  box-sizing: border-box;
  transition: all 250ms;
  -webkit-transform: translateZ(0) translateX(-100%);
  transform: translateZ(0) translateX(-100%);
  text-align:center;
  box-shadow: 0 0 20px #000000;
}

.active {
  transform: translateZ(0) translateX(0);
  transform: translateZ(0) translateX(0);
  -webkit-transition: 0.4s;
  transition: 0.4s;
}

h1 {
  margin-top:60%;
  font-size: 2.5em;
  cursor: default;
}

ul {
  padding:0;
  list-style:none;
  font-size:14px;
}

li {
  padding:10px 10px;
}

a {
  text-decoration:none;
  padding:10px 15px;
  color:#fff;
  font-family:"Roboto";
  font-size: 1.5em;
  font-weight: 300;
}

a:hover {
  text-decoration: line-through;
  color: aqua;
}

.content {
  position:relative;
  width:300px;
}

.button {
  width:50px;
  height:50px;
  margin:24% 36%;
  padding: 10px;
  cursor:pointer;
}

.line {
 width: 40px;
 height: 2px;
    background-color:#fff;
 transition: transform 0.3s ease, background 0.3s ease, opacity 0.3s ease, top 0.3s ease;
}

.line.first {
  transform: translateX(-10px) translateY(22px) rotate(-90deg);
}

.line.second {
  transform: translateX(-10px) translateY(19px) rotate(0deg);
}

.button.on .line.top {
 width: 40px;
 transform: translateX(-10px) translateY(20px) rotate(45deg);
}

.button.on .line.bottom {
 width: 40px;
 transform: translateX(-10px) translateY(17px)rotate(-45deg);
}

@keyframes fadein {
    from {
        opacity:0;
    }
    to {
        opacity:1;
    }
}
@-webkit-keyframes fadein { /* Safari and Chrome */
    from {
        opacity:0;
    }
    to {
        opacity:1;
    }
}

<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <title>Home</title>

    <link href="https://fonts.googleapis.com/css?family=Source+Sans+Pro|Play|Raleway" rel="stylesheet">

    <link rel='stylesheet prefetch' href='http://maxcdn.bootstrapcdn.com/font-awesome/4.5.0/css/font-awesome.min.css'>

    <link rel="stylesheet" type="text/css" href="css/style.css">

AL-SABA

 home

 about

 projects

 contact

Body:
First of all your content elements have width and height set to 100%, you need a parent element with fixed dimensions to grab percentage values from.

Another mistake which you made is adding click handlers when you open your menu. It leads to memory leaks as you will add new handlers over and over when your menu is opened.

To fade in, your element has to be invisible first.

I fixed the about button for you, the rest of them you can do in the same way.

//Menu
function expand() {
  $(this).toggleClass("on");
  $(".menu").toggleClass("active");
};
$(".button").on('click', expand);

//Page transition
$(function() {

  var bodyContent = $('#aboutContent')

  bodyContent.click(function(e) {
    if ($(e.target).hasClass('fa-times')) {
      $(this).fadeOut(400);
    } else if (!$(e.target).hasClass('fa')) {
      $(this).fadeOut(400);
    }
  });

  $('#about').click(function(ev) {
    bodyContent.fadeIn(400);
  });

});

body {
  background-color: black;
  font-family: "Source Sans Pro", sans-serif;
  color: #ccc;
  z-index: -100;
  background-color: black;
  overflow: hidden;
}

#aboutContent {
  width: 1000px;
  height: 1000px;
  background-color: #393939;
  z-index: 1000;
  display: none;
}

#projectsContent {
  width: 100%;
  height: 100%;
  background-color: #393939;
  z-index: 100;
}

#contactContent {
  width: 100%;
  height: 100%;
  background-color: #393939;
  z-index: 100;
}

.menu {
  position: absolute;
  top: 0;
  left: 0;
  bottom: 0;
  padding: 0;
  overflow: hidden;
  background: rgba(25, 25, 25, .5);
  width: 18%;
  box-sizing: border-box;
  transition: all 250ms;
  -webkit-transform: translateZ(0) translateX(-100%);
  transform: translateZ(0) translateX(-100%);
  text-align: center;
  box-shadow: 0 0 20px #000000;
}

.active {
  transform: translateZ(0) translateX(0);
  transform: translateZ(0) translateX(0);
  -webkit-transition: 0.4s;
  transition: 0.4s;
}

h1 {
  margin-top: 60%;
  font-size: 2.5em;
  cursor: default;
}

ul {
  padding: 0;
  list-style: none;
  font-size: 14px;
}

li {
  padding: 10px 10px;
}

a {
  text-decoration: none;
  padding: 10px 15px;
  color: #fff;
  font-family: "Roboto";
  font-size: 1.5em;
  font-weight: 300;
}

a:hover {
  text-decoration: line-through;
  color: aqua;
}

.content {
  position: relative;
  width: 300px;
}

.button {
  width: 50px;
  height: 50px;
  margin: 24% 36%;
  padding: 10px;
  cursor: pointer;
}

.line {
  width: 40px;
  height: 2px;
  background-color: #fff;
  transition: transform 0.3s ease, background 0.3s ease, opacity 0.3s ease, top 0.3s ease;
}

.line.first {
  transform: translateX(-10px) translateY(22px) rotate(-90deg);
}

.line.second {
  transform: translateX(-10px) translateY(19px) rotate(0deg);
}

.button.on .line.top {
  width: 40px;
  transform: translateX(-10px) translateY(20px) rotate(45deg);
}

.button.on .line.bottom {
  width: 40px;
  transform: translateX(-10px) translateY(17px)rotate(-45deg);
}

@keyframes fadein {
  from {
    opacity: 0;
  }
  to {
    opacity: 1;
  }
}

@-webkit-keyframes fadein {
  /* Safari and Chrome */
  from {
    opacity: 0;
  }
  to {
    opacity: 1;
  }
}

<!DOCTYPE html>

<html>

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">

  <title>Home</title>

  <link href="https://fonts.googleapis.com/css?family=Source+Sans+Pro|Play|Raleway" rel="stylesheet">

  <link rel='stylesheet prefetch' href='http://maxcdn.bootstrapcdn.com/font-awesome/4.5.0/css/font-awesome.min.css'>

  <link rel="stylesheet" type="text/css" href="css/style.css">
</head>

<body>

  <div id="wrapper">
    <div class="menu">

      <h1>AL-SABA</h1>

      <ul>
        <div id="home">
          <li><a href="#home"><i class="fa fa-home"></i> home</a></li>
        </div>
        <div id="about">
          <li><a href="#about"><i class="fa fa-user"></i> about</a></li>
        </div>
        <div id="projects">
          <li><a href="#projects"><i class="fa fa-code"></i> projects</a></li>
        </div>
        <div id="contact">
          <li><a href="#contact"><i class="fa fa-paper-plane"></i> contact</a></li>
        </div>
      </ul>
    </div>

    <div class="content">
      <div class="button">
        <div class="line first top"></div>
        <div class="line second bottom"></div>
      </div>
    </div>

    <div id="aboutContent">

    </div>

    <div id="projectsContent">

    </div>

    <div id="contactContent">

    </div>

  </div>

  <script src='http://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js'></script>
  <script src='http://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.11.2/jquery-ui.min.js'></script>

  <script type="text/javascript" src="js/transition.js"></script>
  <script type="text/javascript" src="js/background.js"></script>
</body>

</html>


问:
BigQuery: cast integer column as date interval and add to date column
Using Google BigQuery Standard SQL, I have a date column, and another column that is numeric. I would like to cast the numeric column as an interval (say date or year) and then add this to another date column. So...

```<code>ColA,ColB

'2015-01-01',2
</code>```

would be used as: date_add(ColA interval colB years) -> '2017-01-01'

I'm trying to convert my date column, ColA to it's 2017 date equivalent. Is this the correct approach, or is there a more direct function/operation?

答:
Try below   </p>

<pre class="lang-sql prettyprint-override"><code>#standardSQL
WITH yourTable AS (
  SELECT '2015-01-01' AS colA, 2 AS colB
)
SELECT DATE_ADD(CAST(colA AS DATE), INTERVAL colB YEAR) AS new_dt
FROM yourTable
</code>```

<p>output is  </p>

<pre class="lang-sql prettyprint-override"><code>new_dt
----------
2017-01-01
</code>```

Body:
Using Google BigQuery Standard SQL, I have a date column, and another column that is numeric. I would like to cast the numeric column as an interval (say date or year) and then add this to another date column. So...

ColA,ColB

'2015-01-01',2

would be used as: date_add(ColA interval colB years) -> '2017-01-01'

I'm trying to convert my date column, ColA to it's 2017 date equivalent. Is this the correct approach, or is there a more direct function/operation?

Body:
Try below

#standardSQL
WITH yourTable AS (
  SELECT '2015-01-01' AS colA, 2 AS colB
)
SELECT DATE_ADD(CAST(colA AS DATE), INTERVAL colB YEAR) AS new_dt
FROM yourTable

output is

new_dt
----------
2017-01-01


问:
Django inspectdb error
WHile tryin to run django-admin.py inspectdb command from the home directory of mysite I am getting the below error.

error

```<code>Traceback (most recent call last):
  File "C:\_Data\MyFolder\Python\Scripts\django-admin.py", line 5, in <module> management.execute_from_command_line()
  File "C:\_Data\MyFolder\Python\lib\site-packages\django\core\management\__init__.py", line 453, in execute_from_command_line utility.execute()
  File "C:\_Data\MyFolder\Python\lib\site-packages\django\core\management\__init__.py", line 392, in execute self.fetch_command(subcommand).run_from_argv(self.argv)
  File "C:\_Data\MyFolder\Python\lib\site-packages\django\core\management\__init__.py", line 272, in fetch_command klass = load_command_class(app_name, subcommand)
  File "C:\_Data\MyFolder\Python\lib\site-packages\django\core\management\__init__.py", line 77, in load_command_class module = import_module('%s.management.commands.%s' % (app_name, name))
  File "C:\_Data\MyFolder\Python\lib\site-packages\django\utils\importlib.py", line 35, in import_module __import__(name)
  File "C:\_Data\MyFolder\Python\lib\site-packages\django\core\management\commands\inspectdb.py", line 8, in <module> from django.db import connections, DEFAULT_DB_ALIAS
  File "C:\_Data\MyFolder\Python\lib\site-packages\django\db\__init__.py", line 11, in <module> if settings.DATABASES and DEFAULT_DB_ALIAS not in settings.DATABASES:
  File "C:\_Data\MyFolder\Python\lib\site-packages\django\conf\__init__.py", line53, in __getattr__ self._setup(name)
  File "C:\_Data\MyFolder\Python\lib\site-packages\django\conf\__init__.py", line46, in _setup % (desc, ENVIRONMENT_VARIABLE))
django.core.exceptions.ImproperlyConfigured: Requested setting DATABASES, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings.
</code>```

My settings.py file has the oracle DB settings defined:

```<code>DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.oracle',
        'NAME': 'MyDB',
        'USER': 'MyUser',
        'PASSWORD': 'MyPSW',
        'HOST': 'Host',
        'PORT': '1521',
    }
}
</code>```

Why is the system not able to recognize the DB settings?

答:
Try using
python manage.py inspectdb
instead, worked for me</p>

Title: Django inspectdb error

Body:
WHile tryin to run django-admin.py inspectdb command from the home directory of mysite I am getting the below error.

error

Traceback (most recent call last):
  File "C:\_Data\MyFolder\Python\Scripts\django-admin.py", line 5, in <module> management.execute_from_command_line()
  File "C:\_Data\MyFolder\Python\lib\site-packages\django\core\management\__init__.py", line 453, in execute_from_command_line utility.execute()
  File "C:\_Data\MyFolder\Python\lib\site-packages\django\core\management\__init__.py", line 392, in execute self.fetch_command(subcommand).run_from_argv(self.argv)
  File "C:\_Data\MyFolder\Python\lib\site-packages\django\core\management\__init__.py", line 272, in fetch_command klass = load_command_class(app_name, subcommand)
  File "C:\_Data\MyFolder\Python\lib\site-packages\django\core\management\__init__.py", line 77, in load_command_class module = import_module('%s.management.commands.%s' % (app_name, name))
  File "C:\_Data\MyFolder\Python\lib\site-packages\django\utils\importlib.py", line 35, in import_module __import__(name)
  File "C:\_Data\MyFolder\Python\lib\site-packages\django\core\management\commands\inspectdb.py", line 8, in <module> from django.db import connections, DEFAULT_DB_ALIAS
  File "C:\_Data\MyFolder\Python\lib\site-packages\django\db\__init__.py", line 11, in <module> if settings.DATABASES and DEFAULT_DB_ALIAS not in settings.DATABASES:
  File "C:\_Data\MyFolder\Python\lib\site-packages\django\conf\__init__.py", line53, in __getattr__ self._setup(name)
  File "C:\_Data\MyFolder\Python\lib\site-packages\django\conf\__init__.py", line46, in _setup % (desc, ENVIRONMENT_VARIABLE))
django.core.exceptions.ImproperlyConfigured: Requested setting DATABASES, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings.

My settings.py file has the oracle DB settings defined:

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.oracle',
        'NAME': 'MyDB',
        'USER': 'MyUser',
        'PASSWORD': 'MyPSW',
        'HOST': 'Host',
        'PORT': '1521',
    }
}

Why is the system not able to recognize the DB settings?


问:
vb.net calculation in datagridview
I have a data grid view and in the column "2" (alarmtime) I have times added as shown in the image below.

And a label in the top (label9). if the label text shows as "friday" then the "Alarm Time" cell values should add 10 minutes.
Example if the label show friday then the time should change from 16:10:00 to 16:20:00.

My code:

```<code>Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick

Dim myform As New Form2

DataGridView1.Columns(2).DefaultCellStyle.Format = "h:mm:ss"

For i As Integer = 0 To DataGridView1.Rows.Count - 1

    If Me.DataGridView1.Rows(i).Cells("AlarmTime").Value = Me.MetroLabel2.Text And Me.DataGridView1.Rows(i).Cells("Frequency").Value = "Weekday" Then

        myform.Show()
        myform.msgdisply.Text = Me.DataGridView1.Rows(i).Cells("UpdateName").Value

        If Me.MetroLabel9.Text = "FRIDAY" Then

            Dim iCell1 As String
            Dim dt As DateTime

            iCell1 = Me.DataGridView1.Rows(i).Cells("AlarmTime").Value
            dt = Format(DateTime.Parse(iCell1), "h:mm:ss")

            dt.AddMinutes(10)

            Me.DataGridView1.Rows(i).Cells("AlarmTime").Value = dt.ToString
        End If
next
</code>```

答:
Try this:

```<code>Dim dt as datetime
dt = datetime.parse(iCell1)
dt.addminutes(10)
Me.DataGridView1.Rows(i).Cells("AlarmTime").Value = dt.ToString("HH:mm")
</code>```

You can have a look at the addminutes method information Here

Title: vb.net calculation in datagridview

Body:
I have a data grid view and in the column "2" (alarmtime) I have times added as shown in the image below.

And a label in the top (label9). if the label text shows as "friday" then the "Alarm Time" cell values should add 10 minutes.
Example if the label show friday then the time should change from 16:10:00 to 16:20:00.

My code:

Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick

Dim myform As New Form2

DataGridView1.Columns(2).DefaultCellStyle.Format = "h:mm:ss"

For i As Integer = 0 To DataGridView1.Rows.Count - 1

    If Me.DataGridView1.Rows(i).Cells("AlarmTime").Value = Me.MetroLabel2.Text And Me.DataGridView1.Rows(i).Cells("Frequency").Value = "Weekday" Then

        myform.Show()
        myform.msgdisply.Text = Me.DataGridView1.Rows(i).Cells("UpdateName").Value

        If Me.MetroLabel9.Text = "FRIDAY" Then

            Dim iCell1 As String
            Dim dt As DateTime

            iCell1 = Me.DataGridView1.Rows(i).Cells("AlarmTime").Value
            dt = Format(DateTime.Parse(iCell1), "h:mm:ss")

            dt.AddMinutes(10)

            Me.DataGridView1.Rows(i).Cells("AlarmTime").Value = dt.ToString
        End If
next

Body:
Try this:

Dim dt as datetime
dt = datetime.parse(iCell1)
dt.addminutes(10)
Me.DataGridView1.Rows(i).Cells("AlarmTime").Value = dt.ToString("HH:mm")

You can have a look at the addminutes method information Here


问:
R Wide to long format for multiple variables with patterns
I have a data set with a single identifier and five columns that repeat 18 times. I want to restructure the data into long format keeping the first five column headings as the column headings. Below is a sample with just two repeats:

```<code>structure(list(Response.ID = 1:2, Task = structure(c(1L, 1L), .Label = "task1", class = "factor"),
Freq = structure(c(1L, 1L), .Label = "Daily", class = "factor"),
Hours = c(3L, 2L), Value = c(10L, 8L), Mood = structure(1:2, .Label = c("Engaged",
"Neutral"), class = "factor"), Task.1 = structure(c(1L, 1L
), .Label = "task2", class = "factor"), Freq.1 = structure(c(1L,
1L), .Label = "Weekly", class = "factor"), Hours.1 = c(4L,
4L), Value.1 = c(10L, 6L), Mood.1 = structure(c(2L, 1L), .Label = c("Neutral",
"Optimistic"), class = "factor")), .Names = c("Response.ID", "Task", "Freq", "Hours", "Value", "Mood", "Task.1", "Freq.1", "Hours.1", "Value.1", "Mood.1"), class = "data.frame", row.names = c(NA, -2L))
</code>```

I attempted using the melt and patterns functions, which appears to approximate my desired outcome without the desired column headings:

```<code>df = melt(df1, id.vars = c("Response.ID"), measure.vars = patterns("^Task", "^Freq","^Hours","^Mood"))
</code>```

Here is the result:

```<code>structure(list(Response.ID = c(1L, 2L, 1L, 2L), variable = structure(c(1L, 1L, 2L, 2L), class = "factor", .Label = c("1", "2")), value1 = c("task1", "task1", "task2", "task2"), value2 = c("Daily", "Daily", "Weekly", "Weekly"), value3 = c(3L, 2L, 4L, 4L), value4 = c("Engaged", "Neutral", "Optimistic", "Neutral")), .Names = c("Response.ID", "variable", "value1", "value2", "value3", "value4"), row.names = c(NA, -4L), class = c("data.table", "data.frame"), .internal.selfref = <pointer: 0x0000000000330788>)
</code>```

When I tried to specify names with value.name() below I receive an error:

```<code>df = melt(df1, id.vars = c("Response.ID"),measure.vars = patterns("^Task", "^Freq","^Hours","^Mood"), value.name=c("Task", "Freq", "Hours", "Value","Mood"))
</code>```

My desired result would look like this:

```<code>structure(list(Response.ID = c(1L, 2L, 1L, 2L), Task = structure(c(1L, 1L, 2L, 2L), .Label = c("task1", "task2"), class = "factor"),
Freq = structure(c(1L, 1L, 2L, 2L), .Label = c("Daily", "Weekly"
), class = "factor"), Hours = c(3L, 2L, 4L, 4L), Value = c(10L,
8L, 10L, 6L), Mood = structure(c(1L, 2L, 3L, 2L), .Label = c("Engaged",
"Neutral", "Optimistic"), class = "factor")), .Names = c("Response.ID", "Task", "Freq", "Hours", "Value", "Mood"), class = "data.frame", row.names = c(NA, -4L))
</code>```

答:
It looks to me like you embarked on a difficult journey by using melt: this function is well named in the sense that trying to use it will probably melt your brain. Joke aside, the function melt has lots of underlying computations and its use could be inefficient if you have a large dataset.

I would instead solve the problem manually with rbindlist (from the excellent package data.table, which also ships with an optimized version of melt if you really want to use it), to manually concatenates groups of columns. This also preserves the column names:

```<code>> rbindlist(lapply(1:2, function(i) df1[,c(1,((i-1)*5+2):((i-1)*5+6))]))
   Response.ID  Task   Freq Hours Value       Mood
1:           1 task1  Daily     3    10    Engaged
2:           2 task1  Daily     2     8    Neutral
3:           1 task2 Weekly     4    10 Optimistic
4:           2 task2 Weekly     4     6    Neutral
</code>```

This works on your example: replace the indices 1:2 by the number of repetitions to make it work with the real dataset (so, lapply(1:18)).

Body:
I have a data set with a single identifier and five columns that repeat 18 times. I want to restructure the data into long format keeping the first five column headings as the column headings. Below is a sample with just two repeats:

structure(list(Response.ID = 1:2, Task = structure(c(1L, 1L), .Label = "task1", class = "factor"),
Freq = structure(c(1L, 1L), .Label = "Daily", class = "factor"),
Hours = c(3L, 2L), Value = c(10L, 8L), Mood = structure(1:2, .Label = c("Engaged",
"Neutral"), class = "factor"), Task.1 = structure(c(1L, 1L
), .Label = "task2", class = "factor"), Freq.1 = structure(c(1L,
1L), .Label = "Weekly", class = "factor"), Hours.1 = c(4L,
4L), Value.1 = c(10L, 6L), Mood.1 = structure(c(2L, 1L), .Label = c("Neutral",
"Optimistic"), class = "factor")), .Names = c("Response.ID", "Task", "Freq", "Hours", "Value", "Mood", "Task.1", "Freq.1", "Hours.1", "Value.1", "Mood.1"), class = "data.frame", row.names = c(NA, -2L))

I attempted using the melt and patterns functions, which appears to approximate my desired outcome without the desired column headings:

df = melt(df1, id.vars = c("Response.ID"), measure.vars = patterns("^Task", "^Freq","^Hours","^Mood"))

Here is the result:

structure(list(Response.ID = c(1L, 2L, 1L, 2L), variable = structure(c(1L, 1L, 2L, 2L), class = "factor", .Label = c("1", "2")), value1 = c("task1", "task1", "task2", "task2"), value2 = c("Daily", "Daily", "Weekly", "Weekly"), value3 = c(3L, 2L, 4L, 4L), value4 = c("Engaged", "Neutral", "Optimistic", "Neutral")), .Names = c("Response.ID", "variable", "value1", "value2", "value3", "value4"), row.names = c(NA, -4L), class = c("data.table", "data.frame"), .internal.selfref = <pointer: 0x0000000000330788>)

When I tried to specify names with value.name() below I receive an error:

df = melt(df1, id.vars = c("Response.ID"),measure.vars = patterns("^Task", "^Freq","^Hours","^Mood"), value.name=c("Task", "Freq", "Hours", "Value","Mood"))

My desired result would look like this:

structure(list(Response.ID = c(1L, 2L, 1L, 2L), Task = structure(c(1L, 1L, 2L, 2L), .Label = c("task1", "task2"), class = "factor"),
Freq = structure(c(1L, 1L, 2L, 2L), .Label = c("Daily", "Weekly"
), class = "factor"), Hours = c(3L, 2L, 4L, 4L), Value = c(10L,
8L, 10L, 6L), Mood = structure(c(1L, 2L, 3L, 2L), .Label = c("Engaged",
"Neutral", "Optimistic"), class = "factor")), .Names = c("Response.ID", "Task", "Freq", "Hours", "Value", "Mood"), class = "data.frame", row.names = c(NA, -4L))

Body:
It looks to me like you embarked on a difficult journey by using melt: this function is well named in the sense that trying to use it will probably melt your brain. Joke aside, the function melt has lots of underlying computations and its use could be inefficient if you have a large dataset.

I would instead solve the problem manually with rbindlist (from the excellent package data.table, which also ships with an optimized version of melt if you really want to use it), to manually concatenates groups of columns. This also preserves the column names:

> rbindlist(lapply(1:2, function(i) df1[,c(1,((i-1)*5+2):((i-1)*5+6))]))
   Response.ID  Task   Freq Hours Value       Mood
1:           1 task1  Daily     3    10    Engaged
2:           2 task1  Daily     2     8    Neutral
3:           1 task2 Weekly     4    10 Optimistic
4:           2 task2 Weekly     4     6    Neutral

This works on your example: replace the indices 1:2 by the number of repetitions to make it work with the real dataset (so, lapply(1:18)).


问:
How expensive is it to dereference a pointer?
How expensive is it to perform the dereference operation on a pointer?

I can imagine that the memory transfer is somehow proportional to the object size, but I want to know how expensive the dereference operation part is.

答:
It depends on what you do with the dereferenced pointer. A mere dereference operation does nothing in itself. It just gets an lvalue of type T which represents your object, if your pointer is a T*

```<code>struct a {
    int big[42];
};

void f(a * t) {
    // does nothing. Only interesting for standard or compiler writers.
    // it just binds the lvalue to a reference t1.
    a & t1 = *t;
}
</code>```

If you actually get the value out of that object denoted by the lvalue returned by the dereference operation, the compiler has to copy the data the object contains. For a simple POD, that is just a mere memcpy:

```<code>a aGlobalA;
void f(a * t) {
    // gets the value of of the object denoted by *t, copying it into aGlobalA
    aGlobalA = *t;
}
</code>```

My gcc port outputs this code for f:

```<code>    sub     $29, $29, 24       ; subtract stack-pointer, creating this frame
    stw     $31, $29, 20       ; save return address
    add     $5, $0, $4         ; copy pointer t into $5 (src)
    add     $4, $0, aGlobalA   ; load address of aGlobalA into $4 (dst)
    add     $6, $0, 168        ; put size (168 bytes) as 3rd argument
    jal     memcpy             ; call memcpy
    ldw     $31, $29, 20       ; restore return address
    add     $29, $29, 24       ; add stack-pointer, destroying this frame
    jr      $31
</code>```

Optimized machine code would use in-line code instead of a call to memcpy, but that's really just an implementation detail. What is important is, that merely *t isn't executing any code, but accessing the value of that object actually needs to copy it.

Would we have to do with a type having a user defined copy assignment operator, affairs are more complex:

```<code>struct a {
    int big[42];
    void operator=(a const&) { }
};
</code>```

The code for the same function f now looks like:

```<code>    sub     $29, $29, 8
    add     $29, $29, 8
    jr      $31
</code>```

Hah. But it wasn't such a surprise, wasn't it? After all, the compiler is supposed to call our operator=, and if it does nothing, the whole function also does nothing!

Conclusion

I think the conclusion we can draw is, it all depends on how the returned value of operator* is used. If we have just a pointer that we dereference, we see above that the code generated largely depends on the circumstances. I haven't showed how it behaves if we dereference a class type having overloaded operator* . But essentially, it's just behaving like we saw with operator=. All measurements were done with -O2, so the compiler properly inlined calls :)

OwnerDisplayName: Tunnuz

LastEditorDisplayName: ChrisN

Body:
It depends on what you do with the dereferenced pointer. A mere dereference operation does nothing in itself. It just gets an lvalue of type T which represents your object, if your pointer is a T*

struct a {
    int big[42];
};

void f(a * t) {
    // does nothing. Only interesting for standard or compiler writers.
    // it just binds the lvalue to a reference t1.
    a & t1 = *t;
}

If you actually get the value out of that object denoted by the lvalue returned by the dereference operation, the compiler has to copy the data the object contains. For a simple POD, that is just a mere memcpy:

a aGlobalA;
void f(a * t) {
    // gets the value of of the object denoted by *t, copying it into aGlobalA
    aGlobalA = *t;
}

My gcc port outputs this code for f:

    sub     $29, $29, 24       ; subtract stack-pointer, creating this frame
    stw     $31, $29, 20       ; save return address
    add     $5, $0, $4         ; copy pointer t into $5 (src)
    add     $4, $0, aGlobalA   ; load address of aGlobalA into $4 (dst)
    add     $6, $0, 168        ; put size (168 bytes) as 3rd argument
    jal     memcpy             ; call memcpy
    ldw     $31, $29, 20       ; restore return address
    add     $29, $29, 24       ; add stack-pointer, destroying this frame
    jr      $31

Optimized machine code would use in-line code instead of a call to memcpy, but that's really just an implementation detail. What is important is, that merely *t isn't executing any code, but accessing the value of that object actually needs to copy it.

Would we have to do with a type having a user defined copy assignment operator, affairs are more complex:

struct a {
    int big[42];
    void operator=(a const&) { }
};

The code for the same function f now looks like:

    sub     $29, $29, 8
    add     $29, $29, 8
    jr      $31

Hah. But it wasn't such a surprise, wasn't it? After all, the compiler is supposed to call our operator=, and if it does nothing, the whole function also does nothing!

Conclusion

I think the conclusion we can draw is, it all depends on how the returned value of operator* is used. If we have just a pointer that we dereference, we see above that the code generated largely depends on the circumstances. I haven't showed how it behaves if we dereference a class type having overloaded operator* . But essentially, it's just behaving like we saw with operator=. All measurements were done with -O2, so the compiler properly inlined calls :)

OwnerDisplayName: litb

LastEditorDisplayName: litb


问:
Attempting to include font-awesome without CDN
Before I being I just want to say I did research this question, and I saw this post and followed the top answer's instruction but still nothing.

Okay here is a picture of my directory:

The fonts folder is just the regular fonts folder that comes with the font-awesome download. I then put the css file that came with font-awesome under css/font-awesome as shown below:

Here is a picture of my HTML code:

Here's my HTML Code:

```<code><head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <title>Tinyone</title>

    <!-- CSS -->
    <link href="css/bootstrap/bootstrap.min.css" rel="stylesheet">
    <link href="css/main.css" rel="stylesheet" >
    <link href="css/font-awesome/font-awesome.min.css">

    <!-- jQuery/JS/Fonts -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.js"></script>
    <script type="text/javascript" src="js/main.js"></script>

    <!-- Fonts -->
    <link href="https://fonts.googleapis.com/css?family=PT+Sans:400,700" rel="stylesheet">
</head>
</code>```

I must be missing something, if anybody has any ideas could you please share them?

Thank you so much for reading, it's greatly appreciated.

答:
The paths were all correct, but I forgot to include the rel="stylesheet" attribute to font-awesome <link>.

Thank you to RompePC for pointing this out to me.

Body:
Before I being I just want to say I did research this question, and I saw this post and followed the top answer's instruction but still nothing.

Okay here is a picture of my directory:

The fonts folder is just the regular fonts folder that comes with the font-awesome download. I then put the css file that came with font-awesome under css/font-awesome as shown below:

Here is a picture of my HTML code:

Here's my HTML Code:

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <title>Tinyone</title>

    <link href="css/bootstrap/bootstrap.min.css" rel="stylesheet">
    <link href="css/main.css" rel="stylesheet" >
    <link href="css/font-awesome/font-awesome.min.css">

    <link href="https://fonts.googleapis.com/css?family=PT+Sans:400,700" rel="stylesheet">

I must be missing something, if anybody has any ideas could you please share them?

Thank you so much for reading, it's greatly appreciated.


问:
Php session is not distroyed
I made a wrapper to manage my user sessions in Php, and I want to add a function that destroys the sessions, here is how I did:

```<code><?php
class SessionManager
{
          .
          .
          .
static function destroy()
{
    session_destroy();
}
}
?>
</code>```

When logging out the user I need to destroy its session, so I call the destroy() function like this in the logout.php:

```<code><?php
include('SessionManager.php');
$mySess = new SessionManager();
$session = $mySess -> sessionStart('InstallationName'); // create/start a new session or start the existent session
$mySess -> destroy();
echo $_SESSION['cook'];
?>
</code>```

But the problem is that when executing this code, it still displays the token value of $_SESSION['cook'] (something like t2utt3uejvamu1kq623vl29pd2), which means that the session is not distroyed.

p.s: I made a post before with the same piece of code, but I have a new problem now with the same code.

答:
session_destroy doesn't unset the $_SESSION variable it destroys the session the $_SESSION variable was already set on the same page. the next page you'll load, it will not be set, since the session is destroyed.

If for some reason you want to unset the variable on the same page then do something like unset($_SESSION['cook']);

Title: Php session is not distroyed

Body:
I made a wrapper to manage my user sessions in Php, and I want to add a function that destroys the sessions, here is how I did:

<?php
class SessionManager
{
          .
          .
          .
static function destroy()
{
    session_destroy();
}
}
?>

When logging out the user I need to destroy its session, so I call the destroy() function like this in the logout.php:

<?php
include('SessionManager.php');
$mySess = new SessionManager();
$session = $mySess -> sessionStart('InstallationName'); // create/start a new session or start the existent session
$mySess -> destroy();
echo $_SESSION['cook'];
?>

But the problem is that when executing this code, it still displays the token value of $_SESSION['cook'] (something like t2utt3uejvamu1kq623vl29pd2), which means that the session is not distroyed.

p.s: I made a post before with the same piece of code, but I have a new problem now with the same code.


问:
Dockerizing Delayed Job
We are currently working on Dockerizing our Ruby on Rails application, which also includes Delayed Job. A question buzzing within our development team is whether and/or how to Dockerize the Delayed Job component separately from the application.

This would allow Delayed Job to start up new containers when necessary for high traffic within the jobs queue. In addition, since Delayed Job actually starts up the Rails application each time when first booting up, we thought the following benefits would follow:

The Delayed Job container might start up quicker

Application code would start up regardless of the Delayed Job container startup time

答:
So I know a guy responsible for a rails app that uses delayed jobs.  When it came time to dockerize said app, it got a container for each.  Both containers are using the same codebase but one runs the frontend and one the jobs.  It's not devops microservice-eriffic but it works. </p>

<p>Outside of the logical separation between the two, docker containers are supposed to only have a single process running inside.  Could've hacked it together but it seemed wrong to break a docker fundamental out of the gate. </p>

Title: Dockerizing Delayed Job

Body:
So I know a guy responsible for a rails app that uses delayed jobs.  When it came time to dockerize said app, it got a container for each.  Both containers are using the same codebase but one runs the frontend and one the jobs.  It's not devops microservice-eriffic but it works.

Outside of the logical separation between the two, docker containers are supposed to only have a single process running inside.  Could've hacked it together but it seemed wrong to break a docker fundamental out of the gate.


问:
How do I do a mass delete of custom records in NetSuite suitescript 2.0?
My question is really plain.  I would like to know if someone has figured out how to mass delete custom records using suitescript2.0.

```<code>/** * @NApiVersion 2.x
 * @NScriptType ScheduledScript
 */

define ([
 'N/error',
 'N/record',
 'N/runtime',
 'N/log',
 ],
function(error, record,runtime, log) {
    function execute(context) {

    for(var i=4;i< 11614;i++){
    var objRecord = record.delete({ type: 'customrecord_uber_billing_report_data', id: i});

    }

    }
    return {
        execute: execute
    };

});
</code>```

Eclipse does't seem to like the syntax

答:
You can do that with "promise". Netsuite so far doesn't have a Suitescript function to delete a bunch of records quickly. With this function you can delete one by one, and keep your code working in another thing. Hope this helps.</p>

```<code>require(['N/record', 'N/search'], function (record, search) {
    function deleteUnwantedRecords() {
        var objRecord = search.create.promise({
                type: 'customrecord_your_record',
                columns: [
                    'internalid', // The record's ID
                ],
                filters: []// no filters
            }).then(function (result) {
                var HowManyFound = 0;
                result.run().each(function (rl) {
                    HowManyFound++;
                    var recToDelete = rl.getValue('internalId');
                    var objNewRecord = record.delete ({
                            type: 'customrecord_your_record',
                            id: recToDelete,
                        });
                    console.log('Error ID: ' + rl.getValue('internalId'));
                    return true;
                });
                console.log('#Error Logs found: ' + HowManyFound);
            }).catch (function (reason) {
                log.debug("Failed: " + reason);
            })
    }
    var delRecs = deleteUnwantedRecords();
});
</code>```

Body:
My question is really plain.  I would like to know if someone has figured out how to mass delete custom records using suitescript2.0.

/** * @NApiVersion 2.x
 * @NScriptType ScheduledScript
 */

define ([
 'N/error',
 'N/record',
 'N/runtime',
 'N/log',
 ],
function(error, record,runtime, log) {
    function execute(context) {

    for(var i=4;i< 11614;i++){
    var objRecord = record.delete({ type: 'customrecord_uber_billing_report_data', id: i});

    }

    }
    return {
        execute: execute
    };

});

Eclipse does't seem to like the syntax

Body:
You can do that with "promise". Netsuite so far doesn't have a Suitescript function to delete a bunch of records quickly. With this function you can delete one by one, and keep your code working in another thing. Hope this helps.

require(['N/record', 'N/search'], function (record, search) {
    function deleteUnwantedRecords() {
        var objRecord = search.create.promise({
                type: 'customrecord_your_record',
                columns: [
                    'internalid', // The record's ID
                ],
                filters: []// no filters
            }).then(function (result) {
                var HowManyFound = 0;
                result.run().each(function (rl) {
                    HowManyFound++;
                    var recToDelete = rl.getValue('internalId');
                    var objNewRecord = record.delete ({
                            type: 'customrecord_your_record',
                            id: recToDelete,
                        });
                    console.log('Error ID: ' + rl.getValue('internalId'));
                    return true;
                });
                console.log('#Error Logs found: ' + HowManyFound);
            }).catch (function (reason) {
                log.debug("Failed: " + reason);
            })
    }
    var delRecs = deleteUnwantedRecords();
});