问:
onclick event for telerik radgrid row
I want to make an event occur when I click a row in my rad grid, I basically want to replace the 'editform' with an on click row event.

I've done a bit of searching online, but what works for others is having no impact for me.

The first piece of code is in ASP.NET, the second piece is in C#.

```<code><div id="rgUser" runat="server" style="width: 300px; float: left; margin-left: 15px;">
<telerik:RadGrid ID="rgEffectivePermissions" runat="server" AutoGenerateColumns="false"
    AllowSorting="True" Visible="true" AllowPaging="True"
    OnPageIndexChanged="rgEffectivePermissions_PageIndexChanged"
    OnItemDataBound="rgEffectivePermissions_ItemDataBound"
    OnItemCommand="rgEffectivePermissions_ItemCommand">
    <ClientSettings>
        <Resizing AllowColumnResize="true"></Resizing>
    </ClientSettings>
    <MasterTableView AllowSorting="true" DataKeyNames="SystemUserID">
        <CommandItemSettings ShowAddNewRecordButton="false" ShowRefreshButton="false" ShowExportToExcelButton="false" />
        <SortExpressions>
            <telerik:GridSortExpression FieldName="ClientCode" SortOrder="Ascending" />
        </SortExpressions>
        <Columns>
            <telerik:GridTemplateColumn UniqueName="UserName" DataField="UserName" HeaderText="User Name" SortExpression="UserName">
                <HeaderStyle HorizontalAlign="Center" />
                <ItemStyle HorizontalAlign="Center" VerticalAlign="Middle" Width="100" />
                <ItemTemplate>
                    <asp:Label ID="lblUsername" runat="server"><%# DataBinder.Eval(Container.DataItem, "UserName") %></asp:Label>
                    <asp:HoverMenuExtender ID="hmeSystemUserInfo" runat="server" TargetControlID="lblUsername" PopupControlID="pnlSystemUserInfo" PopupPosition="Bottom" />
                    <asp:Panel ID="pnlSystemUserInfo" runat="server" Style="visibility: hidden;">
                        <asp:Label runat="server" BackColor="Black" ForeColor="White" BorderColor="Black" Font-Bold="true" BorderStyle="Solid">
                        Last Updated By: <%# DataBinder.Eval(Container.DataItem, "LastUpdatedBy") %><br />
                        Last Update Date: <%# DataBinder.Eval(Container.DataItem, "LastUpdateDate") %><br />
                        Is Service Account: <%# DataBinder.Eval(Container.DataItem, "IsServiceAccount") %><br />
                        Is Account Manager: <%# DataBinder.Eval(Container.DataItem, "IsAccountManager") %>
                        </asp:Label>
                    </asp:Panel>
                </ItemTemplate>
            </telerik:GridTemplateColumn>
            <telerik:GridBoundColumn UniqueName="SystemUserID" DataField="SystemUserID" HeaderText="SystemUserID" SortExpression="SystemUserID" ReadOnly="true" Visible="true" Display="false">
                <HeaderStyle HorizontalAlign="Center" />
                <ItemStyle HorizontalAlign="Center" VerticalAlign="Middle" />
            </telerik:GridBoundColumn>
            <telerik:GridTemplateColumn UniqueName="EmailAddress" DataField="EmailAddress" HeaderText="Email Address" SortExpression="EmailAddress">
                <HeaderStyle HorizontalAlign="Center" />
                <ItemStyle HorizontalAlign="Center" VerticalAlign="Middle" Width="100" />
                <ItemTemplate>
                    <%# DataBinder.Eval(Container.DataItem, "EmailAddress") %>
                </ItemTemplate>
            </telerik:GridTemplateColumn>
            <telerik:GridButtonColumn ButtonType="ImageButton" UniqueName="EditButton" HeaderText="Edit"
                HeaderStyle-HorizontalAlign="Center" CommandName="EditForm" ImageUrl="~/Images/editPencil.png">
                <ItemStyle HorizontalAlign="Center" VerticalAlign="Middle" />
            </telerik:GridButtonColumn>
        </Columns>
    </MasterTableView>
</telerik:RadGrid>
</div>

protected void rgEffectivePermissions_ItemCommand(object source, GridCommandEventArgs e)
{
    switch (e.CommandName)
    {
        case ("EditForm"):
            {
                GridDataItem item = (GridDataItem)e.Item;
                String SystemUserID = item["SystemUserID"].Text;
                rgSecurityGroup.DataSource = AdminManager.GetClientGroupBySUSystemUserID(SystemUserID);
                rgSecurityGroup.DataBind();

                //int clientID = Convert.ToInt32(ddlClient1.SelectedValue);
                //rgProductGroup.DataSource = AdminManager.GetActivityGroupsByClientGroupID(41);
                //rgProductGroup.DataBind();
                break;
            }
    }
}
</code>```

答:
One option would be to use the OnRowClick client event of RadGrid to run a script which will fire a command of your choice, and then process it in the code behind.

<telerik:RadGrid ID="rgEffectivePermissions" runat="server"
    <ClientSettings>
        <ClientEvents OnRowClick="onRowClik" />
    </ClientSettings>
</telerik:RadGrid>

<telerik:RadCodeBlock ID="RadCodeBlock1" runat="server">

</telerik:RadCodeBlock>
```
<p>In the code behind:</p>
<pre class="lang-cs prettyprint-override"><code>protected void rgEffectivePermissions_ItemCommand(object sender, Telerik.Web.UI.GridCommandEventArgs e)
{
    if(e.CommandName == "MyCommand")
    {
        rgSecurityGroup.DataSource = GetGridSource(int.Parse(e.CommandArgument.ToString()));
        rgSecurityGroup.Rebind();
    }
}
</code>```

Another option would be to use the approach mentioned by aghilpro. Utilizing the OnSelectedIndexChanged server event of RadGrid.

<telerik:RadGrid ID="rgEffectivePermissions" runat="server"
    OnSelectedIndexChanged="rgEffectivePermissions_SelectedIndexChanged">
    <ClientSettings EnablePostBackOnRowClick="true">
        <Selecting AllowRowSelect="true" />
    </ClientSettings>
</telerik:RadGrid>
```
<p>Code behind:</p>
<pre class="lang-cs prettyprint-override"><code>protected void rgEffectivePermissions_SelectedIndexChanged(object sender, EventArgs e)
{

    if(((RadGrid)sender).SelectedItems.Count > 0)
    {
        rgSecurityGroup.DataSource = GetGridSource(int.Parse(((GridDataItem)((RadGrid)sender).SelectedItems[0])["SystemUserID"].Text));
        rgSecurityGroup.Rebind();
    }
}
</code>```

Title: onclick event for telerik radgrid row

Body:
I want to make an event occur when I click a row in my rad grid, I basically want to replace the 'editform' with an on click row event.

I've done a bit of searching online, but what works for others is having no impact for me.

The first piece of code is in ASP.NET, the second piece is in C#.

<telerik:RadGrid ID="rgEffectivePermissions" runat="server" AutoGenerateColumns="false"
    AllowSorting="True" Visible="true" AllowPaging="True"
    OnPageIndexChanged="rgEffectivePermissions_PageIndexChanged"
    OnItemDataBound="rgEffectivePermissions_ItemDataBound"
    OnItemCommand="rgEffectivePermissions_ItemCommand">
    <ClientSettings>
        <Resizing AllowColumnResize="true"></Resizing>
    </ClientSettings>
    <MasterTableView AllowSorting="true" DataKeyNames="SystemUserID">
        <CommandItemSettings ShowAddNewRecordButton="false" ShowRefreshButton="false" ShowExportToExcelButton="false" />
        <SortExpressions>
            <telerik:GridSortExpression FieldName="ClientCode" SortOrder="Ascending" />
        </SortExpressions>
        <Columns>
            <telerik:GridTemplateColumn UniqueName="UserName" DataField="UserName" HeaderText="User Name" SortExpression="UserName">
                <HeaderStyle HorizontalAlign="Center" />
                <ItemStyle HorizontalAlign="Center" VerticalAlign="Middle" Width="100" />
                <ItemTemplate>
                    <asp:Label ID="lblUsername" runat="server"><%# DataBinder.Eval(Container.DataItem, "UserName") %></asp:Label>
                    <asp:HoverMenuExtender ID="hmeSystemUserInfo" runat="server" TargetControlID="lblUsername" PopupControlID="pnlSystemUserInfo" PopupPosition="Bottom" />
                    <asp:Panel ID="pnlSystemUserInfo" runat="server" Style="visibility: hidden;">
                        <asp:Label runat="server" BackColor="Black" ForeColor="White" BorderColor="Black" Font-Bold="true" BorderStyle="Solid">
                        Last Updated By: <%# DataBinder.Eval(Container.DataItem, "LastUpdatedBy") %>

                        Last Update Date: <%# DataBinder.Eval(Container.DataItem, "LastUpdateDate") %>

                        Is Service Account: <%# DataBinder.Eval(Container.DataItem, "IsServiceAccount") %>

                        Is Account Manager: <%# DataBinder.Eval(Container.DataItem, "IsAccountManager") %>
                        </asp:Label>
                    </asp:Panel>
                </ItemTemplate>
            </telerik:GridTemplateColumn>
            <telerik:GridBoundColumn UniqueName="SystemUserID" DataField="SystemUserID" HeaderText="SystemUserID" SortExpression="SystemUserID" ReadOnly="true" Visible="true" Display="false">
                <HeaderStyle HorizontalAlign="Center" />
                <ItemStyle HorizontalAlign="Center" VerticalAlign="Middle" />
            </telerik:GridBoundColumn>
            <telerik:GridTemplateColumn UniqueName="EmailAddress" DataField="EmailAddress" HeaderText="Email Address" SortExpression="EmailAddress">
                <HeaderStyle HorizontalAlign="Center" />
                <ItemStyle HorizontalAlign="Center" VerticalAlign="Middle" Width="100" />
                <ItemTemplate>
                    <%# DataBinder.Eval(Container.DataItem, "EmailAddress") %>
                </ItemTemplate>
            </telerik:GridTemplateColumn>
            <telerik:GridButtonColumn ButtonType="ImageButton" UniqueName="EditButton" HeaderText="Edit"
                HeaderStyle-HorizontalAlign="Center" CommandName="EditForm" ImageUrl="~/Images/editPencil.png">
                <ItemStyle HorizontalAlign="Center" VerticalAlign="Middle" />
            </telerik:GridButtonColumn>
        </Columns>
    </MasterTableView>
</telerik:RadGrid>

protected void rgEffectivePermissions_ItemCommand(object source, GridCommandEventArgs e)
{
    switch (e.CommandName)
    {
        case ("EditForm"):
            {
                GridDataItem item = (GridDataItem)e.Item;
                String SystemUserID = item["SystemUserID"].Text;
                rgSecurityGroup.DataSource = AdminManager.GetClientGroupBySUSystemUserID(SystemUserID);
                rgSecurityGroup.DataBind();

                //int clientID = Convert.ToInt32(ddlClient1.SelectedValue);
                //rgProductGroup.DataSource = AdminManager.GetActivityGroupsByClientGroupID(41);
                //rgProductGroup.DataBind();
                break;
            }
    }
}

Body:
One option would be to use the OnRowClick client event of RadGrid to run a script which will fire a command of your choice, and then process it in the code behind.

<telerik:RadGrid ID="rgEffectivePermissions" runat="server"
    <ClientSettings>
        <ClientEvents OnRowClick="onRowClik" />
    </ClientSettings>
</telerik:RadGrid>

<telerik:RadCodeBlock ID="RadCodeBlock1" runat="server">
    <script>
        function onRowClik(sender, args) {
            $find("<%= rgEffectivePermissions.ClientID %>").get_masterTableView().fireCommand("MyCommand", args.get_item().getDataKeyValue("SystemUserID"));
        }
    </script>
</telerik:RadCodeBlock>

In the code behind:

protected void rgEffectivePermissions_ItemCommand(object sender, Telerik.Web.UI.GridCommandEventArgs e)
{
    if(e.CommandName == "MyCommand")
    {
        rgSecurityGroup.DataSource = GetGridSource(int.Parse(e.CommandArgument.ToString()));
        rgSecurityGroup.Rebind();
    }
}

Another option would be to use the approach mentioned by aghilpro. Utilizing the OnSelectedIndexChanged server event of RadGrid.

<telerik:RadGrid ID="rgEffectivePermissions" runat="server"
    OnSelectedIndexChanged="rgEffectivePermissions_SelectedIndexChanged">
    <ClientSettings EnablePostBackOnRowClick="true">
        <Selecting AllowRowSelect="true" />
    </ClientSettings>
</telerik:RadGrid>

Code behind:

protected void rgEffectivePermissions_SelectedIndexChanged(object sender, EventArgs e)
{

    if(((RadGrid)sender).SelectedItems.Count > 0)
    {
        rgSecurityGroup.DataSource = GetGridSource(int.Parse(((GridDataItem)((RadGrid)sender).SelectedItems[0])["SystemUserID"].Text));
        rgSecurityGroup.Rebind();
    }
}


来源: stackexchange

问:
procedure type date IN param postgresql
I want to know how I can enter a parameter within a function type date since at the time of doing so, the following error

report_soat(date, date)

Undefined function: 7 ERROR: operator does not exist: date >= character varying LINE 6: BETWEEN fecha_in AND fecha_out ^ HINT: No operator matches the given name and argument type(s). You might need to add explicit type casts. QUERY: SELECT soats.status AS "estado", soats.placa AS "placa" FROM soats where soats.task_id IS NOT NULL and date(soats.created) BETWEEN fecha_in AND fecha_out CONTEXT: PL/pgSQL function report_soat(character varying,character varying) line 2 at RETURN QUERY

```<code>SELECT
    soats.status AS "estado",
    soats.placa AS "placa"
FROM soats
where soats.task_id IS NOT NULL and date(soats.created)
BETWEEN start_date AND end_date;
</code>```

IN start_date date, IN end_date date, OUT status varchar, OUT placa
  varchar

ContentLicense: CC BY-SA 3.0

Title: procedure type date IN param postgresql

Body:
I want to know how I can enter a parameter within a function type date since at the time of doing so, the following error

report_soat(date, date)

Undefined function: 7 ERROR: operator does not exist: date >= character varying LINE 6: BETWEEN fecha_in AND fecha_out ^ HINT: No operator matches the given name and argument type(s). You might need to add explicit type casts. QUERY: SELECT soats.status AS "estado", soats.placa AS "placa" FROM soats where soats.task_id IS NOT NULL and date(soats.created) BETWEEN fecha_in AND fecha_out CONTEXT: PL/pgSQL function report_soat(character varying,character varying) line 2 at RETURN QUERY

SELECT
    soats.status AS "estado",
    soats.placa AS "placa"
FROM soats
where soats.task_id IS NOT NULL and date(soats.created)
BETWEEN start_date AND end_date;

IN start_date date, IN end_date date, OUT status varchar, OUT placa
  varchar

Body:
Try...

report_soat('2017-11-14'::date, '2017-11-14'::date)


问:
How to run several boxes with Vagrant?
I need to run several boxes with Vagrant.

Is there a way to do that?

These don't relate one to another in any way, they can be thought as different environments using for test so it seems that multi-machine setup has nothing to do with this.

答:
Copying the directory holding Vagrantfile to a new place and spinning up the new machine there is the most straight forward way, if machines are not co-operating.

However, you may not want to copy/paste provisioning scripts for VCS tracking/backtracking purposes. Keep all your scripts in a folder, ex. dev, and put your Vagrantfile under numbered folders under dev, ex. dev/10. When you create a newer version, ex. dev/11 and not need the older one, you may just delete it. And refer to the common provisioning scripts using relative path:

```<code>config.vm.provision "shell", path: "../provisioner.sh"
</code>```

Title: How to run several boxes with Vagrant?

Body:
Copying the directory holding Vagrantfile to a new place and spinning up the new machine there is the most straight forward way, if machines are not co-operating.

However, you may not want to copy/paste provisioning scripts for VCS tracking/backtracking purposes. Keep all your scripts in a folder, ex. dev, and put your Vagrantfile under numbered folders under dev, ex. dev/10. When you create a newer version, ex. dev/11 and not need the older one, you may just delete it. And refer to the common provisioning scripts using relative path:

config.vm.provision "shell", path: "../provisioner.sh"


问:
Error in preprocessing with tm package in R
I am trying to do some preprocessing with tm package in R. I wrote the lines below:

```<code>corpus <- Corpus(VectorSource(Data))
corpus <- tm_map(corpus , asPlain)
corpus <- tmMap(corpus , removeSignature)
</code>```

As you can see, I tried both 'tm_map' and 'tmMap'. But I faced these errors each time:

```<code>Error in match.fun(FUN) : object 'asPlain' not found
Error: could not find function "tmMap"
</code>```

Could you please help me to solve this error?

答:
The tm package changed the function calls and some of those methods are no longer available.

Here is some sample code with the new functions.

```<code>require(tm)
text_corpus <- VCorpus( DirSource("20ng_train/sci.electronics"))
corpus_clean <- tm_map(text_corpus, content_transformer(tolower))
corpus_clean <- tm_map(corpus_clean, removeNumbers)
corpus_clean <- tm_map(corpus_clean, removeWords, stopwords())
corpus_clean <- tm_map(corpus_clean, removePunctuation)
corpus_clean <- tm_map(corpus_clean, stemDocument)
corpus_clean <- tm_map(corpus_clean, stripWhitespace)
</code>```

Body:
I am trying to do some preprocessing with tm package in R. I wrote the lines below:

corpus <- Corpus(VectorSource(Data))
corpus <- tm_map(corpus , asPlain)
corpus <- tmMap(corpus , removeSignature)

As you can see, I tried both 'tm_map' and 'tmMap'. But I faced these errors each time:

Error in match.fun(FUN) : object 'asPlain' not found
Error: could not find function "tmMap"

Could you please help me to solve this error?

Body:
The tm package changed the function calls and some of those methods are no longer available.

Here is some sample code with the new functions.

require(tm)
text_corpus <- VCorpus( DirSource("20ng_train/sci.electronics"))
corpus_clean <- tm_map(text_corpus, content_transformer(tolower))
corpus_clean <- tm_map(corpus_clean, removeNumbers)
corpus_clean <- tm_map(corpus_clean, removeWords, stopwords())
corpus_clean <- tm_map(corpus_clean, removePunctuation)
corpus_clean <- tm_map(corpus_clean, stemDocument)
corpus_clean <- tm_map(corpus_clean, stripWhitespace)


问:
In C, I'm unable to copy a single element of an array of character strings to another string
I have a string "prompt" that holds a string of characters. The user must be able to change the prompt with user input, which I've collected and separated (using whitespace as a delimiter) into an array of char strings (tokens).

For example, assume:

```<code>char **tokens[2] = {"setprompt", "newprompt"};
char *prompt = "oldprompt";

if(strcmp(tokens[0], "setprompt") == 0)
{
strcpy(prompt, tokens[1]);
}
</code>```

The strcmp() function works perfectly fine, however when it reaches strcpy(), the element in tokens[1] (which is the string "newprompt") isn't copied into the string prompt. This is my problem.

I've tried troubleshooting, in addition to using strncpy() instead but I think there's an issue somewhere with my declarations of each variable/pointer. Any assistance or ideas would be great.

Note: in my actual program, the tokens array doesn't have a definitive size of 2. This example is modified for simplicity. Thanks!

答:
Your issue is this line:

```<code>char *prompt = "oldprompt";
</code>```

It points to constant memory and cannot be modified (the way it is defined).  Consider leaving it read-only and creating your own buffer instead for copying and modifying  Something like:

```<code>#define MAX_STRING_SIZE 255

char *tokens[2] = {"setprompt", "newprompt"};
char *prompt = "oldprompt";
char myBuffer[MAX_STRING_SIZE];

strcpy(myBuffer, prompt );

if(strcmp(tokens[0], "setprompt") == 0)
{
    strcpy(myBuffer, tokens[1]);
}
</code>```

Body:
I have a string "prompt" that holds a string of characters. The user must be able to change the prompt with user input, which I've collected and separated (using whitespace as a delimiter) into an array of char strings (tokens).

For example, assume:

char **tokens[2] = {"setprompt", "newprompt"};
char *prompt = "oldprompt";

if(strcmp(tokens[0], "setprompt") == 0)
{
strcpy(prompt, tokens[1]);
}

The strcmp() function works perfectly fine, however when it reaches strcpy(), the element in tokens[1] (which is the string "newprompt") isn't copied into the string prompt. This is my problem.

I've tried troubleshooting, in addition to using strncpy() instead but I think there's an issue somewhere with my declarations of each variable/pointer. Any assistance or ideas would be great.

Note: in my actual program, the tokens array doesn't have a definitive size of 2. This example is modified for simplicity. Thanks!

Body:
Your issue is this line:

char *prompt = "oldprompt";

It points to constant memory and cannot be modified (the way it is defined).  Consider leaving it read-only and creating your own buffer instead for copying and modifying  Something like:

#define MAX_STRING_SIZE 255

char *tokens[2] = {"setprompt", "newprompt"};
char *prompt = "oldprompt";
char myBuffer[MAX_STRING_SIZE];

strcpy(myBuffer, prompt );

if(strcmp(tokens[0], "setprompt") == 0)
{
    strcpy(myBuffer, tokens[1]);
}


问:
Get inner html of the component as a variable in vuejs 2
Say I have a vuejs component called child-component which is added to a parent component as follows.

```<code><child-component>
  <div>Hello</div>
</child-component>
</code>```

N.B. this is not the template of the child component. This is how the child component is added to the parent.

How can I get the innerHTML, i.e.
Hello
 in the child component as a string?

答:
Inside the component, child-component, the HTML would be available in the mounted lifecycle handler as this.$el.innerHTML. The parsed vnodes would be available from this.$slots.default.

console.clear()

Vue.component("child-component",{
  template: `<div><slot/></div>`,
  mounted(){
    console.log("HTML", this.$el.innerHTML)
  }
})

new Vue({
  el: "#app"
})```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.3/vue.min.js"></script>
<div id="app">
  <child-component>
    <div>Hello</div>
  </child-component>
</div></code>```

Body:
Say I have a vuejs component called child-component which is added to a parent component as follows.

<child-component>

Hello

</child-component>

N.B. this is not the template of the child component. This is how the child component is added to the parent.

How can I get the innerHTML, i.e.
Hello
 in the child component as a string?

Body:
Inside the component, child-component, the HTML would be available in the mounted lifecycle handler as this.$el.innerHTML. The parsed vnodes would be available from this.$slots.default.

console.clear()

Vue.component("child-component",{
  template: `<div><slot/></div>`,
  mounted(){
    console.log("HTML", this.$el.innerHTML)
  }
})

new Vue({
  el: "#app"
})

<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.3/vue.min.js"></script>
<div id="app">
  <child-component>
    <div>Hello</div>
  </child-component>
</div>


问:
How do I reference a python file nested within a nested package in Python 3?
Trying to understand how to properly use another module when its nested within a folder. I tried implementing a package using the __init__.py as documented in the Packages section of Modules. I am not finding much success. Here is the file structure.

For example, I want to be able to reference a class contained within credentials.py in propeller.py. Another use case, I want to reference a function from within base.py in propeller.py. Looking forward to hearing how other approach this. Thanks!

答: It depends. Is the main module 'the_machine' in your Module Search Path?  If so, you should be able to import the_machine.credentials. Otherwise, either add it to your sys.path or  import it directly using the path..


问:
Removing supplementary characters from a Java string
I have a Java string that contains supplementary characters (characters in the Unicode standard whose code points are above U+FFFF). These characters could for example be emojis. I want to remove those characters from the string, i.e. replace them with the empty string "".

How do I remove supplementary characters from a string?

How do I remove characters from an arbitrary code point range? (For example all characters in the range 1F000–1FFFF)?

答:
Java strings are UTF-16 encoded.  The String type has a codePointAt() method for retrieving a decoded codepoint at a given char (codeunit) index.

So, you can do something like this, for instance:

```<code>String removeSupplementaryChars(String s)
{
    int len = s.length();
    if (len == 0)
        return "";

    StringBuilder sb = new StringBuilder(len);
    int i = 0;

    do
    {
        if (s.codePointAt(i) <= 0xFFFF)
            sb.append(s.charAt[i]);

        i = s.offsetByCodePoints(i, 1);
    }
    while (i < len);

    return sb.toString();
}
</code>```

Or this:

```<code>String removeCodepointsinRange(String s, int lower, int upper)
{
    int len = s.length();
    if (len == 0)
        return "";

    StringBuilder sb = new StringBuilder(len);
    int i = 0;

    do
    {
        int cp = s.codePointAt(i);

        if ((cp < lower) || (cp > upper))
            sb.appendCodePoint(cp);

        i = s.offsetByCodePoints(i, 1);
    }
    while (i < len);

    return sb.toString();
}
</code>```

Body:
Java strings are UTF-16 encoded.  The String type has a codePointAt() method for retrieving a decoded codepoint at a given char (codeunit) index.

So, you can do something like this, for instance:

String removeSupplementaryChars(String s)
{
    int len = s.length();
    if (len == 0)
        return "";

    StringBuilder sb = new StringBuilder(len);
    int i = 0;

    do
    {
        if (s.codePointAt(i) <= 0xFFFF)
            sb.append(s.charAt[i]);

        i = s.offsetByCodePoints(i, 1);
    }
    while (i < len);

    return sb.toString();
}

Or this:

String removeCodepointsinRange(String s, int lower, int upper)
{
    int len = s.length();
    if (len == 0)
        return "";

    StringBuilder sb = new StringBuilder(len);
    int i = 0;

    do
    {
        int cp = s.codePointAt(i);

        if ((cp < lower) || (cp > upper))
            sb.appendCodePoint(cp);

        i = s.offsetByCodePoints(i, 1);
    }
    while (i < len);

    return sb.toString();
}


问:
Three.js - change camera POV on click
Some project background:

I have a Sprite particle field that is randomly generated. The camera is located at position 0, 0, 0. The particle field is all around the camera. I'm using Raycaster to be able to select the particle that is clicked on and change it's color. Once clicked I would like the camera to focus on this particle. I'm also attempting to use Tween to glide the particle into view.

I've attempted several different methods and none of them work. They are described here:

A traditional lookAt method that used Raycaster to pick up the intersect point from clicking.

var raycaster = new THREE.Raycaster();
raycaster.setFromCamera(mouse, this.camera);
var intersects = raycaster.intersectObjects( this.starfield.children );
this.camera.lookAt(intersects[0].object.position)

A distanceTo method where the distance between the camera and the intersect coordinates is used to move the camera. This only moves the camera along the z plane. It wont actually change its POV.

```<code>var cameraPosition = new THREE.Vector3(this.camera.position.x, this.camera.position.y, this.camera.position.z);

var intersectPosition = new THREE.Vector3(intersects[0].object.position.x, intersects[0].object.position.y , intersects[0].object.position.z );

var zoomPos = intersectPosition.distanceTo( cameraPosition );

const newCameraPosition = cameraPosition.addVectors(this.camera.position, vector.setLength(zoomPos));
</code>```

I calculated the angle of rotation for each X, Y, and Z axis via tan and cos equations. I then attempted to rotate the camera by those degrees. I even tried converting them to radians to see if that would make a difference with the rotation method. It didnt :(

I don't know what else to do. At this stage I'm completely open to a different approach as long as I get this camera working. I'm very stuck,
any help would be greatly appreciated!

答:
Instead of using

```<code>intersects[0].object.position
</code>```

try using

```<code>intersects[0].point
</code>```

.point is the world space position of the hit.

.objectis the object the triangle belongs to. .object.position is just the origin of that object, in this case the particle system. The particle positions themselves are relative to this origin.

Title: Three.js - change camera POV on click

Body:
Some project background:

I have a Sprite particle field that is randomly generated. The camera is located at position 0, 0, 0. The particle field is all around the camera. I'm using Raycaster to be able to select the particle that is clicked on and change it's color. Once clicked I would like the camera to focus on this particle. I'm also attempting to use Tween to glide the particle into view.

I've attempted several different methods and none of them work. They are described here:

A traditional lookAt method that used Raycaster to pick up the intersect point from clicking.

var raycaster = new THREE.Raycaster();
raycaster.setFromCamera(mouse, this.camera);
var intersects = raycaster.intersectObjects( this.starfield.children );
this.camera.lookAt(intersects[0].object.position)

A distanceTo method where the distance between the camera and the intersect coordinates is used to move the camera. This only moves the camera along the z plane. It wont actually change its POV.

var cameraPosition = new THREE.Vector3(this.camera.position.x, this.camera.position.y, this.camera.position.z);

var intersectPosition = new THREE.Vector3(intersects[0].object.position.x, intersects[0].object.position.y , intersects[0].object.position.z );

var zoomPos = intersectPosition.distanceTo( cameraPosition );

const newCameraPosition = cameraPosition.addVectors(this.camera.position, vector.setLength(zoomPos));

I calculated the angle of rotation for each X, Y, and Z axis via tan and cos equations. I then attempted to rotate the camera by those degrees. I even tried converting them to radians to see if that would make a difference with the rotation method. It didnt :(

I don't know what else to do. At this stage I'm completely open to a different approach as long as I get this camera working. I'm very stuck,
any help would be greatly appreciated!

Body:
Instead of using

intersects[0].object.position

try using

intersects[0].point

.point is the world space position of the hit.

.objectis the object the triangle belongs to. .object.position is just the origin of that object, in this case the particle system. The particle positions themselves are relative to this origin.


问:
Array filling mistake
I can't understand what's wrong is in my program. I have such input data:

```<code>01000
11110
01000
</code>```

I want to save it into: vector< vector<int> > matrix;

```<code>vector< vector<int> > fillMatrix(vector< vector<int> > matrix, int height, int width, ifstream &read)
{
    // Make 2d-array [matrix]
    matrix.resize(width);
    for (int i=0; i < width; ++i)
        matrix[i].resize(height);

    // Fill it up with data
    for (int i=0; i < height; ++i)
    {
        std::string tempLine;
        std::getline(read, tempLine);
        for (int j=0; j < tempLine.length(); ++j)
        {
            // This shows right information
            //std::cout << tempLine[j] << "  -  " << (int)(tempLine[j] - '0') << "\n";
            matrix[i][j] = (int)(tempLine[j] - '0');
        }
    }

    return matrix;
}

matrix = fillMatrix(matrix, 3, 5, ifstreamHandle);
</code>```

And now, function which shows the matrix:

```<code>void showMatrix(vector< vector<int> > matrix, int width, int height)
{
    // Show the matrix
    for (int i=0; i < height; ++i)
    {
        for (int j=0; j < width; ++j)
        {
            std::cout << matrix[i][j];
        }
        std::cout << "\n";
    }
}

showMatrix(matrix, 5, 3);
</code>```

And the result of showMatrix is:

```<code>01000
11100
01000
</code>```

There are missed '1' in second row. What's wrong?

答:
First of all you are not consistent in your code

```<code>for (int i=0; i < width; ++i)
...
for (int i=0; i < height; ++i)
</code>```

so you are creating matrix like matrix[i].resize(3) for i = 0..4, but write into it using matrix[i][j] where i = 0..2 and j=0..4

ContentLicense: CC BY-SA 2.5

Title: Array filling mistake

Body:
I can't understand what's wrong is in my program. I have such input data:

01000
11110
01000

I want to save it into: vector< vector<int> > matrix;

vector< vector<int> > fillMatrix(vector< vector<int> > matrix, int height, int width, ifstream &read)
{
    // Make 2d-array [matrix]
    matrix.resize(width);
    for (int i=0; i < width; ++i)
        matrix[i].resize(height);

    // Fill it up with data
    for (int i=0; i < height; ++i)
    {
        std::string tempLine;
        std::getline(read, tempLine);
        for (int j=0; j < tempLine.length(); ++j)
        {
            // This shows right information
            //std::cout << tempLine[j] << "  -  " << (int)(tempLine[j] - '0') << "\n";
            matrix[i][j] = (int)(tempLine[j] - '0');
        }
    }

    return matrix;
}

matrix = fillMatrix(matrix, 3, 5, ifstreamHandle);

And now, function which shows the matrix:

void showMatrix(vector< vector<int> > matrix, int width, int height)
{
    // Show the matrix
    for (int i=0; i < height; ++i)
    {
        for (int j=0; j < width; ++j)
        {
            std::cout << matrix[i][j];
        }
        std::cout << "\n";
    }
}

showMatrix(matrix, 5, 3);

And the result of showMatrix is:

01000
11100
01000

There are missed '1' in second row. What's wrong?

Body:
First of all you are not consistent in your code

for (int i=0; i < width; ++i)
...
for (int i=0; i < height; ++i)

so you are creating matrix like matrix[i].resize(3) for i = 0..4, but write into it using matrix[i][j] where i = 0..2 and j=0..4


问:
I'm having trouble understanding this for loop and what its returning
```<code>def double_char(str):
    result = ''
    for char in str:
        result += char + char
    return result
</code>```

this is the function, and when i call it, say:

```<code>double_char(dog)
</code>```

it returns: 'ddoogg'

but on line 4 it's saying result = result + char + char wouldn't that yield ''dogdog? I'm really confused and I think I just dont understand the basics of for loops

答:
As you have mentioned, you are passing string 'dog', implies str:='dog'

Initialised,
result=''

This will initialise result to empty string once.

```<code>for char in str:
</code>```

This loop will iterate through every char.

```<code>result += char + char
</code>```

when you iterate through the loop. char will represent  'd','o','g' respectively at each iteration.

```<code>iteration 1:
result=''
char + char := 'd'+'d'
</code>```

exiting from iteration : result ='dd'

```<code>iteration 2:
result='dd'
char + char := 'o'+'o'
</code>```

exiting from iteration : result ='dd'

```<code>iteration 3:
result='ddoo'
char + char := 'g'+'g'
</code>```

exiting from iteration : result ='ddoogg'

loop finished

if you want to return 'dogdog'

simply do:

```<code>def double_char(str):
    return str+str
</code>```

Body:
def double_char(str):
    result = ''
    for char in str:
        result += char + char
    return result

this is the function, and when i call it, say:

double_char(dog)

it returns: 'ddoogg'

but on line 4 it's saying result = result + char + char wouldn't that yield ''dogdog? I'm really confused and I think I just dont understand the basics of for loops

Body:
As you have mentioned, you are passing string 'dog', implies str:='dog'

Initialised,
result=''

This will initialise result to empty string once.

for char in str:

This loop will iterate through every char.

result += char + char

when you iterate through the loop. char will represent  'd','o','g' respectively at each iteration.

iteration 1:
result=''
char + char := 'd'+'d'

exiting from iteration : result ='dd'

iteration 2:
result='dd'
char + char := 'o'+'o'

exiting from iteration : result ='dd'

iteration 3:
result='ddoo'
char + char := 'g'+'g'

exiting from iteration : result ='ddoogg'

loop finished

if you want to return 'dogdog'

simply do:

def double_char(str):
    return str+str


问:
Does C correctly handle sizeof(...) and sizeof ... in this case?
In the following code, are the functions test and test2 equivalent?

```<code>typedef int rofl;

void test(void) {
    rofl * rofl = malloc(sizeof(rofl)); // Is the final rofl here the TYPE?
}

void test2(void) {
    rofl * rofl = malloc(sizeof *rofl); // Is the final rofl here the VARIABLE?
}
</code>```

In other words:

Does rofl in sizeof(rofl) correctly pick the rofl type because of the parentheses?

Does rofl in sizeof *rofl correctly pick the rofl variable because of a lack of parentheses?

Note: This is a silly-looking example, but it can actually happen in practice that you have a type name that's the same as a variable name. Hence the question.

答:
In both cases, the last rofl  is the variable name. A variable name is in scope as soon as it appears; and for the remainder of the current scope, that identifier in an ordinary context(*) always means the variable name.

The sizeof operator does not introduce any special cases for name lookup. In fact, there are no language constructs that will use the hidden meaning of an identifier.

In practice it is a good idea to not use the same identifier for a type and a variable name.

(*) There are three special contexts for identifiers: label names, structure tags, and structure members. But in all other contexts, all identifiers share a common name space: there are no distinct identifier name spaces for type names versus variable names versus function names etc.

Here is a contrived example:

```<code>typedef int A;      // "A" declared as ordinary identifier, meaning a type name

struct A { A A; };  // "A" declared as struct tag and member name -- OK as these are three different name spaces. Member type is "int"

A main()            // int main() - ordinary context
{
    struct A A();   // "A" declared as ordinary identifier, meaning a function name; hides line 1's A
    // A C;         // Would be error: ordinary A is a function now, not a typedef for int
    struct A B;     // OK, struct tags have separate name space
    A:+A().A;       // OK, labels and struct members have separate name space, calls function
    goto A;         // OK, label name space
}
</code>```

Body:
In the following code, are the functions test and test2 equivalent?

typedef int rofl;

void test(void) {
    rofl * rofl = malloc(sizeof(rofl)); // Is the final rofl here the TYPE?
}

void test2(void) {
    rofl * rofl = malloc(sizeof *rofl); // Is the final rofl here the VARIABLE?
}

In other words:

Does rofl in sizeof(rofl) correctly pick the rofl type because of the parentheses?

Does rofl in sizeof *rofl correctly pick the rofl variable because of a lack of parentheses?

Note: This is a silly-looking example, but it can actually happen in practice that you have a type name that's the same as a variable name. Hence the question.

Body:
In both cases, the last rofl  is the variable name. A variable name is in scope as soon as it appears; and for the remainder of the current scope, that identifier in an ordinary context(*) always means the variable name.

The sizeof operator does not introduce any special cases for name lookup. In fact, there are no language constructs that will use the hidden meaning of an identifier.

In practice it is a good idea to not use the same identifier for a type and a variable name.

(*) There are three special contexts for identifiers: label names, structure tags, and structure members. But in all other contexts, all identifiers share a common name space: there are no distinct identifier name spaces for type names versus variable names versus function names etc.

Here is a contrived example:

typedef int A;      // "A" declared as ordinary identifier, meaning a type name

struct A { A A; };  // "A" declared as struct tag and member name -- OK as these are three different name spaces. Member type is "int"

A main()            // int main() - ordinary context
{
    struct A A();   // "A" declared as ordinary identifier, meaning a function name; hides line 1's A
    // A C;         // Would be error: ordinary A is a function now, not a typedef for int
    struct A B;     // OK, struct tags have separate name space
    A:+A().A;       // OK, labels and struct members have separate name space, calls function
    goto A;         // OK, label name space
}


问:
Is there a way to update a trained machine learning model in Weka while making predictions for new data (Java)?
I have implemented  classification algorithms using machine learning using Weka Java. I would like to deploy the trained model on RasberryPi to test.. I want then the trained model get updated every time when it receive the new data and make predictions?? Is there a way to do that with weka Java ?? Could you share your thoughts how to proceed??

Thanks in Advance

答:
Well, I'm bored so I'll try to help since this is a tough and common problem as more and more people integrate machine learning into their normal dev processes...even though this is a bit broad for SO.

I would ask yourself a few questions:

How often does this particular model need to be refreshed in order to maintain relevancy to the task it is performing for you?

Typically, retraining a classification model when every new row of data is written to the place you get training data from would be insane. So I would think about that.

How long does it take to build the model, and how long WILL it take to build it as more and more training data piles up?

Where do you keep your training data, and how do you label it so fast that you would be able to retrain the model every time you get new data? Or is it not a typical supervised classification model?

I ask this because, from what i've done, the data you train with will go into some kind of database, or file system or whatever, and if the Java code you use to build the model reads from a standard location on disk or a DB, rebuilding the model isn't all that hard...it can be a CRON job or a jenkins job or whatever to rebuild the model (read data, build model, write model to disk, deploy model). You'll want the process that uses the model to be able to read it from configuration, and you'll want the code that builds the model to be able to configure the location of the training data corpus. a simple Java properties file might suffice for this piece.

Will you need to reprocess all your data every time you build a new model? This is also a common problem, sometimes solved by tagging each classified item with the version of the model that you used to classify it. In this case, you can set up a "reprocessing pipeline" that looks for old classification results and pumps them through the new model. This opens up a can of worms depending on how you do you data (dedupe strategy, history keeping, etc) so think about that one.

I don't know anything at all about Raspberry pi, but that part doesn't seem relevant since this is really a software architecture problem. One way I've done the automagic deployment piece is to use Jenkins and something like PUPPET to push/pull the model to machine it will be used on. In my past I've put NLP models on to a Hadoop and Storm cluster with puppet and the java code picks them up from a static NFS mount that is on all nodes. etc.....

HTH


问:
How to increment a number in a string?
I want to increment a number in a string.

My model:

```<code>public partial class updown
{
    public int id { get; set; }
    public string number { get; set; }
}
</code>```

My controller:

```<code>[HttpPost]
public ActionResult Index(updown viewModel)
{
    var lastPO = db.updowns
                   .OrderByDescending(o => o.number)
                   .Select(m => m.number)
                   .FirstOrDefault() ?? "00001";

    item.number = lastPO++; // I get an error on this line
    db.updowns.Add(item);
    db.SaveChanges();

    return View(viewModel);
}
</code>```

The error:

Operator '++' cannot be applied to operand of type 'string'

Expected result:

```<code>item.number // "00002"
</code>```

Update

Based on the now-deleted comments, I have:

```<code>[HttpPost]
public ActionResult Index(updown viewModel)
{
    var s = db.updowns
              .OrderByDescending(o => o.number)
              .Select(m => m.number)
              .FirstOrDefault() ?? "00001/S2";

    var lastPO = Convert.ToInt32(s.Substring(s.Length - 5 - 3, s.Length - 3)); // *
    item.number = "EMOC-" + (++lastPO).ToString("00000");
    db.updowns.Add(item);
    db.SaveChanges();

    return View(viewModel);
}
</code>```

Expected result:

```<code>item.number // "EMOC-00002/S2"
</code>```

But I get an error on the line marked // * when I run it the second time.

答:
I tried doing a little bit of your code. It seems fine

i think the problem lies in here

```<code>var s = db.updowns
              .OrderByDescending(o => o.number)
              .Select(m => m.number)
              .FirstOrDefault() ?? "00001/S2";
</code>```

the ?? "00001/S2" might be triggering the error. try doing a break point in var s ... and see if all of s.number has value or has a correct convertible value (there could be just letters which can't be converted)

Title: How to increment a number in a string?

Body:
I want to increment a number in a string.

My model:

public partial class updown
{
    public int id { get; set; }
    public string number { get; set; }
}

My controller:

[HttpPost]
public ActionResult Index(updown viewModel)
{
    var lastPO = db.updowns
                   .OrderByDescending(o => o.number)
                   .Select(m => m.number)
                   .FirstOrDefault() ?? "00001";

    item.number = lastPO++; // I get an error on this line
    db.updowns.Add(item);
    db.SaveChanges();

    return View(viewModel);
}

The error:

Operator '++' cannot be applied to operand of type 'string'

Expected result:

item.number // "00002"

Update

Based on the now-deleted comments, I have:

[HttpPost]
public ActionResult Index(updown viewModel)
{
    var s = db.updowns
              .OrderByDescending(o => o.number)
              .Select(m => m.number)
              .FirstOrDefault() ?? "00001/S2";

    var lastPO = Convert.ToInt32(s.Substring(s.Length - 5 - 3, s.Length - 3)); // *
    item.number = "EMOC-" + (++lastPO).ToString("00000");
    db.updowns.Add(item);
    db.SaveChanges();

    return View(viewModel);
}

Expected result:

item.number // "EMOC-00002/S2"

But I get an error on the line marked // * when I run it the second time.

Body:
I tried doing a little bit of your code. It seems fine

i think the problem lies in here

var s = db.updowns
              .OrderByDescending(o => o.number)
              .Select(m => m.number)
              .FirstOrDefault() ?? "00001/S2";

the ?? "00001/S2" might be triggering the error. try doing a break point in var s ... and see if all of s.number has value or has a correct convertible value (there could be just letters which can't be converted)


问:
c++ fatal error c1001:an internal error has occurred in the compiler
I have to mix C++ with dot net C++. I see this error. I have already Googled a lot. Tried many methods. Still not working. Any help appreciated.

```<code>int _tmain(int argc, _TCHAR* argv[])
    {

        typedef struct
        {
            char all_srting[200];
            char name_1[100];
            char Max_1[100];
            char Min_1[100];
        }power_line_name;

        int numLines;
        StreamReader ^ sr1=File::OpenText("powerline.txt");
        while(sr1->ReadLine())
        {
            numLines++;
        }
        power_line_name* power_list=new power_line_name[numLines];

        StreamReader ^ sr=File::OpenText("powerline.txt");
        array<System::String ^> ^power_line;
        array<System::String ^> ^power_line_nospace;
        array<System::String ^> ^d_line;
        array<System::String ^> ^all_powrline_string;
        int i=0;
        char nstring[100];

        try
        {
            String^ s="";
            while (s=sr->ReadLine())
            {
                power_line=s->Split(':');
                power_line_nospace=power_line[1]->Split(' ');
                d_line=power_line_nospace[1]->Split('|');
                for(int a=0;a<d_line->Length;a++)
                {
                    pin_ptr<const wchar_t> wch = PtrToStringChars(d_line[a]);
                    size_t origsize = wcslen(wch) + 1;
                    size_t convertedChars = 0;
                    if(a==0)
                    {
                        wcstombs_s(&convertedChars, power_list[i].name_1, origsize, wch, _TRUNCATE);
                        //strcat_s(power_list[i].name_1, " (char *)");
                    }
                    if(a==1)
                    {
                        wcstombs_s(&convertedChars, power_list[i].Max_1, origsize, wch, _TRUNCATE);
                        //strcat_s(power_list[i].Max_1, " (char *)");
                    }
                    if(a==2)
                    {
                        wcstombs_s(&convertedChars, power_list[i].Min_1, origsize, wch, _TRUNCATE);
                        //strcat_s(power_list[i].Min_1, " (char *)");
                    }

                }
                i++;

            }

            Console::WriteLine(s);
        }
        finally
        {
            if(sr)
                delete (IDisposable^)(sr);
        }

        return 0;
    }
</code>```

I get this message: power_line=s->Split(':');<-----fatal error c1001:an internal error has occurred in the compiler

and

error fatal error lnk1000 internal error during image::bulidimage

what can i do?

答:
I met the same error when use boost::iequals to compare two std::string like below:

```<code>std::for_each(bds.begin(),bds.end(),[&](std::string str){if(boost::iequals("must",str)) printf("matched\n");});
</code>```

i compiled this code with vs 2010 and boost version 1.58.

To solved the error just replace the std::for_each() with for().so i guess the compile r and boosts lib conflicted.

Body:
I have to mix C++ with dot net C++. I see this error. I have already Googled a lot. Tried many methods. Still not working. Any help appreciated.

int _tmain(int argc, _TCHAR* argv[])
    {

        typedef struct
        {
            char all_srting[200];
            char name_1[100];
            char Max_1[100];
            char Min_1[100];
        }power_line_name;

        int numLines;
        StreamReader ^ sr1=File::OpenText("powerline.txt");
        while(sr1->ReadLine())
        {
            numLines++;
        }
        power_line_name* power_list=new power_line_name[numLines];

        StreamReader ^ sr=File::OpenText("powerline.txt");
        array<System::String ^> ^power_line;
        array<System::String ^> ^power_line_nospace;
        array<System::String ^> ^d_line;
        array<System::String ^> ^all_powrline_string;
        int i=0;
        char nstring[100];

        try
        {
            String^ s="";
            while (s=sr->ReadLine())
            {
                power_line=s->Split(':');
                power_line_nospace=power_line[1]->Split(' ');
                d_line=power_line_nospace[1]->Split('|');
                for(int a=0;a<d_line->Length;a++)
                {
                    pin_ptr<const wchar_t> wch = PtrToStringChars(d_line[a]);
                    size_t origsize = wcslen(wch) + 1;
                    size_t convertedChars = 0;
                    if(a==0)
                    {
                        wcstombs_s(&convertedChars, power_list[i].name_1, origsize, wch, _TRUNCATE);
                        //strcat_s(power_list[i].name_1, " (char *)");
                    }
                    if(a==1)
                    {
                        wcstombs_s(&convertedChars, power_list[i].Max_1, origsize, wch, _TRUNCATE);
                        //strcat_s(power_list[i].Max_1, " (char *)");
                    }
                    if(a==2)
                    {
                        wcstombs_s(&convertedChars, power_list[i].Min_1, origsize, wch, _TRUNCATE);
                        //strcat_s(power_list[i].Min_1, " (char *)");
                    }

                }
                i++;

            }

            Console::WriteLine(s);
        }
        finally
        {
            if(sr)
                delete (IDisposable^)(sr);
        }

        return 0;
    }

I get this message: power_line=s->Split(':');<-----fatal error c1001:an internal error has occurred in the compiler

and

error fatal error lnk1000 internal error during image::bulidimage

what can i do?

Body:
I met the same error when use boost::iequals to compare two std::string like below:

std::for_each(bds.begin(),bds.end(),[&](std::string str){if(boost::iequals("must",str)) printf("matched\n");});

i compiled this code with vs 2010 and boost version 1.58.

To solved the error just replace the std::for_each() with for().so i guess the compile r and boosts lib conflicted.


问:
How to persist ViewState for reuse later?
Is it possible to save ViewState information, e.g. to session, so that when you navigate away from the page it is persisted somehow? Then when you return to that page you can reload the view state and the choices you've made are preserved.

Background

I have two pages, a report page, where you can pick data, do some filtering and sorting etc. and a chart-page, where the data you picked from the report page can be presented in different ways, with different choices for presentation.

If the user has tested different presentations, simply using the back-button could mean quite a few clicks before the user's back at the report page. I'd like a direct link to the report page.

Using QueryString to save control states is not an option.

I can't customize the ViewState storage for the whole application.

答:
Yes, it's possible to store the Viewstate in something like a database. You just need to implement one of the viewstate providers. See here for an example using the SqlViewStateProvider.

Edit: Just re-read your post, and saw that you said you couldn't customize how the viewstate is stored for the whole application. If that's the case, you might want to look into storing it in a session. Scott Hanselman discusses that here.

OwnerDisplayName: chriscena

LastEditorDisplayName: chriscena

OwnerDisplayName: Alex Fort

LastEditorDisplayName: Rich B


答:
When you initialise the vector, you have width and height the wrong way around. When you later read from the last two columns, the results will be undefined.

```<code>matrix.resize(width);
for (int i=0; i < width; ++i)
    matrix[i].resize(height);
</code>```

should be

```<code>matrix.resize(height);
for (int i=0; i < height; ++i)
    matrix[i].resize(width);
</code>```

Your fillMatrix function has width and height in a different order to that in which you call it later in showMatrix. I would advise swapping the order in fillMatrix to keep it the same as in showMatrix.

Be careful filling each row up to tempLine.length, which may be greater than width which will cause an exception. You could also just get the width and height from the vector within showMatrix instead of having these as arguments. And as @Charles says, you should really pass the vector by reference to avoid a copy being made. The vector argument in fillMatrix is currently pretty useless given that you have to return it, unless you turn it into a reference and make the function void.

Title: Array filling mistake

Body:
When you initialise the vector, you have width and height the wrong way around. When you later read from the last two columns, the results will be undefined.

matrix.resize(width);
for (int i=0; i < width; ++i)
    matrix[i].resize(height);

should be

matrix.resize(height);
for (int i=0; i < height; ++i)
    matrix[i].resize(width);

Your fillMatrix function has width and height in a different order to that in which you call it later in showMatrix. I would advise swapping the order in fillMatrix to keep it the same as in showMatrix.

Be careful filling each row up to tempLine.length, which may be greater than width which will cause an exception. You could also just get the width and height from the vector within showMatrix instead of having these as arguments. And as @Charles says, you should really pass the vector by reference to avoid a copy being made. The vector argument in fillMatrix is currently pretty useless given that you have to return it, unless you turn it into a reference and make the function void.


问:
Best way to create Observable, using from, in RxJS 5.x?
Now that we have "lettable" operators, how should we go about creating an Observable from another?

When I try to do:

import {Observable} from 'rxjs/Observable'
const source = Observable.from(someOtherStream)```
</div>
</div>
</p>

<p>I get the error <code>Observable.from is not a function</code>, which makes sense, because <code>from</code> is now something else that needs to be imported separately.</p>

<p>I don't want to do </p>

<p><code>import 'rxjs/add/observable/from'</code> anymore due to the prototypal problems there.</p>

<p>What I ended up doing was:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="false" data-babel="true">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>import { Observable } from 'rxjs/Observable'
import { from } from 'rxjs/observable/from'

const myNewStream = from.call(
  Observable,
  someOtherStream
)</code>```

But this really feels "hacky" for some reason to me.  Does anyone have any better ways of going about this?

答:
The lettables are behind rxjs/operators here's the write up on it.

For from you should be able to import it without importing Observable.

```<code>import { from } from 'rxjs/observable/from';

const prom = new Promise(res => setTimeout(
  () => res('promise'), 3000
));

from(prom).subscribe(x => console.log(x));
</code>```

webpackbin example

Using from this way allows you to pipe() to the lettable operators.

```<code>import { from } from 'rxjs/observable/from';
import { map } from 'rxjs/operators/map';

const prom = new Promise(res => setTimeout(
  () => res('promise'), 3000
));

from(prom).pipe(
  map(x => x.split('').reverse().join(''))
).subscribe(x => console.log(x));
</code>```

webpackbin example

Body:
Now that we have "lettable" operators, how should we go about creating an Observable from another?

When I try to do:

import {Observable} from 'rxjs/Observable'
const source = Observable.from(someOtherStream)

I get the error Observable.from is not a function, which makes sense, because from is now something else that needs to be imported separately.

I don't want to do

import 'rxjs/add/observable/from' anymore due to the prototypal problems there.

What I ended up doing was:

import { Observable } from 'rxjs/Observable'
import { from } from 'rxjs/observable/from'

const myNewStream = from.call(
  Observable,
  someOtherStream
)

But this really feels "hacky" for some reason to me.  Does anyone have any better ways of going about this?

Body:
The lettables are behind rxjs/operators here's the write up on it.

For from you should be able to import it without importing Observable.

import { from } from 'rxjs/observable/from';

const prom = new Promise(res => setTimeout(
  () => res('promise'), 3000
));

from(prom).subscribe(x => console.log(x));

webpackbin example

Using from this way allows you to pipe() to the lettable operators.

import { from } from 'rxjs/observable/from';
import { map } from 'rxjs/operators/map';

const prom = new Promise(res => setTimeout(
  () => res('promise'), 3000
));

from(prom).pipe(
  map(x => x.split('').reverse().join(''))
).subscribe(x => console.log(x));

webpackbin example


问:
How to read data from nested zip files in Java without using temporary files?
I am trying to to extract files out of a nested zip archive and process them in memory.

What this question is not about:

How to read a zip file in Java: NO, the question is how to read a zip file within a zip file within a zip and so on and so forth (as in nested zip files).

Write temporary results on disk: NO, I'm asking about doing it all in memory. I found many answers using the not-so-efficient technique of writing results temporarily to disk, but that's not what I want to do.

Example:

Zipfile -> Zipfile1 -> Zipfile2 -> Zipfile3

Goal: extract the data found in each of the nested zip files, all in memory and using Java.

ZipFile is the answer, you say? NO, it is not, it works for the first iteration, that is for:

Zipfile -> Zipfile1

But once you get to Zipfile2, and perform a:

```<code>ZipInputStream z = new ZipInputStream(zipFile.getInputStream( zipEntry) ) ;
</code>```

you will get a NullPointerException.

My code:

```<code>public class ZipHandler {

    String findings = new String();
    ZipFile zipFile = null;

    public void init(String fileName) throws AppException{

        try {
        //read file into stream
        zipFile = new ZipFile(fileName);
        Enumeration<?> enu = zipFile.entries();
        exctractInfoFromZip(enu);

        zipFile.close();
        } catch (FileNotFoundException e) {
        e.printStackTrace();

        } catch (IOException e) {
            e.printStackTrace();
    }
}

//The idea was recursively extract entries using ZipFile
public void exctractInfoFromZip(Enumeration<?> enu) throws IOException, AppException{

    try {
        while (enu.hasMoreElements()) {
            ZipEntry zipEntry = (ZipEntry) enu.nextElement();

            String name = zipEntry.getName();
            long size = zipEntry.getSize();
            long compressedSize = zipEntry.getCompressedSize();

            System.out.printf("name: %-20s | size: %6d | compressed size: %6d\n",
                    name, size, compressedSize);

            // directory ?
            if (zipEntry.isDirectory()) {
                System.out.println("dir found:" + name);
                findings+=", " + name;
                continue;
            }

            if (name.toUpperCase().endsWith(".ZIP") ||  name.toUpperCase().endsWith(".GZ")) {
                String fileType = name.substring(
                        name.lastIndexOf(".")+1, name.length());

                System.out.println("File type:" + fileType);
                System.out.println("zipEntry: " + zipEntry);

                if (fileType.equalsIgnoreCase("ZIP")) {
//ZipFile here returns a NULL pointer when you try to get the first nested zip
                    ZipInputStream z = new ZipInputStream(zipFile.getInputStream(zipEntry) ) ;
                    System.out.println("Opening ZIP as stream: " + name);

                    findings+=", " + name;

                    exctractInfoFromZip(zipInputStreamToEnum(z));
                } else if (fileType.equalsIgnoreCase("GZ")) {
//ZipFile here returns a NULL pointer when you try to get the first nested zip
                    GZIPInputStream z = new GZIPInputStream(zipFile.getInputStream(zipEntry) ) ;
                    System.out.println("Opening ZIP as stream: " + name);

                    findings+=", " + name;

                    exctractInfoFromZip(gZipInputStreamToEnum(z));
                } else
                    throw new AppException("extension not recognized!");
            } else {
                System.out.println(name);
                findings+=", " + name;
            }
        }
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    System.out.println("Findings " + findings);
}

public Enumeration<?> zipInputStreamToEnum(ZipInputStream zStream) throws IOException{

    List<ZipEntry> list = new ArrayList<ZipEntry>();

    while (zStream.available() != 0) {
        list.add(zStream.getNextEntry());
    }

    return Collections.enumeration(list);
}
</code>```

答:
this is the way I found to unzip file in memory:

The code is not clean AT ALL, but i understand the rules are to post something working, so i have this hopefully to help so

What I do is use a recursive method to navigate the complex ZIP file and extract
folder
other inner zips
files
and save the results in memory to later work with them.

Main things I found I want to share with you:

1 ZipFile is useless if you have nested zip files
2 You have to use the basic Zip InputStream and Outputstream
3 I only use recursive programming to unzip nested zips

```<code>package course.hernan;

import java.io.BufferedInputStream;

import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayDeque;
import java.util.Deque;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import java.util.zip.ZipOutputStream;

import org.apache.commons.io.IOUtils;

public class FileReader {

private static final int  BUFFER_SIZE = 2048;

    public static void main(String[] args) {
        try {
            File f = new File("DIR/inputs.zip");
            FileInputStream fis = new FileInputStream(f);
            BufferedInputStream bis = new BufferedInputStream(fis);
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            BufferedOutputStream bos = new BufferedOutputStream(baos);
            byte[] buffer = new byte[BUFFER_SIZE];
            while (bis.read(buffer, 0, BUFFER_SIZE) != -1) {
               bos.write(buffer);
            }

            bos.flush();
            bos.close();
            bis.close();

            //This STACK has the output byte array information
            Deque<Map<Integer, Object[]>> outputDataStack = ZipHandler1.unzip(baos);

        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}
package course.hernan;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Deque;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.SortedMap;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;

import org.apache.commons.lang3.StringUtils;

public class ZipHandler1 {

  private static final int BUFFER_SIZE = 2048;

  private static final String ZIP_EXTENSION = ".zip";
  public static final Integer FOLDER = 1;
  public static final Integer ZIP = 2;
  public static final Integer FILE = 3;

  public static Deque<Map<Integer, Object[]>> unzip(ByteArrayOutputStream zippedOutputFile) {

    try {

      ZipInputStream inputStream = new ZipInputStream(
          new BufferedInputStream(new ByteArrayInputStream(
              zippedOutputFile.toByteArray())));

      ZipEntry entry;

      Deque<Map<Integer, Object[]>> result = new ArrayDeque<Map<Integer, Object[]>>();

      while ((entry = inputStream.getNextEntry()) != null) {

        LinkedHashMap<Integer, Object[]> map = new LinkedHashMap<Integer, Object[]>();
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        System.out.println("\tExtracting entry: " + entry);
        int count;
        byte[] data = new byte[BUFFER_SIZE];

        if (!entry.isDirectory()) {
          BufferedOutputStream out = new BufferedOutputStream(
              outputStream, BUFFER_SIZE);

          while ((count = inputStream.read(data, 0, BUFFER_SIZE)) != -1) {
            out.write(data, 0, count);
          }

          out.flush();
          out.close();

          //  recursively unzip files
          if (entry.getName().toUpperCase().endsWith(ZIP_EXTENSION.toUpperCase())) {
            map.put(ZIP, new Object[] {entry.getName(), unzip(outputStream)});
            result.add(map);
            //result.addAll();
          } else {
            map.put(FILE, new Object[] {entry.getName(), outputStream});
            result.add(map);
          }
        } else {
          map.put(FOLDER, new Object[] {entry.getName(), unzip(outputStream)});
          result.add(map);
        }
      }

      inputStream.close();

      return result;

    } catch (Exception e) {
      throw new RuntimeException(e);
    }
  }
</code>```

Body:
I am trying to to extract files out of a nested zip archive and process them in memory.

What this question is not about:

How to read a zip file in Java: NO, the question is how to read a zip file within a zip file within a zip and so on and so forth (as in nested zip files).

Write temporary results on disk: NO, I'm asking about doing it all in memory. I found many answers using the not-so-efficient technique of writing results temporarily to disk, but that's not what I want to do.

Example:

Zipfile -> Zipfile1 -> Zipfile2 -> Zipfile3

Goal: extract the data found in each of the nested zip files, all in memory and using Java.

ZipFile is the answer, you say? NO, it is not, it works for the first iteration, that is for:

Zipfile -> Zipfile1

But once you get to Zipfile2, and perform a:

ZipInputStream z = new ZipInputStream(zipFile.getInputStream( zipEntry) ) ;

you will get a NullPointerException.

My code:

public class ZipHandler {

    String findings = new String();
    ZipFile zipFile = null;

    public void init(String fileName) throws AppException{

        try {
        //read file into stream
        zipFile = new ZipFile(fileName);
        Enumeration<?> enu = zipFile.entries();
        exctractInfoFromZip(enu);

        zipFile.close();
        } catch (FileNotFoundException e) {
        e.printStackTrace();

        } catch (IOException e) {
            e.printStackTrace();
    }
}

//The idea was recursively extract entries using ZipFile
public void exctractInfoFromZip(Enumeration<?> enu) throws IOException, AppException{

    try {
        while (enu.hasMoreElements()) {
            ZipEntry zipEntry = (ZipEntry) enu.nextElement();

            String name = zipEntry.getName();
            long size = zipEntry.getSize();
            long compressedSize = zipEntry.getCompressedSize();

            System.out.printf("name: %-20s | size: %6d | compressed size: %6d\n",
                    name, size, compressedSize);

            // directory ?
            if (zipEntry.isDirectory()) {
                System.out.println("dir found:" + name);
                findings+=", " + name;
                continue;
            }

            if (name.toUpperCase().endsWith(".ZIP") ||  name.toUpperCase().endsWith(".GZ")) {
                String fileType = name.substring(
                        name.lastIndexOf(".")+1, name.length());

                System.out.println("File type:" + fileType);
                System.out.println("zipEntry: " + zipEntry);

                if (fileType.equalsIgnoreCase("ZIP")) {
//ZipFile here returns a NULL pointer when you try to get the first nested zip
                    ZipInputStream z = new ZipInputStream(zipFile.getInputStream(zipEntry) ) ;
                    System.out.println("Opening ZIP as stream: " + name);

                    findings+=", " + name;

                    exctractInfoFromZip(zipInputStreamToEnum(z));
                } else if (fileType.equalsIgnoreCase("GZ")) {
//ZipFile here returns a NULL pointer when you try to get the first nested zip
                    GZIPInputStream z = new GZIPInputStream(zipFile.getInputStream(zipEntry) ) ;
                    System.out.println("Opening ZIP as stream: " + name);

                    findings+=", " + name;

                    exctractInfoFromZip(gZipInputStreamToEnum(z));
                } else
                    throw new AppException("extension not recognized!");
            } else {
                System.out.println(name);
                findings+=", " + name;
            }
        }
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    System.out.println("Findings " + findings);
}

public Enumeration<?> zipInputStreamToEnum(ZipInputStream zStream) throws IOException{

    List<ZipEntry> list = new ArrayList<ZipEntry>();

    while (zStream.available() != 0) {
        list.add(zStream.getNextEntry());
    }

    return Collections.enumeration(list);
}

Body:
this is the way I found to unzip file in memory:

The code is not clean AT ALL, but i understand the rules are to post something working, so i have this hopefully to help so

What I do is use a recursive method to navigate the complex ZIP file and extract
folder
other inner zips
files
and save the results in memory to later work with them.

Main things I found I want to share with you:

1 ZipFile is useless if you have nested zip files
2 You have to use the basic Zip InputStream and Outputstream
3 I only use recursive programming to unzip nested zips

package course.hernan;

import java.io.BufferedInputStream;

import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayDeque;
import java.util.Deque;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import java.util.zip.ZipOutputStream;

import org.apache.commons.io.IOUtils;

public class FileReader {

private static final int  BUFFER_SIZE = 2048;

    public static void main(String[] args) {
        try {
            File f = new File("DIR/inputs.zip");
            FileInputStream fis = new FileInputStream(f);
            BufferedInputStream bis = new BufferedInputStream(fis);
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            BufferedOutputStream bos = new BufferedOutputStream(baos);
            byte[] buffer = new byte[BUFFER_SIZE];
            while (bis.read(buffer, 0, BUFFER_SIZE) != -1) {
               bos.write(buffer);
            }

            bos.flush();
            bos.close();
            bis.close();

            //This STACK has the output byte array information
            Deque<Map<Integer, Object[]>> outputDataStack = ZipHandler1.unzip(baos);

        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}
package course.hernan;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Deque;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.SortedMap;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;

import org.apache.commons.lang3.StringUtils;

public class ZipHandler1 {

  private static final int BUFFER_SIZE = 2048;

  private static final String ZIP_EXTENSION = ".zip";
  public static final Integer FOLDER = 1;
  public static final Integer ZIP = 2;
  public static final Integer FILE = 3;

  public static Deque<Map<Integer, Object[]>> unzip(ByteArrayOutputStream zippedOutputFile) {

    try {

      ZipInputStream inputStream = new ZipInputStream(
          new BufferedInputStream(new ByteArrayInputStream(
              zippedOutputFile.toByteArray())));

      ZipEntry entry;

      Deque<Map<Integer, Object[]>> result = new ArrayDeque<Map<Integer, Object[]>>();

      while ((entry = inputStream.getNextEntry()) != null) {

        LinkedHashMap<Integer, Object[]> map = new LinkedHashMap<Integer, Object[]>();
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        System.out.println("\tExtracting entry: " + entry);
        int count;
        byte[] data = new byte[BUFFER_SIZE];

        if (!entry.isDirectory()) {
          BufferedOutputStream out = new BufferedOutputStream(
              outputStream, BUFFER_SIZE);

          while ((count = inputStream.read(data, 0, BUFFER_SIZE)) != -1) {
            out.write(data, 0, count);
          }

          out.flush();
          out.close();

          //  recursively unzip files
          if (entry.getName().toUpperCase().endsWith(ZIP_EXTENSION.toUpperCase())) {
            map.put(ZIP, new Object[] {entry.getName(), unzip(outputStream)});
            result.add(map);
            //result.addAll();
          } else {
            map.put(FILE, new Object[] {entry.getName(), outputStream});
            result.add(map);
          }
        } else {
          map.put(FOLDER, new Object[] {entry.getName(), unzip(outputStream)});
          result.add(map);
        }
      }

      inputStream.close();

      return result;

    } catch (Exception e) {
      throw new RuntimeException(e);
    }
  }


问:
.Rprofile not invoked under cron
I am running Ubuntu 16.04.3 LTS on the cloud. When I run a program from the command line with Rscript everything goes as expected. However, when I run the same program with Rscript through cron it appears that my .Rprofile file is not invoked. I have written a small program to demonstrate this problem:

```<code>test_cron = function() {
    #The next 3 lines are base R.
    sink('~/test_cron.out')
    on.exit(sink())
    cat('The date and time are:', as.character(Sys.time()), '\n')
    #Now try to access a personal option, set by .Rprofile.
    root = getOption('root')
    cat('Option root:', root, '\n')
}
test_cron()
</code>```

I run this from the command line using this command:

```<code>Rscript test_cron.r
</code>```

The cron_test.out file contains the following:

```<code>The date and time are: 2017-11-14 06:15:46
Option root: /home/ubuntu/_algi/
</code>```

The relevant line in crontab is as follows:

```<code>20 6 * * * /usr/bin/Rscript ~/test_cron.r
</code>```

When this is run by cron, cron_test.out contains the following:

```<code>The date and time are: 2017-11-14 06:20:01
Option root:
</code>```

Evidently the program, when run by cron, could not access my personal option 'root'. This is one among a number of experiments I have run that convince me that .Rprofile is not invoked under cron. Is there a fix for this?

Note: The R_PROFILE_USER environment variable is set to point to my .Rprofile file. Apparently, Rscript under cron ignores it.

答:
It transpires that cron does not load the user's environment. This has caused endless confusion and anguish, with no commonly accepted solution. See, for example,

```<code>https://serverfault.com/questions/673480/load-users-environment-variables-in-a-cronjob
https://stackoverflow.com/questions/15557777/cron-job-does-not-get-the-environment-variables-set-in-bashrc
https://stackoverflow.com/questions/2229825/where-can-i-set-environment-variables-that-crontab-will-use
https://unix.stackexchange.com/questions/27289/how-can-i-run-a-cron-command-with-existing-environmental-variables
</code>```

A closely related problem is that .bashrc will only run in an interactive shell::

```<code>https://unix.stackexchange.com/questions/257571/why-does-bashrc-check-whether-the-current-shell-is-interactive
</code>```

My solution is to write a shell script in which I set the necessary environment variables, then run my program:

```<code>#!/bin/bash
export CODE_HOME='/home/ubuntu/'
export OS='Ubuntu'
export R_PROFILE_USER=~/R/.Rprofile
/usr/bin/Rscript ~/test_cron.r
</code>```

After making the script executable, it successfully runs under crontab.

Title: .Rprofile not invoked under cron

Body:
I am running Ubuntu 16.04.3 LTS on the cloud. When I run a program from the command line with Rscript everything goes as expected. However, when I run the same program with Rscript through cron it appears that my .Rprofile file is not invoked. I have written a small program to demonstrate this problem:

test_cron = function() {
    #The next 3 lines are base R.
    sink('~/test_cron.out')
    on.exit(sink())
    cat('The date and time are:', as.character(Sys.time()), '\n')
    #Now try to access a personal option, set by .Rprofile.
    root = getOption('root')
    cat('Option root:', root, '\n')
}
test_cron()

I run this from the command line using this command:

Rscript test_cron.r

The cron_test.out file contains the following:

The date and time are: 2017-11-14 06:15:46
Option root: /home/ubuntu/_algi/

The relevant line in crontab is as follows:

20 6 * * * /usr/bin/Rscript ~/test_cron.r

When this is run by cron, cron_test.out contains the following:

The date and time are: 2017-11-14 06:20:01
Option root:

Evidently the program, when run by cron, could not access my personal option 'root'. This is one among a number of experiments I have run that convince me that .Rprofile is not invoked under cron. Is there a fix for this?

Note: The R_PROFILE_USER environment variable is set to point to my .Rprofile file. Apparently, Rscript under cron ignores it.

Body:
It transpires that cron does not load the user's environment. This has caused endless confusion and anguish, with no commonly accepted solution. See, for example,

https://serverfault.com/questions/673480/load-users-environment-variables-in-a-cronjob
https://stackoverflow.com/questions/15557777/cron-job-does-not-get-the-environment-variables-set-in-bashrc
https://stackoverflow.com/questions/2229825/where-can-i-set-environment-variables-that-crontab-will-use
https://unix.stackexchange.com/questions/27289/how-can-i-run-a-cron-command-with-existing-environmental-variables

A closely related problem is that .bashrc will only run in an interactive shell::

https://unix.stackexchange.com/questions/257571/why-does-bashrc-check-whether-the-current-shell-is-interactive

My solution is to write a shell script in which I set the necessary environment variables, then run my program:

#!/bin/bash
export CODE_HOME='/home/ubuntu/'
export OS='Ubuntu'
export R_PROFILE_USER=~/R/.Rprofile
/usr/bin/Rscript ~/test_cron.r

After making the script executable, it successfully runs under crontab.


问:
How do you provide domain credentials to ansible's mount module?
I've figured out how to use the shell module to create a mount on the network using the following command:

```<code>- name: mount image folder share
  shell: "mount -t cifs -o domain=MY_DOMAIN,username=USER,password=PASSWORD  //network_path/folder /local_path/folder
  sudo_user: root
  args:
    executable: /bin/bash
</code>```

But it seems like it's better practice to use Ansible's mount module to do the same thing.

Specifically, I'm confused about going about providing the options for domain=MY_DOMAIN,username=USER,password=PASSWORD.  I see there is a flag for opts, but I'm not quite sure how this would look.

答:
Expanding on @adam-kalnas answer:

Creating an fstab entry and then calling mount will allow you to mount the file-system in more appropriate permission level (i.e. not 0777). By doing state: present ansible will only create the entry in /etc/fstab and then can be mounted by the user. From ansible mount module documentation:

absent and present only deal with fstab but will not affect current
  mounting.

Additionally, you'd want to avoid leaving credentials in the /etc/fstab file (as its readable by all, human or service). To avoid that, create a credential file that is appropriately secured.

All together looks something like this:

```<code>- name: Create credential file (used for fstab entry)
  copy:
    content: |
      username=USER
      password=PASSWORD
    dest: /home/myusername/.credential
    mode: 0600
  become: true
  become_user: myusername

- name: Create fstab entry for product image folder share
  mount:
    state: present
    fstype: cifs
    opts: "credentials=/home/myusername/.credential,file_mode=0755,dir_mode=0755,user"
    src="//network_path/folder"
    path="/local_path/folder"
  become: true

- name: Mount product image folder share
  shell: |
    mount "/local_path/folder"
  become: true
  become_user: myusername
</code>```

Body:
I've figured out how to use the shell module to create a mount on the network using the following command:

- name: mount image folder share
  shell: "mount -t cifs -o domain=MY_DOMAIN,username=USER,password=PASSWORD  //network_path/folder /local_path/folder
  sudo_user: root
  args:
    executable: /bin/bash

But it seems like it's better practice to use Ansible's mount module to do the same thing.

Specifically, I'm confused about going about providing the options for domain=MY_DOMAIN,username=USER,password=PASSWORD.  I see there is a flag for opts, but I'm not quite sure how this would look.

Body:
Expanding on @adam-kalnas answer:

Creating an fstab entry and then calling mount will allow you to mount the file-system in more appropriate permission level (i.e. not 0777). By doing state: present ansible will only create the entry in /etc/fstab and then can be mounted by the user. From ansible mount module documentation:

absent and present only deal with fstab but will not affect current
  mounting.

Additionally, you'd want to avoid leaving credentials in the /etc/fstab file (as its readable by all, human or service). To avoid that, create a credential file that is appropriately secured.

All together looks something like this:

- name: Create credential file (used for fstab entry)
  copy:
    content: |
      username=USER
      password=PASSWORD
    dest: /home/myusername/.credential
    mode: 0600
  become: true
  become_user: myusername

- name: Create fstab entry for product image folder share
  mount:
    state: present
    fstype: cifs
    opts: "credentials=/home/myusername/.credential,file_mode=0755,dir_mode=0755,user"
    src="//network_path/folder"
    path="/local_path/folder"
  become: true

- name: Mount product image folder share
  shell: |
    mount "/local_path/folder"
  become: true
  become_user: myusername


答:
You could look at using Vue Child Component Refs.  That will let you access the child component's innerHTML from the parent component.

Just add a ref attribute to your child component. It can be anything you choose:

```<code><child-component ref="mychildcomponent">
   <div>Hello</div>
</child-component>
</code>```

Then in the parent methods, you can do something like:

```<code>let childEl = this.$refs.mychildcomponent
</code>```

That will set childEl the entire child component that you've referenced.  To get the innerHTML youd just have to go a little further, and do something like this:

```<code>let childEl = this.$refs.mychildcomponent.$el.innerHTML
</code>```

That should give you a string of the child component's innerHTML.

This might help: https://v2.vuejs.org/v2/guide/components.html#Child-Component-Refs

Alternatively if you want to get it from the child component itself, just do the following within a method:

```<code>let componentHTML = this.$el.innerHTML
</code>```

Hope that helps.

Title: Get inner html of the component as a variable in vuejs 2

Body:
Say I have a vuejs component called child-component which is added to a parent component as follows.

<child-component>

Hello

</child-component>

N.B. this is not the template of the child component. This is how the child component is added to the parent.

How can I get the innerHTML, i.e.
Hello
 in the child component as a string?

Body:
You could look at using Vue Child Component Refs.  That will let you access the child component's innerHTML from the parent component.

Just add a ref attribute to your child component. It can be anything you choose:

<child-component ref="mychildcomponent">
   <div>Hello</div>
</child-component>

Then in the parent methods, you can do something like:

let childEl = this.$refs.mychildcomponent

That will set childEl the entire child component that you've referenced.  To get the innerHTML youd just have to go a little further, and do something like this:

let childEl = this.$refs.mychildcomponent.$el.innerHTML

That should give you a string of the child component's innerHTML.

This might help: https://v2.vuejs.org/v2/guide/components.html#Child-Component-Refs

Alternatively if you want to get it from the child component itself, just do the following within a method:

let componentHTML = this.$el.innerHTML

Hope that helps.

ContentLicense: CC BY-SA 4.0


问:
generate all possible combinations of a number while each digit got different range
i been searching the internet for few days now but haven't found good approach for my needs. so ill try asking.

Im looking for a way to generate all possible combinations of a number while each digit got different range.

let me give you an example:

my input: [1-3],[0-9],[4],[2-3]
few of the combinations will be:
1042
1043
1142
1143
1242
and so on...

the code must not store all of the combinations at some variable in memory, because i'll be working with big numbers (up to 10 digits) the program can make txt file with all the possibilities and write them one by one or just print them in console.

the input number length and the range for each digit is unknown until it been given. so no hard coded nested loops. it must be dynamic.

i hope i was clear..

tnx

答:
Even though this is a very old question, seeing as it's tagged C# but has no C# answers, here's my variant. It's non-recursive, which helps with performance in tight loops:

```<code>var minimums = new[] { 2, 0, 1, 7, 1 };
var maximums = new[] { 4, 6, 3, 9, 4 };

var current = minimums.ToArray();
while (true)
{
    Console.WriteLine(string.Join("", current));

    int pos = 0;
    while (pos < maximums.Length)
    {
        current[pos]++;
        if (current[pos] <= maximums[pos])
            break;
        current[pos] = minimums[pos];
        pos++;
    }
    if (pos == maximums.Length)
        break;
}
</code>```

Body:
Even though this is a very old question, seeing as it's tagged C# but has no C# answers, here's my variant. It's non-recursive, which helps with performance in tight loops:

var minimums = new[] { 2, 0, 1, 7, 1 };
var maximums = new[] { 4, 6, 3, 9, 4 };

var current = minimums.ToArray();
while (true)
{
    Console.WriteLine(string.Join("", current));

    int pos = 0;
    while (pos < maximums.Length)
    {
        current[pos]++;
        if (current[pos] <= maximums[pos])
            break;
        current[pos] = minimums[pos];
        pos++;
    }
    if (pos == maximums.Length)
        break;
}


问:
PhoneGap not running Angular JS code
I just started learning angularJS using phonegap and I have a simple HTML code and a few lines of angularjs code. Everything works fine in the browser but only the HTML code works in the phonegap when I try to run it on my Android phone. Why?

```<code><!DOCTYPE html>
<html>
<script src="C:\Users\Ghaith Haddad\Desktop\learning\learn\angular-1.5.8"></script>

    <script src="C:\Users\Ghaith Haddad\Desktop\learning\learn\www\me.js"></script>
    <head>
        <meta charset="utf-8">
        <meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=no, width=device-width">
    <title>AngularJS Tutorial</title>
    </head>
    <body>
        <script type="text/javascript" src="cordova.js"></script>
         <div ng-app="app3" ng-controller="ctrl1">
      <span>Values:</span>

      <input type="text" ng-model="first" />
      <input type="text" ng-model="second" />

      <h1>hello there buddy</h1>
      <button ng-click="update()">Sum</button>
      <br><br>

      {{calculation}}
     </div>

 <script>
        var app = angular.module('app3', []);

    app.controller('ctrl1', function($scope) {

    $scope.first = 1;
    $scope.second = 2;

    $scope.update = function(){

        $scope.calculation = (+$scope.first + +$scope.second);
    };
    });
    <!-- Load the AngularJS library -->
    </script>

    <!-- Load the JS Module -->
    </body>
</html>
</code>```

Here is the JS code:

```<code>    var app = angular.module('app3', []);

    app.controller('ctrl1', function($scope) {

$scope.first = 1;
$scope.second = 2;

$scope.update = function(){

    $scope.calculation = (+$scope.first + +$scope.second);
};
});
</code>```

答:
Use relative path for cordova (like "./") instead of absolute path (
), that's way the script can't be loaded. Anyway you can debug your solution in android using chrome and attaching device or iOS using safari inspector.

Example:

```<code><!DOCTYPE html>
<html>
  <head>
    <base href=".">
  </head>
  <body>
    <script type="text/javascript" src="bundle.js"></script>
  </body>
</html>
</code>```

Title: PhoneGap not running Angular JS code

Body:
I just started learning angularJS using phonegap and I have a simple HTML code and a few lines of angularjs code. Everything works fine in the browser but only the HTML code works in the phonegap when I try to run it on my Android phone. Why?

<!DOCTYPE html>

        <meta charset="utf-8">
        <meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=no, width=device-width">
    <title>AngularJS Tutorial</title>

      Values:

      <input type="text" ng-model="first" />
      <input type="text" ng-model="second" />

hello there buddy

      <button ng-click="update()">Sum</button>

      {{calculation}}

Here is the JS code:

    var app = angular.module('app3', []);

    app.controller('ctrl1', function($scope) {

$scope.first = 1;
$scope.second = 2;

$scope.update = function(){

    $scope.calculation = (+$scope.first + +$scope.second);
};
});

Body:
Use relative path for cordova (like "./") instead of absolute path (
), that's way the script can't be loaded. Anyway you can debug your solution in android using chrome and attaching device or iOS using safari inspector.

Example:

<!DOCTYPE html>
<html>
  <head>
    <base href=".">
  </head>
  <body>
    <script type="text/javascript" src="bundle.js"></script>
  </body>
</html>


问:
How to automatically use different set of application icons based on chosen buildType?
Iam trying to automatically switch between two sets of app icons based on the buildTypes i defined here at build.gradle:

```<code>buildTypes {
    release {
        minifyEnabled false
        proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        applicationIdSuffix ".release"
    }
    debug {
        applicationIdSuffix ".debug"

    }
}
</code>```

I have already looked at this post, however my files structure is different and the offered solution does not work for my case.
How to provide different Android app icons for different gradle buildTypes?

Here is my files structure where there are two sets of icons stored at res-debug and res-release. How can I automatically switch between the two?

```<code>\app\src\main:
├───assets
├───java
│   └───com
│       └───myproj
│           └───videoplayer
│               ├───dialog
│               ├───dto
│               ├───entity
│               └───utils
├───res-debug
│   ├───layout
│   ├───mipmap-hdpi
│   ├───mipmap-mdpi
│   ├───mipmap-xhdpi
│   ├───mipmap-xxhdpi
│   ├───mipmap-xxxhdpi
│   └───values
└───res-release
    ├───layout
    ├───mipmap-hdpi
    ├───mipmap-mdpi
    ├───mipmap-xhdpi
    ├───mipmap-xxhdpi
    ├───mipmap-xxxhdpi
    └───values
</code>```

答:
The correct folder structure should be:</p>

```<code>└─src
    ├─debug
    │  └─res
    │      ├─layout
    │      ├─mipmap-*
    │      └─values
    ├─main
    │  ├─java
    │  │  └─com.any.package
    │  └─res
    │      ├─drawable
    │      ├─layout
    │      ├─mipmap-mdpi
    │      ├─mipmap-xhdpi
    │      ├─mipmap-xxhdpi
    │      ├─mipmap-xxxhdpi
    │      └─values
    └─release
       └─res
           ├─layout
           ├─mipmap-*
           └─values
</code>```

Body:
Iam trying to automatically switch between two sets of app icons based on the buildTypes i defined here at build.gradle:

buildTypes {
    release {
        minifyEnabled false
        proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        applicationIdSuffix ".release"
    }
    debug {
        applicationIdSuffix ".debug"

    }
}

I have already looked at this post, however my files structure is different and the offered solution does not work for my case.
How to provide different Android app icons for different gradle buildTypes?

Here is my files structure where there are two sets of icons stored at res-debug and res-release. How can I automatically switch between the two?

\app\src\main:
├───assets
├───java
│   └───com
│       └───myproj
│           └───videoplayer
│               ├───dialog
│               ├───dto
│               ├───entity
│               └───utils
├───res-debug
│   ├───layout
│   ├───mipmap-hdpi
│   ├───mipmap-mdpi
│   ├───mipmap-xhdpi
│   ├───mipmap-xxhdpi
│   ├───mipmap-xxxhdpi
│   └───values
└───res-release
    ├───layout
    ├───mipmap-hdpi
    ├───mipmap-mdpi
    ├───mipmap-xhdpi
    ├───mipmap-xxhdpi
    ├───mipmap-xxxhdpi
    └───values

Body:
The correct folder structure should be:

└─src
    ├─debug
    │  └─res
    │      ├─layout
    │      ├─mipmap-*
    │      └─values
    ├─main
    │  ├─java
    │  │  └─com.any.package
    │  └─res
    │      ├─drawable
    │      ├─layout
    │      ├─mipmap-mdpi
    │      ├─mipmap-xhdpi
    │      ├─mipmap-xxhdpi
    │      ├─mipmap-xxxhdpi
    │      └─values
    └─release
       └─res
           ├─layout
           ├─mipmap-*
           └─values