问:
I need this code with dynamicly
I have a header menu and i do not want to add for each menu link in switch case like this, how can i do it dynamic...</p>

```<code>var sections = $(".href a");
var content = $("#load");

sections.click(function(){
    switch(this.id){
        case ('/p/settings/header-settings'):
            $(content).load('/p/settings/header-settings #load');
            window.history.pushState('user', 'user', '/p/settings/header-settings');
            break;
        case ('/p/settings/site-verifications'):
            $(content).load('/p/settings/site-verifications #load');
            window.history.pushState('user', 'user', '/p/settings/site-verifications');
            break;
        case ('/p/settings/analysis-settings'):
            $(content).load('/p/settings/analysis-settings #load');
            window.history.pushState('user', 'user', '/p/settings/header-settings');
            break;
        default:
            $(content).load('/p #load' );
            break;
    }
});
</code>```

答:
Use this JS instead of your switch case. if you don't worry about default case

```<code>sections.click(function(){

    $(content).load(this.id+' #load');
    window.history.pushState('user', 'user', this.id);

});
</code>```

If you want to take care of default condition too then you can use simplified switch case as shown below.

```<code>sections.click(function(){
    switch(this.id){
        case ('/p/settings/header-settings'):
        case ('/p/settings/site-verifications'):
        case ('/p/settings/analysis-settings'):

        //For more case just add here the below code remain same

        $(content).load(this.id+' #load');
        window.history.pushState('user', 'user', this.id);

        break;
        default:
            $(content).load('/p #load' );
            break;
    }
});
</code>```

Title: I need this code with dynamicly

Body:
I have a header menu and i do not want to add for each menu link in switch case like this, how can i do it dynamic...

var sections = $(".href a");
var content = $("#load");

sections.click(function(){
    switch(this.id){
        case ('/p/settings/header-settings'):
            $(content).load('/p/settings/header-settings #load');
            window.history.pushState('user', 'user', '/p/settings/header-settings');
            break;
        case ('/p/settings/site-verifications'):
            $(content).load('/p/settings/site-verifications #load');
            window.history.pushState('user', 'user', '/p/settings/site-verifications');
            break;
        case ('/p/settings/analysis-settings'):
            $(content).load('/p/settings/analysis-settings #load');
            window.history.pushState('user', 'user', '/p/settings/header-settings');
            break;
        default:
            $(content).load('/p #load' );
            break;
    }
});

Body:
Use this JS instead of your switch case. if you don't worry about default case

sections.click(function(){

    $(content).load(this.id+' #load');
    window.history.pushState('user', 'user', this.id);

});

If you want to take care of default condition too then you can use simplified switch case as shown below.

sections.click(function(){
    switch(this.id){
        case ('/p/settings/header-settings'):
        case ('/p/settings/site-verifications'):
        case ('/p/settings/analysis-settings'):

        //For more case just add here the below code remain same

        $(content).load(this.id+' #load');
        window.history.pushState('user', 'user', this.id);

        break;
        default:
            $(content).load('/p #load' );
            break;
    }
});


来源: stackexchange

问:
C# - FrameworkElement.FindName returns null
I spent the past one hour trying to figure this out. I have a CheckBox inside DataGrid as follows:

```<code><DataGridTemplateColumn>
    <DataGridTemplateColumn.Header>
        <CheckBox Name="chkall" Content="Select All" Checked="chkall_Checked" Unchecked="chkall_Unchecked"/>
    </DataGridTemplateColumn.Header>
    <DataGridTemplateColumn.CellTemplate>
        <DataTemplate>
            <CheckBox Tag="{Binding Path=id}" x:Name="chksingle"  Checked="chksingle_Checked" Unchecked="chksingle_Unchecked"/>
        </DataTemplate>
    </DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
</code>```

As you can see I am trying to check and uncheck the CheckBoxes inside DataGrid rows when the CheckBox in the header is checked or unchecked. This is the code where I am trying to retrieve the CheckBox and mark it as checked:

```<code>private void chkall_Checked(object sender, RoutedEventArgs e)
{
    foreach (var r in userDG.Items)
    {
        DataGridRow row =(DataGridRow)userDG.ItemContainerGenerator.ContainerFromItem(r);
        FrameworkElement FW_element = userDG.Columns[0].GetCellContent(row);
        FW_element.ApplyTemplate();
        var checkbox = FW_element.FindName("chksingle") as CheckBox;
        checkbox.IsChecked = false;
    }
}
</code>```

I have already tried RegisterName() method and I've tried VisualTreeHelper but nothing works.

This line always returns null:

```<code>var checkbox = FW_element.FindName("chksingle") as CheckBox;
</code>```

Here is a WPF visualizer screenshot for my FrameworkElement where I can clearly see the checkbox I am trying to find:

Please tell me what am I doing wrong? Thank you.

答:
The CheckBox does not exist in the scope that the Row knows. It is not a Direct child of its Template.

You need to use the static class VisualTreeHelper to drill down from the row to find an instance of type CheckBox, and compare against its x:Name.

ContentLicense: CC BY-SA 3.0

Body:
I spent the past one hour trying to figure this out. I have a CheckBox inside DataGrid as follows:

<DataGridTemplateColumn>
    <DataGridTemplateColumn.Header>
        <CheckBox Name="chkall" Content="Select All" Checked="chkall_Checked" Unchecked="chkall_Unchecked"/>
    </DataGridTemplateColumn.Header>
    <DataGridTemplateColumn.CellTemplate>
        <DataTemplate>
            <CheckBox Tag="{Binding Path=id}" x:Name="chksingle"  Checked="chksingle_Checked" Unchecked="chksingle_Unchecked"/>
        </DataTemplate>
    </DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>

As you can see I am trying to check and uncheck the CheckBoxes inside DataGrid rows when the CheckBox in the header is checked or unchecked. This is the code where I am trying to retrieve the CheckBox and mark it as checked:

private void chkall_Checked(object sender, RoutedEventArgs e)
{
    foreach (var r in userDG.Items)
    {
        DataGridRow row =(DataGridRow)userDG.ItemContainerGenerator.ContainerFromItem(r);
        FrameworkElement FW_element = userDG.Columns[0].GetCellContent(row);
        FW_element.ApplyTemplate();
        var checkbox = FW_element.FindName("chksingle") as CheckBox;
        checkbox.IsChecked = false;
    }
}

I have already tried RegisterName() method and I've tried VisualTreeHelper but nothing works.

This line always returns null:

var checkbox = FW_element.FindName("chksingle") as CheckBox;

Here is a WPF visualizer screenshot for my FrameworkElement where I can clearly see the checkbox I am trying to find:

Please tell me what am I doing wrong? Thank you.


问:
Programming rev in sed
I'm trying to write an utility that reverses lines of input. The following just prints the lines as they are though:

```<code>#!/bin/sed -f
#insert newline at the beginning
s/^/\n/
#while the newline hasnt moved to the end of pattern space, rotate
: loop
/\n$/{!s/\(.*\)\(.$\)/\2\1/;!b loop}
#delete the newline
s/\n//
</code>```

Any ideas on what's wrong?

答:
Solution 1

```<code>$ echo -e '123\n456\n789' |sed -nr '/\n/!G;s/(.)(.*\n)/&\2\1/;/^\n/!D;s/\n//p'
321
654
987
</code>```

the core ideas:

we need a loop to deal with each line, and fortunately we can use D command can simulate a loop;

we need to loop over ONE line, which is difficult, because sed deals with  one line every time; but we can use s and D command to simulate a loop over one line.

how to avoid infinite loop? we need a flag char to identify the end of each line, \n is the perfect choice.

D command delete chars util first \n in the pattern space every time,
and then force sed jump to its first command, which is a loop actually! So we also need to add some useless placeholder to be deleted by D command before the final string, and we can just use contents in current line before \n (\n also included).

Explains:

/\n/!G: if current pattern space contain \n, which means this command is in a loop of dealing with one line; otherwise, use G command to append the \n and hold space to the pattern space (sed will delete \n of every line before putting it into pattern space), the content of pattern space after G command is the origin content and a \n.

s/(.)(.*\n)/&\2\1/;: use s command to delete the first char (util \n) and then insert it after the final string.

/^\n/!D;s/\n//p: if current pattern space starts with \n, which means this line has been resolved already, so use s/\n//p to delete the flag char: \n and print the final string; otherwise use D command to delete the useless placeholder, and then jump to the first command to deal with the second char...

To make a summary, the contents in pattern space in a loop are shown as the followings:

```<code>123\n [(1)(23\n)] =s=> 123\n23\n1 [(123\n)(23\n)(1)] =D=> 23\n1
23\n1 [(2)(3\n)1] =s=> 23\n3\n21 [(23\n)(3\n)(2)1] =D=> 3\n21
3\n21 [(3)(\n)21] =s=> 3\n\n321 [(3\n)(\n)(3)21] =D=> \n321
\n321 [()(\n)321] =s=> \n321 =!D=> \n321 =s-p=> 321
</code>```

There are some derived solutions:

Solution 2

the placeholder can be set another string ending with a \n:

```<code>$ echo -e '123\n456\n789' |sed -nr '/\n/!G;s/(.)(.*\n)/USELESS\n\2\1/;/^\n/!D;s/\n//p'
321
654
987
</code>```

Solution 3

Use a direct loop instead of obscure D command

```<code>$ echo -e '123\n456\n789' |sed -nr '/\n/!G;s/(.)(.*\n)/&\2\1/;Tend;D;:end;s/\n//p'
321
654
987
</code>```

Solution 4

Use . to fetch the first char \n

```<code>$ echo -e '123\n456\n789' |sed -nr '/\n/!G;s/(.)(.*\n)/&\2\1/;/^\n/!D;s/.//p'
321
654
987
</code>```

Solution 5

```<code>$ echo -e '123\n456\n789' |sed -nr ':loop;/\n/!G;s/(.)(.*\n)/\2\1/;tloop;s/.//p'
321
654
987
</code>```

This solution is much easier to understand, the contents in pattern space res shown as the followings:

```<code>123\n [(1)(23\n)] =s=> 23\n1 [(23\n)(1)]
23\n1 [(2)(3\n)1] =s=> 3\n21 [(3\n)(2)1]
3\n21 [(3)(\n)21] =s=> \n321 [(\n)(3)21]
\n321 [()(\n)321] =s=> \n321 =s=> 321
</code>```

Title: Programming rev in sed

Body:
I'm trying to write an utility that reverses lines of input. The following just prints the lines as they are though:

#!/bin/sed -f
#insert newline at the beginning
s/^/\n/
#while the newline hasnt moved to the end of pattern space, rotate
: loop
/\n$/{!s/\(.*\)\(.$\)/\2\1/;!b loop}
#delete the newline
s/\n//

Any ideas on what's wrong?

Body:
Solution 1

$ echo -e '123\n456\n789' |sed -nr '/\n/!G;s/(.)(.*\n)/&\2\1/;/^\n/!D;s/\n//p'
321
654
987

the core ideas:

we need a loop to deal with each line, and fortunately we can use D command can simulate a loop;

we need to loop over ONE line, which is difficult, because sed deals with  one line every time; but we can use s and D command to simulate a loop over one line.

how to avoid infinite loop? we need a flag char to identify the end of each line, \n is the perfect choice.

D command delete chars util first \n in the pattern space every time,
and then force sed jump to its first command, which is a loop actually! So we also need to add some useless placeholder to be deleted by D command before the final string, and we can just use contents in current line before \n (\n also included).

Explains:

/\n/!G: if current pattern space contain \n, which means this command is in a loop of dealing with one line; otherwise, use G command to append the \n and hold space to the pattern space (sed will delete \n of every line before putting it into pattern space), the content of pattern space after G command is the origin content and a \n.

s/(.)(.*\n)/&\2\1/;: use s command to delete the first char (util \n) and then insert it after the final string.

/^\n/!D;s/\n//p: if current pattern space starts with \n, which means this line has been resolved already, so use s/\n//p to delete the flag char: \n and print the final string; otherwise use D command to delete the useless placeholder, and then jump to the first command to deal with the second char...

To make a summary, the contents in pattern space in a loop are shown as the followings:

123\n [(1)(23\n)] =s=> 123\n23\n1 [(123\n)(23\n)(1)] =D=> 23\n1
23\n1 [(2)(3\n)1] =s=> 23\n3\n21 [(23\n)(3\n)(2)1] =D=> 3\n21
3\n21 [(3)(\n)21] =s=> 3\n\n321 [(3\n)(\n)(3)21] =D=> \n321
\n321 [()(\n)321] =s=> \n321 =!D=> \n321 =s-p=> 321

There are some derived solutions:

Solution 2

the placeholder can be set another string ending with a \n:

$ echo -e '123\n456\n789' |sed -nr '/\n/!G;s/(.)(.*\n)/USELESS\n\2\1/;/^\n/!D;s/\n//p'
321
654
987

Solution 3

Use a direct loop instead of obscure D command

$ echo -e '123\n456\n789' |sed -nr '/\n/!G;s/(.)(.*\n)/&\2\1/;Tend;D;:end;s/\n//p'
321
654
987

Solution 4

Use . to fetch the first char \n

$ echo -e '123\n456\n789' |sed -nr '/\n/!G;s/(.)(.*\n)/&\2\1/;/^\n/!D;s/.//p'
321
654
987

Solution 5

$ echo -e '123\n456\n789' |sed -nr ':loop;/\n/!G;s/(.)(.*\n)/\2\1/;tloop;s/.//p'
321
654
987

This solution is much easier to understand, the contents in pattern space res shown as the followings:

123\n [(1)(23\n)] =s=> 23\n1 [(23\n)(1)]
23\n1 [(2)(3\n)1] =s=> 3\n21 [(3\n)(2)1]
3\n21 [(3)(\n)21] =s=> \n321 [(\n)(3)21]
\n321 [()(\n)321] =s=> \n321 =s=> 321


问:
Can't access @Viewbag properties after using statement
The view is no longer accessing the @ViewBag after the @using(html.BeginForm)statement, and I don't know why.  I get an error "The name 'ViewBag' does not exist in the current context". Why is that?  Any help would be appreciated. </p>

```<code>@{ Layout = null; }

@model IEnumerable<ReportViewModel>
<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <link href="StyleSheets/css" rel="stylesheet" />
    <link rel="stylesheet" type="text/css" href="~/StyleSheets/css" />
    <link rel="stylesheet" type="text/css" href="~/StyleSheets/css" />

    <script src="@Url.Content("~/Js/utills.js")" type="text/javascript"></script>
    <script src="@Url.Content("~/Js/jQuery/jquery-1.11.0.js")" type="text/javascript"></script>
    <script src="@Url.Content("~/Js/rt.js")" type="text/javascript"></script>

    <title>@ViewBag.title</title>

</head>
<body>

    @*@if ((ViewBag.site != "Sites" && ViewBag.site != null) || ViewBag.site != "PrintThis")
        {*@
    @using (Html.BeginForm(null, null, FormMethod.Post, new { id = "ReportForm" }))
        {
            if (@ViewBag.print != "PrintReport")
            {
            <div class="im-row im-padding-4 im-padding-top-16" id="Header" style="width: 100%;">

                <div class="im-container" style="width: 95%;">

                    <div class="im-col--3">
                        @Html.DropDownList(
                                 "OrderSelector",
                                 new SelectList(new[]
                                 {
                                     new SelectListItem {Text = "L", Value = @Url.Action("Pdf", "Report/", new {SecurityCode = @ViewData["SCode"], site = @ViewBag.site, team = @ViewBag.team, sortOrder = "L"})},
                                     new SelectListItem {Text = "R", Value = @Url.Action("Pdf", "Report/", new {SecurityCode = @ViewData["SCode"], site = @ViewBag.site, team = @ViewBag.team, sortOrder = "R"})},
                                     new SelectListItem {Text = "D", Value = @Url.Action("Pdf", "Report/", new {SecurityCode = @ViewData["SCode"], site = @ViewBag.site, team = @ViewBag.team, sortOrder = "D"})},
                                     new SelectListItem {Text = "T", Value = @Url.Action("tPdf", "Report/", new {SecurityCode = @ViewData["SCode"], site = @ViewBag.site, team = @ViewBag.team, sortOrder = "T"})},
                                 }, "Value", "Text"),
                                 new { id = "OrderSelector", @class = "sortOrder", onchange = "CallChangeFunc(this.value)" }
                                 )
                        <input id="SCode" type="hidden" value="@ViewData["SCode"]" />
                        <input id="SelectedSort" type="hidden" value="@ViewBag.sortOrder" />
                    </div>
                    <div class="im-col--5" style="margin-top: 15px;">
                        <span>(to change your default sort preference, click on the 'Settings' tab)</span>
                    </div>
                    <div class="im-col--2">
                        @Html.ActionLink("Print", "Print", "Report", new { site = @ViewBag.site, team = @ViewBag.team, sortOrder = @ViewBag.sortOrder }, new { @class = "im-btn im-btn--primary im-btn--sm printBtn", id = "PrintPdf" })
                    </div>

                    <div class="im-row im-padding-4  im-col--12" style="width: 100%;">
                        <div class="im-container">
                            <hr />
                        </div>
                    </div>
                </div>
            </div>
        }
    }
    <div class="im-container Report im-no-padding-left" style="width: 95%;" id="Report">
        <div class="im-row title">
            <div class="im-col--6 im-no-padding-left">
                <p class="im-text--extra-bold-weight inline">
                    CC
                </p>
                <p class="inline">
                    - @ViewBag.status, @ViewBag.site, @ViewBag.team, @ViewBag.user
                </p>
            </div>
            <div class="im-col--6">
                <p class="im-text--extra-bold-weight inline">
                    @{ string[] currentDate = DateTime.Now.ToString("g").Split(' ');}
                    @currentDate[0] at @currentDate[1]
                </p>
                <p class="im-float--right im-text--color-grey im-text--extra-bold-weight inline">
                    @Model.Count() Rat(s)
                </p>
            </div>

        </div>
</code>```

答:
You should remove the @ character in your if statement. Because @ is used to specify the C# code in razor. But if you start a C# code like if statement, you should not use the @ character again. Like this:

```<code>if (ViewBag.print != "PrintReport")
{
...

}
</code>```

But if your is statement nested in your HTML codes, you should start if statement with @. For example:

```<code><div class="im-container" style="width: 95%;">
     @if(ViewBag.print != "PrintReport")
     {
       ...
     }
     <div class="im-col--3">
     </div>
</div>
</code>```

The view is no longer accessing the @ViewBag after the
  @using(html.BeginForm)statement, and I don't know why.

Because you just used a C# code:

```<code>@using (Html.BeginForm(null, null, FormMethod.Post, new { id = "ReportForm" }))
{
if (ViewBag.print != "PrintReport")
        {
</code>```

And you didn't add a HTML code now. So, it percieves that you are using C# code. But if you start to add HTML codes, it realises the HTML code and after that you should add @ before adding new C# codes.

So you don't have to use @ in your C# statements but you have to use it where your C# codes nested in HTML codes. Like this:

```<code><p class="inline">
     - @ViewBag.status, @ViewBag.site, @ViewBag.team, @ViewBag.user
</p>
</code>```

Finally, for your code sample, you should change it like that:

```<code><body>
    @*@if ((ViewBag.site != "Sites" && ViewBag.site != null) || ViewBag.site != "PrintThis")
        {*@
    @using (Html.BeginForm(null, null, FormMethod.Post, new { id = "ReportForm" }))
    {
        if (@ViewBag.print != "PrintReport")
        {
            <div class="im-row im-padding-4 im-padding-top-16" id="Header" style="width: 100%;">

                <div class="im-container" style="width: 95%;">

                    <div class="im-col--3">
                        @Html.DropDownList(
                                 "OrderSelector",
                                 new SelectList(new[]
                                 {
                                     new SelectListItem {Text = "L", Value = Url.Action("Pdf", "Report/", new {SecurityCode = ViewData["SCode"], site = ViewBag.site, team = ViewBag.team, sortOrder = "L"})},
                                     new SelectListItem {Text = "R", Value = Url.Action("Pdf", "Report/", new {SecurityCode = ViewData["SCode"], site = ViewBag.site, team = ViewBag.team, sortOrder = "R"})},
                                     new SelectListItem {Text = "D", Value = Url.Action("Pdf", "Report/", new {SecurityCode = ViewData["SCode"], site = ViewBag.site, team = ViewBag.team, sortOrder = "D"})},
                                     new SelectListItem {Text = "T", Value = Url.Action("tPdf", "Report/", new {SecurityCode = ViewData["SCode"], site = ViewBag.site, team = ViewBag.team, sortOrder = "T"})},
                                 }, "Value", "Text"),
                                 new { id = "OrderSelector", @class = "sortOrder", onchange = "CallChangeFunc(this.value)" }
                                 )
                        <input id="SCode" type="hidden" value="@ViewData["SCode"]" />
                        <input id="SelectedSort" type="hidden" value="@ViewBag.sortOrder" />
                    </div>
                    <div class="im-col--5" style="margin-top: 15px;">
                        <span>(to change your default sort preference, click on the 'Settings' tab)</span>
                    </div>
                    <div class="im-col--2">
                        @Html.ActionLink("Print", "Print", "Report", new { site = ViewBag.site, team = ViewBag.team, sortOrder = ViewBag.sortOrder }, new { @class = "im-btn im-btn--primary im-btn--sm printBtn", id = "PrintPdf" })
                    </div>

                    <div class="im-row im-padding-4  im-col--12" style="width: 100%;">
                        <div class="im-container">
                            <hr />
                        </div>
                    </div>
                </div>
            </div>
        }
    }
    <div class="im-container Report im-no-padding-left" style="width: 95%;" id="Report">
        <div class="im-row title">
            <div class="im-col--6 im-no-padding-left">
                <p class="im-text--extra-bold-weight inline">
                    CC
                </p>
                <p class="inline">
                    - @ViewBag.status, @ViewBag.site, @ViewBag.team, @ViewBag.user
                </p>
            </div>
            <div class="im-col--6">
                <p class="im-text--extra-bold-weight inline">
                    @{ string[] currentDate = DateTime.Now.ToString("g").Split(' ');}
                    @currentDate[0] at @currentDate[1]
                </p>
                <p class="im-float--right im-text--color-grey im-text--extra-bold-weight inline">
                    @Model.Count() Rat(s)
                </p>
            </div>

        </div>
    </div>
</body>
</code>```

Body:
The view is no longer accessing the @ViewBag after the @using(html.BeginForm)statement, and I don't know why.  I get an error "The name 'ViewBag' does not exist in the current context". Why is that?  Any help would be appreciated.

@{ Layout = null; }

@model IEnumerable<ReportViewModel>
<!DOCTYPE html>

    <meta name="viewport" content="width=device-width" />
    <link href="StyleSheets/css" rel="stylesheet" />
    <link rel="stylesheet" type="text/css" href="~/StyleSheets/css" />
    <link rel="stylesheet" type="text/css" href="~/StyleSheets/css" />

    <title>@ViewBag.title</title>

    @*@if ((ViewBag.site != "Sites" && ViewBag.site != null) || ViewBag.site != "PrintThis")
        {*@
    @using (Html.BeginForm(null, null, FormMethod.Post, new { id = "ReportForm" }))
        {
            if (@ViewBag.print != "PrintReport")
            {

                        @Html.DropDownList(
                                 "OrderSelector",
                                 new SelectList(new[]
                                 {
                                     new SelectListItem {Text = "L", Value = @Url.Action("Pdf", "Report/", new {SecurityCode = @ViewData["SCode"], site = @ViewBag.site, team = @ViewBag.team, sortOrder = "L"})},
                                     new SelectListItem {Text = "R", Value = @Url.Action("Pdf", "Report/", new {SecurityCode = @ViewData["SCode"], site = @ViewBag.site, team = @ViewBag.team, sortOrder = "R"})},
                                     new SelectListItem {Text = "D", Value = @Url.Action("Pdf", "Report/", new {SecurityCode = @ViewData["SCode"], site = @ViewBag.site, team = @ViewBag.team, sortOrder = "D"})},
                                     new SelectListItem {Text = "T", Value = @Url.Action("tPdf", "Report/", new {SecurityCode = @ViewData["SCode"], site = @ViewBag.site, team = @ViewBag.team, sortOrder = "T"})},
                                 }, "Value", "Text"),
                                 new { id = "OrderSelector", @class = "sortOrder", onchange = "CallChangeFunc(this.value)" }
                                 )
                        <input id="SCode" type="hidden" value="@ViewData["SCode"]" />
                        <input id="SelectedSort" type="hidden" value="@ViewBag.sortOrder" />

                        (to change your default sort preference, click on the 'Settings' tab)

                        @Html.ActionLink("Print", "Print", "Report", new { site = @ViewBag.site, team = @ViewBag.team, sortOrder = @ViewBag.sortOrder }, new { @class = "im-btn im-btn--primary im-btn--sm printBtn", id = "PrintPdf" })

        }
    }

                    CC

                    - @ViewBag.status, @ViewBag.site, @ViewBag.team, @ViewBag.user

                    @{ string[] currentDate = DateTime.Now.ToString("g").Split(' ');}
                    @currentDate[0] at @currentDate[1]

                    @Model.Count() Rat(s)

Body:
You should remove the @ character in your if statement. Because @ is used to specify the C# code in razor. But if you start a C# code like if statement, you should not use the @ character again. Like this:

if (ViewBag.print != "PrintReport")
{
...

}

But if your is statement nested in your HTML codes, you should start if statement with @. For example:

<div class="im-container" style="width: 95%;">
     @if(ViewBag.print != "PrintReport")
     {
       ...
     }
     <div class="im-col--3">
     </div>
</div>

The view is no longer accessing the @ViewBag after the
  @using(html.BeginForm)statement, and I don't know why.

Because you just used a C# code:

@using (Html.BeginForm(null, null, FormMethod.Post, new { id = "ReportForm" }))
{
if (ViewBag.print != "PrintReport")
        {

And you didn't add a HTML code now. So, it percieves that you are using C# code. But if you start to add HTML codes, it realises the HTML code and after that you should add @ before adding new C# codes.

So you don't have to use @ in your C# statements but you have to use it where your C# codes nested in HTML codes. Like this:

<p class="inline">
     - @ViewBag.status, @ViewBag.site, @ViewBag.team, @ViewBag.user
</p>

Finally, for your code sample, you should change it like that:

<body>
    @*@if ((ViewBag.site != "Sites" && ViewBag.site != null) || ViewBag.site != "PrintThis")
        {*@
    @using (Html.BeginForm(null, null, FormMethod.Post, new { id = "ReportForm" }))
    {
        if (@ViewBag.print != "PrintReport")
        {
            <div class="im-row im-padding-4 im-padding-top-16" id="Header" style="width: 100%;">

                <div class="im-container" style="width: 95%;">

                    <div class="im-col--3">
                        @Html.DropDownList(
                                 "OrderSelector",
                                 new SelectList(new[]
                                 {
                                     new SelectListItem {Text = "L", Value = Url.Action("Pdf", "Report/", new {SecurityCode = ViewData["SCode"], site = ViewBag.site, team = ViewBag.team, sortOrder = "L"})},
                                     new SelectListItem {Text = "R", Value = Url.Action("Pdf", "Report/", new {SecurityCode = ViewData["SCode"], site = ViewBag.site, team = ViewBag.team, sortOrder = "R"})},
                                     new SelectListItem {Text = "D", Value = Url.Action("Pdf", "Report/", new {SecurityCode = ViewData["SCode"], site = ViewBag.site, team = ViewBag.team, sortOrder = "D"})},
                                     new SelectListItem {Text = "T", Value = Url.Action("tPdf", "Report/", new {SecurityCode = ViewData["SCode"], site = ViewBag.site, team = ViewBag.team, sortOrder = "T"})},
                                 }, "Value", "Text"),
                                 new { id = "OrderSelector", @class = "sortOrder", onchange = "CallChangeFunc(this.value)" }
                                 )
                        <input id="SCode" type="hidden" value="@ViewData["SCode"]" />
                        <input id="SelectedSort" type="hidden" value="@ViewBag.sortOrder" />
                    </div>
                    <div class="im-col--5" style="margin-top: 15px;">
                        <span>(to change your default sort preference, click on the 'Settings' tab)</span>
                    </div>
                    <div class="im-col--2">
                        @Html.ActionLink("Print", "Print", "Report", new { site = ViewBag.site, team = ViewBag.team, sortOrder = ViewBag.sortOrder }, new { @class = "im-btn im-btn--primary im-btn--sm printBtn", id = "PrintPdf" })
                    </div>

                    <div class="im-row im-padding-4  im-col--12" style="width: 100%;">
                        <div class="im-container">
                            <hr />
                        </div>
                    </div>
                </div>
            </div>
        }
    }
    <div class="im-container Report im-no-padding-left" style="width: 95%;" id="Report">
        <div class="im-row title">
            <div class="im-col--6 im-no-padding-left">
                <p class="im-text--extra-bold-weight inline">
                    CC
                </p>
                <p class="inline">
                    - @ViewBag.status, @ViewBag.site, @ViewBag.team, @ViewBag.user
                </p>
            </div>
            <div class="im-col--6">
                <p class="im-text--extra-bold-weight inline">
                    @{ string[] currentDate = DateTime.Now.ToString("g").Split(' ');}
                    @currentDate[0] at @currentDate[1]
                </p>
                <p class="im-float--right im-text--color-grey im-text--extra-bold-weight inline">
                    @Model.Count() Rat(s)
                </p>
            </div>

        </div>
    </div>
</body>


问:
"invalid (do_set) left-hand side to assignment" when trying to summarize
I'm trying to summarize some grouped data and have the following code:

```<code>yearly.users <- group_by(df, Year)

yearly.users <- summarise(yearly.users,
                         total.users <- sum(participants),
                         mean.users <- mean(participants))
</code>```

This actually works the first time I pass through it. But if I try to change the parameters in the summarize variable, I get:

```<code>Error in summarise_impl(.data, dots) :
  invalid (do_set) left-hand side to assignment
</code>```

Don't know how to interpret this. Any help is appreciated.

答:
The issue is stemming from the use of <- in summarise().

The operation will work the first time, but with some side-effects that cause the error.  When using <- we assign the results both to global and the resulting data.frame (see the ls() output).  We also create some weird variable names.  If you clear out your environment each time before running these commands you won't get the error (but definitely not the safest thing to do).  Using = for defining values in summarise() will get the desired behavior without these side-effects.

using <-

```<code>library(dplyr)

df_1 <- group_by(mtcars, gear)
df_1 <- summarise(df_1,
                  total.wt <- sum(wt),
                  mean.wt  <- mean(wt))
ls()
# [1] "df_1"     "mean.wt"  "total.wt"
names(df_1)
# [1] "gear"                "total.wt <- sum(wt)" "mean.wt <- mean(wt)"

#running the above code will now give the below error if we dont run rm(list=ls()) first
#Error in summarise_impl(.data, dots) :
#   invalid (do_set) left-hand side to assignment
</code>```

using =

```<code>rm(list=ls())
df_2 <- group_by(mtcars, gear)
df_2 <- summarise(df_2,
                  total.wt = sum(wt),
                  mean.wt  = mean(wt))
ls()
# [1] "df_2"
names(df_2)
# [1] "gear"     "total.wt" "mean.wt"
</code>```

Body:
I'm trying to summarize some grouped data and have the following code:

yearly.users <- group_by(df, Year)

yearly.users <- summarise(yearly.users,
                         total.users <- sum(participants),
                         mean.users <- mean(participants))

This actually works the first time I pass through it. But if I try to change the parameters in the summarize variable, I get:

Error in summarise_impl(.data, dots) :
  invalid (do_set) left-hand side to assignment

Don't know how to interpret this. Any help is appreciated.

Body:
The issue is stemming from the use of <- in summarise().

The operation will work the first time, but with some side-effects that cause the error.  When using <- we assign the results both to global and the resulting data.frame (see the ls() output).  We also create some weird variable names.  If you clear out your environment each time before running these commands you won't get the error (but definitely not the safest thing to do).  Using = for defining values in summarise() will get the desired behavior without these side-effects.

using <-

library(dplyr)

df_1 <- group_by(mtcars, gear)
df_1 <- summarise(df_1,
                  total.wt <- sum(wt),
                  mean.wt  <- mean(wt))
ls()
# [1] "df_1"     "mean.wt"  "total.wt"
names(df_1)
# [1] "gear"                "total.wt <- sum(wt)" "mean.wt <- mean(wt)"

#running the above code will now give the below error if we dont run rm(list=ls()) first
#Error in summarise_impl(.data, dots) :
#   invalid (do_set) left-hand side to assignment

using =

rm(list=ls())
df_2 <- group_by(mtcars, gear)
df_2 <- summarise(df_2,
                  total.wt = sum(wt),
                  mean.wt  = mean(wt))
ls()
# [1] "df_2"
names(df_2)
# [1] "gear"     "total.wt" "mean.wt"


问:
FileNotFoundException when clicking on button to upload audio
I am uploading audio on soundcloud server but when i click upload button it throws FileNotFoundException.After uploading a response from server has to be generated.plss help me guys. please correct me if i am making mistake somewhere.

There are 2 situation in which upload function is performed.
1.Recording of only one page story audio and uloding it.(in this case the audio is being uploade).
2. Recording of more than one page story in which after uploading of 1st page audio the 2nd page will come as response from my server.(In this case its throwing FileNotFound Exception).

```<code>        upload.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String tag_string_req = "req_login";
                StringRequest postStringRequest = new StringRequest(Request.Method.POST, SC_LOGIN_LINK,
                        new Response.Listener<String>() {

                            @Override
                            public void onResponse(String response) {
                                Log.d(TAG,"Reponse Check for sound upload login :"+response);

                                // Log.d(TAG,"Object Check :"+json);
                                try {
                                    JSONObject json = new JSONObject(response);
                                    access_token = json.getString("access_token");
                                    expires_in = json.getString("expires_in");
                                    refresh_token = json.getString("refresh_token");
//                                doFileUpload();
                                    new AsyncTaskRunner().execute();
                                } catch (JSONException e) {
                                    e.printStackTrace();
                                }
                            }
                        },
                        new Response.ErrorListener() {
                            @Override
                            public void onErrorResponse(VolleyError error) {
                                //Toast.makeText(AccessToken.this, error.toString(), Toast.LENGTH_LONG).show();
                                Log.e(TAG, "Error Response Check :" + error);

                            }
                        }){

                    @Override
                    protected Map<String, String> getParams() {
                        Map<String, String> params = new HashMap<String, String>();
                        params.put("client_id", client_id);
                        params.put("client_secret",client_secret);
                        params.put("grant_type",grant_type);
                        params.put("username",username);
                        params.put("password",user_password);
                        Log.d(TAG, "Params :" + params);
                        return params;

                    }

                };                    AppController.getInstance().addToRequestQueue(postStringRequest, tag_string_req);
            }
        });

    }
    private void mergeAudioFiles(){
        try {
            File tempFolder = new File(mRawAudioFolder.getPath());
            Movie[] movies = new Movie[tempFolder.listFiles().length];
            int i = 0;
            for (File saveTempFile : tempFolder.listFiles()) {
                try {
                    movies[i] = MovieCreator.build(new FileDataSourceImpl(saveTempFile));
                } catch (IOException e) {
                    e.printStackTrace();
                }
                i++;
            }

            final Movie finalMovie = new Movie();

            List<Track> audioTracks = new ArrayList<>();
            for (Movie movie : movies) {
                for (Track track : movie.getTracks()) {
                }
            }
            finalMovie.addTrack(new AppendTrack(audioTracks.toArray(new Track[audioTracks.size()])));
            final Container container = new DefaultMp4Builder().build(finalMovie);
            mergedFile = new File(mAudioFolder.getPath()+"/merged.3gp");
            final FileOutputStream fos = new FileOutputStream(mergedFile);
            FileChannel fc = new RandomAccessFile(mergedFile, "rw").getChannel();
            container.writeContainer(fc);
            fc.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    public static void createAudioFolder() {
        File movieFile = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MOVIES);
        mRawAudioFolder = new File(movieFile, "Temp");
        mAudioFolder = new File(movieFile, "The Tagore Project");
        if (!mAudioFolder.exists()) {
            mAudioFolder.mkdirs();
        }
        if (!mRawAudioFolder.exists()) {
            mRawAudioFolder.mkdirs();
        }
    }
    public byte[] toByteArray(InputStream in) throws IOException {
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        int read = 0;
        byte[] buffer = new byte[1024];
        while (read != -1) {
            read = in.read(buffer);
            if (read != -1)
                out.write(buffer,0,read);
        }
        out.close();
        return out.toByteArray();
    }

    public void forwardtoOurServer() {

        String tag_string_req = "req_login";
        StringRequest postStringRequest = new StringRequest(Request.Method.POST, RECORD_COMPOSITION_API,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        Log.d(TAG, "Audio Upload Response Check :" + response);

                        Log.d(TAG,"Object Check :"+response);
                        try {
                            JSONObject json = new JSONObject(response);
                            String code = json.getString("code");
                            if (String.valueOf(code).equals("200")) {

                                JSONObject upload = json.getJSONObject("upload");
                                JSONObject Booking = json.getJSONObject("upload").getJSONObject("Booking");
                                JSONObject Composition = json.getJSONObject("upload").getJSONObject("Composition");
                                JSONObject TableofContents = json.getJSONObject("upload").getJSONObject("TableOfContent");
                                String content = Composition.getString("content");
                                String pageno = Composition.getString("pageno");
                                String tocid = Composition.getString("table_of_content_id");
                                String wrd_count = Composition.getString("wordcount");
                                String tocName = TableofContents.getString("name");

                            } else {
                                String errorMsg = json.getString("error_msg");
                                Toast.makeText(getApplicationContext(),
                                        errorMsg, Toast.LENGTH_LONG).show();
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        Log.e(TAG, "Error Response Check :" + error);

                    }
                }) {

            @RequiresApi(api = Build.VERSION_CODES.N)
            @Override
            protected Map<String, String> getParams() {
                Map<String, String> params = new HashMap<String, String>();
                params.put("data[Booking][id]",bookingId);
                params.put("data[Booking][contributor_id]",contributor_id);
                params.put("data[Booking][table_of_content_id]",tocId);
                params.put("data[Booking][cdn_id]",vs_cdn_id);
                params.put("data[Booking][secret_token]",secret_token);
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
                sdf.setTimeZone(TimeZone.getTimeZone("GMT"));
                Date now = new Date();
                String strDate = sdf.format(now);
                params.put("data[Booking][uploaded_on]",strDate);
                Log.d(TAG, "Params :" + params);
                return params;
            }

            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                Map<String, String> headers = new HashMap<String, String>();
                headers.put("Content-Type", "application/x-www-form-urlencoded");
                headers.put("UUID", device_uuid);
                headers.put("APPID", "2A192A0C22");
                headers.put("USERID", "1");
                headers.put("PLATFORM", "Andriod");
                headers.put("APP_REQUEST", "1");
                headers.put("PLATFORMVERSION",androidOS);
                return headers;
            }

        };

        AppController.getInstance().addToRequestQueue(postStringRequest, tag_string_req);

    }
    public void MediaRecorderReady(){
        mediaRecorder=new MediaRecorder();
        mediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
        mediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
        mediaRecorder.setAudioEncoder(MediaRecorder.OutputFormat.AMR_NB);
        mediaRecorder.setOutputFile(AudioSavePathInDevice);
    }

    public String CreateRandomAudioFileName(int string){
        StringBuilder stringBuilder = new StringBuilder( string );
        int i = 0 ;
        while(i < string ) {
            stringBuilder.append(RandomAudioFileName.
                    charAt(random.nextInt(RandomAudioFileName.length())));

            i++ ;
        }
        return stringBuilder.toString();
    }

    private void requestPermission() {
        ActivityCompat.requestPermissions(RecordComposition.this, new
                String[]{WRITE_EXTERNAL_STORAGE, RECORD_AUDIO}, RequestPermissionCode);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode,
                                           String permissions[], int[] grantResults) {
        switch (requestCode) {
            case RequestPermissionCode:
                if (grantResults.length> 0) {
                    boolean StoragePermission = grantResults[0] ==
                            PackageManager.PERMISSION_GRANTED;
                    boolean RecordPermission = grantResults[1] ==
                            PackageManager.PERMISSION_GRANTED;

                    if (StoragePermission && RecordPermission) {
                        Toast.makeText(RecordComposition.this, "Permission Granted",
                                Toast.LENGTH_LONG).show();
                    } else {
                        Toast.makeText(RecordComposition.this,"Permission Denied",Toast.LENGTH_LONG).show();
                    }
                }
                break;
        }
    }

    public boolean checkPermission() {
        int result = ContextCompat.checkSelfPermission(getApplicationContext(),
                WRITE_EXTERNAL_STORAGE);
        int result1 = ContextCompat.checkSelfPermission(getApplicationContext(),
                RECORD_AUDIO);
        return result == PackageManager.PERMISSION_GRANTED &&
                result1 == PackageManager.PERMISSION_GRANTED;
    }
    private class AsyncTaskRunner extends AsyncTask<String,Void,String> {
        @Override
        protected String doInBackground(String... params) {
            doFileUpload();
            return null;
        }
    }
    private void doFileUpload(){
        HttpURLConnection conn = null;
        //DataOutputStream dos = null;
        //DataInputStream inStream = null;
        String lineEnd = "\r\n";
        String twoHyphens = "--";
        String boundary =  "*****";
        int bytesRead, bytesAvailable, bufferSize;
        byte[] buffer;
        int maxBufferSize = 1*1024*1024;
        String responseFromServer = "";
        String urlString = "https://api.soundcloud.com/tracks";
        try
        {
            //------------------ CLIENT REQUEST
            FileInputStream fileInputStream = new FileInputStream(mergedFile);
            // open a URL connection to the Servlet
            URL url = new URL   (urlString);
            // Open a HTTP connection to the URL
            conn = (HttpURLConnection) url.openConnection();
            conn.setDoInput(true);
            conn.setDoOutput(true);

            conn.setUseCaches(false);

            conn.setRequestMethod("POST");
            conn.setRequestProperty("Connection", "Keep-Alive");
            conn.setRequestProperty("Content-Type", "multipart/form-data;boundary="+boundary);
            DataOutputStream dos = new DataOutputStream( conn.getOutputStream() );
            //Adding oauth token
            dos.writeBytes(twoHyphens + boundary + lineEnd);
            dos.writeBytes("Content-Disposition: form-data; name=\"oauth_token\""+lineEnd+lineEnd+access_token+lineEnd);
//            dos.writeBytes(lineEnd);
            //Adding Track title
            dos.writeBytes(twoHyphens + boundary + lineEnd);
            dos.writeBytes("Content-Disposition: form-data; name=\"track[title]\""+lineEnd+lineEnd+tocName+"by Contributor"+":"+" "+contributorName+lineEnd);
            //Track taglist
            dos.writeBytes(twoHyphens + boundary + lineEnd);
            dos.writeBytes("Content-Disposition: form-data; name=\"track[tag_list]\""+lineEnd+lineEnd+"Tagore Project"+lineEnd);
            //Add sharing
            dos.writeBytes(twoHyphens + boundary + lineEnd);
            dos.writeBytes("Content-Disposition: form-data; name=\"track[sharing]\""+lineEnd+lineEnd+"private"+lineEnd);
            dos.writeBytes(lineEnd);

            dos.writeBytes(twoHyphens + boundary + lineEnd);
            dos.writeBytes("Content-Disposition: form-data; name=\"track[asset_data]\";filename=\"" + mergedFile + "\"" + lineEnd);
            dos.writeBytes("Content-Type: audio/mpeg"+lineEnd+lineEnd);
            // create a buffer of maximum size
            bytesAvailable = fileInputStream.available();
            bufferSize = Math.min(bytesAvailable, maxBufferSize);
            buffer = new byte[bufferSize];
            // read file and write it into form...
            bytesRead = fileInputStream.read(buffer, 0, bufferSize);

            while (bytesRead > 0)
            {
                dos.write(buffer, 0, bufferSize);
                bytesAvailable = fileInputStream.available();
                bufferSize = Math.min(bytesAvailable, maxBufferSize);
                bytesRead = fileInputStream.read(buffer, 0, bufferSize);
            }

            dos.writeBytes(lineEnd+twoHyphens + boundary + twoHyphens + lineEnd);
            fileInputStream.close();
            dos.flush();
            dos.close();
            Log.e("Debug","File is written - "+mergedFile+" - "+conn.getResponseCode());
        }
        catch (MalformedURLException ex)
        {
            Log.e("Debug", "error: " + ex.getMessage(), ex);
            Toast.makeText(this, ex.getMessage(), Toast.LENGTH_SHORT).show();
        }
        catch (IOException ioe)
        {
            Log.e("Debug", "error: " + ioe.getMessage(), ioe);
            Toast.makeText(this, ioe.getMessage(), Toast.LENGTH_SHORT).show();
        }
        try {
            BufferedReader inStream = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            String str;
            Log.e("Debug","Before while");
            while (( str = inStream.readLine()  ) != null)
            {
                Log.e("Debug","Server Response "+str);
                JSONObject response = new JSONObject(str);
                vs_cdn_id = response.getString("id");
                secret_token = response.getString("secret_token");
                forwardtoOurServer();
            }
            inStream.close();
        }
        catch (IOException ioex){
            Log.e("Debug", "error: " + ioex.getMessage(), ioex);
        } catch (JSONException e) {
            e.printStackTrace();
        } catch (Exception ex){
            ex.printStackTrace();
        }
    }
</code>```

Log:

```<code>File is written - /storage/emulated/0/Movies/The Tagore Project/merged.3gp - 500
      error: https://api.soundcloud.com/tracks
                                                                                java.io.FileNotFoundException: https://api.soundcloud.com/tracks
                                                                                at com.android.okhttp.internal.huc.HttpURLConnectionImpl.getInputStream(HttpURLConnectionImpl.java:238)
                                                                                at com.android.okhttp.internal.huc.DelegatingHttpsURLConnection.getInputStream(DelegatingHttpsURLConnection.java:210)
                                                                                at com.android.okhttp.internal.huc.HttpsURLConnectionImpl.getInputStream(HttpsURLConnectionImpl.java)
                                                                                at com.showhow2.www.thetagoreproject.RecordComposition.doFileUpload(RecordComposition.java:923)
                                                                                at com.showhow2.www.thetagoreproject.RecordComposition.access$2400(RecordComposition.java:73)
                                                                                at com.showhow2.www.thetagoreproject.RecordComposition$AsyncTaskRunner.doInBackground(RecordComposition.java:829)
                                                                                at com.showhow2.www.thetagoreproject.RecordComposition$AsyncTaskRunner.doInBackground(RecordComposition.java:824)
                                                                                at android.os.AsyncTask$2.call(AsyncTask.java:295)
                                                                                at java.util.concurrent.FutureTask.run(FutureTask.java:237)
                                                                                at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:234)
                                                                                at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113)
                                                                                at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588)
                                                                                at java.lang.Thread.run(Thread.java:818)
</code>```

答:
Add this on your code in your Activity class

```<code>@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_login);

    ArrayList<String> names = new ArrayList<>();
    ArrayList<Integer> types = new ArrayList<>();

    //add item to manes and types array

    ListViewAdapter customList = new ListViewAdapter(this, names, types);
    list = (ListView) findViewById(R.id.lv);
    list.setAdapter(customList);
}
</code>```

This is ListViewAdapter class

```<code>public class ListViewAdapter extends ArrayAdapter<String> {
private ArrayList<String> names;
ArrayList<Integer> types;
private Activity context;

public ListViewAdapter(Activity context, ArrayList<String> names, ArrayList<Integer> types) {
    super(context, R.layout.item_rating_rows, names);
    this.context = context;
    this.names = names;
    this.types = types;
}

@Override
public View getView(final int position, View convertView, ViewGroup parent) {
    LayoutInflater inflater = context.getLayoutInflater();
    View listViewItem = inflater.inflate(R.layout.item_rating_rows, null, true);

    Button btn = (Button) listViewItem.findViewById(R.id.btn);

    btn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Log.d("__onclick", "" + view.getId());
        }
    });

    return listViewItem;
}
</code>```

}

Body:
I am uploading audio on soundcloud server but when i click upload button it throws FileNotFoundException.After uploading a response from server has to be generated.plss help me guys. please correct me if i am making mistake somewhere.

There are 2 situation in which upload function is performed.
1.Recording of only one page story audio and uloding it.(in this case the audio is being uploade).
2. Recording of more than one page story in which after uploading of 1st page audio the 2nd page will come as response from my server.(In this case its throwing FileNotFound Exception).

        upload.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String tag_string_req = "req_login";
                StringRequest postStringRequest = new StringRequest(Request.Method.POST, SC_LOGIN_LINK,
                        new Response.Listener<String>() {

                            @Override
                            public void onResponse(String response) {
                                Log.d(TAG,"Reponse Check for sound upload login :"+response);

                                // Log.d(TAG,"Object Check :"+json);
                                try {
                                    JSONObject json = new JSONObject(response);
                                    access_token = json.getString("access_token");
                                    expires_in = json.getString("expires_in");
                                    refresh_token = json.getString("refresh_token");
//                                doFileUpload();
                                    new AsyncTaskRunner().execute();
                                } catch (JSONException e) {
                                    e.printStackTrace();
                                }
                            }
                        },
                        new Response.ErrorListener() {
                            @Override
                            public void onErrorResponse(VolleyError error) {
                                //Toast.makeText(AccessToken.this, error.toString(), Toast.LENGTH_LONG).show();
                                Log.e(TAG, "Error Response Check :" + error);

                            }
                        }){

                    @Override
                    protected Map<String, String> getParams() {
                        Map<String, String> params = new HashMap<String, String>();
                        params.put("client_id", client_id);
                        params.put("client_secret",client_secret);
                        params.put("grant_type",grant_type);
                        params.put("username",username);
                        params.put("password",user_password);
                        Log.d(TAG, "Params :" + params);
                        return params;

                    }

                };                    AppController.getInstance().addToRequestQueue(postStringRequest, tag_string_req);
            }
        });

    }
    private void mergeAudioFiles(){
        try {
            File tempFolder = new File(mRawAudioFolder.getPath());
            Movie[] movies = new Movie[tempFolder.listFiles().length];
            int i = 0;
            for (File saveTempFile : tempFolder.listFiles()) {
                try {
                    movies[i] = MovieCreator.build(new FileDataSourceImpl(saveTempFile));
                } catch (IOException e) {
                    e.printStackTrace();
                }
                i++;
            }

            final Movie finalMovie = new Movie();

            List<Track> audioTracks = new ArrayList<>();
            for (Movie movie : movies) {
                for (Track track : movie.getTracks()) {
                }
            }
            finalMovie.addTrack(new AppendTrack(audioTracks.toArray(new Track[audioTracks.size()])));
            final Container container = new DefaultMp4Builder().build(finalMovie);
            mergedFile = new File(mAudioFolder.getPath()+"/merged.3gp");
            final FileOutputStream fos = new FileOutputStream(mergedFile);
            FileChannel fc = new RandomAccessFile(mergedFile, "rw").getChannel();
            container.writeContainer(fc);
            fc.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    public static void createAudioFolder() {
        File movieFile = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MOVIES);
        mRawAudioFolder = new File(movieFile, "Temp");
        mAudioFolder = new File(movieFile, "The Tagore Project");
        if (!mAudioFolder.exists()) {
            mAudioFolder.mkdirs();
        }
        if (!mRawAudioFolder.exists()) {
            mRawAudioFolder.mkdirs();
        }
    }
    public byte[] toByteArray(InputStream in) throws IOException {
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        int read = 0;
        byte[] buffer = new byte[1024];
        while (read != -1) {
            read = in.read(buffer);
            if (read != -1)
                out.write(buffer,0,read);
        }
        out.close();
        return out.toByteArray();
    }

    public void forwardtoOurServer() {

        String tag_string_req = "req_login";
        StringRequest postStringRequest = new StringRequest(Request.Method.POST, RECORD_COMPOSITION_API,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        Log.d(TAG, "Audio Upload Response Check :" + response);

                        Log.d(TAG,"Object Check :"+response);
                        try {
                            JSONObject json = new JSONObject(response);
                            String code = json.getString("code");
                            if (String.valueOf(code).equals("200")) {

                                JSONObject upload = json.getJSONObject("upload");
                                JSONObject Booking = json.getJSONObject("upload").getJSONObject("Booking");
                                JSONObject Composition = json.getJSONObject("upload").getJSONObject("Composition");
                                JSONObject TableofContents = json.getJSONObject("upload").getJSONObject("TableOfContent");
                                String content = Composition.getString("content");
                                String pageno = Composition.getString("pageno");
                                String tocid = Composition.getString("table_of_content_id");
                                String wrd_count = Composition.getString("wordcount");
                                String tocName = TableofContents.getString("name");

                            } else {
                                String errorMsg = json.getString("error_msg");
                                Toast.makeText(getApplicationContext(),
                                        errorMsg, Toast.LENGTH_LONG).show();
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        Log.e(TAG, "Error Response Check :" + error);

                    }
                }) {

            @RequiresApi(api = Build.VERSION_CODES.N)
            @Override
            protected Map<String, String> getParams() {
                Map<String, String> params = new HashMap<String, String>();
                params.put("data[Booking][id]",bookingId);
                params.put("data[Booking][contributor_id]",contributor_id);
                params.put("data[Booking][table_of_content_id]",tocId);
                params.put("data[Booking][cdn_id]",vs_cdn_id);
                params.put("data[Booking][secret_token]",secret_token);
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
                sdf.setTimeZone(TimeZone.getTimeZone("GMT"));
                Date now = new Date();
                String strDate = sdf.format(now);
                params.put("data[Booking][uploaded_on]",strDate);
                Log.d(TAG, "Params :" + params);
                return params;
            }

            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                Map<String, String> headers = new HashMap<String, String>();
                headers.put("Content-Type", "application/x-www-form-urlencoded");
                headers.put("UUID", device_uuid);
                headers.put("APPID", "2A192A0C22");
                headers.put("USERID", "1");
                headers.put("PLATFORM", "Andriod");
                headers.put("APP_REQUEST", "1");
                headers.put("PLATFORMVERSION",androidOS);
                return headers;
            }

        };

        AppController.getInstance().addToRequestQueue(postStringRequest, tag_string_req);

    }
    public void MediaRecorderReady(){
        mediaRecorder=new MediaRecorder();
        mediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
        mediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
        mediaRecorder.setAudioEncoder(MediaRecorder.OutputFormat.AMR_NB);
        mediaRecorder.setOutputFile(AudioSavePathInDevice);
    }

    public String CreateRandomAudioFileName(int string){
        StringBuilder stringBuilder = new StringBuilder( string );
        int i = 0 ;
        while(i < string ) {
            stringBuilder.append(RandomAudioFileName.
                    charAt(random.nextInt(RandomAudioFileName.length())));

            i++ ;
        }
        return stringBuilder.toString();
    }

    private void requestPermission() {
        ActivityCompat.requestPermissions(RecordComposition.this, new
                String[]{WRITE_EXTERNAL_STORAGE, RECORD_AUDIO}, RequestPermissionCode);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode,
                                           String permissions[], int[] grantResults) {
        switch (requestCode) {
            case RequestPermissionCode:
                if (grantResults.length> 0) {
                    boolean StoragePermission = grantResults[0] ==
                            PackageManager.PERMISSION_GRANTED;
                    boolean RecordPermission = grantResults[1] ==
                            PackageManager.PERMISSION_GRANTED;

                    if (StoragePermission && RecordPermission) {
                        Toast.makeText(RecordComposition.this, "Permission Granted",
                                Toast.LENGTH_LONG).show();
                    } else {
                        Toast.makeText(RecordComposition.this,"Permission Denied",Toast.LENGTH_LONG).show();
                    }
                }
                break;
        }
    }

    public boolean checkPermission() {
        int result = ContextCompat.checkSelfPermission(getApplicationContext(),
                WRITE_EXTERNAL_STORAGE);
        int result1 = ContextCompat.checkSelfPermission(getApplicationContext(),
                RECORD_AUDIO);
        return result == PackageManager.PERMISSION_GRANTED &&
                result1 == PackageManager.PERMISSION_GRANTED;
    }
    private class AsyncTaskRunner extends AsyncTask<String,Void,String> {
        @Override
        protected String doInBackground(String... params) {
            doFileUpload();
            return null;
        }
    }
    private void doFileUpload(){
        HttpURLConnection conn = null;
        //DataOutputStream dos = null;
        //DataInputStream inStream = null;
        String lineEnd = "\r\n";
        String twoHyphens = "--";
        String boundary =  "*****";
        int bytesRead, bytesAvailable, bufferSize;
        byte[] buffer;
        int maxBufferSize = 1*1024*1024;
        String responseFromServer = "";
        String urlString = "https://api.soundcloud.com/tracks";
        try
        {
            //------------------ CLIENT REQUEST
            FileInputStream fileInputStream = new FileInputStream(mergedFile);
            // open a URL connection to the Servlet
            URL url = new URL   (urlString);
            // Open a HTTP connection to the URL
            conn = (HttpURLConnection) url.openConnection();
            conn.setDoInput(true);
            conn.setDoOutput(true);

            conn.setUseCaches(false);

            conn.setRequestMethod("POST");
            conn.setRequestProperty("Connection", "Keep-Alive");
            conn.setRequestProperty("Content-Type", "multipart/form-data;boundary="+boundary);
            DataOutputStream dos = new DataOutputStream( conn.getOutputStream() );
            //Adding oauth token
            dos.writeBytes(twoHyphens + boundary + lineEnd);
            dos.writeBytes("Content-Disposition: form-data; name=\"oauth_token\""+lineEnd+lineEnd+access_token+lineEnd);
//            dos.writeBytes(lineEnd);
            //Adding Track title
            dos.writeBytes(twoHyphens + boundary + lineEnd);
            dos.writeBytes("Content-Disposition: form-data; name=\"track[title]\""+lineEnd+lineEnd+tocName+"by Contributor"+":"+" "+contributorName+lineEnd);
            //Track taglist
            dos.writeBytes(twoHyphens + boundary + lineEnd);
            dos.writeBytes("Content-Disposition: form-data; name=\"track[tag_list]\""+lineEnd+lineEnd+"Tagore Project"+lineEnd);
            //Add sharing
            dos.writeBytes(twoHyphens + boundary + lineEnd);
            dos.writeBytes("Content-Disposition: form-data; name=\"track[sharing]\""+lineEnd+lineEnd+"private"+lineEnd);
            dos.writeBytes(lineEnd);

            dos.writeBytes(twoHyphens + boundary + lineEnd);
            dos.writeBytes("Content-Disposition: form-data; name=\"track[asset_data]\";filename=\"" + mergedFile + "\"" + lineEnd);
            dos.writeBytes("Content-Type: audio/mpeg"+lineEnd+lineEnd);
            // create a buffer of maximum size
            bytesAvailable = fileInputStream.available();
            bufferSize = Math.min(bytesAvailable, maxBufferSize);
            buffer = new byte[bufferSize];
            // read file and write it into form...
            bytesRead = fileInputStream.read(buffer, 0, bufferSize);

            while (bytesRead > 0)
            {
                dos.write(buffer, 0, bufferSize);
                bytesAvailable = fileInputStream.available();
                bufferSize = Math.min(bytesAvailable, maxBufferSize);
                bytesRead = fileInputStream.read(buffer, 0, bufferSize);
            }

            dos.writeBytes(lineEnd+twoHyphens + boundary + twoHyphens + lineEnd);
            fileInputStream.close();
            dos.flush();
            dos.close();
            Log.e("Debug","File is written - "+mergedFile+" - "+conn.getResponseCode());
        }
        catch (MalformedURLException ex)
        {
            Log.e("Debug", "error: " + ex.getMessage(), ex);
            Toast.makeText(this, ex.getMessage(), Toast.LENGTH_SHORT).show();
        }
        catch (IOException ioe)
        {
            Log.e("Debug", "error: " + ioe.getMessage(), ioe);
            Toast.makeText(this, ioe.getMessage(), Toast.LENGTH_SHORT).show();
        }
        try {
            BufferedReader inStream = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            String str;
            Log.e("Debug","Before while");
            while (( str = inStream.readLine()  ) != null)
            {
                Log.e("Debug","Server Response "+str);
                JSONObject response = new JSONObject(str);
                vs_cdn_id = response.getString("id");
                secret_token = response.getString("secret_token");
                forwardtoOurServer();
            }
            inStream.close();
        }
        catch (IOException ioex){
            Log.e("Debug", "error: " + ioex.getMessage(), ioex);
        } catch (JSONException e) {
            e.printStackTrace();
        } catch (Exception ex){
            ex.printStackTrace();
        }
    }

Log:

File is written - /storage/emulated/0/Movies/The Tagore Project/merged.3gp - 500
      error: https://api.soundcloud.com/tracks
                                                                                java.io.FileNotFoundException: https://api.soundcloud.com/tracks
                                                                                at com.android.okhttp.internal.huc.HttpURLConnectionImpl.getInputStream(HttpURLConnectionImpl.java:238)
                                                                                at com.android.okhttp.internal.huc.DelegatingHttpsURLConnection.getInputStream(DelegatingHttpsURLConnection.java:210)
                                                                                at com.android.okhttp.internal.huc.HttpsURLConnectionImpl.getInputStream(HttpsURLConnectionImpl.java)
                                                                                at com.showhow2.www.thetagoreproject.RecordComposition.doFileUpload(RecordComposition.java:923)
                                                                                at com.showhow2.www.thetagoreproject.RecordComposition.access$2400(RecordComposition.java:73)
                                                                                at com.showhow2.www.thetagoreproject.RecordComposition$AsyncTaskRunner.doInBackground(RecordComposition.java:829)
                                                                                at com.showhow2.www.thetagoreproject.RecordComposition$AsyncTaskRunner.doInBackground(RecordComposition.java:824)
                                                                                at android.os.AsyncTask$2.call(AsyncTask.java:295)
                                                                                at java.util.concurrent.FutureTask.run(FutureTask.java:237)
                                                                                at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:234)
                                                                                at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113)
                                                                                at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588)
                                                                                at java.lang.Thread.run(Thread.java:818)

Body:
Add this on your code in your Activity class

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_login);

    ArrayList<String> names = new ArrayList<>();
    ArrayList<Integer> types = new ArrayList<>();

    //add item to manes and types array

    ListViewAdapter customList = new ListViewAdapter(this, names, types);
    list = (ListView) findViewById(R.id.lv);
    list.setAdapter(customList);
}

This is ListViewAdapter class

public class ListViewAdapter extends ArrayAdapter<String> {
private ArrayList<String> names;
ArrayList<Integer> types;
private Activity context;

public ListViewAdapter(Activity context, ArrayList<String> names, ArrayList<Integer> types) {
    super(context, R.layout.item_rating_rows, names);
    this.context = context;
    this.names = names;
    this.types = types;
}

@Override
public View getView(final int position, View convertView, ViewGroup parent) {
    LayoutInflater inflater = context.getLayoutInflater();
    View listViewItem = inflater.inflate(R.layout.item_rating_rows, null, true);

    Button btn = (Button) listViewItem.findViewById(R.id.btn);

    btn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Log.d("__onclick", "" + view.getId());
        }
    });

    return listViewItem;
}

}


问:
Java 8 Distinct by property
In Java 8 how can I filter a collection using the Stream API by checking the distinctness of a property of each object?

For example I have a list of Person object and I want to remove people with the same name,

```<code>persons.stream().distinct();
</code>```

Will use the default equality check for a Person object, so I need something like,

```<code>persons.stream().distinct(p -> p.getName());
</code>```

Unfortunately the distinct() method has no such overload. Without modifying the equality check inside the Person class is it possible to do this succinctly?

答:
Similar approach which Saeed Zarinfam used but more Java 8 style:)</p>

```<code>persons.collect(Collectors.groupingBy(p -> p.getName())).values().stream()
 .map(plans -> plans.stream().findFirst().get())
 .collect(toList());
</code>```

Title: Java 8 Distinct by property

Body:
In Java 8 how can I filter a collection using the Stream API by checking the distinctness of a property of each object?

For example I have a list of Person object and I want to remove people with the same name,

persons.stream().distinct();

Will use the default equality check for a Person object, so I need something like,

persons.stream().distinct(p -> p.getName());

Unfortunately the distinct() method has no such overload. Without modifying the equality check inside the Person class is it possible to do this succinctly?

Body:
Similar approach which Saeed Zarinfam used but more Java 8 style:)

persons.collect(Collectors.groupingBy(p -> p.getName())).values().stream()
 .map(plans -> plans.stream().findFirst().get())
 .collect(toList());

ContentLicense: CC BY-SA 4.0


问:
Convert C array Record to Delphi
I Have this C code:

```<code>typedef enum { STB_Expression_Max} STB_OKAO_EXPRESSION;

typedef struct {STB_INT32 anScore[STB_Expression_Max];} STB_FRAME_RESULT_EXPRESSION;
</code>```

How can I convert the above code to array in Delphi?

答:
It could be:

const
  STB_Expression_Max = 0;

type
  STB_INT32 = ?; { ← define here }
  STB_FRAME_RESULT_EXPRESSION = record
    anScore: array[0..STB_Expression_Max] of STB_INT32;
  end;
```

Title: Convert C array Record to Delphi

Body:
I Have this C code:

typedef enum { STB_Expression_Max} STB_OKAO_EXPRESSION;

typedef struct {STB_INT32 anScore[STB_Expression_Max];} STB_FRAME_RESULT_EXPRESSION;

How can I convert the above code to array in Delphi?


问:
Checking if a file exists from stdin <
I'm trying to create validation on a Python script that should take a file from the commandline. Much like:

./script.py < somefilename

As you can see the filename could come without any sort of extension on it. This should also work on multiple platforms, preferably.

In terms of validation it should be able to hold lines of strings separated by a newline character \n.

This poses two problems that I can't really solve:

I want to ensure that the file is of a correct filetype (ie. can hold text)

Check so the file actually exists.

In my current form I use argparse to parse flags, but since the requirements have changed I need to use a more dynamic (they say), solution where I implement the < "piper". This is quite simple by using stdin.

But using stdin poses a problem as I can't verify that the file exists; a user might input textfile without a correct extension, which would display

'No such file or directory'

What I'd like to do is create a list of possible extensions that could hold text (like '.txt') and check if a file with that extension exists in case the inputted file doesn't exist in the current folder. Just to make it more robust...

This seems to be very difficult (if not impossible) when using stdin, as you can't properly interface with the filename on multiple platforms.

I've also tried using fileinput, but I can't use a fileinput.filename() until I'm already reading the file:

```<code>for line in fileinput.input():
    print fileinput.filename()
</code>```

Does anyone have any suggestions on how I can add some robust file validation on the above mentioned example (./script.py < somefilename)?

Is it even possible on multiple platforms?

答:
I'd suggest going back to argparse and checking for existence of input files. This function:

```<code>import os
def check_file(filename):
    possible_extensions = ('', '.txt', '.dat')
    for e in possible_extensions:
        if os.path.isfile(filename + e):
            return filename + e
    else:
        return None
</code>```

will return its argument if a file under that name exists, otherwise it will test possible extensions and return the first match, or return None if no match is found.

Title: Checking if a file exists from stdin <

Body:
I'm trying to create validation on a Python script that should take a file from the commandline. Much like:

./script.py < somefilename

As you can see the filename could come without any sort of extension on it. This should also work on multiple platforms, preferably.

In terms of validation it should be able to hold lines of strings separated by a newline character \n.

This poses two problems that I can't really solve:

I want to ensure that the file is of a correct filetype (ie. can hold text)

Check so the file actually exists.

In my current form I use argparse to parse flags, but since the requirements have changed I need to use a more dynamic (they say), solution where I implement the < "piper". This is quite simple by using stdin.

But using stdin poses a problem as I can't verify that the file exists; a user might input textfile without a correct extension, which would display

'No such file or directory'

What I'd like to do is create a list of possible extensions that could hold text (like '.txt') and check if a file with that extension exists in case the inputted file doesn't exist in the current folder. Just to make it more robust...

This seems to be very difficult (if not impossible) when using stdin, as you can't properly interface with the filename on multiple platforms.

I've also tried using fileinput, but I can't use a fileinput.filename() until I'm already reading the file:

for line in fileinput.input():
    print fileinput.filename()

Does anyone have any suggestions on how I can add some robust file validation on the above mentioned example (./script.py < somefilename)?

Is it even possible on multiple platforms?

Body:
I'd suggest going back to argparse and checking for existence of input files. This function:

import os
def check_file(filename):
    possible_extensions = ('', '.txt', '.dat')
    for e in possible_extensions:
        if os.path.isfile(filename + e):
            return filename + e
    else:
        return None

will return its argument if a file under that name exists, otherwise it will test possible extensions and return the first match, or return None if no match is found.


问:
How can I disable Ctrl+p in Awesomium?
I'm trying to disable the ctrl+p command in a WPF application with Awesomium. When you press ctrl+p Awesomium saves a pdf from the document.

I try with JavaScript and c# code but nothing works.

JS (it open the window before the function):

```<code>$(document).ready(function (e) {
    $('body').keydown(function (event) {
        // alert('this');
        if (event.which == 80 && event.ctrlKey) {
            return false;
            //alert('me');
        }
    });
});
</code>```

C# (just ignore it):

```<code>myAwesomium.KeyDown +) KeyyDown;

private void KeyyDown(object sender, KeyEventArgs e)
  {
    if ((Keyboard.Modifiers & ModifierKeys.Control) == ModifierKeys.Control)
  {
    #Something
  }
}
</code>```

答:
you should use PreviewKeyDown for that. There you need to set e.Handled = true, this will stop processing the keyhandling.

```<code>private void WebControl1_PreviewKeyDown(object sender, KeyEventArgs e)
{
    e.Handled = true;
}
</code>```

Hint: You should also set the ContextMenu of the WebControl to a new ContextMenu to prevent printing via the contextmenu entry.

Hope that it help.

Title: How can I disable Ctrl+p in Awesomium?

Body:
I'm trying to disable the ctrl+p command in a WPF application with Awesomium. When you press ctrl+p Awesomium saves a pdf from the document.

I try with JavaScript and c# code but nothing works.

JS (it open the window before the function):

$(document).ready(function (e) {
    $('body').keydown(function (event) {
        // alert('this');
        if (event.which == 80 && event.ctrlKey) {
            return false;
            //alert('me');
        }
    });
});

C# (just ignore it):

myAwesomium.KeyDown +) KeyyDown;

private void KeyyDown(object sender, KeyEventArgs e)
  {
    if ((Keyboard.Modifiers & ModifierKeys.Control) == ModifierKeys.Control)
  {
    #Something
  }
}

Body:
you should use PreviewKeyDown for that. There you need to set e.Handled = true, this will stop processing the keyhandling.

private void WebControl1_PreviewKeyDown(object sender, KeyEventArgs e)
{
    e.Handled = true;
}

Hint: You should also set the ContextMenu of the WebControl to a new ContextMenu to prevent printing via the contextmenu entry.

Hope that it help.


问:
Validate duplicate rows / columns
I need to do data validation to identify is there any duplicates in CodeA1, CodeA2 and Code A3 (columns).

```<code>  CodeA1 CodeA2 CodeA3
1   1     NA      5
2   3     1       3
3   8     3       3
4   3     NA      NA
5   4     1       2
6   1     8       3
</code>```

The rows in all columns (CodeA1, CodeA2, CodeA3) should be unique across.

Can somebody please help in R?

I would like to identify the duplicates across all the rows and have the result as below

```<code>  CodeA1 CodeA2 CodeA3  Duplicate
1   1     NA       5    No
2   3     1       3     Yes
3   8     3       3     Yes
4   3     NA      NA     No
5   4     1       2     No
6   1     8       3     No
</code>```

答:
Another possible solution using apply and unique. This will also identify a double NA as a duplicated, although you could modify it.

```<code> mydf <-
     data.frame(
         CodeA1 = c(1, 3, 8, 3, 4, 1),
         CodeA2 = c(NA, 1, 3, NA, 1, 9),
         CodeA3 = c(5, 3, 3, NA, 2, 3)
     )
 mydf$duplicated <-
     apply(mydf[, 1:3], 1, function(x) {
         ifelse(length(unique(x, is.na  = T)) < length(x), TRUE, FALSE)
     })
 mydf

  CodeA1 CodeA2 CodeA3 duplicated
1      1     NA      5      FALSE
2      3      1      3       TRUE
3      8      3      3       TRUE
4      3     NA     NA       TRUE
5      4      1      2      FALSE
6      1      9      3      FALSE
</code>```

Title: Validate duplicate rows / columns

Body:
I need to do data validation to identify is there any duplicates in CodeA1, CodeA2 and Code A3 (columns).

  CodeA1 CodeA2 CodeA3
1   1     NA      5
2   3     1       3
3   8     3       3
4   3     NA      NA
5   4     1       2
6   1     8       3

The rows in all columns (CodeA1, CodeA2, CodeA3) should be unique across.

Can somebody please help in R?

I would like to identify the duplicates across all the rows and have the result as below

  CodeA1 CodeA2 CodeA3  Duplicate
1   1     NA       5    No
2   3     1       3     Yes
3   8     3       3     Yes
4   3     NA      NA     No
5   4     1       2     No
6   1     8       3     No

Body:
Another possible solution using apply and unique. This will also identify a double NA as a duplicated, although you could modify it.

 mydf <-
     data.frame(
         CodeA1 = c(1, 3, 8, 3, 4, 1),
         CodeA2 = c(NA, 1, 3, NA, 1, 9),
         CodeA3 = c(5, 3, 3, NA, 2, 3)
     )
 mydf$duplicated <-
     apply(mydf[, 1:3], 1, function(x) {
         ifelse(length(unique(x, is.na  = T)) < length(x), TRUE, FALSE)
     })
 mydf

  CodeA1 CodeA2 CodeA3 duplicated
1      1     NA      5      FALSE
2      3      1      3       TRUE
3      8      3      3       TRUE
4      3     NA     NA       TRUE
5      4      1      2      FALSE
6      1      9      3      FALSE


问:
Key Value Pair in C Language
I am new to C programming and I am trying to create a key value structure as in Perl Programming. I saw one solution like :-

```<code>struct key_value
{
   int key;
   char* value;
};

struct key_value kv;

kv.key = 1;
kv.value = "foo";
</code>```

But I don't know how to access these values from this structure. Can someone enlight on this ?

答:
```<code>typedef struct key_value
{
   int key;
   char* value;
}List;

struct key_value k1;
struct key_value k2;
struct key_value k3;

k1.key = 1;
k1.value = "foo";
k2.key = 2;
k2.value = "sec";
k3.key = 3;
k3.value = "third";
</code>```

You will need to create N times the struct and give them values the way you did the first one. Or create array with N structs and iterate assign it values with a loop.

Array:

```<code>List arr[29];

int i;
for(i = 0;i<=28;i++){
    arr[i].key = i;
    arr[i].value = "W/e it needs to be";
}
</code>```

Title: Key Value Pair in C Language

Body:
I am new to C programming and I am trying to create a key value structure as in Perl Programming. I saw one solution like :-

struct key_value
{
   int key;
   char* value;
};

struct key_value kv;

kv.key = 1;
kv.value = "foo";

But I don't know how to access these values from this structure. Can someone enlight on this ?

Body:
typedef struct key_value
{
   int key;
   char* value;
}List;

struct key_value k1;
struct key_value k2;
struct key_value k3;

k1.key = 1;
k1.value = "foo";
k2.key = 2;
k2.value = "sec";
k3.key = 3;
k3.value = "third";

You will need to create N times the struct and give them values the way you did the first one. Or create array with N structs and iterate assign it values with a loop.

Array:

List arr[29];

int i;
for(i = 0;i<=28;i++){
    arr[i].key = i;
    arr[i].value = "W/e it needs to be";
}


问:
ListView baseadapter class implement TextWatcher
i have an baseadapter custom listview and edittext. I want to get data from edittext and change values of all the listview items with text watcher on text change. when i enter a new value text start changing instead of after i finish entering values.
im working in fragment.</p>

答:
You Try this
 Example and also search in google "listview Filter" you will get so many examples</p>


问:
Month and Date stored the wrong way around in ASP to SQL Server
I am creating a C# ASP page that takes dates set by the users in a text box (the date is cheosen using a calendar object and then sent to the text box) and saves them to an SQL server.  When the dates are entered, it stores them in MM-DD-YYYY instead of DD-MM-YYYY.  This obviously generates errors!  Can anyone help me to get the dates to store them in the format I want it in?</p>

```<code>protected void Page_Load(object sender, EventArgs e)
{

    if (!Page.IsPostBack)
    {
        DateTime today = DateTime.Now;
        DateTime sevenDays = today.AddDays(7);
        btnDelete.Enabled = false;
        txtStart.Text = today.ToShortDateString();
        txtEnd.Text = sevenDays.ToShortDateString();
    }
    updateGrid();
}
protected void btnSave_Click(object sender, EventArgs e)
{
    if (sqlCon.State == System.Data.ConnectionState.Closed)
        sqlCon.Open();
    SqlCommand sqlCmd = new SqlCommand("MessageUpdateOrCreate", sqlCon);
    sqlCmd.CommandType = System.Data.CommandType.StoredProcedure;
    sqlCmd.Parameters.AddWithValue("@MessageID", (hfMessageID.Value == "" ? 0 : Convert.ToInt32(hfMessageID.Value)));
    sqlCmd.Parameters.AddWithValue("@Sender", txtSender.Text.Trim());
    sqlCmd.Parameters.AddWithValue("@Receiver", txtReceiver.Text.Trim());
    sqlCmd.Parameters.AddWithValue("@Message", txtMessage.Text.Trim());
    sqlCmd.Parameters.AddWithValue("@Yeargroup", ddYear.Text.Trim());
    sqlCmd.Parameters.AddWithValue("@Title", txtTitle.Text.Trim());
    sqlCmd.Parameters.AddWithValue("@Date", txtStart.Text.Trim());
    sqlCmd.Parameters.AddWithValue("@Expiry", txtEnd.Text.Trim());

    sqlCmd.ExecuteNonQuery();
    sqlCon.Close();
    string messageID = hfMessageID.Value;
    clear();

    if (messageID == "")
        lblSuccess.Text = "New message Success";
    else
        lblSuccess.Text = "Updated Success";
    updateGrid();
}
</code>```

答:
Your problem is these two lines:

```<code>sqlCmd.Parameters.AddWithValue("@Date", txtStart.Text.Trim());
sqlCmd.Parameters.AddWithValue("@Expiry", txtEnd.Text.Trim());
</code>```

You are passing strings to a stored procedure that almost certainly expects a date. Which means the string will be converted to a date in a way you don't control.

So you need to take control. You need to parse the date in the way you need it to be (e.g. dd/mm/yyyy or mm/dd/yyyy). These links will help you with that:

datetime.parse and making it work with a specific format

https://www.hanselman.com/blog/DateParseExactAndTheSubtleGooThatIsDateTimeFormatStrings.aspx

Once you have parsed the string as a date:

Check that the date result is what you expected it to be

Pass that date (rather than the existing string) to the stored procedure

Body:
I am creating a C# ASP page that takes dates set by the users in a text box (the date is cheosen using a calendar object and then sent to the text box) and saves them to an SQL server.  When the dates are entered, it stores them in MM-DD-YYYY instead of DD-MM-YYYY.  This obviously generates errors!  Can anyone help me to get the dates to store them in the format I want it in?

protected void Page_Load(object sender, EventArgs e)
{

    if (!Page.IsPostBack)
    {
        DateTime today = DateTime.Now;
        DateTime sevenDays = today.AddDays(7);
        btnDelete.Enabled = false;
        txtStart.Text = today.ToShortDateString();
        txtEnd.Text = sevenDays.ToShortDateString();
    }
    updateGrid();
}
protected void btnSave_Click(object sender, EventArgs e)
{
    if (sqlCon.State == System.Data.ConnectionState.Closed)
        sqlCon.Open();
    SqlCommand sqlCmd = new SqlCommand("MessageUpdateOrCreate", sqlCon);
    sqlCmd.CommandType = System.Data.CommandType.StoredProcedure;
    sqlCmd.Parameters.AddWithValue("@MessageID", (hfMessageID.Value == "" ? 0 : Convert.ToInt32(hfMessageID.Value)));
    sqlCmd.Parameters.AddWithValue("@Sender", txtSender.Text.Trim());
    sqlCmd.Parameters.AddWithValue("@Receiver", txtReceiver.Text.Trim());
    sqlCmd.Parameters.AddWithValue("@Message", txtMessage.Text.Trim());
    sqlCmd.Parameters.AddWithValue("@Yeargroup", ddYear.Text.Trim());
    sqlCmd.Parameters.AddWithValue("@Title", txtTitle.Text.Trim());
    sqlCmd.Parameters.AddWithValue("@Date", txtStart.Text.Trim());
    sqlCmd.Parameters.AddWithValue("@Expiry", txtEnd.Text.Trim());

    sqlCmd.ExecuteNonQuery();
    sqlCon.Close();
    string messageID = hfMessageID.Value;
    clear();

    if (messageID == "")
        lblSuccess.Text = "New message Success";
    else
        lblSuccess.Text = "Updated Success";
    updateGrid();
}

Body:
Your problem is these two lines:

sqlCmd.Parameters.AddWithValue("@Date", txtStart.Text.Trim());
sqlCmd.Parameters.AddWithValue("@Expiry", txtEnd.Text.Trim());

You are passing strings to a stored procedure that almost certainly expects a date. Which means the string will be converted to a date in a way you don't control.

So you need to take control. You need to parse the date in the way you need it to be (e.g. dd/mm/yyyy or mm/dd/yyyy). These links will help you with that:

datetime.parse and making it work with a specific format

https://www.hanselman.com/blog/DateParseExactAndTheSubtleGooThatIsDateTimeFormatStrings.aspx

Once you have parsed the string as a date:

Check that the date result is what you expected it to be

Pass that date (rather than the existing string) to the stored procedure


问:
XCode: linker command failed with exit code 1 (use -v to see invocation). How?
I am getting this error pretty often, but nevertheless - how do I use -v? Is there anything in the XCode GUI that lets me do it? Thanks.

答: Sometimes linker command failed with exit code 1 means that you have something duplicate (a var, a class... with the same name) in somewhere.</p>