问:
Hmisc separate column headings with rowname = NULL
I'm trying to have column headings and the horizontal line underneath the headings separated by the groups. When I do the following it works,

```<code>library(Hmisc)
data(mtcars)
latex(mtcars, file ='', cgroup = c("Group 1", "Group 2"), n.cgroup = c(5, 6))
</code>```

but when I try to remove the rownames, the line under Group 1 & 2 merge into the same line

```<code>library(Hmisc)
data(mtcars)
latex(mtcars, file ='', cgroup = c("Group 1", "Group 2"), n.cgroup = c(5, 6), rowname = NULL)
</code>```

Does anyone know of a way to fix this?

答:
One way using my own huxtable package:

```<code>library(huxtable)
mt_hux <- as_huxtable(mtcars, add_rownames = TRUE, add_colnames = TRUE)
mt_hux <- insert_column(mt_hux, rep("", nrow(mt_hux)), after = 6)
mt_hux <- insert_row(mt_hux, c("", "Group 1", "", "", "", "", "", "Group 2", "", "", "", "", ""))
mt_hux[2, 1] <- "" # get rid of ugly 'row names'

colspan(mt_hux)[1, c(2, 8)] <- c(5, 6)
align(mt_hux)[1, c(2, 8)] <- "center"
top_border(mt_hux)[1,] <- 1
bottom_border(mt_hux)[1, c(2, 8)] <- 1
bottom_border(mt_hux)[2,] <- 1

# this should be what you want:
mt_hux
</code>```

This has a limitation: you can't get the nice double line. But you can vary the line width, if that is an adequate substitute. You could also try the pixiedust package.

Body:
I'm trying to have column headings and the horizontal line underneath the headings separated by the groups. When I do the following it works,

library(Hmisc)
data(mtcars)
latex(mtcars, file ='', cgroup = c("Group 1", "Group 2"), n.cgroup = c(5, 6))

but when I try to remove the rownames, the line under Group 1 & 2 merge into the same line

library(Hmisc)
data(mtcars)
latex(mtcars, file ='', cgroup = c("Group 1", "Group 2"), n.cgroup = c(5, 6), rowname = NULL)

Does anyone know of a way to fix this?

Body:
One way using my own huxtable package:

library(huxtable)
mt_hux <- as_huxtable(mtcars, add_rownames = TRUE, add_colnames = TRUE)
mt_hux <- insert_column(mt_hux, rep("", nrow(mt_hux)), after = 6)
mt_hux <- insert_row(mt_hux, c("", "Group 1", "", "", "", "", "", "Group 2", "", "", "", "", ""))
mt_hux[2, 1] <- "" # get rid of ugly 'row names'

colspan(mt_hux)[1, c(2, 8)] <- c(5, 6)
align(mt_hux)[1, c(2, 8)] <- "center"
top_border(mt_hux)[1,] <- 1
bottom_border(mt_hux)[1, c(2, 8)] <- 1
bottom_border(mt_hux)[2,] <- 1

# this should be what you want:
mt_hux

This has a limitation: you can't get the nice double line. But you can vary the line width, if that is an adequate substitute. You could also try the pixiedust package.


来源: stackexchange

问:
Regexp to extract studyinstanceuid from dump
I need to capture numbers and dots between brackets on lines containing the string 0020,000d, for example:

```<code>I: (0020,000d) UI [1.2.410.200001.1104.20160720104648421 ] #  38, 1 StudyInstanceUID
</code>```

Using this regexp 0020,000d.*\[([\.0-9]+)\] I can match the needed value only if it doesn't have a space inside the brackets. How can I match the needed value ignoring any other character?.

Edit
If I use this regexp 0020,000d.*\[([\.0-9(\s|^\s))]+)\] I can capture numbers and dots and/or spaces, now if the string contains a space how can I capture in a group everything but the space?.

To clarify, I want to extract the 1.2.410.200001.1104.20160720104648421 string.

ContentLicense: CC BY-SA 3.0

Body:
I need to capture numbers and dots between brackets on lines containing the string 0020,000d, for example:

I: (0020,000d) UI [1.2.410.200001.1104.20160720104648421 ] #  38, 1 StudyInstanceUID

Using this regexp 0020,000d.*\[([\.0-9]+)\] I can match the needed value only if it doesn't have a space inside the brackets. How can I match the needed value ignoring any other character?.

Edit
If I use this regexp 0020,000d.*\[([\.0-9(\s|^\s))]+)\] I can capture numbers and dots and/or spaces, now if the string contains a space how can I capture in a group everything but the space?.

To clarify, I want to extract the 1.2.410.200001.1104.20160720104648421 string.

Body:
Try this

let regex = /(?!\[)[.\d]+(?=[(\s)*\]])/g

let str = 'I: (0020,000d) UI [1.2.410.200001.1104.20160720104648421   ]'

let result = str.match(regex);

console.log(result);


问:
Explaining margins and dealing with tiles
I have few problems that I cannot fix, I will be grateful if somebody will explain me how it works. Firstly, i have a container with id "kafle", I positioned it as I wanted, and now i want to place a few tiles into it. I want do something like this:  I want to tile 1 be 50% width of container with id "kafle", and tile to be another 50% width. I set margin and padding of tile 1 and 2 to 0, but despite this, there is something what makes that tile 2 is going under tile 1, and i don't know why. The other problem is that i don't know how i can place tile 3, 4, 5 and 6 under tile 1, but in one line with tile 2. When im setting display: inline-block to all of the tiles, tile 3, 4, 5 and 6 are going under height of tile 2. How can I deal with it? I will be grateful for explaining it.

html, body{
    height: 100%;
    min-height: 100%;
    margin:0;
}

#kafle{
    position:relative;
    height: 80%;
    width: 60%;
    top:10%;
    left:20%;
    background-color: aquamarine;
}

#onas{
    background-color: coral;
    height:33%;
    width:49%;
    display: inline-block;
    margin:0;
    padding:0;
}

#aktualnosci{
    background-color: firebrick;
    height:90%;
    width:49%;
    display: inline-block;
    margin:0;
    padding:0;
}

#galeria{
    background-color: forestgreen;
    height:10%;
    width:15%;
    display: inline-block;
}

#wspierajanas{
    background-color: khaki;
    height:10%;
    width:15%;
    display: inline-block;
}

#kontakt{
    background-color: fuchsia;
    height:10%;
    width:15%;
    display: inline-block;
}

#minigra{
    background-color: fuchsia;
    height:10%;
    width:15%;
    display: inline-block;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title></title>
  <link rel="stylesheet" href="style.css">
</head>

<body>
  <script src="javascript.js"></script>

    <div id="kafle">
        <div id="onas">1</div>
        <div id="aktualnosci">2</div>
       <div id="galeria">3</div>
        <div id="wspierajanas">4</div>
        <div id="kontakt">5</div>
        <div id="minigra">6</div>
    </div>

</body>

</html></code>```

答:
It looks like the position of the objects with respect to one another is troubling you.

Set #id{display:inline:block;}
Now the div behaves like block.

Use #id{position:relative widthtomove px lengthtomove px;}
Now set the two relative parameters accordingly for each of your box(or division) and keep varying till they align themselves perfectly.

You may consider referring to detailed use of position:relative but the above should do the work!

Body:
I have few problems that I cannot fix, I will be grateful if somebody will explain me how it works. Firstly, i have a container with id "kafle", I positioned it as I wanted, and now i want to place a few tiles into it. I want do something like this:  I want to tile 1 be 50% width of container with id "kafle", and tile to be another 50% width. I set margin and padding of tile 1 and 2 to 0, but despite this, there is something what makes that tile 2 is going under tile 1, and i don't know why. The other problem is that i don't know how i can place tile 3, 4, 5 and 6 under tile 1, but in one line with tile 2. When im setting display: inline-block to all of the tiles, tile 3, 4, 5 and 6 are going under height of tile 2. How can I deal with it? I will be grateful for explaining it.

html, body{
    height: 100%;
    min-height: 100%;
    margin:0;
}

#kafle{
    position:relative;
    height: 80%;
    width: 60%;
    top:10%;
    left:20%;
    background-color: aquamarine;
}

#onas{
    background-color: coral;
    height:33%;
    width:49%;
    display: inline-block;
    margin:0;
    padding:0;
}

#aktualnosci{
    background-color: firebrick;
    height:90%;
    width:49%;
    display: inline-block;
    margin:0;
    padding:0;
}

#galeria{
    background-color: forestgreen;
    height:10%;
    width:15%;
    display: inline-block;
}

#wspierajanas{
    background-color: khaki;
    height:10%;
    width:15%;
    display: inline-block;
}

#kontakt{
    background-color: fuchsia;
    height:10%;
    width:15%;
    display: inline-block;
}

#minigra{
    background-color: fuchsia;
    height:10%;
    width:15%;
    display: inline-block;
}

<!DOCTYPE html>

  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title></title>
  <link rel="stylesheet" href="style.css">

1

2

3

4

5

6


问:
Recordset Not Iterating
I am sure this is strictly user error, but for the life of me, I can not discover how to iterate a table, and write the records to Excel.  I have the below code, but it hangs on the first Manager ID and just repeats the write for that one constantly in a loop.  I want to iterate all the Manager ID in the table and write them to the same workbook.

How should I tweak this code in order to do such?

```<code>  Set xlR = xlWb.Worksheets(1).Range("$R$2")
  i=0
  Set rs2 = Db.OpenRecordset("SELECT * FROM TestTable ORDER BY [Manager ID] ASC", dbOpenDynaset)
  managerName = CLng(rs2.Fields(3).Value)
  Debug.Print managerName
  With rs2
     .MoveLast
     .MoveFirst
     Do While Not .EOF
        xlR.Value = .Fields(0).Value
        xlR.Offset(ColumnOffset:=1 + (i * 2)).Value = .Fields(2).Value
        xlR.Offset(ColumnOffset:=2 + (i * 2)).Value = "ENTATH01"
        i = i + 1
        .MoveNext
     Loop
     .Close
  End With
  xlWb.SaveAs FileName:=sPath & sFile, FileFormat:=xlOpenXMLWorkbook
  xlWb.Close SaveChanges:=True
  rs2.MoveNext
</code>```

答:
Change:¨

```<code>i = i + 1
.MoveNext
</code>```

to

```<code>i = i + 2
.MoveNext
</code>```

Title: Recordset Not Iterating

Body:
I am sure this is strictly user error, but for the life of me, I can not discover how to iterate a table, and write the records to Excel.  I have the below code, but it hangs on the first Manager ID and just repeats the write for that one constantly in a loop.  I want to iterate all the Manager ID in the table and write them to the same workbook.

How should I tweak this code in order to do such?

  Set xlR = xlWb.Worksheets(1).Range("$R$2")
  i=0
  Set rs2 = Db.OpenRecordset("SELECT * FROM TestTable ORDER BY [Manager ID] ASC", dbOpenDynaset)
  managerName = CLng(rs2.Fields(3).Value)
  Debug.Print managerName
  With rs2
     .MoveLast
     .MoveFirst
     Do While Not .EOF
        xlR.Value = .Fields(0).Value
        xlR.Offset(ColumnOffset:=1 + (i * 2)).Value = .Fields(2).Value
        xlR.Offset(ColumnOffset:=2 + (i * 2)).Value = "ENTATH01"
        i = i + 1
        .MoveNext
     Loop
     .Close
  End With
  xlWb.SaveAs FileName:=sPath & sFile, FileFormat:=xlOpenXMLWorkbook
  xlWb.Close SaveChanges:=True
  rs2.MoveNext

Body:
Change:¨

i = i + 1
.MoveNext

to

i = i + 2
.MoveNext


问:
Best way to make search full width
First time using this component, and I am looking to make the search input box full width.

What would be the best way to accomplish this? Is it plain CSS, or is there an option in the script?

Here is my current script that generates the table

```<code>   initializeBootstrapTable() {
            let $table = jQuery(this.$refs.table);

            jQuery.fn.bootstrapTable.columnDefaults.formatter = function(value, row, index) {
                if(typeof(value) === 'boolean') {
                    return value ? 'Yes' : 'No';
                }

                if(value === 'ug') {
                    return 'UG';
                }

                if(value === 'pg') {
                    return 'PG';
                }

                return value;
            };

            $table.bootstrapTable({
                data: this.applicants,
                showColumns: true,
                toolbarAlign: 'right',
                buttonsAlign: 'right',
                pagination: true,
                search: true,
                iconsPrefix: 'fa',
                icons: {
                    paginationSwitchDown: 'fa-collapse-down icon-chevron-down',
                    paginationSwitchUp: 'fa-collapse-up icon-chevron-up',
                    refresh: 'fa-refresh icon-refresh',
                    toggle: 'fa-list-alt icon-list-alt',
                    columns: 'fa-th icon-th',
                    detailOpen: 'fa-plus icon-plus',
                    detailClose: 'fa-minus icon-minus'
                }
            });

            $table.on('click-row.bs.table', (e, row) => this.handleApplicantSelection(row));
        }
</code>```

Thanks!

答:
There doesn't seem to be an option to remove the float, it's either choose left or right looking at the options. Instead, add the BS4 no float class. JS is a good approach here.

Vanilla:

```<code>var d = document.getElementById("my-search");
d.className += " float-none";
</code>```

jQuery

```<code>$("#my-search").addClass('float-none');
</code>```

Plain CSS

```<code>#my-search {
  float:none;
}
</code>```

If you must, you can use the !important rule too.

Title: Best way to make search full width

Body:
First time using this component, and I am looking to make the search input box full width.

What would be the best way to accomplish this? Is it plain CSS, or is there an option in the script?

Here is my current script that generates the table

   initializeBootstrapTable() {
            let $table = jQuery(this.$refs.table);

            jQuery.fn.bootstrapTable.columnDefaults.formatter = function(value, row, index) {
                if(typeof(value) === 'boolean') {
                    return value ? 'Yes' : 'No';
                }

                if(value === 'ug') {
                    return 'UG';
                }

                if(value === 'pg') {
                    return 'PG';
                }

                return value;
            };

            $table.bootstrapTable({
                data: this.applicants,
                showColumns: true,
                toolbarAlign: 'right',
                buttonsAlign: 'right',
                pagination: true,
                search: true,
                iconsPrefix: 'fa',
                icons: {
                    paginationSwitchDown: 'fa-collapse-down icon-chevron-down',
                    paginationSwitchUp: 'fa-collapse-up icon-chevron-up',
                    refresh: 'fa-refresh icon-refresh',
                    toggle: 'fa-list-alt icon-list-alt',
                    columns: 'fa-th icon-th',
                    detailOpen: 'fa-plus icon-plus',
                    detailClose: 'fa-minus icon-minus'
                }
            });

            $table.on('click-row.bs.table', (e, row) => this.handleApplicantSelection(row));
        }

Thanks!

Body:
There doesn't seem to be an option to remove the float, it's either choose left or right looking at the options. Instead, add the BS4 no float class. JS is a good approach here.

Vanilla:

var d = document.getElementById("my-search");
d.className += " float-none";

jQuery

$("#my-search").addClass('float-none');

Plain CSS

#my-search {
  float:none;
}

If you must, you can use the !important rule too.


问:
Application.Index results in Compile Error: Type mismatch: Array or user-defined type expected
I know this error pops up a lot on the forum, but none of the posts I have seen have the same issue. I get a compile error when trying to use the Application.Index function to slice a 2D array. I have used the function before for simple indexing but there are multiple examples on the web of slicing being done.

Below is the code. It always highlights ".index" and gives me the compile error. I have tried casting the array as double, integer, and variant but nothing works. Please help.

```<code>    Dim test_z(2, 2) As Double

     Dim new_z As Double

    'fill the text_z array with values

    test_z(0,0) = 1

    'etc....

    new_z = Application.index(test_z, 1, 0)
</code>```

答:
Index returns an array if you pass 0 as the last argument. You can't assign that to Double - maybe try

```<code>Dim new_z As Variant
</code>```

Body:
I know this error pops up a lot on the forum, but none of the posts I have seen have the same issue. I get a compile error when trying to use the Application.Index function to slice a 2D array. I have used the function before for simple indexing but there are multiple examples on the web of slicing being done.

Below is the code. It always highlights ".index" and gives me the compile error. I have tried casting the array as double, integer, and variant but nothing works. Please help.

    Dim test_z(2, 2) As Double

     Dim new_z As Double

    'fill the text_z array with values

    test_z(0,0) = 1

    'etc....

    new_z = Application.index(test_z, 1, 0)

Body:
Index returns an array if you pass 0 as the last argument. You can't assign that to Double - maybe try

Dim new_z As Variant


问:
Automatically leave field after value is entered
I am creating a form in Visual FoxPro where the user will be entering a large number of values that are only one character values.  So that the user does not have to press tab after every key press, I would like to setup the form so that once the value is entered the cursor automatically goes to the next field.

What is a good way to do this?

答:
Herb's answer is correct, but keep in mind that the cursor will jump to the next field in the TAB Order.

So if you entered your Textbox fields in some other order you might need to re-order the TAB's.

To verify that you have your TAB Order as you need, with the Form open in the VFP Development environment, from the Menu, click View - Tab Order - Assign Interactively.   Then using your mouse, you can re-order the TAB settings for your Textboxes.

Also note that the TAB Order also includes the other Form objects such as Buttons, Grids, etc.

Good Luck


问:
Access command line arguments in C++
Is it possible to get the command line arguments without receiving them via int main(int, char**)? I don't want to pass the arguments to multiple methods, so a global function would be perfect. Also, I do not want to store the arguments by myself via global variables. I'm running Windows and Linux.

edit:
Example:

```<code>int main()
{
   int argc = GetArgumentCount();
   char ** argv = GetArguments();
   return 0;
}
</code>```

edit:
It's possible to use LPTSTR WINAPI GetCommandLine(void); in win32.

https://msdn.microsoft.com/en-us/library/ms683156(v=vs.85).aspx

I'm looking for equivalent functions in Linux.

答:
Is it possible to get the command line arguments without receiving
  them via int main(int, char**)?

Yes, with platform-specific functions. But that's not necessary (see below).

I don't want to pass the arguments to multiple methods,

That's understandable. It's an anti-pattern also known as "tramp data".

Also, I do not want to store the arguments by myself via global variables.

Yes, global variables are rarely a good idea.

Here's an alternative approach: store them as a static local container object in some globally available non-member function which returns the container by reference.

Example:

```<code>#include <iostream>
#include <string>
#include <vector>

std::vector<std::string>& Arguments()
{
    static std::vector<std::string> arguments;
    return arguments;
}

void f()
{
    // use arguments anywhere else:
    std::cout << Arguments()[0];
}

int main(int argc, char* argv[])
{
    for (int i = 0; i < argc; ++i)
    {
        Arguments().push_back(argv[i]);
    }

    f();
}
</code>```

Of course, this can be made more sophisticated. For example, you might want to prevent anyone else but main from changing the vector by wrapping the vector in a class and declaring main as a friend, something like this:

```<code>#include <iostream>
#include <string>
#include <vector>

class Arguments final
{
public:
    static int Count()
    {
        return arguments.size();
    }

    static std::string Get(int index)
    {
        return arguments[index];
    };

private:
    Arguments() = delete;
    friend int main(int argc, char* argv[]);
    static std::vector<std::string> arguments;
};

std::vector<std::string> Arguments::arguments;

void f()
{
    // use Arguments anywhere else:
    std::cout << Arguments::Get(0);
}

int main(int argc, char* argv[])
{
    for (int i = 0; i < argc; ++i)
    {
        Arguments::arguments.push_back(argv[i]);
    }

    f();
}
</code>```

Note that special care is needed to avoid bugs at program shutdown, when static objects are destroyed. You must make sure that no destructor of a static object accesses Arguments, or else you risk undefined behaviour.

Title: Access command line arguments in C++

Body:
Is it possible to get the command line arguments without receiving them via int main(int, char**)? I don't want to pass the arguments to multiple methods, so a global function would be perfect. Also, I do not want to store the arguments by myself via global variables. I'm running Windows and Linux.

edit:
Example:

int main()
{
   int argc = GetArgumentCount();
   char ** argv = GetArguments();
   return 0;
}

edit:
It's possible to use LPTSTR WINAPI GetCommandLine(void); in win32.

https://msdn.microsoft.com/en-us/library/ms683156(v=vs.85).aspx

I'm looking for equivalent functions in Linux.

Body:
Is it possible to get the command line arguments without receiving
  them via int main(int, char**)?

Yes, with platform-specific functions. But that's not necessary (see below).

I don't want to pass the arguments to multiple methods,

That's understandable. It's an anti-pattern also known as "tramp data".

Also, I do not want to store the arguments by myself via global variables.

Yes, global variables are rarely a good idea.

Here's an alternative approach: store them as a static local container object in some globally available non-member function which returns the container by reference.

Example:

#include <iostream>
#include <string>
#include <vector>

std::vector<std::string>& Arguments()
{
    static std::vector<std::string> arguments;
    return arguments;
}

void f()
{
    // use arguments anywhere else:
    std::cout << Arguments()[0];
}

int main(int argc, char* argv[])
{
    for (int i = 0; i < argc; ++i)
    {
        Arguments().push_back(argv[i]);
    }

    f();
}

Of course, this can be made more sophisticated. For example, you might want to prevent anyone else but main from changing the vector by wrapping the vector in a class and declaring main as a friend, something like this:

#include <iostream>
#include <string>
#include <vector>

class Arguments final
{
public:
    static int Count()
    {
        return arguments.size();
    }

    static std::string Get(int index)
    {
        return arguments[index];
    };

private:
    Arguments() = delete;
    friend int main(int argc, char* argv[]);
    static std::vector<std::string> arguments;
};

std::vector<std::string> Arguments::arguments;

void f()
{
    // use Arguments anywhere else:
    std::cout << Arguments::Get(0);
}

int main(int argc, char* argv[])
{
    for (int i = 0; i < argc; ++i)
    {
        Arguments::arguments.push_back(argv[i]);
    }

    f();
}

Note that special care is needed to avoid bugs at program shutdown, when static objects are destroyed. You must make sure that no destructor of a static object accesses Arguments, or else you risk undefined behaviour.


问:
Get style/font (font size, color etc) of current paragraph via Word API
I am working on a word web add-in that involves inserting some text (as OOXML) into a word document.

The insert functionality is working fine but I want the inserted text to have the same font size and colour etc as the area the user is currently editing.

I have got this working to some degree by getting the current paragraph at the cursor like so:

```<code>Word.run((context) => {
    var pars = context.document.getSelection().paragraphs;
    pars.load();

    return context.sync().then(() => {
            var par = pars.items[0];
            var font = par.font.load();
            var style = par.style;

            // Do stuff with the style & font...
    });
});
</code>```

However this seems to be unreliable and sometimes doesn't work.

I want to get the style at the current typing location, or somehow read them directly from the values in the ribbon:

Is there a good way to do this? It seems like this would be a pretty common use case in a word add-in.

答:
The paragraph isn't going to be reliable scope since it could easily contain content using multiple fonts and sizes. You're also retrieving only the 1st paragraph which even more likely to have a different properties (i.e. a title).

To grab the font information for the exact spot you want to insert your OOXML, you want to use document.getSelection() to return a range object. This will let you fetch the current font at the cursor's location:

return Word.run(function (context) {
    var range = context.document.getSelection();
    range.load('font');

    return context.sync()
        .then(function () {
            console.log("Font: " + range.font.name);
            console.log("Size: " + range.font.size);
        });
});
```

<p>Note that if the user has a selection that contains multiple fonts, this will return a <code>null</code> for <code>font</code>. To get around that you can rescope the <code>range</code> to the start of the section using <code>getRange("start")</code>:</p>

<pre class="lang-js prettyprint-override"><code>return Word.run(function (context) {
    var range = context.document.getSelection();
    range = range.getRange("start");
    range.load('font');

    return context.sync()
        .then(function () {
            console.log("Font: " + range.font.name);
            console.log("Size: " + range.font.size);
        });
});
</code>```

Body:
I am working on a word web add-in that involves inserting some text (as OOXML) into a word document.

The insert functionality is working fine but I want the inserted text to have the same font size and colour etc as the area the user is currently editing.

I have got this working to some degree by getting the current paragraph at the cursor like so:

Word.run((context) => {
    var pars = context.document.getSelection().paragraphs;
    pars.load();

    return context.sync().then(() => {
            var par = pars.items[0];
            var font = par.font.load();
            var style = par.style;

            // Do stuff with the style & font...
    });
});

However this seems to be unreliable and sometimes doesn't work.

I want to get the style at the current typing location, or somehow read them directly from the values in the ribbon:

Is there a good way to do this? It seems like this would be a pretty common use case in a word add-in.

Body:
The paragraph isn't going to be reliable scope since it could easily contain content using multiple fonts and sizes. You're also retrieving only the 1st paragraph which even more likely to have a different properties (i.e. a title).

To grab the font information for the exact spot you want to insert your OOXML, you want to use document.getSelection() to return a range object. This will let you fetch the current font at the cursor's location:

return Word.run(function (context) {
    var range = context.document.getSelection();
    range.load('font');

    return context.sync()
        .then(function () {
            console.log("Font: " + range.font.name);
            console.log("Size: " + range.font.size);
        });
});

Note that if the user has a selection that contains multiple fonts, this will return a null for font. To get around that you can rescope the range to the start of the section using getRange("start"):

return Word.run(function (context) {
    var range = context.document.getSelection();
    range = range.getRange("start");
    range.load('font');

    return context.sync()
        .then(function () {
            console.log("Font: " + range.font.name);
            console.log("Size: " + range.font.size);
        });
});


问:
Python Variables across Class functions - how to call them?
Instead of using a global variable, I'm trying to make an instance of a variable in a class, as it seems to be best practice. How do I reference this variable across other functions in the class?  I would have thought that Test.running_sum would work or at least running_sum in test_function, but I'm not having any luck with either. Thanks very much!

```<code>class Test:
    def __init__(self):
        self.root = None
        running_sum = 0

    def test_function(self):
        print(Test.running_sum)
        return

    x = Test()
    x.test_function()
</code>```

Error:

```<code>Traceback (most recent call last):
  File "so.py", line 1, in <module>
    class Test:
  File "so.py", line 10, in Test
    x = Test()
NameError: name 'Test' is not defined
</code>```

答:
As an object attribute: each object gets its own.
Test is the class; self is the Test object that invoked the method.

```<code>class Test:
    def __init__(self):
        self.root = None
        self.running_sum = 0

    def test_function(self):
        self.running_sum += 1
        print(self.running_sum)
        return

x = Test()
y = Test()
x.test_function()
y.test_function()
</code>```

Output:
    1
    1

As a class attribute: all objects share the same variable.
self.__class__ is the class of the invoking object (i.e. Test).

```<code>class Test:
    running_sum = 0

    def __init__(self):
        self.root = None

    def test_function(self):
        self.__class__.running_sum += 1
        print(self.__class__.running_sum)
        return

x = Test()
y = Test()
x.test_function()
y.test_function()
</code>```

Output:

```<code>1
2
</code>```

Body:
Instead of using a global variable, I'm trying to make an instance of a variable in a class, as it seems to be best practice. How do I reference this variable across other functions in the class?  I would have thought that Test.running_sum would work or at least running_sum in test_function, but I'm not having any luck with either. Thanks very much!

class Test:
    def __init__(self):
        self.root = None
        running_sum = 0

    def test_function(self):
        print(Test.running_sum)
        return

    x = Test()
    x.test_function()

Error:

Traceback (most recent call last):
  File "so.py", line 1, in <module>
    class Test:
  File "so.py", line 10, in Test
    x = Test()
NameError: name 'Test' is not defined

Body:
As an object attribute: each object gets its own.
Test is the class; self is the Test object that invoked the method.

class Test:
    def __init__(self):
        self.root = None
        self.running_sum = 0

    def test_function(self):
        self.running_sum += 1
        print(self.running_sum)
        return

x = Test()
y = Test()
x.test_function()
y.test_function()

Output:
    1
    1

As a class attribute: all objects share the same variable.
self.__class__ is the class of the invoking object (i.e. Test).

class Test:
    running_sum = 0

    def __init__(self):
        self.root = None

    def test_function(self):
        self.__class__.running_sum += 1
        print(self.__class__.running_sum)
        return

x = Test()
y = Test()
x.test_function()
y.test_function()

Output:

1
2


问:
Way to reduce size of .ttf fonts?
Is there any way to reduce the size of the .ttf fonts? i.e. if we want to remove some glyps which we are not using.</p>

答:
You can use fontforge to reduce the file size

This is explained at http://www.cnx-software.com/2010/02/19/reducing-truetype-font-file-size-for-embedded-systems/

ContentLicense: CC BY-SA 2.5

Title: Way to reduce size of .ttf fonts?


问:
How do I get the average of a count in Microsoft SQL Server 2008
How can I get the average of this count? </p>

```<code>SELECT
    driver,
    COUNT(order_number) as month_total
FROM
    Unloads
WHERE
    completiondate BETWEEN '11-06-2017' AND '11-10-2017'
GROUP BY
    driver
ORDER BY
    month_total DESC;
</code>```

答:
If you want the average of the driver by day- you can subquery and divide the count for each driver by the number of days passed.  Number of days passed is the datediff of the two dates plus 1 day.  It is plus 1 day since you have used BETWEEN, which is inclusive.  IOW, for days 6, 7, 8, 9, and 10- this is 5 days.  But datediff(DAY, '2017-11-06', '2017-11-10') is only 4 days- so you must add +1 day to divide by the correct number of days.  So the algorithm looks something like:

```<code>SELECT dT.driver
      ,month_total / (DATEDIFF(DAY, '2017-11-06', '2017-11-10') + 1) [Daily Driver Avg]

  FROM (
        SELECT
            driver,
            COUNT(order_number) as month_total
        FROM
            Unloads
        WHERE
            completiondate BETWEEN '2017-11-06' AND '2017-11-10'
        GROUP BY
            driver
       ) AS dT
</code>```

Body:
How can I get the average of this count?

SELECT
    driver,
    COUNT(order_number) as month_total
FROM
    Unloads
WHERE
    completiondate BETWEEN '11-06-2017' AND '11-10-2017'
GROUP BY
    driver
ORDER BY
    month_total DESC;

Body:
If you want the average of the driver by day- you can subquery and divide the count for each driver by the number of days passed.  Number of days passed is the datediff of the two dates plus 1 day.  It is plus 1 day since you have used BETWEEN, which is inclusive.  IOW, for days 6, 7, 8, 9, and 10- this is 5 days.  But datediff(DAY, '2017-11-06', '2017-11-10') is only 4 days- so you must add +1 day to divide by the correct number of days.  So the algorithm looks something like:

SELECT dT.driver
      ,month_total / (DATEDIFF(DAY, '2017-11-06', '2017-11-10') + 1) [Daily Driver Avg]

  FROM (
        SELECT
            driver,
            COUNT(order_number) as month_total
        FROM
            Unloads
        WHERE
            completiondate BETWEEN '2017-11-06' AND '2017-11-10'
        GROUP BY
            driver
       ) AS dT


问:
Spark 2.2.0 on AWS EMR writing to Parquet drops rows
So I have an issue where by certain rows in a DataFrame get dropped when writing to partitioned Parquet files.

Here are my steps:

Read CSV data files from S3 with specified schema

Partition by 'date' column (DateType)

write as Parquet with mode=append

First step of reading works as expected, no parsing issues. For quality checks I do the following:

For a particular partition for date='2012-11-22', perform a count on CSV files, loaded DataFrame and parquet files.

Here's some code to reproduce using pyspark :

```<code>logs_df = spark.read.csv('s3://../logs_2012/', multiLine=True, schema=get_schema()')
logs_df.filter(logs_df.date=='2012-11-22').count() # results in 5000
logs_df.write.partitionBy('date').parquet('s3://.../logs_2012_parquet/', mode='append')
par_df = spark.read.parquet('s3://.../logs_2012_parquet/')
par_df.filter(par_df.date=='2012-11-22').count() # results in 4999, always the same record that is omitted
</code>```

I have tried writing to HDFS too and result is same. This happens on multiple partitions. There are no records in default/null partition. logs_df above is accurate and correct.

Second experiment I tried was to write an unpartitioned parquet files. The only difference in above code was omission of partitionBy():

logs_df.write.parquet('s3://.../logs_2012_parquet/', mode='append')

Loading this parquet set and running a count as above yielded the correct result of 5000 for date='2012-11-22' and other dates. setting mode to overwrite or not setting (using default) results in same data loss.

My environment is:

EMR 5.9.0

Spark 2.2.0

Hadoop distribution: Amazon 2.7.3

Tried with both EMRFS consistent view and not. However most testing was done writing to HDFS to avoid any S3 consistency issues.

I would very much appreciate a fix or workaround or another way of converting to parquet files using Spark.

Thanks,

Edit: I was not able to reproduce the second experiment. so let's say both partitioned and unpartitioned seems to drop records when writing to Parquet or JSON.

答:
So the mystery was definitely in the schema definitions. However, unexpectedly it wasn't dates or timestamps. It was in fact boolean values.

I had exported the CSV from Redshift which writes bools as t and f. When I inspected the inferred schema those fields were marked as string types. A simple test with true and false in a CSV file recognised them as boolean.

So I was expecting date and timestamp parsing to go wrong as usual but it was booleans. Lesson learnt.

Thanks for the pointers.

Body:
So I have an issue where by certain rows in a DataFrame get dropped when writing to partitioned Parquet files.

Here are my steps:

Read CSV data files from S3 with specified schema

Partition by 'date' column (DateType)

write as Parquet with mode=append

First step of reading works as expected, no parsing issues. For quality checks I do the following:

For a particular partition for date='2012-11-22', perform a count on CSV files, loaded DataFrame and parquet files.

Here's some code to reproduce using pyspark :

logs_df = spark.read.csv('s3://../logs_2012/', multiLine=True, schema=get_schema()')
logs_df.filter(logs_df.date=='2012-11-22').count() # results in 5000
logs_df.write.partitionBy('date').parquet('s3://.../logs_2012_parquet/', mode='append')
par_df = spark.read.parquet('s3://.../logs_2012_parquet/')
par_df.filter(par_df.date=='2012-11-22').count() # results in 4999, always the same record that is omitted

I have tried writing to HDFS too and result is same. This happens on multiple partitions. There are no records in default/null partition. logs_df above is accurate and correct.

Second experiment I tried was to write an unpartitioned parquet files. The only difference in above code was omission of partitionBy():

logs_df.write.parquet('s3://.../logs_2012_parquet/', mode='append')

Loading this parquet set and running a count as above yielded the correct result of 5000 for date='2012-11-22' and other dates. setting mode to overwrite or not setting (using default) results in same data loss.

My environment is:

EMR 5.9.0

Spark 2.2.0

Hadoop distribution: Amazon 2.7.3

Tried with both EMRFS consistent view and not. However most testing was done writing to HDFS to avoid any S3 consistency issues.

I would very much appreciate a fix or workaround or another way of converting to parquet files using Spark.

Thanks,

Edit: I was not able to reproduce the second experiment. so let's say both partitioned and unpartitioned seems to drop records when writing to Parquet or JSON.


问:
Download multiple files from Google Cloud Storage (using node.js)
I am using a node.js webserver (NOT hosted in Google Cloud) with Google Cloud Storage to store the files my users upload. Everything is working fine so far but I could not figure out how to allow the users to download their files to their computer. It is simple for single files but for multiple files or folders I would like to create a zip file for download by the user.

Is there any possibility besides downloading the files to my node.js-webserver (not hosted in Google Cloud), create a zip on the webserver and afterwards provide it for download? Which is not working for large files/large amounts of files.
Providing multiple google cloud storage files for download via a webpage doesn't seem to be very exotic...? What did I overlook?

答:
From command line:</p>

```<code>gsutil -m cp -R gs://<bucket_name>/folder/filematch* /localfolder
</code>```

Body:
From command line:

gsutil -m cp -R gs://<bucket_name>/folder/filematch* /localfolder


问:
how to add relations for imported data besides server-side scripting in Google App Maker?
My company has lots of data in Google Sheets which is nowadays too slow to work with so I built an app and data models with relations to handle the tasks. Next I need to import the data but is there any way to map the data relations while importing from Google Sheets?

The only way I could come up with is to write a server-side script but considering that App Maker is a platform for non-developers I think there could be some build-in way for this..? And thanks for the help in advance :)

答:
App Maker recently released first party support for Export and Import data with relations. You can find more details by following these links:

https://developers.google.com/appmaker/release-notes#import_and_export_relations

https://developers.google.com/appmaker/models/import-export#what_you_can_expect_as_a_result

https://developers.google.com/appmaker/models/import-export#what_you_can_expect_as_a_result_1


问:
Difference between RxJava API and the Java 9 Flow API
It seems on every iteration of Java for the last few major releases, there are consistently new ways to manage concurrent tasks.

In Java 9, we have the Flow API which resembles the Flowable API of RxJava but with Java 9 has a much simpler set of classes and interfaces.

Java 9

Has a Flow.Publisher, Flow.Subscriber, Flow.Processor, Flow.Subscription, and SubmissionPublisher, and that's about it.

RxJava

Has whole packages of Flow API-like classes, i.e. io.reactivex.flowables, io.reactivex.subscribers, io.reactivex.processors, io.reactivex.observers, and io.reactivex.observables which seem to do something similar.

What are the main differences between these two libraries? Why would someone use the Java 9 Flow library over the much more diverse RxJava library or vice versa?

答:
What are the main differences between these two libraries?

This mostly holds true as an informative comment(but too long to fit in), the JEP 266: More Concurrency Updates responsible for the introduction of the Flow API in Java9 states this in its description(emphasis mine) -

Interfaces supporting the Reactive Streams publish-subscribe
  framework, nested within the new class Flow.

Publishers produce items
  consumed by one or more Subscribers, each managed by a Subscription.

Communication relies on a simple form of flow control (method
  Subscription.request, for communicating back pressure) that can be
  used to avoid resource management problems that may otherwise occur in
  "push" based systems. A utility class SubmissionPublisher is provided
  that developers can use to create custom components.

These (very
  small) interfaces correspond to those defined with broad participation
  (from the Reactive Streams initiative) and support interoperability
  across a number of async systems running on JVMs.

Nesting the interfaces within a class is a conservative policy allowing
  their use across various short-term and long-term possibilities. There
  are no plans to provide network- or I/O-based java.util.concurrent
  components for distributed messaging, but it is possible that future JDK
  releases will include such APIs in other packages.

 Why would someone use the Java 9 Flow library over the much more diverse RxJava library or vice versa?

Looking at a wider prospect this is completely opinion based on factors like the type of application a client is developing and its usages of the framework.


问:
center alignment ANTD calendar design
how to align the date of the antd calendar to the center alignment in the calendar display?

答:
The easiest way to do it is to add a CSS style override, by finding out which class to override. In this case, add a CSS file with following rule to override:

```<code>.ant-fullcalendar-value,
.ant-fullcalendar-fullscreen {
  text-align: center !important;
}
</code>```

In case you were wondering, I found the classes via inspecting.

There is also a dataCellRender prop for the <Calendar> component, in case you need to format the output in each cell, or add content ( but the date remains there ). Hope this helps!

Title: center alignment ANTD calendar design

Body:
The easiest way to do it is to add a CSS style override, by finding out which class to override. In this case, add a CSS file with following rule to override:

.ant-fullcalendar-value,
.ant-fullcalendar-fullscreen {
  text-align: center !important;
}

In case you were wondering, I found the classes via inspecting.

There is also a dataCellRender prop for the <Calendar> component, in case you need to format the output in each cell, or add content ( but the date remains there ). Hope this helps!


问:
How to get an input to display and edit currency with angular 4 pipes
My goal is to have an input field that allows the user to edit a number as currency.  E.g.  The user sees "$1,000", they can type a '0', and the edit box shows "$10,000".  And the resulting data model is a number 10000.

```<code><input type="text" name="Data" [ngModel]="Data | currency:'USD':true:'4.0-0'" (ngModelChange)="Data=$event" >
</code>```

The above displays in the edit box '$1,000', but when I edit the value in the input box, the value is no longer a number 1000, it is a string "$1,000".  Meaning my data model went from

```<code>{ myCost: 1000 }
</code>```

to become

```<code>{ myCost: "$1,000" }
</code>```

Any ideas on the correct way to do this?  It's looking like I need to create a new function to convert from currency back to number.  Which is possible, but it seems like there is a better way.

答:
You can handle ngModelChange in your component class
(ngModelChange)="onInputValueChange($event)"

In component.ts

onInputValueChange(newValue: any):Number {
 return <Number>newValue;
}

Body:
My goal is to have an input field that allows the user to edit a number as currency.  E.g.  The user sees "$1,000", they can type a '0', and the edit box shows "$10,000".  And the resulting data model is a number 10000.

<input type="text" name="Data" [ngModel]="Data | currency:'USD':true:'4.0-0'" (ngModelChange)="Data=$event" >

The above displays in the edit box '$1,000', but when I edit the value in the input box, the value is no longer a number 1000, it is a string "$1,000".  Meaning my data model went from

{ myCost: 1000 }

to become

{ myCost: "$1,000" }

Any ideas on the correct way to do this?  It's looking like I need to create a new function to convert from currency back to number.  Which is possible, but it seems like there is a better way.


问:
Assign values of an object in different class
I am trying to print out xx, yy values of an object which gets those values from a generator class where I assign them. For example:

Object.h

```<code>class Object {
public:
  // Define default constructors as this is an abstract class
  Object() = default;
  Object(const Object&) = default;
  Object(Object&&) = default;
  virtual ~Object() {};

  // Object properties
  glm::vec3 position{0,0,0};
  glm::vec3 rotation{0,0,0};
  /* I tried to define those variables here instead
  of defining in cube.h but on print, values are never changed. */
  //int xx=-1;
  //int yy=-1;

protected:
  void generateModelMatrix();
};
</code>```

Cube.h:

```<code>#include "object.h"

class Cube final : public Object{

private:
   //some code

public:
   int xx=-1;
   int yy=-1;

   Cube();

private:
};
</code>```

Generator.cpp

```<code>#include "cube.h"
bool Generator::update() {
   for (int x = 0; x < 5; ++x) {
       for (int y = 0; y < 5; ++y) {
          auto obj = make_unique<Cube>();
          obj->position.x += 2.1f * (float) x - 4.0f; //this works fine
          obj->xx = x;   //In this case, I get debugger error for xx: -var-create: unable to create variable object.
          obj->yy = y;   //same error here
       }
    if(x==4) return false;
   }
return true;
}
</code>```

Cube.cpp

```<code>#include "cube.h"

Cube::Cube(){
   printf("x: %d, y: %d\n", xx, yy);
}
</code>```

And in class Cube I tried to print out xx and yy values and I get -1 for every object, obviously it is not assigning those values at all. What did I do wrong?

答:
The constructor is called when the object is created. Which for the Cube objects happens with the make_unique call.

You set the values after the objects are created, long (relatively speaking) after the Cube constructor have returned.

Body:
I am trying to print out xx, yy values of an object which gets those values from a generator class where I assign them. For example:

Object.h

class Object {
public:
  // Define default constructors as this is an abstract class
  Object() = default;
  Object(const Object&) = default;
  Object(Object&&) = default;
  virtual ~Object() {};

  // Object properties
  glm::vec3 position{0,0,0};
  glm::vec3 rotation{0,0,0};
  /* I tried to define those variables here instead
  of defining in cube.h but on print, values are never changed. */
  //int xx=-1;
  //int yy=-1;

protected:
  void generateModelMatrix();
};

Cube.h:

#include "object.h"

class Cube final : public Object{

private:
   //some code

public:
   int xx=-1;
   int yy=-1;

   Cube();

private:
};

Generator.cpp

#include "cube.h"
bool Generator::update() {
   for (int x = 0; x < 5; ++x) {
       for (int y = 0; y < 5; ++y) {
          auto obj = make_unique<Cube>();
          obj->position.x += 2.1f * (float) x - 4.0f; //this works fine
          obj->xx = x;   //In this case, I get debugger error for xx: -var-create: unable to create variable object.
          obj->yy = y;   //same error here
       }
    if(x==4) return false;
   }
return true;
}

Cube.cpp

#include "cube.h"

Cube::Cube(){
   printf("x: %d, y: %d\n", xx, yy);
}

And in class Cube I tried to print out xx and yy values and I get -1 for every object, obviously it is not assigning those values at all. What did I do wrong?


问:
Tokenizer efficiency question
I'm writing a compiler front end for a project and I'm trying to understand what's the best method of tokenize the source code.
I can't choose between two ways:

1) the tokenizer read all tokens:

```<code>bool Parser::ReadAllTokens()
{
  Token token;
  while( m_Lexer->ReadToken( &token ) )
  {
    m_Tokens->push_back( token );
    token.Reset(); // reset the token values..
  }

  return !m_Tokens->empty();
}
</code>```

and then the parsing phase begins, operating on the m_Tokens list. In this way the methods getNextToken(), peekNextToken() and ungetToken() are relatively easy to implement by iterator, and the parsing code is well written and clear ( not broken by getNextToken() i.e. :

```<code> getNextToken();
 useToken();
 getNextToken();
 peekNextToken();
 if( peeked is something )
  ungetToken();
 ..
 ..
</code>```

)

2) the parsing phase begins and when needed, the token is created and used ( the code seems not so clear )

What's the best method??and why??and the efficiency??
thanks in advance for the answers

答: The first method is better, as you can then also understand the code 3 month later...</p>

Title: Tokenizer efficiency question

Body:
I'm writing a compiler front end for a project and I'm trying to understand what's the best method of tokenize the source code.
I can't choose between two ways:

1) the tokenizer read all tokens:

bool Parser::ReadAllTokens()
{
  Token token;
  while( m_Lexer->ReadToken( &token ) )
  {
    m_Tokens->push_back( token );
    token.Reset(); // reset the token values..
  }

  return !m_Tokens->empty();
}

and then the parsing phase begins, operating on the m_Tokens list. In this way the methods getNextToken(), peekNextToken() and ungetToken() are relatively easy to implement by iterator, and the parsing code is well written and clear ( not broken by getNextToken() i.e. :

 getNextToken();
 useToken();
 getNextToken();
 peekNextToken();
 if( peeked is something )
  ungetToken();
 ..
 ..

)

2) the parsing phase begins and when needed, the token is created and used ( the code seems not so clear )

What's the best method??and why??and the efficiency??
thanks in advance for the answers


问:
Debug puppeteer
Is there some way to debug a puppeteer script? One of the buttons just doesn't get clicked for some reason. I've tried all different ways, and actually in another script I get it clicked, but in this one I don't.</p>

```<code>await page.focus('#outer-container > nav > span.right > span.search-notification-wrapper > span > form > input[type="text"]');
await page.type("Some text");
await page.click('#outer-container > nav > span.right > span.search-notification-wrapper > span > form'); // I am clicking on the form because it did work in the other script
</code>```

答:
If you're looking for something interactive, I have a Github repo/docker image that ships with an interactive debugger which makes debugging at the browser level a lot easier since you both visually see what's going on and inspect the page itself. I've found that doing debugging in your node/puppeteer script really isn't valuable as all the action is taking place on the remote browser.

Github repo is here, docker repo is here.

Title: Debug puppeteer

Body:
Is there some way to debug a puppeteer script? One of the buttons just doesn't get clicked for some reason. I've tried all different ways, and actually in another script I get it clicked, but in this one I don't.

await page.focus('#outer-container > nav > span.right > span.search-notification-wrapper > span > form > input[type="text"]');
await page.type("Some text");
await page.click('#outer-container > nav > span.right > span.search-notification-wrapper > span > form'); // I am clicking on the form because it did work in the other script


问:
How to right-align drop-down menu in nav?
I am trying to add a dropdown-menu to a navbar - but while the icon is right-aligned, the menu opens left-aligned, despite me using dropdown-menu-right. I saw a remark about poppr being used for positioning - except in nav. So how can I right-align the menu then?

Fiddle here: https://jsfiddle.net/mbaas/dk3tpeex/5/

```<code><nav id="TOP" class="navbar navbar-light d-flex">
  <div class="navbar-brand d-inline">BLA</div>
  <div data-toggle="dropdown" class="navbar-brand d-inline ml-auto" id="menu" aria-expanded="false"><span class="fa fa-bars"></span></div>
  <div class="dropdown-menu dropdown-menu-right" aria-labelledby="menu">
    <button onclick="javascript:alert('Hi!');" class="dropdown-item" type="button" id="toggleLeft">MenuItem</button>
  </div>
</nav>
</code>```

答:
In this specific case I would change the following attributes of the dropdown-menu class:

```<code>.dropdown-menu {
    left: initial;
    right: 0; /* add right with 0 or a low pixel value */
}
</code>```

You could follow also the approach of creating your own class and override the original attributes of this dropdown-menu class.

Here is another suggestion how to right align the menu:

```<code>#dd.dropdown-menu {
    left: initial;
    right: 0
}
</code>```

Body:
I am trying to add a dropdown-menu to a navbar - but while the icon is right-aligned, the menu opens left-aligned, despite me using dropdown-menu-right. I saw a remark about poppr being used for positioning - except in nav. So how can I right-align the menu then?

Fiddle here: https://jsfiddle.net/mbaas/dk3tpeex/5/

BLA

    <button onclick="javascript:alert('Hi!');" class="dropdown-item" type="button" id="toggleLeft">MenuItem</button>

Body:
In this specific case I would change the following attributes of the dropdown-menu class:

.dropdown-menu {
    left: initial;
    right: 0; /* add right with 0 or a low pixel value */
}

You could follow also the approach of creating your own class and override the original attributes of this dropdown-menu class.

Here is another suggestion how to right align the menu:

#dd.dropdown-menu {
    left: initial;
    right: 0
}


问:
NodeJS unusual Require - what's going on here?
Per the documentation at https://nodejs.org/api/child_process.html

What is happening on this next line and why does this work?

```<code>const { exec } = require('child_process');
</code>```

From what I understand, it's merely wrapping exec into another object ie

```<code>var a = { exec }
// a is now { exec: exec }
</code>```

but then there's an assignment.. -Mind Blown-

答:
Your code example:

```<code>const { exec } = require('child_process');
</code>```

produces the same result as:

```<code>const exec = require('child_process').exec;
</code>```

This is known as destructuring assignment and is something new in ES2015 (ES6) and is described here: Destructuring Assignment on MDN.  It allows various shortcuts for assigning one or more properties from a source object to various types of destinations.  In this case, the source object is the result of require('child_process') and the desired destination is a single variable named exec which is to receive a single named property from the source.

It gets even more useful when you specify multiple properties:

```<code>const { exec, spawn, fork } = require('child_process');
</code>```

This creates module level variables named exec, spawn and fork that contain those exported properties from the child process module.  Before destructuring assignment, one would have either done:

```<code>const child = require('child_process');
const exec = child.exec;
const spawn = child.spawn;
const fork = child.fork;
</code>```

or would have just done this:

```<code>const child = require('child_process');
</code>```

And, then used child.exec() and child.spawn() and child.fork() to use those methods.  As you can see the destructuring assignment is a significant shortcut.  There are many forms of destructuring and you can do more advanced things such as specify the name of the receiving variable to be different than the property named and destructuring can be used with arrays, not only objects.

Here are several other reference articles on the topic:

Destructuring and parameter handling in ECMAScript 6

Code Examples of destructing in ECMAScript 6

Explanation of Destructuring

Body:
Per the documentation at https://nodejs.org/api/child_process.html

What is happening on this next line and why does this work?

const { exec } = require('child_process');

From what I understand, it's merely wrapping exec into another object ie

var a = { exec }
// a is now { exec: exec }

but then there's an assignment.. -Mind Blown-

Body:
Your code example:

const { exec } = require('child_process');

produces the same result as:

const exec = require('child_process').exec;

This is known as destructuring assignment and is something new in ES2015 (ES6) and is described here: Destructuring Assignment on MDN.  It allows various shortcuts for assigning one or more properties from a source object to various types of destinations.  In this case, the source object is the result of require('child_process') and the desired destination is a single variable named exec which is to receive a single named property from the source.

It gets even more useful when you specify multiple properties:

const { exec, spawn, fork } = require('child_process');

This creates module level variables named exec, spawn and fork that contain those exported properties from the child process module.  Before destructuring assignment, one would have either done:

const child = require('child_process');
const exec = child.exec;
const spawn = child.spawn;
const fork = child.fork;

or would have just done this:

const child = require('child_process');

And, then used child.exec() and child.spawn() and child.fork() to use those methods.  As you can see the destructuring assignment is a significant shortcut.  There are many forms of destructuring and you can do more advanced things such as specify the name of the receiving variable to be different than the property named and destructuring can be used with arrays, not only objects.

Here are several other reference articles on the topic:

Destructuring and parameter handling in ECMAScript 6

Code Examples of destructing in ECMAScript 6

Explanation of Destructuring


问:
Calling to UpdateModel in a controller is follow MVC pattern?? How could I do the same in the model layer?
newbie writing, I'm new to MVC 2 C# and using EntityFramework with LINQ.

In many examples (including the MVC 2 MusicStore of Microsoft) I've noticed that the Database updates are made in the Controllers layers. For example If I want to update a Database Product I call to UpdateModel(product,"Products" ) and call to SaveChanges() in the ProductController class

Ok, simple and easy but is this following MVC "traditional" pattern ??

Instead of this, I try to delegate the responsibility to the ProductModel class (I've made it with success in Adding and Deleting with AutoMapper) but I don't find the way to update from the model
I tried something like

```<code>        Mapper.CreateMap<Product, ProductModels>();
        Mapper.CreateMap<ProductModels, Product>();
        var p = Mapper.Map<Product, ProductModels>(prod);

        productosBD.AttachTo("Products", p);
        productosBD.SaveChanges();
</code>```

but no way...

Could somebody tell me how can I update an entity in the model layer??

Thanks in advance

答:
ASP NET MVC has evolved a lot from version 1 Beta to version 2 and now version 3 although 2 and 3 are much more similar.

A lot of such samples are related to MVC 1 - something I learnt the hard way. I am pretty new to ASP NET MVC but realised in MVC 2, ModelBinder looks after updating the model so normally if you define your method signature as your model, you do not need to call UpdateModel.

For example:

```<code> public ActionResult Create(MyModel model)
 {
      ... // no need to call UpdateModel
</code>```

However if you define it like this, then you need to do that:

```<code> public ActionResult Create(int id, FormCollection collection)
 {
      MyModel model = Repository.Get(id); // in your case EF productosBD.Where(x=>x.Id = id)
      UpdateMode(model, collection);
      Repository.Save(model);
</code>```

In terms of where the update happens, yes, it will happen in your controller but it depends if you use a Repository pattern or use the bare database context. I personally use a ServiceProxy which then talks to a WCF Service which talks to a Manager which uses a Repository to do that.

Body:
newbie writing, I'm new to MVC 2 C# and using EntityFramework with LINQ.

In many examples (including the MVC 2 MusicStore of Microsoft) I've noticed that the Database updates are made in the Controllers layers. For example If I want to update a Database Product I call to UpdateModel(product,"Products" ) and call to SaveChanges() in the ProductController class

Ok, simple and easy but is this following MVC "traditional" pattern ??

Instead of this, I try to delegate the responsibility to the ProductModel class (I've made it with success in Adding and Deleting with AutoMapper) but I don't find the way to update from the model
I tried something like

        Mapper.CreateMap<Product, ProductModels>();
        Mapper.CreateMap<ProductModels, Product>();
        var p = Mapper.Map<Product, ProductModels>(prod);

        productosBD.AttachTo("Products", p);
        productosBD.SaveChanges();

but no way...

Could somebody tell me how can I update an entity in the model layer??

Thanks in advance

Body:
ASP NET MVC has evolved a lot from version 1 Beta to version 2 and now version 3 although 2 and 3 are much more similar.

A lot of such samples are related to MVC 1 - something I learnt the hard way. I am pretty new to ASP NET MVC but realised in MVC 2, ModelBinder looks after updating the model so normally if you define your method signature as your model, you do not need to call UpdateModel.

For example:

 public ActionResult Create(MyModel model)
 {
      ... // no need to call UpdateModel

However if you define it like this, then you need to do that:

 public ActionResult Create(int id, FormCollection collection)
 {
      MyModel model = Repository.Get(id); // in your case EF productosBD.Where(x=>x.Id = id)
      UpdateMode(model, collection);
      Repository.Save(model);

In terms of where the update happens, yes, it will happen in your controller but it depends if you use a Repository pattern or use the bare database context. I personally use a ServiceProxy which then talks to a WCF Service which talks to a Manager which uses a Repository to do that.


问:
Replace all occurrences of a substring, one at a time
I have the following method which replaces all occurrences of a {TIMESTAMP} substring with the value returned by String.valueOf(System.nanoTime()), the intention is to get a different time mark per substring occurrence, but it results in all substrings being replaced by just the same value.

```<code>class StringUtils {
    private static String resolveTimestamp(String s) {
        String timestamp = "\\{TIMESTAMP}";
        return s.replaceAll(timestamp, String.valueOf(System.currentTimeMillis()));
    }
}

class Sample {
    public static void main(String[] args) {
        StringUtils.resolveTimestamp("{TIMESTAMP}, {TIMESTAMP}, {TIMESTAMP}")
    }
}

// The execution of the code above would result in:
// 241170886964203, 241170886964203, 241170886964203

// But I want to get this:
// 241733154573329, 241734822930540, 241751957270934
</code>```

I would like to know which is the best way of doing what I want, as there are several ways of doing that coming to my mind right now:

A loop with s.matches(timestamp) as condition to iterate over each occurrence of the substring, and s.replaceFirst(timestamp, String.valueOf(System.nanoTime())) to perform the replacement inside the loop.

Use the substring to explode the string into several chunks with s.split(timestamp), and iterate over the chunks joining each pair with the value returned by String.valueOf(System.nanoTime()))

Probably some other choices

NOTE: Please be aware that this is not the same problem addressed in this question. There they need to replace several occurrences of a fixed pattern with just the same value, while I need to replace several occurrences of the same substring, each one by a different value calculated at runtime.

答:
Sounds like what you want to do is modify: replaceAll with replaceFirst
this way every time you'll call the method with the string - it will replace only the next occurrence:

```<code>public static void main(String[] args) {
    String req = "\\{TIMESTAMP} \\{TIMESTAMP} \\{TIMESTAMP} \\{TIMESTAMP}";
    req = resolveTimestamp(req);
    req = resolveTimestamp(req);
    req = resolveTimestamp(req);
    req = resolveTimestamp(req);
    System.out.println("req = " + req);
}

private static String resolveTimestamp(String s) {
    String timestamp = "\\{TIMESTAMP}";
    return s.replaceFirst(timestamp, String.valueOf(System.currentTimeMillis()));
}
</code>```

OUTPUT:

```<code>req = \1510940324918 \1510940324921 \1510940324921 \1510940324921
</code>```

Comment: you should consider using System.nanoTime() instead of System.currentTimeMillis() if you want better precision.

Body:
I have the following method which replaces all occurrences of a {TIMESTAMP} substring with the value returned by String.valueOf(System.nanoTime()), the intention is to get a different time mark per substring occurrence, but it results in all substrings being replaced by just the same value.

class StringUtils {
    private static String resolveTimestamp(String s) {
        String timestamp = "\\{TIMESTAMP}";
        return s.replaceAll(timestamp, String.valueOf(System.currentTimeMillis()));
    }
}

class Sample {
    public static void main(String[] args) {
        StringUtils.resolveTimestamp("{TIMESTAMP}, {TIMESTAMP}, {TIMESTAMP}")
    }
}

// The execution of the code above would result in:
// 241170886964203, 241170886964203, 241170886964203

// But I want to get this:
// 241733154573329, 241734822930540, 241751957270934

I would like to know which is the best way of doing what I want, as there are several ways of doing that coming to my mind right now:

A loop with s.matches(timestamp) as condition to iterate over each occurrence of the substring, and s.replaceFirst(timestamp, String.valueOf(System.nanoTime())) to perform the replacement inside the loop.

Use the substring to explode the string into several chunks with s.split(timestamp), and iterate over the chunks joining each pair with the value returned by String.valueOf(System.nanoTime()))

Probably some other choices

NOTE: Please be aware that this is not the same problem addressed in this question. There they need to replace several occurrences of a fixed pattern with just the same value, while I need to replace several occurrences of the same substring, each one by a different value calculated at runtime.

Body:
Sounds like what you want to do is modify: replaceAll with replaceFirst
this way every time you'll call the method with the string - it will replace only the next occurrence:

public static void main(String[] args) {
    String req = "\\{TIMESTAMP} \\{TIMESTAMP} \\{TIMESTAMP} \\{TIMESTAMP}";
    req = resolveTimestamp(req);
    req = resolveTimestamp(req);
    req = resolveTimestamp(req);
    req = resolveTimestamp(req);
    System.out.println("req = " + req);
}

private static String resolveTimestamp(String s) {
    String timestamp = "\\{TIMESTAMP}";
    return s.replaceFirst(timestamp, String.valueOf(System.currentTimeMillis()));
}

OUTPUT:

req = \1510940324918 \1510940324921 \1510940324921 \1510940324921

Comment: you should consider using System.nanoTime() instead of System.currentTimeMillis() if you want better precision.


问:
Angular 5 - Can't set header for HttpClient
I am trying to make a POST call using HttpClient in an Angular 5 project, and I want to set the header:

```<code>import { HttpClient, HttpHeaders, HttpRequest } from '@angular/common/http';
import { Injectable } from '@angular/core';

import { AuthData }    from './models/auth-data';

@Injectable()
export class AuthService {

    constructor(private http: HttpClient) { }

    auth = (data: AuthData) => {

        var url = "https://.../login";
        var payload = data;
        var headers = new HttpHeaders().set('Content-Type', 'application/json; charset=utf-8');
        var options =  {
            headers: headers
        };

        this.http.post(url, payload, options).subscribe();
    }
}
</code>```

For some reason, the Content-Type header does not seem to be in the request I am making.

Why is this?

答:
Try this:</p>

```<code>var headers = new HttpHeaders();
headers.append('Content-Type', 'application/json');
</code>```

Body:
I am trying to make a POST call using HttpClient in an Angular 5 project, and I want to set the header:

import { HttpClient, HttpHeaders, HttpRequest } from '@angular/common/http';
import { Injectable } from '@angular/core';

import { AuthData }    from './models/auth-data';

@Injectable()
export class AuthService {

    constructor(private http: HttpClient) { }

    auth = (data: AuthData) => {

        var url = "https://.../login";
        var payload = data;
        var headers = new HttpHeaders().set('Content-Type', 'application/json; charset=utf-8');
        var options =  {
            headers: headers
        };

        this.http.post(url, payload, options).subscribe();
    }
}

For some reason, the Content-Type header does not seem to be in the request I am making.

Why is this?

Body:
Try this:

var headers = new HttpHeaders();
headers.append('Content-Type', 'application/json');


问:
Why are my files not getting pushed on github?
I try pushing the files and wait for the process to end. Neither the process ends not I can see any change on github.</p>

```<code>C:\git\btprc\btprc>git push origin master
Counting objects: 5847, done.
Delta compression using up to 4 threads.
Compressing objects: 100% (5845/5845), done.
Writing objects: 100% (5847/5847), 867.55 MiB | 13.45 MiB/s, done.
Total 5847 (delta 3406), reused 0 (delta 0)
</code>```

答:
I'm not quite sure what you mean by the process not ending, as the output you pasted shows that changes were successfully pushed onto your repo, but is it stalled at the Total line? Here's a link to a similar post: Git fails when pushing commit to github

It could be that you've added a file that exceeded the size limitations for your repo, and the push is stalling. You would simply have to wait a longer amount of time for the process to complete, with a chance of another output line at the end that will state failed files pushed.

If that's the case, your best bet is to compress various assets via clean and smudge. This will convert large files into txt format, and revert back upon call.

```<code>git config filter.compress.clean gzip
git config filter.compress.smudge gzip -d
</code>```

For more info on that, check out this post: https://git-scm.com/book/en/v2/Customizing-Git-Git-Attributes

If you mean to add new files onto the repo, and don't know how, try using git add <FILES>. This will mark the specified files to be added into your next commit. For example, if you want to include all files in a specific directory, use git add *, git add -A, or git add --all. For more info on that, check out https://git-scm.com/docs/git-add

Body:
I try pushing the files and wait for the process to end. Neither the process ends not I can see any change on github.

C:\git\btprc\btprc>git push origin master
Counting objects: 5847, done.
Delta compression using up to 4 threads.
Compressing objects: 100% (5845/5845), done.
Writing objects: 100% (5847/5847), 867.55 MiB | 13.45 MiB/s, done.
Total 5847 (delta 3406), reused 0 (delta 0)

Body:
I'm not quite sure what you mean by the process not ending, as the output you pasted shows that changes were successfully pushed onto your repo, but is it stalled at the Total line? Here's a link to a similar post: Git fails when pushing commit to github

It could be that you've added a file that exceeded the size limitations for your repo, and the push is stalling. You would simply have to wait a longer amount of time for the process to complete, with a chance of another output line at the end that will state failed files pushed.

If that's the case, your best bet is to compress various assets via clean and smudge. This will convert large files into txt format, and revert back upon call.

git config filter.compress.clean gzip
git config filter.compress.smudge gzip -d

For more info on that, check out this post: https://git-scm.com/book/en/v2/Customizing-Git-Git-Attributes

If you mean to add new files onto the repo, and don't know how, try using git add <FILES>. This will mark the specified files to be added into your next commit. For example, if you want to include all files in a specific directory, use git add *, git add -A, or git add --all. For more info on that, check out https://git-scm.com/docs/git-add


问:
Confused about the Alarm
What I want on paper is pretty simple: trigger an alarm every midnights

But being a newbie, I'm having troubles setting up such an alarm. In fact, it works okay for the most part, but it also triggers on first time activity start (after a memory wipe for instance). I understand, to some extent, that it checks if the time occured in the past or something, which doesn't really make sense to me with my poor programming knowledge.

My calendar

```<code>Calendar calendar = Calendar.getInstance();

calendar.set(Calendar.HOUR_OF_DAY, 0);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 1);
calendar.set(Calendar.DAY_OF_YEAR, 1);
calendar.set(Calendar.MILLISECOND, 0);

setAlarm(calendar.getTimeInMillis());
</code>```

setAlarm method

```<code>private void setAlarm(long timeInMillis) {
// Check if Calendar is set in the past to prevent an immediate alarm */
if (mCalendar.getTimeInMillis() < System.currentTimeMillis()) {
//Add one day to the calendar (or whatever repeat interval you would like)
        mCalendar.add(Calendar.DAY_OF_YEAR, 1); }

AlarmManager alarmManager = (AlarmManager)
getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(this, AlarmReceiver.class);
PendingIntent pi = PendingIntent.getBroadcast(this, 0, intent, 0);
alarmManager.setRepeating(AlarmManager.RTC, timeInMillis, AlarmManager.INTERVAL_DAY, pi);

}
</code>```

I think it must be pretty obvious what's wrong for veterans, but I've been stuck on this for hours. Thanks a lot if you can help me.

答:
search for the broadcastreceiver. even you turn off your phone, it will
somewhat reload your pendingintent.</p>

Title: Confused about the Alarm

Body:
What I want on paper is pretty simple: trigger an alarm every midnights

But being a newbie, I'm having troubles setting up such an alarm. In fact, it works okay for the most part, but it also triggers on first time activity start (after a memory wipe for instance). I understand, to some extent, that it checks if the time occured in the past or something, which doesn't really make sense to me with my poor programming knowledge.

My calendar

Calendar calendar = Calendar.getInstance();

calendar.set(Calendar.HOUR_OF_DAY, 0);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 1);
calendar.set(Calendar.DAY_OF_YEAR, 1);
calendar.set(Calendar.MILLISECOND, 0);

setAlarm(calendar.getTimeInMillis());

setAlarm method

private void setAlarm(long timeInMillis) {
// Check if Calendar is set in the past to prevent an immediate alarm */
if (mCalendar.getTimeInMillis() < System.currentTimeMillis()) {
//Add one day to the calendar (or whatever repeat interval you would like)
        mCalendar.add(Calendar.DAY_OF_YEAR, 1); }

AlarmManager alarmManager = (AlarmManager)
getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(this, AlarmReceiver.class);
PendingIntent pi = PendingIntent.getBroadcast(this, 0, intent, 0);
alarmManager.setRepeating(AlarmManager.RTC, timeInMillis, AlarmManager.INTERVAL_DAY, pi);

}

I think it must be pretty obvious what's wrong for veterans, but I've been stuck on this for hours. Thanks a lot if you can help me.


问:
why ionic 3 google map with lat lang is not loading on android
Why my google map is not appearing in on android device.

I'm able console.log(); lat, lang in browser. device will ask permission for location access but it will not render map.

below code works fine for predefined lat, lang

```<code> ionViewDidLoad() {
    console.log('ionViewDidLoad GoogleMapTestPage');
   this.loadMapHandler();

  }

    loadMapHandler() {

      //console.log(lat,lang);

     // create a new map by passing HTMLElement
     let element: HTMLElement = document.getElementById('map');

     let map: GoogleMap = this.googleMaps.create(element);

     // create CameraPosition
     let position: any = {
       target: LatLng,
       zoom: 18,
       tilt: 30
     };

     map.one(GoogleMapsEvent.MAP_READY).then(() => {
         console.log('Map is ready!');
         // Now you can add elements to the map like the marker
          map.moveCamera(position);

         // create new marker
        let markerOptions:any = {
            position: LatLng,
            title: 'Ionic'
        };

        const marker:any = map.addMarker(markerOptions)
            .then((marker: Marker) => {
                marker.showInfoWindow();
            });
        });

      }
</code>```

The above code works fine on android

when i try to get current location of user and  and pass lat, lang to another

function then i will not work

below is my code which is not working

code not working on android: ask permission but doesn't work

```<code>    import { Geolocation ,GeolocationOptions } from '@ionic-native/geolocation';
     constructor(...,public googleMaps: GoogleMaps,private geolocation : Geolocation) {
      }

  ionViewDidLoad() {

   this.loadMap();

  }
    loadMap(){

         this.geolocation.getCurrentPosition().then((position) => {

           this.loadMapHandler(position.coords.latitude,position.coords.longitude);

        }, (err) => {
          console.log(err);
        });
    }

    loadMapHandler(lat,lang) {

      console.log(lat,lang);  // console.log('is giving map co-ordinates');

     // create a new map by passing HTMLElement
     let element: HTMLElement = document.getElementById('map');

     let map: GoogleMap = this.googleMaps.create(element);

     let ionic: LatLng = new LatLng(lat,lang);

     // create CameraPosition
     let position: any = {
       target: LatLng,
       zoom: 18,
       tilt: 30
     };

     map.one(GoogleMapsEvent.MAP_READY).then(() => {
         console.log('Map is ready!');
         // Now you can add elements to the map like the marker
          map.moveCamera(position);

         // create new marker
        let markerOptions:any = {
            position: LatLng,
            title: 'Ionic'
        };

        const marker:any = map.addMarker(markerOptions)
            .then((marker: Marker) => {
                marker.showInfoWindow();
            });
        });

    }
</code>```

Thanks in Advance!!!

答:
Please use @ionic-native/core@4.4.0 and @ionic-native/google-maps@4.4.0

```<code>$> npm uninstall @ionic-native/core @ionic-native/google-maps

$> npm install @ionic-native/core@4.4.0 @ionic-native/google-maps@4.4.0
</code>```

Then replace your code like this:

```<code>import { Geolocation ,GeolocationOptions } from '@ionic-native/geolocation';

class MapPage {
  map: GoogleMap;

  constructor(..., private geolocation : Geolocation) {
  }

  ionViewDidLoad() {

   this.loadMap();

  }

  loadMap(){

    this.geolocation.getCurrentPosition()
      .then((position) => {
        console.log('--->step1 clear');

        this.loadMapHandler(position.coords.latitude,position.coords.longitude);

      })
      .catch((err) => {
        console.log(err);
      });
  }

  loadMapHandler(lat,lang) {

    console.log('step2', lat,lang);  // console.log('is giving map co-ordinates');

    let position: ILatLng = {
      lat: lat,
      lng: lang
    };

    this.map = GoogleMaps.create('map', {
      camera: {
        target: position,
        zoom: 18,
        tilt: 30
      }
    });

    this.map.one(GoogleMapsEvent.MAP_READY).then(() => {
      console.log('Map is ready!');

      // create new marker
      let markerOptions: MarkerOptions = {
        position: position,
        title: 'Ionic'
      };

      this.map.addMarker(markerOptions)
        .then((marker: Marker) => {
            marker.showInfoWindow();
        });
    });
  }
}
</code>```

Body:
Why my google map is not appearing in on android device.

I'm able console.log(); lat, lang in browser. device will ask permission for location access but it will not render map.

below code works fine for predefined lat, lang

 ionViewDidLoad() {
    console.log('ionViewDidLoad GoogleMapTestPage');
   this.loadMapHandler();

  }

    loadMapHandler() {

      //console.log(lat,lang);

     // create a new map by passing HTMLElement
     let element: HTMLElement = document.getElementById('map');

     let map: GoogleMap = this.googleMaps.create(element);

     // create CameraPosition
     let position: any = {
       target: LatLng,
       zoom: 18,
       tilt: 30
     };

     map.one(GoogleMapsEvent.MAP_READY).then(() => {
         console.log('Map is ready!');
         // Now you can add elements to the map like the marker
          map.moveCamera(position);

         // create new marker
        let markerOptions:any = {
            position: LatLng,
            title: 'Ionic'
        };

        const marker:any = map.addMarker(markerOptions)
            .then((marker: Marker) => {
                marker.showInfoWindow();
            });
        });

      }

The above code works fine on android

when i try to get current location of user and  and pass lat, lang to another

function then i will not work

below is my code which is not working

code not working on android: ask permission but doesn't work

    import { Geolocation ,GeolocationOptions } from '@ionic-native/geolocation';
     constructor(...,public googleMaps: GoogleMaps,private geolocation : Geolocation) {
      }

  ionViewDidLoad() {

   this.loadMap();

  }
    loadMap(){

         this.geolocation.getCurrentPosition().then((position) => {

           this.loadMapHandler(position.coords.latitude,position.coords.longitude);

        }, (err) => {
          console.log(err);
        });
    }

    loadMapHandler(lat,lang) {

      console.log(lat,lang);  // console.log('is giving map co-ordinates');

     // create a new map by passing HTMLElement
     let element: HTMLElement = document.getElementById('map');

     let map: GoogleMap = this.googleMaps.create(element);

     let ionic: LatLng = new LatLng(lat,lang);

     // create CameraPosition
     let position: any = {
       target: LatLng,
       zoom: 18,
       tilt: 30
     };

     map.one(GoogleMapsEvent.MAP_READY).then(() => {
         console.log('Map is ready!');
         // Now you can add elements to the map like the marker
          map.moveCamera(position);

         // create new marker
        let markerOptions:any = {
            position: LatLng,
            title: 'Ionic'
        };

        const marker:any = map.addMarker(markerOptions)
            .then((marker: Marker) => {
                marker.showInfoWindow();
            });
        });

    }

Thanks in Advance!!!

Body:
Please use @ionic-native/core@4.4.0 and @ionic-native/google-maps@4.4.0

$> npm uninstall @ionic-native/core @ionic-native/google-maps

$> npm install @ionic-native/core@4.4.0 @ionic-native/google-maps@4.4.0

Then replace your code like this:

import { Geolocation ,GeolocationOptions } from '@ionic-native/geolocation';

class MapPage {
  map: GoogleMap;

  constructor(..., private geolocation : Geolocation) {
  }

  ionViewDidLoad() {

   this.loadMap();

  }

  loadMap(){

    this.geolocation.getCurrentPosition()
      .then((position) => {
        console.log('--->step1 clear');

        this.loadMapHandler(position.coords.latitude,position.coords.longitude);

      })
      .catch((err) => {
        console.log(err);
      });
  }

  loadMapHandler(lat,lang) {

    console.log('step2', lat,lang);  // console.log('is giving map co-ordinates');

    let position: ILatLng = {
      lat: lat,
      lng: lang
    };

    this.map = GoogleMaps.create('map', {
      camera: {
        target: position,
        zoom: 18,
        tilt: 30
      }
    });

    this.map.one(GoogleMapsEvent.MAP_READY).then(() => {
      console.log('Map is ready!');

      // create new marker
      let markerOptions: MarkerOptions = {
        position: position,
        title: 'Ionic'
      };

      this.map.addMarker(markerOptions)
        .then((marker: Marker) => {
            marker.showInfoWindow();
        });
    });
  }
}


问:
VB.NET Multilingual resource files - work fine in dev - missing in publish
My click-once app has english and spanish content. In development, it runs fine with the two resource files I have - named multilingual.en-US.resx &  multilingual.es-MX.resx accordingly. When I publish it looses these resources for referencing. Anyone have any idea why it would do that? The files reside in the root directory for the app.</p>

答:
A couple of things you can check:

Make sure the build action is set to "Embedded Resource" for those two files. (Click on them in solution explorer and check the properties window.)

In the Publish settings for your application, click the "Application Files" button and make sure the resource dlls are set to "Include". If they're not, ClickOnce might not pick them up.


答:
This is a special notation that comme with ES6 specification.
Here, you extract the value of the property exec of the object return by the require in a variable with the same name.

```<code>const { exec } = require('child_process');
// Equals
const exec = require('child_process').exec;
</code>```

You can extract somme property a an object like this.

```<code>const { exec, spawn, fork } = require('child_process');
let { a, b } = { a: 'foo', b: 'bar' };
</code>```

It's particularly useful when you load libraries.

This is call destructuring assignment

Title: NodeJS unusual Require - what's going on here?

Body:
This is a special notation that comme with ES6 specification.
Here, you extract the value of the property exec of the object return by the require in a variable with the same name.

const { exec } = require('child_process');
// Equals
const exec = require('child_process').exec;

You can extract somme property a an object like this.

const { exec, spawn, fork } = require('child_process');
let { a, b } = { a: 'foo', b: 'bar' };

It's particularly useful when you load libraries.

This is call destructuring assignment


问:
How to choose between the lower value of a where condition in postgresql?
This one is hard to explain but basically I want pick the condition that has the smaller distance. The query is the following:

```<code>update point_a a
set c_id = (select b.otherid
from point_b b, line c
where a.pointid = c.lineconnecting_a_id
and (st_endpoint(c.geom) = b.geom or st_startpoint(c.geom) = b.geom order by distance limit 1
</code>```

Basically on the last line I want to use the line to pick the point in which it connects to and I want the point that's closer to the origin point. Problem is that with my OR, I'm getting 2 points and I don't know how to limit to be able to use st_distance and pick the one closest.

In other words, for each row I need to pick the startpoint or endpoint depending on their distance to the origin point

答:
Please post valid queries. And table definitions. This might also make it easier to understand your problem

Anyway, if I understood your problem correctly, this should work (untested)

```<code>update point_a a
set c_id = (

  select  otherid
  from (
    select b.otherid, distance
    from point_b b, line c
    where a.pointid = c.lineconnecting_a_id
    and (st_endpoint(c.geom) = b.geom)
   UNION
    select b.otherid, distance
    from point_b b, line c
    where a.pointid = c.lineconnecting_a_id
    and (st_startpoint(c.geom) = b.geom)
  )
  order by distance limit 1
);
</code>```

Body:
This one is hard to explain but basically I want pick the condition that has the smaller distance. The query is the following:

update point_a a
set c_id = (select b.otherid
from point_b b, line c
where a.pointid = c.lineconnecting_a_id
and (st_endpoint(c.geom) = b.geom or st_startpoint(c.geom) = b.geom order by distance limit 1

Basically on the last line I want to use the line to pick the point in which it connects to and I want the point that's closer to the origin point. Problem is that with my OR, I'm getting 2 points and I don't know how to limit to be able to use st_distance and pick the one closest.

In other words, for each row I need to pick the startpoint or endpoint depending on their distance to the origin point

Body:
Please post valid queries. And table definitions. This might also make it easier to understand your problem

Anyway, if I understood your problem correctly, this should work (untested)

update point_a a
set c_id = (

  select  otherid
  from (
    select b.otherid, distance
    from point_b b, line c
    where a.pointid = c.lineconnecting_a_id
    and (st_endpoint(c.geom) = b.geom)
   UNION
    select b.otherid, distance
    from point_b b, line c
    where a.pointid = c.lineconnecting_a_id
    and (st_startpoint(c.geom) = b.geom)
  )
  order by distance limit 1
);


问:
Pandas: fill column based on data in different column
I Have the following Dataframe:

```<code>test_df['A'] = [100, 100, 100, 0, 0, 100, 100, 0, 100, 100, 100]
test_df['B'] = [100, 0, 0, 0, 0, 0, 0, 0, 100, 0, 0]
</code>```

What I want to achieve is a new column C where if I iterate on column B and I find a 100 value then I want to forward fill until the column A has 100 value in it. Which will result in a column like this:

```<code>test_df['C'] = [100, 100, 100, 0, 0, 0, 0, 0, 100, 100, 100]
</code>```

This can be achieved by a simple iteration of all values with something like the following:

```<code>test_df['C'] = 0
is_valid_row = False
for index, row in test_df.iterrows():
    if (row['B'] == 100):
        is_valid_row = True
    if (is_valid_row == True and row['A'] == 100):
        row['C'] = 100
    else:
        is_valid_row = False
</code>```

I wanted to ask if there is any more efficient way to achieve the same result with pandas or numpy

答:
You can use the apply method.

```<code>def my_func(input):
   #do whatever

test_df['B'] = test_df['A'].apply(my_func)
</code>```

You obviously have to fill it in with your own code...

Body:
I Have the following Dataframe:

test_df['A'] = [100, 100, 100, 0, 0, 100, 100, 0, 100, 100, 100]
test_df['B'] = [100, 0, 0, 0, 0, 0, 0, 0, 100, 0, 0]

What I want to achieve is a new column C where if I iterate on column B and I find a 100 value then I want to forward fill until the column A has 100 value in it. Which will result in a column like this:

test_df['C'] = [100, 100, 100, 0, 0, 0, 0, 0, 100, 100, 100]

This can be achieved by a simple iteration of all values with something like the following:

test_df['C'] = 0
is_valid_row = False
for index, row in test_df.iterrows():
    if (row['B'] == 100):
        is_valid_row = True
    if (is_valid_row == True and row['A'] == 100):
        row['C'] = 100
    else:
        is_valid_row = False

I wanted to ask if there is any more efficient way to achieve the same result with pandas or numpy

Body:
You can use the apply method.

def my_func(input):
   #do whatever

test_df['B'] = test_df['A'].apply(my_func)

You obviously have to fill it in with your own code...


问:
Internal Action was not loaded Error: java.lang.ClassNotFoundException
I am trying to run an implementation a jason code that is using some Internal Actions. The interpreter is showing that it was not possible to find the "java" code of the internal action, as showed:

```<code>Server running on http://191.36.8.42:3272
[aslparser] [peleus.asl:29] warning: The internal action class for 'org.soton.peleus.act.plan(Goals)' was not loaded! Error:
java.lang.ClassNotFoundException: org.soton.peleus.act.plan
[aslparser] [peleus.asl:42] warning: The internal action class for 'org.soton.peleus.act.isTrue(H)' was not loaded! Error:
java.lang.ClassNotFoundException: org.soton.peleus.act.isTrue
[peleus] Could not finish intention: intention 1:  +des([on(b3,table),on(b2,b3),on(b1,b2)])[source(self)] <- ... org.soton.peleus.act.plan(Goals); !checkGoals(Goals); .print("Goals ",Goals," were satisfied") /
{Goals=[on(b3,table),on(b2,b3),on(b1,b2)]}Trigger: +des([on(b3,table),on(b2,b3),on(b1,b2)])[noenv,code(org.soton.peleus.act.plan([on(b3,table),on(b2,b3),on(b1,b2)])),code_line(29),code_src("peleus.asl"),error(action_failed),error_msg("no environment configured!"),source(self)]
[peleus] Adding belief clear(table)
</code>```

This mas2j file is as following:

```<code>MAS peleus {
    infrastructure: Centralised
    agents:
        peleus;
}
</code>```

Part of agent code (written by Felipe Meneguzzi) is showed bellow:

```<code>//The next line is line 28
+des(Goals) : true
     <- org.soton.peleus.act.plan(Goals);
         !checkGoals(Goals);
         .print("Goals ",Goals," were satisfied").

+!checkGoals([]) : true <- true.

//The next line is line 40
+!checkGoals([H|T]) : true
    <- .print("Checking ", H);
        org.soton.peleus.act.isTrue(H);
        !checkGoals(T).
</code>```

I guess it is about the folder structure, how to set up Jason to search for java files in specific locations?

The folders structure is like this:

```<code> Peleus\src\org\soton\peleus for java files
 Peleus\examples for mas2j and asl tested project
</code>```

答:
It all depends on how you are executing the application.

If you are using java, the CLASSPATH should be defined to include the missing classes.

if you are using jason script (that uses Ant), the .mas2j file should include the class path as well.

More on that in the FAQ. Notice that CLASSPATH is where .class files are found, not .java source code files. The error regards a missing class, not a missing source code.

Body:
I am trying to run an implementation a jason code that is using some Internal Actions. The interpreter is showing that it was not possible to find the "java" code of the internal action, as showed:

Server running on http://191.36.8.42:3272
[aslparser] [peleus.asl:29] warning: The internal action class for 'org.soton.peleus.act.plan(Goals)' was not loaded! Error:
java.lang.ClassNotFoundException: org.soton.peleus.act.plan
[aslparser] [peleus.asl:42] warning: The internal action class for 'org.soton.peleus.act.isTrue(H)' was not loaded! Error:
java.lang.ClassNotFoundException: org.soton.peleus.act.isTrue
[peleus] Could not finish intention: intention 1:  +des([on(b3,table),on(b2,b3),on(b1,b2)])[source(self)] <- ... org.soton.peleus.act.plan(Goals); !checkGoals(Goals); .print("Goals ",Goals," were satisfied") /
{Goals=[on(b3,table),on(b2,b3),on(b1,b2)]}Trigger: +des([on(b3,table),on(b2,b3),on(b1,b2)])[noenv,code(org.soton.peleus.act.plan([on(b3,table),on(b2,b3),on(b1,b2)])),code_line(29),code_src("peleus.asl"),error(action_failed),error_msg("no environment configured!"),source(self)]
[peleus] Adding belief clear(table)

This mas2j file is as following:

MAS peleus {
    infrastructure: Centralised
    agents:
        peleus;
}

Part of agent code (written by Felipe Meneguzzi) is showed bellow:

//The next line is line 28
+des(Goals) : true
     <- org.soton.peleus.act.plan(Goals);
         !checkGoals(Goals);
         .print("Goals ",Goals," were satisfied").

+!checkGoals([]) : true <- true.

//The next line is line 40
+!checkGoals([H|T]) : true
    <- .print("Checking ", H);
        org.soton.peleus.act.isTrue(H);
        !checkGoals(T).

I guess it is about the folder structure, how to set up Jason to search for java files in specific locations?

The folders structure is like this:

 Peleus\src\org\soton\peleus for java files
 Peleus\examples for mas2j and asl tested project