问:
how to do the validation of content page using jquery
hii all
this is my master page

```<code><%@ Master Language="C#" AutoEventWireup="true" CodeFile="OfficeApps.master.cs" Inherits="master1" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
  <head runat="server">
  <meta http-equiv="content-type" content="text/html;charset=utf-8" />
  <link rel="Stylesheet" type="text/css" href="Styles/jquery-ui-1.8.1.custom.css" />
  <link rel="Stylesheet" type="text/css" href="Styles/ui.jqgrid.css" />
  <link rel="Stylesheet" type="text/css" href="Styles/ui.multiselect.css" />

  <script src="JS/jquery.js" type="text/javascript"></script>
  <script src="JS/jquery-1.3.1.min.js" type="text/javascript"></script>
  <script src="JS/hoverIntent.js" type="text/javascript"></script>
  <link href="Styles/MasterStyleSheet.css" rel="stylesheet" type="text/css" />
  <title></title>
  <asp:ContentPlaceHolder ID="head" runat="server">
  </asp:ContentPlaceHolder>
</head>

<body>

<form id="form1" runat="server">

<div>
    <table class="mastertable">
        <tr>
            <td class="masterheader">
                <asp:ContentPlaceHolder ID="ContentPlaceHolder1" runat="server">

                    <div class="logo">
                        <asp:Image ID="image2" class="logo1" src="Images/OfficeApps.png" runat="server" />
                    </div>
                    <div class="menubar">
                        <asp:Literal ID="Literal1" runat="server"></asp:Literal>
                    </div>
                </asp:ContentPlaceHolder>
            </td>
        </tr>

          <tr>
            <td class="mastercontent">

                <asp:ContentPlaceHolder ID="ContentPlaceHolder2" runat="server">
                </asp:ContentPlaceHolder>

              <div class="divbutpos">

    <asp:Button ID="Button1" runat="server" Text="LOGOUT" OnClick="Button1_Click" BackColor="#00CCFF"
        BorderStyle="None" Font-Bold="True" Font-Names="Verdana" Font-Underline="True"
        ForeColor="White" Style="cursor: hand" />
    <%-- <asp:ImageButton ID="ImageButton1"  CssClass="divbutpos" OnClick="Button1_Click" ImageUrl="~/Images/signout.JPG" runat="server" />--%>
   </div>

            </td>
        </tr>
         <tr>

            <td class="masterfooter">
                <asp:ContentPlaceHolder ID="ContentPlaceHolder3" runat="server">
                </asp:ContentPlaceHolder>
            </td>
        </tr>

  </table>
</div>
</code>```

the reason i posted my entire masterpage is that it has multiple contentplaceholders in a table format.....

my content page looks like this

```<code><%@ Page Title="" Language="C#" MasterPageFile="~/OfficeApps.master" AutoEventWireup="true"
    CodeFile="UsersGrid.aspx.cs" Inherits="UsersGrid" %>

<asp:Content ID="Content1" ContentPlaceHolderID="head" runat="Server">
</asp:Content>

<asp:Content ID="Content3" ContentPlaceHolderID="ContentPlaceHolder2" runat="Server">

<div class = "scroll">

    <div id="searchbox" title="SearchBox" class="SearchBox">
        <div class="SearchBoxHeader">
            <h2 style="text-align: center; color: #2E6E9E;">
                SEARCH</h2>
        </div>

        <asp:Label ID="lbl_FilterStatus" runat="server">Status: </asp:Label>  <asp:DropDownList
            ID="dl_FilterStatus" runat="server">
            <asp:ListItem Value="1" Selected="True">Active</asp:ListItem>
            <asp:ListItem Value="0">InActive</asp:ListItem>
        </asp:DropDownList>
        <asp:Label ID="lbl_FilterUname" runat="server">Username: </asp:Label><asp:TextBox
            ID="tb_FilterUname" runat="server"></asp:TextBox>
        <asp:Label ID="lbl_FilterSname" runat="server">Shortname: </asp:Label><asp:TextBox
            ID="tb_FilterSname" runat="server"></asp:TextBox>
        <asp:ImageButton ID="ImageButton1" runat="server" ImageUrl="Images/search_icon.gif"
            ImageAlign="AbsBottom" OnClientClick="return searchuser();" />
    </div>

<table id="usergrid">
</table>

<div id="pager1" style="text-align: center;">
</div>

</div>

<div class="divlblpos">
        <asp:Label CssClass="welcomelogo" ID="Label1" runat="server" Text="Welcome"></asp:Label>
        <asp:Label ID="Label2" runat="server" CssClass="welcomelogo"></asp:Label>
</div>
<asp:HiddenField ID="Hf_SelectedID" runat="server" />

<div id="dialog" title="UserDetails" style="display: none;">

    <table  cellspacing="5px" cellpadding="10px">
        <tr>
            <td>
                <asp:Label ID="lbl_usrnm" CssClass="popuptxt" runat="server" Text="UserName"></asp:Label>
            </td>
            <td>
                <asp:TextBox ID="Tb_UserName" Height="15px" Font-Size="13px" runat="server"></asp:TextBox>
            </td>

         <td>
                <asp:Label ID="unameerror" runat="server" Text=""></asp:Label>
            </td>

        </tr>
        <tr>
            <td>
                <asp:Label ID="lbl_name" CssClass="popuptxt" runat="server" Text="Name"></asp:Label>
            </td>
            <td>
                <asp:TextBox ID="Tb_Name" Height="15px" Font-Size="13px" runat="server"></asp:TextBox>
            </td>
        </tr>
        <tr>
            <td>
                <asp:Label ID="lbl_shortnm" CssClass="popuptxt" runat="server" Text="ShortName"></asp:Label>
            </td>
            <td>
                <asp:TextBox ID="Tb_SName" Height="15px" Font-Size="13px" runat="server"></asp:TextBox>
            </td>
        </tr>
        <tr>
            <td>
                <asp:Label ID="lbl_Admin" CssClass="popuptxt" runat="server" Text="IsAdmin"></asp:Label>
            </td>
            <td>
                <asp:CheckBox ID="Cb_Admin" Checked="false" runat="server" />
            </td>
        </tr>
        <tr>
            <td>
                <asp:Label ID="lbl_Active" CssClass="popuptxt" runat="server" Text="IsActive"></asp:Label>
            </td>
            <td>
                <asp:CheckBox ID="Cb_Active" Checked="false" runat="server" />
            </td>
        </tr>
        <tr>
            <td>
                <asp:Label ID="lbl_Email" CssClass="popuptxt" runat="server" Text="Email"></asp:Label>
            </td>
            <td>
                <asp:TextBox ID="Tb_Email" Height="15px" Font-Size="13px" runat="server"></asp:TextBox>
            </td>
        </tr>
        <tr>
            <td>
                <asp:Label ID="lbl_phone" CssClass="popuptxt" runat="server" Text="Phone"></asp:Label>
            </td>
            <td>
                <asp:TextBox ID="Tb_Phone" Height="15px" Font-Size="13px" runat="server"></asp:TextBox>
            </td>
        </tr>
        <tr>
            <td>
                <asp:Label ID="lbl_mob" CssClass="popuptxt" runat="server" Text="Mobile"></asp:Label>
            </td>
            <td>
                <asp:TextBox ID="Tb_Mobile" Height="15px" Font-Size="13px" runat="server"></asp:TextBox>
            </td>
        </tr>
        <tr>
            <td>
                <asp:Label ID="lbl_Depts" CssClass="popuptxt" runat="server" Text="Departments"></asp:Label>
            </td>
            <td>
                <asp:ListBox ID="Lb_Departments" Font-Size="13px" DataTextField="DepartmentName"
                    Width="154px" DataValueField="DepartmentID" runat="server" SelectionMode="Multiple">
                </asp:ListBox>
            </td>
        </tr>
        <tr>
            <td>
                <asp:Label ID="lbl_App" CssClass="popuptxt" runat="server" Text="Applications"></asp:Label>
            </td>
            <td>
                <asp:ListBox ID="Lb_Applications" DataTextField="ApplicationName" Font-Size="13px"
                    Width="154px" DataValueField="ApplicationID" runat="server" SelectionMode="Multiple">
                </asp:ListBox>
            </td>
        </tr>
        <tr>
            <td>
                <asp:Label ID="lbl_Sup" CssClass="popuptxt" runat="server" Text="Supervisors"></asp:Label>
            </td>
            <td>
                <asp:ListBox ID="Lb_Supervisor" DataTextField="UserName" Font-Size="13px" Width="154px"
                    DataValueField="UserID" runat="server" SelectionMode="Multiple"></asp:ListBox>
            </td>
        </tr>
        <tr>
            <td>
                <asp:Label ID="Lb_Success" Font-Size="10px" runat="server" Text=""></asp:Label>
            </td>
            <td>
                <asp:Button ID="Button_Edit" Width="150px" runat="server" Text="Edit" OnClientClick="return edituser();" />
            </td>
        </tr>
    </table>
</div>
</asp:Content>
<asp:Content ID="Content4" ContentPlaceHolderID="ContentPlaceHolder3" runat="Server">
</asp:Content>
</code>```

my problem is when i have to validate using the below code inside the contentplaceholder validation is not being done
the code is

```<code><script type="text/javascript">

     $.validator.addMethod("regex",function(value, element, regexp)
            {
                var check = false;
                var re = new RegExp(regexp);
             return this.optional(element) || re.test(value);
            },"<p style='color:red'>*Please check your input</p>");

        $(document).ready(function() {
            $("#aspnetForm").validate({
                rules: {
                    <%=Tb_UserName.UniqueID %>: {
                        minlength: 5,
                        required: true,
                     regex: "^[a-zA-Z0-9'.\\s\]{3,15}$"

                    },
                    <%=Tb_Name.UniqueID %>: {
                        minlength: 5,
                        required: true,
                    regex: "^[a-zA-Z0-9'.\\s\]{3,15}$"
                    },
                    <%=Tb_SName.UniqueID %>: {
                        required: true,
                    maxlength:4,
                    regex: "^[a-zA-Z0-9'.\\s\]{1,4}$"
                    },
                    <%=Tb_Email.UniqueID %>: {
                     required: true,
                    regex:"^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$"
                    },
                    <%=Tb_Phone.UniqueID %>: {
                        minlength: 8,
                        maxlength: 8,
                        required: true,
                    regex:"^[0-9\s]{8}$"
                    },
                    <%=Tb_Mobile.UniqueID %>: {
                        minlength: 10,
                        maxlength:10,
                        required: true,
                        regex:"^[0-9\s]{10}$"
                    }
                },
                messages: {
                    <%=Tb_UserName.UniqueID %>:{
                        required: "Please Enter your username",
                        minlength: "User name must be atleast of 5 characters"
                    },
                     <%=Tb_Name.UniqueID %>:{
                        required: "Please Enter your name",
                        minlength: "name must be atleast of 5 characters"
                    },
                     <%=Tb_SName.UniqueID %>:{
                        required: "Please Enter your shortname",
                      maxlength:"Shortname cant exceed 4 characters"
                    },
                     <%=Tb_Email.UniqueID %>:{
                        required: "Please Enter email",

                    },
                    <%=Tb_Phone.UniqueID %>:{
                        required: "Please Enter phone",
                      minlength:"phone number should have 8 digits",
                      maxlength:"phone number should have 8 digits only"
                    },

                <%=Tb_Mobile.UniqueID %>:{
                        required: "Please Entermobile number",
                        minlength: "mobile number should have 10 digits"
                        maxlength:"mobile number should have 10 digits only"
                    }
                    }
            });
        });
    </script>
</code>```

答:
Why not use the asp.net validators, they do the same thing you're trying to do, PLUS server side validation!

RegularExpressionValidator(can also be used for min and max length)

RequiredFieldValidator

Server side validation is a must because javascript can always be disabled or modified by the user.

Body:
hii all
this is my master page

<%@ Master Language="C#" AutoEventWireup="true" CodeFile="OfficeApps.master.cs" Inherits="master1" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

  <meta http-equiv="content-type" content="text/html;charset=utf-8" />
  <link rel="Stylesheet" type="text/css" href="Styles/jquery-ui-1.8.1.custom.css" />
  <link rel="Stylesheet" type="text/css" href="Styles/ui.jqgrid.css" />
  <link rel="Stylesheet" type="text/css" href="Styles/ui.multiselect.css" />

  <link href="Styles/MasterStyleSheet.css" rel="stylesheet" type="text/css" />
  <title></title>
  <asp:ContentPlaceHolder ID="head" runat="server">
  </asp:ContentPlaceHolder>

<form id="form1" runat="server">

                <asp:ContentPlaceHolder ID="ContentPlaceHolder1" runat="server">

                        <asp:Image ID="image2" class="logo1" src="Images/OfficeApps.png" runat="server" />

                        <asp:Literal ID="Literal1" runat="server"></asp:Literal>

                </asp:ContentPlaceHolder>

                <asp:ContentPlaceHolder ID="ContentPlaceHolder2" runat="server">
                </asp:ContentPlaceHolder>

    <asp:Button ID="Button1" runat="server" Text="LOGOUT" OnClick="Button1_Click" BackColor="#00CCFF"
        BorderStyle="None" Font-Bold="True" Font-Names="Verdana" Font-Underline="True"
        ForeColor="White" Style="cursor: hand" />
    <%-- <asp:ImageButton ID="ImageButton1"  CssClass="divbutpos" OnClick="Button1_Click" ImageUrl="~/Images/signout.JPG" runat="server" />--%>

                <asp:ContentPlaceHolder ID="ContentPlaceHolder3" runat="server">
                </asp:ContentPlaceHolder>

the reason i posted my entire masterpage is that it has multiple contentplaceholders in a table format.....

my content page looks like this

<%@ Page Title="" Language="C#" MasterPageFile="~/OfficeApps.master" AutoEventWireup="true"
    CodeFile="UsersGrid.aspx.cs" Inherits="UsersGrid" %>

<asp:Content ID="Content1" ContentPlaceHolderID="head" runat="Server">
</asp:Content>

<asp:Content ID="Content3" ContentPlaceHolderID="ContentPlaceHolder2" runat="Server">

                SEARCH

        <asp:Label ID="lbl_FilterStatus" runat="server">Status: </asp:Label>  <asp:DropDownList
            ID="dl_FilterStatus" runat="server">
            <asp:ListItem Value="1" Selected="True">Active</asp:ListItem>
            <asp:ListItem Value="0">InActive</asp:ListItem>
        </asp:DropDownList>
        <asp:Label ID="lbl_FilterUname" runat="server">Username: </asp:Label><asp:TextBox
            ID="tb_FilterUname" runat="server"></asp:TextBox>
        <asp:Label ID="lbl_FilterSname" runat="server">Shortname: </asp:Label><asp:TextBox
            ID="tb_FilterSname" runat="server"></asp:TextBox>
        <asp:ImageButton ID="ImageButton1" runat="server" ImageUrl="Images/search_icon.gif"
            ImageAlign="AbsBottom" OnClientClick="return searchuser();" />

        <asp:Label CssClass="welcomelogo" ID="Label1" runat="server" Text="Welcome"></asp:Label>
        <asp:Label ID="Label2" runat="server" CssClass="welcomelogo"></asp:Label>

<asp:HiddenField ID="Hf_SelectedID" runat="server" />

                <asp:Label ID="lbl_usrnm" CssClass="popuptxt" runat="server" Text="UserName"></asp:Label>

                <asp:TextBox ID="Tb_UserName" Height="15px" Font-Size="13px" runat="server"></asp:TextBox>

                <asp:Label ID="unameerror" runat="server" Text=""></asp:Label>

                <asp:Label ID="lbl_name" CssClass="popuptxt" runat="server" Text="Name"></asp:Label>

                <asp:TextBox ID="Tb_Name" Height="15px" Font-Size="13px" runat="server"></asp:TextBox>

                <asp:Label ID="lbl_shortnm" CssClass="popuptxt" runat="server" Text="ShortName"></asp:Label>

                <asp:TextBox ID="Tb_SName" Height="15px" Font-Size="13px" runat="server"></asp:TextBox>

                <asp:Label ID="lbl_Admin" CssClass="popuptxt" runat="server" Text="IsAdmin"></asp:Label>

                <asp:CheckBox ID="Cb_Admin" Checked="false" runat="server" />

                <asp:Label ID="lbl_Active" CssClass="popuptxt" runat="server" Text="IsActive"></asp:Label>

                <asp:CheckBox ID="Cb_Active" Checked="false" runat="server" />

                <asp:Label ID="lbl_Email" CssClass="popuptxt" runat="server" Text="Email"></asp:Label>

                <asp:TextBox ID="Tb_Email" Height="15px" Font-Size="13px" runat="server"></asp:TextBox>

                <asp:Label ID="lbl_phone" CssClass="popuptxt" runat="server" Text="Phone"></asp:Label>

                <asp:TextBox ID="Tb_Phone" Height="15px" Font-Size="13px" runat="server"></asp:TextBox>

                <asp:Label ID="lbl_mob" CssClass="popuptxt" runat="server" Text="Mobile"></asp:Label>

                <asp:TextBox ID="Tb_Mobile" Height="15px" Font-Size="13px" runat="server"></asp:TextBox>

                <asp:Label ID="lbl_Depts" CssClass="popuptxt" runat="server" Text="Departments"></asp:Label>

                <asp:ListBox ID="Lb_Departments" Font-Size="13px" DataTextField="DepartmentName"
                    Width="154px" DataValueField="DepartmentID" runat="server" SelectionMode="Multiple">
                </asp:ListBox>

                <asp:Label ID="lbl_App" CssClass="popuptxt" runat="server" Text="Applications"></asp:Label>

                <asp:ListBox ID="Lb_Applications" DataTextField="ApplicationName" Font-Size="13px"
                    Width="154px" DataValueField="ApplicationID" runat="server" SelectionMode="Multiple">
                </asp:ListBox>

                <asp:Label ID="lbl_Sup" CssClass="popuptxt" runat="server" Text="Supervisors"></asp:Label>

                <asp:ListBox ID="Lb_Supervisor" DataTextField="UserName" Font-Size="13px" Width="154px"
                    DataValueField="UserID" runat="server" SelectionMode="Multiple"></asp:ListBox>

                <asp:Label ID="Lb_Success" Font-Size="10px" runat="server" Text=""></asp:Label>

                <asp:Button ID="Button_Edit" Width="150px" runat="server" Text="Edit" OnClientClick="return edituser();" />

</asp:Content>
<asp:Content ID="Content4" ContentPlaceHolderID="ContentPlaceHolder3" runat="Server">
</asp:Content>

my problem is when i have to validate using the below code inside the contentplaceholder validation is not being done
the code is


来源: stackexchange

问:
Creating shorter link for image folder
I created new disks for images in my project, and I want to use URL that I added to userImage disk in my view in blade.php.

The disk works perfect in my controller, I use it to detect if the folder path exists, if not I am creating one:

if (!Storage::disk('userImage')->has('standard')) {
     Storage::disk('userImage')->makeDirectory('standard');
}
```

<p>But I want to use it also in my blade.php pageview, right now I am using:</p>

<p>(C:\xampp\htdocs\rps\public\storage\images\userImage\standard\default.png) </p>

```src="{{asset('storage/images/userImage/standard/default.png')}}"
```

<p>The code above works perfectly, it displays the image but I want to shorten it to:</p>

```src="{{asset('userImage/standard/default.png')}}"
```

<p>and I hoped it will work by how my userImage disk works but it doesn't. Anyone has an idea of how to solve this issue?</p>

<pre class="lang-php prettyprint-override"><code>    'disks' => [

        'local' => [
            'driver' => 'local',
            'root' => storage_path('app'),
        ],

        'public' => [
            'driver' => 'local',
            'root' => storage_path('app/public'),
            'url' => env('APP_URL').'/storage',
            'visibility' => 'public',
        ],

        'images' => [
            'driver' => 'local',
            'root' => storage_path('app/public/images'),
            'url' => env('APP_URL').'/images',
            'visibility' => 'public',
        ],

        'userImage' => [
            'driver' => 'local',
            'root' => storage_path('app/public/images/userImage'),
            'url' => env('APP_URL').'/userImage',
            'visibility' => 'public',
        ],

        's3' => [
            'driver' => 's3',
            'key' => env('AWS_ACCESS_KEY_ID'),
            'secret' => env('AWS_SECRET_ACCESS_KEY'),
            'region' => env('AWS_DEFAULT_REGION'),
            'bucket' => env('AWS_BUCKET'),
            'url' => env('AWS_URL'),
        ],

    ],
</code>```

答:
Your question is not clear.

If you want shorter img url:

You can make symbol link from public/userImage to storage/app/public/images/userImage.

Add to your console.php in routes folder.

```<code>Artisan::command('link', function(){
    $this->laravel->make('files')->link(
        storage_path('app/public/images/userImage'), public_path('userImage')
    );
});
</code>```

And then console command:

```<code>php artisan link
</code>```

If you want shorter code (path in blade):

You can create your own helper function.

Create file app/Helpers/helpers.php

```<code>function image($path){
    $path = trim($path, '/');
    return asset('storage/images/' . $path);
}
</code>```

Add it to composer's autoload

```<code>"autoload": {
     "files": [
         "app/Helpers/helpers.php"
    ],
    "psr-4": {
         "App\\": "app/"
    },
    "classmap": [
         "database/seeds",
         "database/factories"
    ]
},
</code>```

Use it in blade:

```<code>{{ image('userImage/standard/default.png') }}
</code>```

ContentLicense: CC BY-SA 4.0

Title: Creating shorter link for image folder

Body:
I created new disks for images in my project, and I want to use URL that I added to userImage disk in my view in blade.php.

The disk works perfect in my controller, I use it to detect if the folder path exists, if not I am creating one:

if (!Storage::disk('userImage')->has('standard')) {
     Storage::disk('userImage')->makeDirectory('standard');
}

But I want to use it also in my blade.php pageview, right now I am using:

(C:\xampp\htdocs\rps\public\storage\images\userImage\standard\default.png)

src="{{asset('storage/images/userImage/standard/default.png')}}"

The code above works perfectly, it displays the image but I want to shorten it to:

src="{{asset('userImage/standard/default.png')}}"

and I hoped it will work by how my userImage disk works but it doesn't. Anyone has an idea of how to solve this issue?

    'disks' => [

        'local' => [
            'driver' => 'local',
            'root' => storage_path('app'),
        ],

        'public' => [
            'driver' => 'local',
            'root' => storage_path('app/public'),
            'url' => env('APP_URL').'/storage',
            'visibility' => 'public',
        ],

        'images' => [
            'driver' => 'local',
            'root' => storage_path('app/public/images'),
            'url' => env('APP_URL').'/images',
            'visibility' => 'public',
        ],

        'userImage' => [
            'driver' => 'local',
            'root' => storage_path('app/public/images/userImage'),
            'url' => env('APP_URL').'/userImage',
            'visibility' => 'public',
        ],

        's3' => [
            'driver' => 's3',
            'key' => env('AWS_ACCESS_KEY_ID'),
            'secret' => env('AWS_SECRET_ACCESS_KEY'),
            'region' => env('AWS_DEFAULT_REGION'),
            'bucket' => env('AWS_BUCKET'),
            'url' => env('AWS_URL'),
        ],

    ],

Body:
Your question is not clear.

If you want shorter img url:

You can make symbol link from public/userImage to storage/app/public/images/userImage.

Add to your console.php in routes folder.

Artisan::command('link', function(){
    $this->laravel->make('files')->link(
        storage_path('app/public/images/userImage'), public_path('userImage')
    );
});

And then console command:

php artisan link

If you want shorter code (path in blade):

You can create your own helper function.

Create file app/Helpers/helpers.php

function image($path){
    $path = trim($path, '/');
    return asset('storage/images/' . $path);
}

Add it to composer's autoload

"autoload": {
     "files": [
         "app/Helpers/helpers.php"
    ],
    "psr-4": {
         "App\\": "app/"
    },
    "classmap": [
         "database/seeds",
         "database/factories"
    ]
},

Use it in blade:

{{ image('userImage/standard/default.png') }}


问:
Display dynamic number of fields
I'm new to progress and I'm trying to learn dynamic queries. As a Task I gave to myself I want to read a csv file and create a table based on the contents of said file. So far everything works but I can't really seem to find a way to display the contents properly.

I have a temp-table created based on a csv input with the first line being the columns or fields of the table and everything after being the records.

```<code>Field1,Field2,Field3,Field4,Fieldn...
Value1.1,Value2.1,Value3.1,Value4.1,Valuen.1...
Value1.2,Value2.2,Value3.2,Value4.2,Valuen.1...
Value1.3,Value2.3,Value3.3,Value4.3,Valuen.1...
Value1.4,Value2.4,Value3.4,Value4.4,Valuen.1...
etc...
</code>```

How can I display a dynamic number of fields and their names properly?

The following things are unknown:

Number of fields

Name of fields

Values of records

The following works and shows the data in the desired format (but it's hard coded):

```<code>DO WHILE qMyTable:GET-NEXT():
    DISPLAY
        bMyTable:BUFFER-FIELD(1):BUFFER-VALUE LABEL 'PK'
        bMyTable:BUFFER-FIELD(2):BUFFER-VALUE LABEL 'Field1'
        bMyTable:BUFFER-FIELD(3):BUFFER-VALUE LABEL 'Field2'
        bMyTable:BUFFER-FIELD(4):BUFFER-VALUE LABEL 'Field3'
        bMyTable:BUFFER-FIELD(5):BUFFER-VALUE LABEL 'Field4'
        WITH FRAME f DOWN.
        DOWN WITH FRAME f.
END.
</code>```

I'm trying to loop over the buffer fields but I can't find a way to do it without redefining the DISPLAY command every iteration. Also I don't know how to display the labels of the fields in as a header row.

I'm looking for something like this :

```<code>/*
This doesn't work
*/
DO WHILE qMyTable:GET-NEXT():
    DO i = 1 to iNumFields:
        DISPLAY bMyTable:BUFFER-FIELD(i):BUFFER-VALUE LABEL cTitlerow[i].
    END.
END.
</code>```

This would be the full code:

```<code>/*
Variables
*/
DEF VAR i AS INTEGER INITIAL 0 NO-UNDO. //Counter
DEF VAR iEntry AS INTEGER INITIAL 0 NO-UNDO. //Counter2
DEF VAR cTitleRow AS CHARACTER NO-UNDO. //Fields csv
DEF VAR cDataRow AS CHARACTER NO-UNDO. //Entries csv
DEF VAR cFieldName AS CHARACTER NO-UNDO. //Field
DEF VAR iNumFields AS INTEGER NO-UNDO. //Amount of Fields
DEF VAR iNumLines AS INTEGER NO-UNDO. //Amount of records
DEF VAR cTitleArray AS CHARACTER EXTENT NO-UNDO. //Fields Array
/*
Handles
*/
DEF VAR ttMyTable AS HANDLE NO-UNDO. //Temp table
DEF VAR bMyTable AS HANDLE NO-UNDO. //Buffer
DEF VAR qMyTable AS HANDLE NO-UNDO. //Query

INPUT FROM 'C:\Path\To\CSV\mycsv.csv'.

/*
Get first row for fields and field names
*/
IMPORT UNFORMATTED cTitleRow.
iNumFields = NUM-ENTRIES(cTitleRow) + 1. //Additional field for PK
EXTENT(cTitleArray) = iNumFields.

/*
Dynamic table creation
*/
CREATE TEMP-TABLE ttMyTable.
ttMyTable:ADD-NEW-FIELD('PK', 'integer').
cTitleArray[1] = 'PK'.
DO i = 2 to iNumFields:
    iEntry = i - 1.
    cFieldName = ENTRY(iEntry,cTitleRow).
    ttMyTable:ADD-NEW-FIELD(cFieldName, 'character').
    cTitleArray[i] = cFieldName.
END.

/*
Adding and defining indexes
*/
ttMyTable:ADD-NEW-INDEX('idx', TRUE, TRUE).
ttMyTable:ADD-INDEX-FIELD('idx', 'PK', 'asc').
ttMyTable:TEMP-TABLE-PREPARE('myTable').

/*
Creating buffer
*/
bMyTable = ttMyTable:DEFAULT-BUFFER-HANDLE.

/*
Populating data
*/
REPEAT:
    IMPORT UNFORMATTED cDataRow.
    bMyTable:BUFFER-CREATE.
    bMyTable::pk = iNumLines.
    DO i = 2 to iNumFields:
        iEntry = i - 1.
        bMyTable:BUFFER-FIELD(i):BUFFER-VALUE = ENTRY(iEntry,cDataRow).
        bMyTable:BUFFER-FIELD(i):COLUMN-LABEL = cTitleArray[i].
        bMyTable:BUFFER-FIELD(i):LABEL = cTitleArray[i].
    END.

    iNumLines = iNumLines + 1.
END.

/*
Creating query
*/
CREATE QUERY qMyTable.
qMyTable:SET-BUFFERS(bMyTable).
qMyTable:QUERY-PREPARE('for each myTable').
qMyTable:QUERY-OPEN().

/*
/*
This doesn't work
*/
DO WHILE qMyTable:GET-NEXT():
    DO i = 1 to iNumFields:
        DISPLAY bMyTable:BUFFER-FIELD(i):BUFFER-VALUE.
    END.
END.
*/

DO WHILE qMyTable:GET-NEXT():
    DISPLAY
        bMyTable:BUFFER-FIELD(1):BUFFER-VALUE LABEL 'PK'
        bMyTable:BUFFER-FIELD(2):BUFFER-VALUE LABEL 'Field1'
        bMyTable:BUFFER-FIELD(3):BUFFER-VALUE LABEL 'Field2'
        bMyTable:BUFFER-FIELD(4):BUFFER-VALUE LABEL 'Field3'
        bMyTable:BUFFER-FIELD(5):BUFFER-VALUE LABEL 'Field4'
        WITH FRAME f DOWN.
        DOWN WITH FRAME f.
END.

qMyTable:QUERY-CLOSE().

DELETE OBJECT qMyTable.
</code>```

答:
I think you only might have some frame issues. Your code should basically  work.

This minor change with display your data but for it will display them all in one column.

```<code>DO WHILE qMyTable:GET-NEXT():
    DO i = 1 to iNumFields:
        DISPLAY bMyTable:BUFFER-FIELD(i):BUFFER-VALUE WITH FRAME f2 DOWN TITLE "Dynamic" .
        DOWN  WITH FRAME f2 .
    END.
END.
</code>```

So output will basically be

```<code>row1column1
row1column2
row1column3
...
row1columnN
row2column1
row2column2
row2column3
...
row2columnN
etc
</code>```

Instead of

```<code>row1column1    row1column2    row1column3    ...    row1columnN
row2column1    row2column2    row2column3    ...    row2columnN
</code>```

One idea to get the same result is to create a frame widget dynamically as well...

Title: Display dynamic number of fields

Body:
I'm new to progress and I'm trying to learn dynamic queries. As a Task I gave to myself I want to read a csv file and create a table based on the contents of said file. So far everything works but I can't really seem to find a way to display the contents properly.

I have a temp-table created based on a csv input with the first line being the columns or fields of the table and everything after being the records.

Field1,Field2,Field3,Field4,Fieldn...
Value1.1,Value2.1,Value3.1,Value4.1,Valuen.1...
Value1.2,Value2.2,Value3.2,Value4.2,Valuen.1...
Value1.3,Value2.3,Value3.3,Value4.3,Valuen.1...
Value1.4,Value2.4,Value3.4,Value4.4,Valuen.1...
etc...

How can I display a dynamic number of fields and their names properly?

The following things are unknown:

Number of fields

Name of fields

Values of records

The following works and shows the data in the desired format (but it's hard coded):

DO WHILE qMyTable:GET-NEXT():
    DISPLAY
        bMyTable:BUFFER-FIELD(1):BUFFER-VALUE LABEL 'PK'
        bMyTable:BUFFER-FIELD(2):BUFFER-VALUE LABEL 'Field1'
        bMyTable:BUFFER-FIELD(3):BUFFER-VALUE LABEL 'Field2'
        bMyTable:BUFFER-FIELD(4):BUFFER-VALUE LABEL 'Field3'
        bMyTable:BUFFER-FIELD(5):BUFFER-VALUE LABEL 'Field4'
        WITH FRAME f DOWN.
        DOWN WITH FRAME f.
END.

I'm trying to loop over the buffer fields but I can't find a way to do it without redefining the DISPLAY command every iteration. Also I don't know how to display the labels of the fields in as a header row.

I'm looking for something like this :

/*
This doesn't work
*/
DO WHILE qMyTable:GET-NEXT():
    DO i = 1 to iNumFields:
        DISPLAY bMyTable:BUFFER-FIELD(i):BUFFER-VALUE LABEL cTitlerow[i].
    END.
END.

This would be the full code:

/*
Variables
*/
DEF VAR i AS INTEGER INITIAL 0 NO-UNDO. //Counter
DEF VAR iEntry AS INTEGER INITIAL 0 NO-UNDO. //Counter2
DEF VAR cTitleRow AS CHARACTER NO-UNDO. //Fields csv
DEF VAR cDataRow AS CHARACTER NO-UNDO. //Entries csv
DEF VAR cFieldName AS CHARACTER NO-UNDO. //Field
DEF VAR iNumFields AS INTEGER NO-UNDO. //Amount of Fields
DEF VAR iNumLines AS INTEGER NO-UNDO. //Amount of records
DEF VAR cTitleArray AS CHARACTER EXTENT NO-UNDO. //Fields Array
/*
Handles
*/
DEF VAR ttMyTable AS HANDLE NO-UNDO. //Temp table
DEF VAR bMyTable AS HANDLE NO-UNDO. //Buffer
DEF VAR qMyTable AS HANDLE NO-UNDO. //Query

INPUT FROM 'C:\Path\To\CSV\mycsv.csv'.

/*
Get first row for fields and field names
*/
IMPORT UNFORMATTED cTitleRow.
iNumFields = NUM-ENTRIES(cTitleRow) + 1. //Additional field for PK
EXTENT(cTitleArray) = iNumFields.

/*
Dynamic table creation
*/
CREATE TEMP-TABLE ttMyTable.
ttMyTable:ADD-NEW-FIELD('PK', 'integer').
cTitleArray[1] = 'PK'.
DO i = 2 to iNumFields:
    iEntry = i - 1.
    cFieldName = ENTRY(iEntry,cTitleRow).
    ttMyTable:ADD-NEW-FIELD(cFieldName, 'character').
    cTitleArray[i] = cFieldName.
END.

/*
Adding and defining indexes
*/
ttMyTable:ADD-NEW-INDEX('idx', TRUE, TRUE).
ttMyTable:ADD-INDEX-FIELD('idx', 'PK', 'asc').
ttMyTable:TEMP-TABLE-PREPARE('myTable').

/*
Creating buffer
*/
bMyTable = ttMyTable:DEFAULT-BUFFER-HANDLE.

/*
Populating data
*/
REPEAT:
    IMPORT UNFORMATTED cDataRow.
    bMyTable:BUFFER-CREATE.
    bMyTable::pk = iNumLines.
    DO i = 2 to iNumFields:
        iEntry = i - 1.
        bMyTable:BUFFER-FIELD(i):BUFFER-VALUE = ENTRY(iEntry,cDataRow).
        bMyTable:BUFFER-FIELD(i):COLUMN-LABEL = cTitleArray[i].
        bMyTable:BUFFER-FIELD(i):LABEL = cTitleArray[i].
    END.

    iNumLines = iNumLines + 1.
END.

/*
Creating query
*/
CREATE QUERY qMyTable.
qMyTable:SET-BUFFERS(bMyTable).
qMyTable:QUERY-PREPARE('for each myTable').
qMyTable:QUERY-OPEN().

/*
/*
This doesn't work
*/
DO WHILE qMyTable:GET-NEXT():
    DO i = 1 to iNumFields:
        DISPLAY bMyTable:BUFFER-FIELD(i):BUFFER-VALUE.
    END.
END.
*/

DO WHILE qMyTable:GET-NEXT():
    DISPLAY
        bMyTable:BUFFER-FIELD(1):BUFFER-VALUE LABEL 'PK'
        bMyTable:BUFFER-FIELD(2):BUFFER-VALUE LABEL 'Field1'
        bMyTable:BUFFER-FIELD(3):BUFFER-VALUE LABEL 'Field2'
        bMyTable:BUFFER-FIELD(4):BUFFER-VALUE LABEL 'Field3'
        bMyTable:BUFFER-FIELD(5):BUFFER-VALUE LABEL 'Field4'
        WITH FRAME f DOWN.
        DOWN WITH FRAME f.
END.

qMyTable:QUERY-CLOSE().

DELETE OBJECT qMyTable.

Body:
I think you only might have some frame issues. Your code should basically  work.

This minor change with display your data but for it will display them all in one column.

DO WHILE qMyTable:GET-NEXT():
    DO i = 1 to iNumFields:
        DISPLAY bMyTable:BUFFER-FIELD(i):BUFFER-VALUE WITH FRAME f2 DOWN TITLE "Dynamic" .
        DOWN  WITH FRAME f2 .
    END.
END.

So output will basically be

row1column1
row1column2
row1column3
...
row1columnN
row2column1
row2column2
row2column3
...
row2columnN
etc

Instead of

row1column1    row1column2    row1column3    ...    row1columnN
row2column1    row2column2    row2column3    ...    row2columnN

One idea to get the same result is to create a frame widget dynamically as well...


问:
How can i change storyboard speed programmatically?
I have a storyboard in my WPF application. In storyboard, I have a lot of animation. After begin storyboard, I want to set storyboard current speed

According to my search, I have to use below code.

```<code>storyboard.SpeedRatio=New Speed;
</code>```

With the above code, Storyboard speed is changing. But the storyboard should end so I can see this effect. I want to change storyboard speed real time.

答:
i found the solution of my problem. You can use below code for change speed of storyboard real time

```<code> storyboard.SetSpeedRatio(this,newSpeed);
</code>```

This code works clearly.

Body:
I have a storyboard in my WPF application. In storyboard, I have a lot of animation. After begin storyboard, I want to set storyboard current speed

According to my search, I have to use below code.

storyboard.SpeedRatio=New Speed;

With the above code, Storyboard speed is changing. But the storyboard should end so I can see this effect. I want to change storyboard speed real time.

Body:
i found the solution of my problem. You can use below code for change speed of storyboard real time

 storyboard.SetSpeedRatio(this,newSpeed);

This code works clearly.


问:
How to cut paper to be of picture size in C#?
I have to make an application to print pictures in this printer DNP DSRX1, it has many different paper sizes to cut them in different formats, like 6x4" or 2x6".

I can print already, my problem is to cut these papers in the right format.

I tried setting the paper size with PrinterSettings.DefaultPageSettings.PaperSize, but it doesn't cut the paper as I expected.

I have no idea how I can use the PrintDocument to do this, or if I need to use something else.

I am really stuck on this, appreciate any help.

This is my code to set the paper size:

```<code>printDocument1.PrinterSettings.DefaultPageSettings.PaperSize = new PaperSize("size", (int)Width, (int)Height);
</code>```

答: So, I don't think this is possible after quite some research. The solution to my problem was to use Linux print terminal commands in the application. Linux has plenty of configurations for printing, so that was the best solution I got.</p>

Body:
I have to make an application to print pictures in this printer DNP DSRX1, it has many different paper sizes to cut them in different formats, like 6x4" or 2x6".

I can print already, my problem is to cut these papers in the right format.

I tried setting the paper size with PrinterSettings.DefaultPageSettings.PaperSize, but it doesn't cut the paper as I expected.

I have no idea how I can use the PrintDocument to do this, or if I need to use something else.

I am really stuck on this, appreciate any help.

This is my code to set the paper size:

printDocument1.PrinterSettings.DefaultPageSettings.PaperSize = new PaperSize("size", (int)Width, (int)Height);


问:
How to filter out item based on properties?
i wanted to refactor code use filter instead of lodash _forEach , Below filter code is not returning expected response. any idea what is implemented wrong here ?

main.js

const response = [];
const data = [{
    "isBrand": true,
    "drugName": "Lipitor",
    "specialtyPrice": {}
  },
  {
    "isBrand": false,
    "drugName": "Atorvastatin Calcium",
    "drugStrength": "80mg",
    "drugForm": "Tablet",
    "mailPrice": {
      "totalQuantity": 90,
      "rejectMessage": [{
        "settlementCode": "99",
        "settlementDesc": "Sorry, the system is temporarily:Lo sentimos,Intente(Código de error 85)"
      }]
    },
    "retailPrice": {
      "totalQuantity": 30,
      "rejectMessage": [{
        "settlementCode": "99",
        "settlementDesc": "Sorry, the system is temporarily:Lo sentimos,Intente(Código de error 85)"
      }]
    },
    "specialtyPrice": {}
  }
];
_.forEach(data, function(drug) {
  if (drug.retailPrice !== undefined || drug.mailPrice !== undefined) {
    response.push(drug);
  }
});

const filterItems = data.filter(item => item.retailPrice && item.mailPrice)

console.log(filterItems);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.min.js"></script></code>```

expected result

```<code>[{
            "isBrand": false,
            "drugName": "Atorvastatin Calcium",
            "drugStrength": "80mg",
            "drugForm": "Tablet",
            "mailPrice": {
                "totalQuantity": 90,
                "rejectMessage": [{
                    "settlementCode": "99",
                    "settlementDesc": "Sorry, the system is temporarily:Lo sentimos,Intente(Código de error 85)"
                }]
            },
            "retailPrice": {
                "totalQuantity": 30,
                "rejectMessage": [{
                    "settlementCode": "99",
                    "settlementDesc": "Sorry, the system is temporarily:Lo sentimos,Intente(Código de error 85)"
                }]
            },
            "specialtyPrice": {}
        }
    ];
</code>```

答:
This should work.</p>

```<code>var objNotEmpty = function(obj){
    return Object.keys(obj).length > 0;
 },
 objHasPrice = function(obj){
    return obj.hasOwnProperty("mailPrice") && obj.hasOwnProperty("retailPrice");
 };

const filterItems = data.filter( item => return objHasPrice(item) && objNotEmpty(item.mailPrice) && objNotEmpty(item.retailPrice);
</code>```

Body:
i wanted to refactor code use filter instead of lodash _forEach , Below filter code is not returning expected response. any idea what is implemented wrong here ?

main.js

const response = [];
const data = [{
    "isBrand": true,
    "drugName": "Lipitor",
    "specialtyPrice": {}
  },
  {
    "isBrand": false,
    "drugName": "Atorvastatin Calcium",
    "drugStrength": "80mg",
    "drugForm": "Tablet",
    "mailPrice": {
      "totalQuantity": 90,
      "rejectMessage": [{
        "settlementCode": "99",
        "settlementDesc": "Sorry, the system is temporarily:Lo sentimos,Intente(Código de error 85)"
      }]
    },
    "retailPrice": {
      "totalQuantity": 30,
      "rejectMessage": [{
        "settlementCode": "99",
        "settlementDesc": "Sorry, the system is temporarily:Lo sentimos,Intente(Código de error 85)"
      }]
    },
    "specialtyPrice": {}
  }
];
_.forEach(data, function(drug) {
  if (drug.retailPrice !== undefined || drug.mailPrice !== undefined) {
    response.push(drug);
  }
});

const filterItems = data.filter(item => item.retailPrice && item.mailPrice)

console.log(filterItems);

expected result

[{
            "isBrand": false,
            "drugName": "Atorvastatin Calcium",
            "drugStrength": "80mg",
            "drugForm": "Tablet",
            "mailPrice": {
                "totalQuantity": 90,
                "rejectMessage": [{
                    "settlementCode": "99",
                    "settlementDesc": "Sorry, the system is temporarily:Lo sentimos,Intente(Código de error 85)"
                }]
            },
            "retailPrice": {
                "totalQuantity": 30,
                "rejectMessage": [{
                    "settlementCode": "99",
                    "settlementDesc": "Sorry, the system is temporarily:Lo sentimos,Intente(Código de error 85)"
                }]
            },
            "specialtyPrice": {}
        }
    ];

Body:
This should work.

var objNotEmpty = function(obj){
    return Object.keys(obj).length > 0;
 },
 objHasPrice = function(obj){
    return obj.hasOwnProperty("mailPrice") && obj.hasOwnProperty("retailPrice");
 };

const filterItems = data.filter( item => return objHasPrice(item) && objNotEmpty(item.mailPrice) && objNotEmpty(item.retailPrice);


问:
When does the onLoad function of React Native webview execute?
https://facebook.github.io/react-native/docs/webview#onload

The documentation states that onload is a Function that is invoked when the WebView has finished loading.

What action specifically triggers this? Is it fired after all of the scripts within a page have been run or simply when the DOM has finished loading? Is there a callback that executes to tell webview that the page is finished?

答:
https://developer.mozilla.org/en-US/docs/Web/API/Window/DOMContentLoaded_event

When the DOMContentLoaded event is fired, React Native's webview is kicked off. That would mean that the DOM is finished loading, but the website is not necessarily completely finished loading everything, and is likely continuing to run scripts (if there are any) at this time.


问:
Fatal error when starting orion context broker
My orion context broker does not start and when I enter the command
/etc/init.d/contextBroker start I get this message

```<code>[root@context-broker ~]# /etc/init.d/contextBroker start
Starting contextBroker (via systemctl):  Job for contextBroker.service failed because the control process exited with error code. See "systemctl status contextBroker.service" and "journalctl -xe" for details.
                                                           [FAILED]

</code>```

The systemctl status contextBroker.service commannd gives this message

```<code>[root@context-broker ~]# systemctl status contextBroker.service
● contextBroker.service - LSB: run contextBroker
   Loaded: loaded (/etc/rc.d/init.d/contextBroker; bad; vendor preset: disabled)
   Active: failed (Result: exit-code) since Fri 2019-05-24 11:38:50 UTC; 1min 11s ago
     Docs: man:systemd-sysv-generator(8)
  Process: 9782 ExecStart=/etc/rc.d/init.d/contextBroker start (code=exited, status=1/FAILURE)

May 24 11:38:47 context-broker.novalocal systemd[1]: Starting LSB: run contextBroker...
May 24 11:38:48 context-broker.novalocal contextBroker[9782]: contextBroker is stopped
May 24 11:38:48 context-broker.novalocal contextBroker[9782]: Starting...
May 24 11:38:48 context-broker.novalocal su[9788]: (to orion) root on none
May 24 11:38:50 context-broker.novalocal contextBroker[9782]: Starting contextBroker...                         cat: /var/run/contextBroker/contextBroker.pid...irectory
May 24 11:38:50 context-broker.novalocal systemd[1]: contextBroker.service: control process exited, code=exited status=1
May 24 11:38:50 context-broker.novalocal contextBroker[9782]: pidfile not found[FAILED]
May 24 11:38:50 context-broker.novalocal systemd[1]: Failed to start LSB: run contextBroker.
May 24 11:38:50 context-broker.novalocal systemd[1]: Unit contextBroker.service entered failed state.
May 24 11:38:50 context-broker.novalocal systemd[1]: contextBroker.service failed.
Hint: Some lines were ellipsized, use -l to show in full.
</code>```

Also the /tmp/contextBroker.log file looks like this

```<code>time=2019-05-24T11:41:12.971Z | lvl=FATAL | corr=N/A | trans=N/A | from=N/A | srv=N/A | subsrv=N/A | comp=Orion | op=rest.cpp[1753]:restStart | msg=Fatal Error (error starting REST interface)
</code>```

I checked if mongodb is running and it is running correctly.
UPDATE
With some searching I realised I had to kill the pid of the process and after I did that the service successfully starts according to the messaags but I find it doesnt actually work. When I ask for the status I get the following:

```<code>[root@context-broker centos]# /etc/init.d/contextBroker status
● contextBroker.service - LSB: run contextBroker
   Loaded: loaded (/etc/rc.d/init.d/contextBroker; bad; vendor preset: disabled)
   Active: active (exited) since Sun 2019-05-26 18:34:49 UTC; 4min 56s ago
     Docs: man:systemd-sysv-generator(8)
  Process: 16295 ExecStop=/etc/rc.d/init.d/contextBroker stop (code=exited, status=0/SUCCESS)
  Process: 16319 ExecStart=/etc/rc.d/init.d/contextBroker start (code=exited, status=0/SUCCESS)

May 26 18:34:47 context-broker.novalocal systemd[1]: Starting LSB: run contextBroker...
May 26 18:34:47 context-broker.novalocal contextBroker[16319]: contextBroker is stopped
May 26 18:34:47 context-broker.novalocal contextBroker[16319]: Starting...
May 26 18:34:47 context-broker.novalocal su[16325]: (to orion) root on none
May 26 18:34:49 context-broker.novalocal systemd[1]: Started LSB: run contextBroker.
May 26 18:34:49 context-broker.novalocal contextBroker[16319]: Starting contextBroker...                         [  OK  ]

</code>```

The log file has the same message as previously.
With some searching again I believe the cause is that the service doesnt have a daemon(??). So if that is the case how do I add one?

答: Normally when getting the error starting REST interface, it's because there is already a broker running, which means the port is already taken. Make sure there is no broker already running.</p>

Body:
My orion context broker does not start and when I enter the command
/etc/init.d/contextBroker start I get this message

[root@context-broker ~]# /etc/init.d/contextBroker start
Starting contextBroker (via systemctl):  Job for contextBroker.service failed because the control process exited with error code. See "systemctl status contextBroker.service" and "journalctl -xe" for details.
                                                           [FAILED]

The systemctl status contextBroker.service commannd gives this message

[root@context-broker ~]# systemctl status contextBroker.service
● contextBroker.service - LSB: run contextBroker
   Loaded: loaded (/etc/rc.d/init.d/contextBroker; bad; vendor preset: disabled)
   Active: failed (Result: exit-code) since Fri 2019-05-24 11:38:50 UTC; 1min 11s ago
     Docs: man:systemd-sysv-generator(8)
  Process: 9782 ExecStart=/etc/rc.d/init.d/contextBroker start (code=exited, status=1/FAILURE)

May 24 11:38:47 context-broker.novalocal systemd[1]: Starting LSB: run contextBroker...
May 24 11:38:48 context-broker.novalocal contextBroker[9782]: contextBroker is stopped
May 24 11:38:48 context-broker.novalocal contextBroker[9782]: Starting...
May 24 11:38:48 context-broker.novalocal su[9788]: (to orion) root on none
May 24 11:38:50 context-broker.novalocal contextBroker[9782]: Starting contextBroker...                         cat: /var/run/contextBroker/contextBroker.pid...irectory
May 24 11:38:50 context-broker.novalocal systemd[1]: contextBroker.service: control process exited, code=exited status=1
May 24 11:38:50 context-broker.novalocal contextBroker[9782]: pidfile not found[FAILED]
May 24 11:38:50 context-broker.novalocal systemd[1]: Failed to start LSB: run contextBroker.
May 24 11:38:50 context-broker.novalocal systemd[1]: Unit contextBroker.service entered failed state.
May 24 11:38:50 context-broker.novalocal systemd[1]: contextBroker.service failed.
Hint: Some lines were ellipsized, use -l to show in full.

Also the /tmp/contextBroker.log file looks like this

time=2019-05-24T11:41:12.971Z | lvl=FATAL | corr=N/A | trans=N/A | from=N/A | srv=N/A | subsrv=N/A | comp=Orion | op=rest.cpp[1753]:restStart | msg=Fatal Error (error starting REST interface)

I checked if mongodb is running and it is running correctly.
UPDATE
With some searching I realised I had to kill the pid of the process and after I did that the service successfully starts according to the messaags but I find it doesnt actually work. When I ask for the status I get the following:

[root@context-broker centos]# /etc/init.d/contextBroker status
● contextBroker.service - LSB: run contextBroker
   Loaded: loaded (/etc/rc.d/init.d/contextBroker; bad; vendor preset: disabled)
   Active: active (exited) since Sun 2019-05-26 18:34:49 UTC; 4min 56s ago
     Docs: man:systemd-sysv-generator(8)
  Process: 16295 ExecStop=/etc/rc.d/init.d/contextBroker stop (code=exited, status=0/SUCCESS)
  Process: 16319 ExecStart=/etc/rc.d/init.d/contextBroker start (code=exited, status=0/SUCCESS)

May 26 18:34:47 context-broker.novalocal systemd[1]: Starting LSB: run contextBroker...
May 26 18:34:47 context-broker.novalocal contextBroker[16319]: contextBroker is stopped
May 26 18:34:47 context-broker.novalocal contextBroker[16319]: Starting...
May 26 18:34:47 context-broker.novalocal su[16325]: (to orion) root on none
May 26 18:34:49 context-broker.novalocal systemd[1]: Started LSB: run contextBroker.
May 26 18:34:49 context-broker.novalocal contextBroker[16319]: Starting contextBroker...                         [  OK  ]

The log file has the same message as previously.
With some searching again I believe the cause is that the service doesnt have a daemon(??). So if that is the case how do I add one?


问:
EnvoyProxy, Diffie Hellman Key and ssl security
I'm trying to get A+ 100% ssl labs ranking on my server.
When I had Nginx I could set Diffie Hellman key in the config (ssl_dhparam).

Now I migrated to EnvoyProxy but I could not find a way to specify the Diffie Hellman Key.

Envoy uses BoringSSL not OpenSSL.
I dig in the code of BoringSSL and it have references of Diffie Hellman, but envoy don't.

What you think ? Is envoy less secure that other reverse proxies ?

答:
After further investigation, I found that BoringSSL does not implement chippers that uses the Diffie Hellman (DH), but that does not mean it is less secure or whatever.

I could not get 100% SSL rating because currently there are only a few chippers that are "secure" and they are not implemented on all old reference browsers, so, I have to deal with the true story.

All CBC-mode ciphers in TLS are vulnerable to the Lucky 13 attack, due to a flaw in the ordering between encryption and MAC. ECDHE-ECDSA-AES256-SHA384 and ECDHE-RSA-AES256-SHA384 (standard names are TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384 and TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384) switched HMAC-SHA-1 to HMAC-SHA-384, but SHA-1 was not the main problem with those ciphers.

The only strong cipher suites in TLS 1.2 are ECDHE paired with an AEAD bulk cipher (one based on AES-GCM or ChaCha20-Poly1305). Everything else is legacy and should be phased out over time.

Here is my config:

```<code>              tls_params:
                tls_maximum_protocol_version: TLSv1_3
                tls_minimum_protocol_version: TLSv1_2
                cipher_suites: [
                  "ECDHE-RSA-CHACHA20-POLY1305",
                  "ECDHE-RSA-AES256-GCM-SHA384",
                  "ECDHE-RSA-AES256-SHA"
                ]
                ecdh_curves: [
                  "P-256"
                ]
</code>```

Where I keep ECDHE-RSA-AES256-SHA for compatibility purposes.

Body:
After further investigation, I found that BoringSSL does not implement chippers that uses the Diffie Hellman (DH), but that does not mean it is less secure or whatever.

I could not get 100% SSL rating because currently there are only a few chippers that are "secure" and they are not implemented on all old reference browsers, so, I have to deal with the true story.

All CBC-mode ciphers in TLS are vulnerable to the Lucky 13 attack, due to a flaw in the ordering between encryption and MAC. ECDHE-ECDSA-AES256-SHA384 and ECDHE-RSA-AES256-SHA384 (standard names are TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384 and TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384) switched HMAC-SHA-1 to HMAC-SHA-384, but SHA-1 was not the main problem with those ciphers.

The only strong cipher suites in TLS 1.2 are ECDHE paired with an AEAD bulk cipher (one based on AES-GCM or ChaCha20-Poly1305). Everything else is legacy and should be phased out over time.

Here is my config:

              tls_params:
                tls_maximum_protocol_version: TLSv1_3
                tls_minimum_protocol_version: TLSv1_2
                cipher_suites: [
                  "ECDHE-RSA-CHACHA20-POLY1305",
                  "ECDHE-RSA-AES256-GCM-SHA384",
                  "ECDHE-RSA-AES256-SHA"
                ]
                ecdh_curves: [
                  "P-256"
                ]

Where I keep ECDHE-RSA-AES256-SHA for compatibility purposes.


问:
SwaggerUI delete endpoint showing wrong parameter
My SwaggerUI is showing the wrong parameter for the Delete Endpoint. I'm passing an object to delete but in SwaggerUI the parameter showed is the Id of the object. There is a way to correct this?

Api Method:

[SwaggerResponse(HttpStatusCode.OK)]
 public IHttpActionResult Delete([FromBody]CargoApiDTO cargoDto)

答:
I did think whether I should post this as the answer as it doesn't directly answer the question.

This being said, I think you're going about this the wrong way. A DELETE request obviously passes a delete request to an endpoint. As such it doesn't need the whole object.

Think what you need to delete something, all you need is the unique identifier of the resource you want to delete. I guess Swagger is trying to point you in the right direction.

Even if you pass the whole object, in the end you'll only extract the ID from your entire DTO, which makes it pointless to transfer potentially a lot of data over the wire for literally nothing.

So, change your endpoint, only have the id as a parameter and Swagger won't be confused any more.


问:
Cronjobs in node.js
Is there a possibility to periodically call functions at a specific time of the day in node.js? My first implementation was

```<code>setInterval(functionName(),(24*60*60*1000));
</code>```

This is suboptimal, because it will restart every time I restart node. Are there better possibilities to implement this?

答:
To guard against restarts you need to create a persistent data stored job.

Something like :

```<code>Job = {
    _id: Number,
    job: String,
    dueDate: Date,
    completed: Boolean
}
</code>```

Then have some code as follows:

```<code>var createJob = function(url, date) {
    var j = db.create(Job, function(j) {
         j.job = url;
         j.dueDate = date;
         j.save();
    });
};

var runJob = function(j) {
    var id = j._id;
    setInterval(j.dueDate - Date.now(), function() {
         db.getOne(Job, { _id : id }, function(j) {
             require(j.job);
             j.finished = true;
             j.save();
         });
    });
    j = null;
};
</code>```

On start up you just have to do something like :

```<code>db.get(Job, { finished: false }, function(jobs) {
    jobs.forEach(runJob);
});
</code>```

Replace the generic db with MongoDB, CouchDB, Redis, etc.

ContentLicense: CC BY-SA 3.0

Title: Cronjobs in node.js

Body:
Is there a possibility to periodically call functions at a specific time of the day in node.js? My first implementation was

setInterval(functionName(),(24*60*60*1000));

This is suboptimal, because it will restart every time I restart node. Are there better possibilities to implement this?

Body:
To guard against restarts you need to create a persistent data stored job.

Something like :

Job = {
    _id: Number,
    job: String,
    dueDate: Date,
    completed: Boolean
}

Then have some code as follows:

var createJob = function(url, date) {
    var j = db.create(Job, function(j) {
         j.job = url;
         j.dueDate = date;
         j.save();
    });
};

var runJob = function(j) {
    var id = j._id;
    setInterval(j.dueDate - Date.now(), function() {
         db.getOne(Job, { _id : id }, function(j) {
             require(j.job);
             j.finished = true;
             j.save();
         });
    });
    j = null;
};

On start up you just have to do something like :

db.get(Job, { finished: false }, function(jobs) {
    jobs.forEach(runJob);
});

Replace the generic db with MongoDB, CouchDB, Redis, etc.


问:
Redirecting directly from phoenix router
I'm trying to redirect from my router.ex.

I'm got something like:

```<code>import Phoenix.Controller, only: [redirect: 2]

scope("/", MyApp) do
  forward "/test", :redirect, to: "/new-url"
end
</code>```

The current error I'm getting is:

```<code>== Compilation error in file lib/myapp_web/router.ex ==
** (ArgumentError) expected an Elixir module, got: "redirect"
</code>```

What am I doing wrong?

答:
Phoenix.Router.forward/4 expects a plug as the second parameter.

Outside of any scope add the line:

```<code>forward "/test", MyApp.NewUrl
</code>```

where MyApp.NewUrl is either a plug module or a phoenix controller.

Body:
I'm trying to redirect from my router.ex.

I'm got something like:

import Phoenix.Controller, only: [redirect: 2]

scope("/", MyApp) do
  forward "/test", :redirect, to: "/new-url"
end

The current error I'm getting is:

== Compilation error in file lib/myapp_web/router.ex ==
** (ArgumentError) expected an Elixir module, got: "redirect"

What am I doing wrong?

Body:
Phoenix.Router.forward/4 expects a plug as the second parameter.

Outside of any scope add the line:

forward "/test", MyApp.NewUrl

where MyApp.NewUrl is either a plug module or a phoenix controller.


问:
Translate R code to Python in visualization
I am trying to learn python recently.

I tried to translate R code to Python so I can check whether the result is correct.

Here is the dataset in R:

```<code>> dt
          date  Factors val_sum
 1: 2015-09-01        I   66084
 2: 2017-11-01        I   17096
 3: 2015-10-01        G    7988
 4: 2013-03-01        I    3726
 5: 2013-12-01        I     139
 6: 2013-03-01        I      45
 7: 2018-02-01        I   19674
 8: 2015-12-01        I   45654
 9: 2014-12-01        I  207240
10: 2015-07-01        G    7642
11: 2013-03-01        I   29054
12: 2015-12-01        I   24030
13: 2017-06-01        I  234142
14: 2018-11-01        I    2633
15: 2018-11-01        I  152254

> str(dt)
Classes ‘data.table’ and 'data.frame':  15 obs. of  3 variables:
$ date   : Date, format: "2015-09-01" "2017-11-01" "2015-10-01" "2013-03-01" ...
$ Factors: chr  "I" "I" "G" "I" ...
$ val_sum: int  66084 17096 7988 3726 139 45 19674 45654 207240 7642 ...
- attr(*, ".internal.selfref")=<externalptr>
</code>```

Now, the R code I use as below:

```<code>library(data.table)
dt <- dt[order(Factors, date)]
dt[, yq := as.yearqtr(dt$date, format = "%Y-%m-%d")]
dt <- dt[, lapply(.SD, as.numeric), .SDcols = 3, by = .(yq, Factors)][, lapply(.SD, function(x) sum = sum(x, na.rm = T)), .SDcols = 3, by = .(yq, Factors)][]
dt <- dt[, paste0(names(dt)[3], ".R") := lapply(.SD, function(x) R = x / x[1]), .SDcols = 3, by = .(Factors)][order(Factors, yq)][]
dt[, paste0(names(dt)[3], ".YQGR") := lapply(.SD, function(x) x / shift(x) - 1), .SDcols = 3, by = .(quarter(yq), Factors)]
</code>```

I manipulate the data first as above and I will use ggplot2 to draw and customize the plot.

```<code>ggplot(data = dt, aes(x = yq, colour = Factors, fill = Factors,
                       label = scales::percent(val_sum.YQGR, accuracy = 0.1))) +
geom_col(aes(y = 0.1 * val_sum.YQGR), position = position_dodge2(width = 0)) +
geom_line(aes(y = val_sum.R)) +
scale_colour_manual(values = c("red", "darkblue"), labels = c("G", "I")) +
scale_fill_manual(values = c("red", "darkblue"), labels = NULL, breaks = NULL) +
scale_x_yearqtr(format = "%YQ%q", breaks = unique(dt$yq)) +
scale_y_continuous(name = "R",
                   sec.axis = sec_axis(~./0.1, name = "YQGR",
                                       labels = scales::percent)) +
theme_bw() +
theme(axis.title.x = element_blank(),
      axis.title.y = element_blank(),
      axis.title.y.right = element_blank(),
      axis.ticks.x=element_blank(),
      axis.ticks.y=element_blank(),
      axis.text.x=element_text(angle = 45, size = 12, vjust = 0.5, face = "bold"),
      axis.text.y=element_blank(),
      axis.line = element_line(colour = "white"),
      panel.grid.major = element_blank(),
      panel.grid.minor = element_blank(),
      panel.border = element_blank(),
      panel.background = element_blank(),
      plot.background=element_blank(),
      legend.position="left",
      legend.title=element_blank(),
      legend.text = element_text(size = 16, face = "bold"),
      legend.key = element_blank(),
      legend.box.background =  element_blank()) +
guides(colour = guide_legend(override.aes = list(shape = 15, size = 10))) +
geom_text(data = dt, aes(y = 0.1 * val_sum.YQGR, colour = Factors),
          position = position_dodge(width = 0.25),
          vjust = -0.3, size = 4)
</code>```

How to translate this R code to Python 3 efficiently.

DATA:

```<code>dt <- data.table::fread("          date  Factors val_sum
2015-09-01        I   66084
2017-11-01        I   17096
2015-10-01        G    7988
2013-03-01        I    3726
2013-12-01        I     139
2013-03-01        I      45
2018-02-01        I   19674
2015-12-01        I   45654
2014-12-01        I  207240
2015-07-01        G    7642
2013-03-01        I   29054
2015-12-01        I   24030
2017-06-01        I  234142
2018-11-01        I    2633
2018-11-01        I  152254", header = T)
</code>```

Thank you.

Result:

```<code>         yq Factors val_sum   val_sum.R val_sum.YQGR
 1: 2015 Q3       G    7642 1.000000000           NA
 2: 2015 Q4       G    7988 1.045276106           NA
 3: 2013 Q1       I   32825 1.000000000           NA
 4: 2013 Q4       I     139 0.004234577           NA
 5: 2014 Q4       I  207240 6.313480579 1489.9352518
 6: 2015 Q3       I   66084 2.013221630           NA
 7: 2015 Q4       I   69684 2.122894136   -0.6637522
 8: 2017 Q2       I  234142 7.133038842           NA
 9: 2017 Q4       I   17096 0.520822544   -0.7546639
10: 2018 Q1       I   19674 0.599360244   -0.4006398
11: 2018 Q4       I  154887 4.718568165    8.0598386
</code>```

Because the data is I simply created, the plot seems weird due to extremely high value and the x-axis is weird as well due to lots of missing year and quarter.

But the logic is the same.

Body:
I am trying to learn python recently.

I tried to translate R code to Python so I can check whether the result is correct.

Here is the dataset in R:

> dt
          date  Factors val_sum
 1: 2015-09-01        I   66084
 2: 2017-11-01        I   17096
 3: 2015-10-01        G    7988
 4: 2013-03-01        I    3726
 5: 2013-12-01        I     139
 6: 2013-03-01        I      45
 7: 2018-02-01        I   19674
 8: 2015-12-01        I   45654
 9: 2014-12-01        I  207240
10: 2015-07-01        G    7642
11: 2013-03-01        I   29054
12: 2015-12-01        I   24030
13: 2017-06-01        I  234142
14: 2018-11-01        I    2633
15: 2018-11-01        I  152254

> str(dt)
Classes ‘data.table’ and 'data.frame':  15 obs. of  3 variables:
$ date   : Date, format: "2015-09-01" "2017-11-01" "2015-10-01" "2013-03-01" ...
$ Factors: chr  "I" "I" "G" "I" ...
$ val_sum: int  66084 17096 7988 3726 139 45 19674 45654 207240 7642 ...
- attr(*, ".internal.selfref")=<externalptr>

Now, the R code I use as below:

library(data.table)
dt <- dt[order(Factors, date)]
dt[, yq := as.yearqtr(dt$date, format = "%Y-%m-%d")]
dt <- dt[, lapply(.SD, as.numeric), .SDcols = 3, by = .(yq, Factors)][, lapply(.SD, function(x) sum = sum(x, na.rm = T)), .SDcols = 3, by = .(yq, Factors)][]
dt <- dt[, paste0(names(dt)[3], ".R") := lapply(.SD, function(x) R = x / x[1]), .SDcols = 3, by = .(Factors)][order(Factors, yq)][]
dt[, paste0(names(dt)[3], ".YQGR") := lapply(.SD, function(x) x / shift(x) - 1), .SDcols = 3, by = .(quarter(yq), Factors)]

I manipulate the data first as above and I will use ggplot2 to draw and customize the plot.

ggplot(data = dt, aes(x = yq, colour = Factors, fill = Factors,
                       label = scales::percent(val_sum.YQGR, accuracy = 0.1))) +
geom_col(aes(y = 0.1 * val_sum.YQGR), position = position_dodge2(width = 0)) +
geom_line(aes(y = val_sum.R)) +
scale_colour_manual(values = c("red", "darkblue"), labels = c("G", "I")) +
scale_fill_manual(values = c("red", "darkblue"), labels = NULL, breaks = NULL) +
scale_x_yearqtr(format = "%YQ%q", breaks = unique(dt$yq)) +
scale_y_continuous(name = "R",
                   sec.axis = sec_axis(~./0.1, name = "YQGR",
                                       labels = scales::percent)) +
theme_bw() +
theme(axis.title.x = element_blank(),
      axis.title.y = element_blank(),
      axis.title.y.right = element_blank(),
      axis.ticks.x=element_blank(),
      axis.ticks.y=element_blank(),
      axis.text.x=element_text(angle = 45, size = 12, vjust = 0.5, face = "bold"),
      axis.text.y=element_blank(),
      axis.line = element_line(colour = "white"),
      panel.grid.major = element_blank(),
      panel.grid.minor = element_blank(),
      panel.border = element_blank(),
      panel.background = element_blank(),
      plot.background=element_blank(),
      legend.position="left",
      legend.title=element_blank(),
      legend.text = element_text(size = 16, face = "bold"),
      legend.key = element_blank(),
      legend.box.background =  element_blank()) +
guides(colour = guide_legend(override.aes = list(shape = 15, size = 10))) +
geom_text(data = dt, aes(y = 0.1 * val_sum.YQGR, colour = Factors),
          position = position_dodge(width = 0.25),
          vjust = -0.3, size = 4)

How to translate this R code to Python 3 efficiently.

DATA:

dt <- data.table::fread("          date  Factors val_sum
2015-09-01        I   66084
2017-11-01        I   17096
2015-10-01        G    7988
2013-03-01        I    3726
2013-12-01        I     139
2013-03-01        I      45
2018-02-01        I   19674
2015-12-01        I   45654
2014-12-01        I  207240
2015-07-01        G    7642
2013-03-01        I   29054
2015-12-01        I   24030
2017-06-01        I  234142
2018-11-01        I    2633
2018-11-01        I  152254", header = T)

Thank you.

Result:

         yq Factors val_sum   val_sum.R val_sum.YQGR
 1: 2015 Q3       G    7642 1.000000000           NA
 2: 2015 Q4       G    7988 1.045276106           NA
 3: 2013 Q1       I   32825 1.000000000           NA
 4: 2013 Q4       I     139 0.004234577           NA
 5: 2014 Q4       I  207240 6.313480579 1489.9352518
 6: 2015 Q3       I   66084 2.013221630           NA
 7: 2015 Q4       I   69684 2.122894136   -0.6637522
 8: 2017 Q2       I  234142 7.133038842           NA
 9: 2017 Q4       I   17096 0.520822544   -0.7546639
10: 2018 Q1       I   19674 0.599360244   -0.4006398
11: 2018 Q4       I  154887 4.718568165    8.0598386

Because the data is I simply created, the plot seems weird due to extremely high value and the x-axis is weird as well due to lots of missing year and quarter.

But the logic is the same.

Body:
Here's a python translation of your R code:

dfstr = '''         date  Factors val_sum
2015-09-01        I   66084
2017-11-01        I   17096
2015-10-01        G    7988
2013-03-01        I    3726
2013-12-01        I     139
2013-03-01        I      45
2018-02-01        I   19674
2015-12-01        I   45654
2014-12-01        I  207240
2015-07-01        G    7642
2013-03-01        I   29054
2015-12-01        I   24030
2017-06-01        I  234142
2018-11-01        I    2633
2018-11-01        I  152254'''

df = pd.read_csv(pd.compat.StringIO(dfstr), sep='\s+')

df.date = pd.to_datetime(df.date)

df['year']= df.date.dt.year
df['qtr'] = df.date.dt.month//4 + 1

df = df.groupby(['Factors', 'year', 'qtr']).val_sum.sum().reset_index()

df['val_sum.R'] = df.val_sum / df.groupby('Factors').val_sum.transform('first')
df['val_sum.YQGR'] = df.val_sum / df.groupby(['qtr', 'Factors']).val_sum.transform('shift') - 1

Output:

+----+-----------+--------+-------+-----------+-------------+----------------+
|    | Factors   |   year |   qtr |   val_sum |   val_sum.R |   val_sum.YQGR |
|----+-----------+--------+-------+-----------+-------------+----------------|
|  0 | G         |   2015 |     2 |      7642 |  1          |     nan        |
|  1 | G         |   2015 |     3 |      7988 |  1.04528    |     nan        |
|  2 | I         |   2013 |     1 |     32825 |  1          |     nan        |
|  3 | I         |   2013 |     4 |       139 |  0.00423458 |     nan        |
|  4 | I         |   2014 |     4 |    207240 |  6.31348    |    1489.94     |
|  5 | I         |   2015 |     3 |     66084 |  2.01322    |     nan        |
|  6 | I         |   2015 |     4 |     69684 |  2.12289    |      -0.663752 |
|  7 | I         |   2017 |     2 |    234142 |  7.13304    |     nan        |
|  8 | I         |   2017 |     3 |     17096 |  0.520823   |      -0.741299 |
|  9 | I         |   2018 |     1 |     19674 |  0.59936    |      -0.40064  |
| 10 | I         |   2018 |     3 |    154887 |  4.71857    |       8.05984  |
+----+-----------+--------+-------+-----------+-------------+----------------+


问:
this.get(...).then is not a function when using init: ember.js
I am using init() in my component to load some data for a dropdown. On refresh it works but when I leave the tab to another tab then come back I get the following error:
index.js:143322 Uncaught TypeError: this.get(...).then is not a function

This code is in my init function and I suspect it has something to do with how ember.js renders but I am struggling to figure out how to make it work. I tried using the other lifestyle hooks but none of them worked.

This is the init function which is in a component:

```<code>init() {
      this._super(...arguments)
      this.get('popularTags').then(function(result) {
        const newArray = []
        for (var i = 0; i < result.length; i++) {
          newArray.push({
            name: result[i],
            value: result[i],
            group: 'Popular'
          })
        }
        const popularTags = this.get('popularTags')
        this.set('popularTags', newArray)
        this.get('queryResults').then(function(result) {
          const tagArray = []
          for (var i = 0; i < result.length; i++) {
            let popular = newArray.filter(tag => tag['value'] === result[i].value)

            if (popular.length === 0) {
              tagArray.push({
                name: result[i].value,
                value: result[i].value,
                group: ''
              })
            }
          }
          const queryResults = this.get('queryResults')

          return this.set('queryResults', tagArray)
        }.bind(this))

      }.bind(this))

    },
</code>```

答:
Your problem could be that youre calling the component with curlies and passing popularTags:

{{your-component popularTags=something}}

This is two-way bound. Precisely this means that changing popularTags inside the component will change something on the caller.

This means that if you remove this component and re-create it later (what your mention of some tabbing indicates) you've changes something on the outside. And your component expects popularTags (and so something) to be a promise (when calling this.get('popularTags').then). However because you changes it (with this.set('popularTags', newArray)) its no longer a promise but an array.

Generally I would recommend you to be careful when changing passed attributes.

Body:
I am using init() in my component to load some data for a dropdown. On refresh it works but when I leave the tab to another tab then come back I get the following error:
index.js:143322 Uncaught TypeError: this.get(...).then is not a function

This code is in my init function and I suspect it has something to do with how ember.js renders but I am struggling to figure out how to make it work. I tried using the other lifestyle hooks but none of them worked.

This is the init function which is in a component:

init() {
      this._super(...arguments)
      this.get('popularTags').then(function(result) {
        const newArray = []
        for (var i = 0; i < result.length; i++) {
          newArray.push({
            name: result[i],
            value: result[i],
            group: 'Popular'
          })
        }
        const popularTags = this.get('popularTags')
        this.set('popularTags', newArray)
        this.get('queryResults').then(function(result) {
          const tagArray = []
          for (var i = 0; i < result.length; i++) {
            let popular = newArray.filter(tag => tag['value'] === result[i].value)

            if (popular.length === 0) {
              tagArray.push({
                name: result[i].value,
                value: result[i].value,
                group: ''
              })
            }
          }
          const queryResults = this.get('queryResults')

          return this.set('queryResults', tagArray)
        }.bind(this))

      }.bind(this))

    },


问:
Reversing string in C using for loop
I'm a beginner in C and I don't understand why my code isn't working. The aim is simply just to reverse a string.</p>

```<code>char word[20];
int i, len;

printf("Enter word: ");
    scanf("%s", &word);

len = strlen(word);

printf("String reversed: ");
for (i = len-1; i >= 0; i--){
    printf("%s", word[i]);
}
</code>```

答:
In

```<code>printf("%s", word[i]);
</code>```

%s is a wrong format because you write a character, not a string

Out of that :

the natural type for an index is size_tnot int, use size_tfor both i and len, and in that case change the loop to use index without supposing it can be negative

if the input string has more than 19 characters scanf will write out of word with an undefined behavior, limit the size using the format %19s (19 rather than 20 to have the place for the ending null character)

word is an array, do not use a '&' to give its address in scanf

check the result of scanf if you want to detect EOF

flush the output writing a newline after the loop

So a possible way is :

```<code>char word[20];

printf("Enter word: ");
if (scanf("%19s", word) == 1) {
  printf("String reversed: ");

  for (size_t i = strlen(word); i != 0; i--){
    printf("%c", word[i-1]);
  }
  putchar('\n');
}
</code>```

Title: Reversing string in C using for loop

Body:
I'm a beginner in C and I don't understand why my code isn't working. The aim is simply just to reverse a string.

char word[20];
int i, len;

printf("Enter word: ");
    scanf("%s", &word);

len = strlen(word);

printf("String reversed: ");
for (i = len-1; i >= 0; i--){
    printf("%s", word[i]);
}

Body:
In

printf("%s", word[i]);

%s is a wrong format because you write a character, not a string

Out of that :

the natural type for an index is size_tnot int, use size_tfor both i and len, and in that case change the loop to use index without supposing it can be negative

if the input string has more than 19 characters scanf will write out of word with an undefined behavior, limit the size using the format %19s (19 rather than 20 to have the place for the ending null character)

word is an array, do not use a '&' to give its address in scanf

check the result of scanf if you want to detect EOF

flush the output writing a newline after the loop

So a possible way is :

char word[20];

printf("Enter word: ");
if (scanf("%19s", word) == 1) {
  printf("String reversed: ");

  for (size_t i = strlen(word); i != 0; i--){
    printf("%c", word[i-1]);
  }
  putchar('\n');
}


问:
Spring Integration JDBC execution times statistics
I am using spring-integration in order to connect to an external JDBC database and I want to track execution times per db connection.

Apart from using Spring AOP and wrapping my service method to measure statistics, is there any way to measure times directly in the spring-integration? Meaning to get exactly how much the database connection was used per request?

Thanks

答:
The JDBC is used not only in Spring Integration, so it is not correct to request such a feature exactly from the Spring Integration perspective. Any other applications without any integration features should benefit from such a feature as well.

I think what you are looking for is covered by the DB metrics in Spring Boot: https://docs.spring.io/spring-boot/docs/2.1.5.RELEASE/reference/htmlsingle/#production-ready-metrics-jdbc

If you don't use Spring Boot, consider to apply the mentioned HikariCP: https://github.com/brettwooldridge/HikariCP/wiki/Dropwizard-Metrics

Otherwise you always can override execute(PreparedStatementCreator psc, PreparedStatementCallback<T> action) and wrap a super call into your own metric to measure a time for that execute() call.


问:
Airbnb style guide:rules for naming conventions not working
According to the Airbnb doc, this is the best practice for naming objects

```<code>// bad
const OBJEcttsssss = {};

// good
const thisIsMyObject = {};
</code>```

But which rule I need to add to achieve the same

Here is my .eslintrc.json

```<code>{
  "extends": "airbnb",
  "env": {
    "browser": true,
    "node": true
  },
  "rules":{
    "camelcase":true
  }
}
</code>```

I've added camelcase rule but it didn't work

Also, I can't find the rules belong to the following

1) Variable naming
2) Function naming
3) Class Naming

答:
You are  not defining the rule correctly it need to be an array

eg : "camelcase": [2, {"properties": "always"}]

More info about the options there :
https://eslint.org/docs/2.0.0/rules/camelcase

Body:
According to the Airbnb doc, this is the best practice for naming objects

// bad
const OBJEcttsssss = {};

// good
const thisIsMyObject = {};

But which rule I need to add to achieve the same

Here is my .eslintrc.json

{
  "extends": "airbnb",
  "env": {
    "browser": true,
    "node": true
  },
  "rules":{
    "camelcase":true
  }
}

I've added camelcase rule but it didn't work

Also, I can't find the rules belong to the following

1) Variable naming
2) Function naming
3) Class Naming


问:
Cannot zoom tkinter PhotoImage: _tkinter.TclError: not enough free memory for image buffer
I have a canvas that has a width of w and a height of h. I'm trying to fit my (1000 x 800) image on it using image = image.zoom(w).subsample(800). But it's giving me the error: _tkinter.TclError: not enough free memory for image buffer. Can someone please help?

答: When you call zoom, the first parameter specifies how much to multiply each pixel by. If you only provide an x value, the y value will be the same as the x value. Thus, if w is 1000, zoom(x) will attempt to create an image that is one million pixels wide by 800,000 pixels tall. That's nearly a terabyte of image data.


问:
Assign pathnames returned from bash command(s) to an AppleScript list
I want to prompt the paths of the 10 recently added files of a directory (recursively) in Applescript as a list. This works fine in bash:

```<code>SAVEIFS=$IFS
IFS=$(echo -en "\n\b")

array=(`find . -type f -print0 | xargs -0 ls -t | head -n 10`)

echo "${array[*]}"

IFS=$SAVEIFS
</code>```

I’d like to store the resulting array in an Applescript Variable:

```<code>set l to (do shell script "______________")
</code>```

How can I put the bash part into a working 1-liner? Maybe there is also an Applescript-only solution?

答:
When you "shell out" from AppleScript the class of the value that you assign to a variable, (i.e. the variable named l in your example), will always be text and not a list.

In your scenario you're essentially capturing the pathname(s) that the find utility etc send to stdout (fd 1) which Applescript just recognizes as text.

To convert each line (i.e. a pathname that is printed to stdout via your bash commands) you'll need to utilize a helper subroutine/function as shown in the following gist.

  set stdout to do shell script "/usr/bin/find " & quoted form of "/absolute/path/to/target/directory" & " -type f -print0 | xargs -0 ls -t | head -n 10"

  set latestList to transformStdoutToList(stdout)

  -- Test it's a proper AppleScript list.
  log class of latestList
  log (item 1 of latestList)
  log (item 2 of latestList)
  -- ...

  (**
   * Transforms each line printed to stdout to form a new list of pathnames.
   *
   * Pathname(s) may contain newline `\n` characters in any part, including
   * their basenames. Below we read each line, if it begins with a forward
   * slash `/` it is considered to be the start of a pathname. If a line does
   * not begin with a forward slash `/` it is considered to be part of the
   * prevous pathname. In this scenario the line is appended to previous item
   * of the list and the newline character `\n` is reinstated.
   *
   * @param {String} pathsString - The pathname(s) printed to stdout.
   * @return {List} - A list whereby each item is a pathname.
   *)
  on transformStdoutToList(pathsString)
    set pathList to {}
    repeat with aLine in paragraphs of pathsString
        if aLine starts with "/" then
            set end of pathList to aLine
        else
            set last item of pathList to last item of pathList & "\n" & aLine
        end if
    end repeat
    return pathList
  end transformStdoutToList
```

<hr>

<p><strong>Explanation:</strong></p>

<ol>
<li><p>In the first line reading:</p>

<pre class="lang-none prettyprint-override"><code>set stdout to do shell script "/usr/bin/find " & quoted form of "/absolute/path/to/target/directory" & " -type f -print0 | xargs -0 ls -t | head -n 10"
</code>```

we utilize AppleScript's do shell script command to execute your bash commands.

Assign the result of the bash commands (which is typically a multi-line string of pathnames) to the AppleScript variable named stdout. The class of the value assigned to stdout will be text - you can verify this by temporarily adding the following line to the script:

log class of stdout
```</li>
<li><p><strong>Note:</strong> You'll need to redefine the part that currently reads; <code>/absolute/path/to/target/directory</code>, with a real absolute path to the directory/folder that you want to search. You'll also notice that this target <em>pathname</em> is preceded with <code>& quoted form of</code> - this just ensures any space character(s) in the given <em>pathname</em> are interpreted correctly.</p></li>
</ul></li>
<li><p>The second line reading:</p>

<pre class="lang-none prettyprint-override"><code>set latestList to transformStdoutToList(stdout)
</code>```

invokes the transformStdoutToList subroutine passing in the value of stdout and assigns the result returned to the variable named latestList. The class of the value assigned to latestList will be list. Again, you can verify this by temporarily adding the following line to the script:

log class of latestList
```</li>
<li><p>The <code>transformStdoutToList</code> subroutine transforms each line (i.e. a <em>pathname</em>) that is passed to it and forms a new <code>list</code> of <em>pathname(s)</em>. Please read the comments in the code above for further explanation - you'll notice that is successfully handles any <em>pathname(s)</em> that may include newline character(s).</p></li>
</ol>

<hr>

<p><strong>Additional Note:</strong></p>

<p>The aforementioned <code>transformStdoutToList</code> subroutine includes a line that reads:</p>

<pre class="lang-none prettyprint-override"><code>set last item of pathList to last item of pathList & "\n" & aLine
</code>```

The "\n" part exists to reinstate any newline characters that may exist in a pathname. However when you compile the script in the AppleScript Editor this will appear as follows:

set last item of pathList to last item of pathList & "
" & aLine
```

<p><sub><strong>Note:</strong> the newline character, i.e. the <code>\n</code> part, has disappeared and has created an actual line-break.</sub></p>

<p><strong><em>This is normal and the script will produce the expected result</em></strong>. However, if you want to preserve the <code>"\n"</code> part in your <em>AppleScript Editor</em> then please change your preferences as described below:</p>

<ol>
<li>Select <code>AppleScript Editor</code> > <code>Preferences...</code> from the menu bar.</li>
<li>Select the <code>Editing</code> tab.</li>
<li>Click the checkbox for the <code>Formatting: Escape tabs and line breaks in strings</code> (i.e. switch this option on).</li>
</ol>

<hr>

<p><strong>Edit:</strong></p>

<blockquote>
  <p>How can I put the bash part into a working <strong>1-liner</strong></p>
</blockquote>

<p>If you <em>must</em> have a <em>"1-liner"</em> and are willing to sacrifice readability then you could do something like this instead:</p>

<pre class="lang-none prettyprint-override"><code>set l to transformStdoutToList(do shell script "/usr/bin/find " & quoted form of "/absolute/path/to/target/directory" & " -type f -print0 | xargs -0 ls -t | head -n 10")
</code>```

However, you'll still need to utilize the aforementioned transformStdoutToList subroutine, so that will need to be present in your script too.

Body:
I want to prompt the paths of the 10 recently added files of a directory (recursively) in Applescript as a list. This works fine in bash:

SAVEIFS=$IFS
IFS=$(echo -en "\n\b")

array=(`find . -type f -print0 | xargs -0 ls -t | head -n 10`)

echo "${array[*]}"

IFS=$SAVEIFS

I’d like to store the resulting array in an Applescript Variable:

set l to (do shell script "______________")

How can I put the bash part into a working 1-liner? Maybe there is also an Applescript-only solution?

Body:
When you "shell out" from AppleScript the class of the value that you assign to a variable, (i.e. the variable named l in your example), will always be text and not a list.

In your scenario you're essentially capturing the pathname(s) that the find utility etc send to stdout (fd 1) which Applescript just recognizes as text.

To convert each line (i.e. a pathname that is printed to stdout via your bash commands) you'll need to utilize a helper subroutine/function as shown in the following gist.

  set stdout to do shell script "/usr/bin/find " & quoted form of "/absolute/path/to/target/directory" & " -type f -print0 | xargs -0 ls -t | head -n 10"

  set latestList to transformStdoutToList(stdout)

  -- Test it's a proper AppleScript list.
  log class of latestList
  log (item 1 of latestList)
  log (item 2 of latestList)
  -- ...

  (**
   * Transforms each line printed to stdout to form a new list of pathnames.
   *
   * Pathname(s) may contain newline `\n` characters in any part, including
   * their basenames. Below we read each line, if it begins with a forward
   * slash `/` it is considered to be the start of a pathname. If a line does
   * not begin with a forward slash `/` it is considered to be part of the
   * prevous pathname. In this scenario the line is appended to previous item
   * of the list and the newline character `\n` is reinstated.
   *
   * @param {String} pathsString - The pathname(s) printed to stdout.
   * @return {List} - A list whereby each item is a pathname.
   *)
  on transformStdoutToList(pathsString)
    set pathList to {}
    repeat with aLine in paragraphs of pathsString
        if aLine starts with "/" then
            set end of pathList to aLine
        else
            set last item of pathList to last item of pathList & "\n" & aLine
        end if
    end repeat
    return pathList
  end transformStdoutToList

Explanation:

In the first line reading:

set stdout to do shell script "/usr/bin/find " & quoted form of "/absolute/path/to/target/directory" & " -type f -print0 | xargs -0 ls -t | head -n 10"

we utilize AppleScript's do shell script command to execute your bash commands.

Assign the result of the bash commands (which is typically a multi-line string of pathnames) to the AppleScript variable named stdout. The class of the value assigned to stdout will be text - you can verify this by temporarily adding the following line to the script:

log class of stdout

Note: You'll need to redefine the part that currently reads; /absolute/path/to/target/directory, with a real absolute path to the directory/folder that you want to search. You'll also notice that this target pathname is preceded with & quoted form of - this just ensures any space character(s) in the given pathname are interpreted correctly.

The second line reading:

set latestList to transformStdoutToList(stdout)

invokes the transformStdoutToList subroutine passing in the value of stdout and assigns the result returned to the variable named latestList. The class of the value assigned to latestList will be list. Again, you can verify this by temporarily adding the following line to the script:

log class of latestList

The transformStdoutToList subroutine transforms each line (i.e. a pathname) that is passed to it and forms a new list of pathname(s). Please read the comments in the code above for further explanation - you'll notice that is successfully handles any pathname(s) that may include newline character(s).

Additional Note:

The aforementioned transformStdoutToList subroutine includes a line that reads:

set last item of pathList to last item of pathList & "\n" & aLine

The "\n" part exists to reinstate any newline characters that may exist in a pathname. However when you compile the script in the AppleScript Editor this will appear as follows:

set last item of pathList to last item of pathList & "
" & aLine

Note: the newline character, i.e. the \n part, has disappeared and has created an actual line-break.

This is normal and the script will produce the expected result. However, if you want to preserve the "\n" part in your AppleScript Editor then please change your preferences as described below:

Select AppleScript Editor > Preferences... from the menu bar.

Select the Editing tab.

Click the checkbox for the Formatting: Escape tabs and line breaks in strings (i.e. switch this option on).

Edit:

How can I put the bash part into a working 1-liner

If you must have a "1-liner" and are willing to sacrifice readability then you could do something like this instead:

set l to transformStdoutToList(do shell script "/usr/bin/find " & quoted form of "/absolute/path/to/target/directory" & " -type f -print0 | xargs -0 ls -t | head -n 10")

However, you'll still need to utilize the aforementioned transformStdoutToList subroutine, so that will need to be present in your script too.


问:
EditText is growing as text entered
I have an edittext that is 80% of the screen across and a button that should take the remaining 20%, but when text is entered into the box or removed the edittext grows and shrinks.

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout
   xmlns:android="http://schemas.android.com/apk/res/android"
   android:layout_width="fill_parent"
   android:layout_height="fill_parent"
   android:orientation="vertical">

   <LinearLayout
      android:layout_width="fill_parent"
      android:layout_height="wrap_content"
      android:orientation="horizontal"
      android:weightSum="100">

      <Button
         android:id="@+id/people_relationFilterB"
         android:layout_width="wrap_content"
         android:layout_height="wrap_content"
         android:layout_weight="20" />

      <EditText
         android:id="@+id/people_searchBoxET"
         android:text="Search Known"
         android:singleLine="true"
         android:layout_width="wrap_content"
         android:layout_height="wrap_content"
         android:layout_weight="80" />
   </LinearLayout>

   <ListView
     android:id="@+id/people_listLV"
     android:layout_width="fill_parent"
     android:layout_height="wrap_content" />

</LinearLayout>
</code>```

Any Clues? Thanks!

答: Try to set android:layout_width="0dp"</p>

Title: EditText is growing as text entered

Body:
I have an edittext that is 80% of the screen across and a button that should take the remaining 20%, but when text is entered into the box or removed the edittext grows and shrinks.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
   xmlns:android="http://schemas.android.com/apk/res/android"
   android:layout_width="fill_parent"
   android:layout_height="fill_parent"
   android:orientation="vertical">

   <LinearLayout
      android:layout_width="fill_parent"
      android:layout_height="wrap_content"
      android:orientation="horizontal"
      android:weightSum="100">

      <Button
         android:id="@+id/people_relationFilterB"
         android:layout_width="wrap_content"
         android:layout_height="wrap_content"
         android:layout_weight="20" />

      <EditText
         android:id="@+id/people_searchBoxET"
         android:text="Search Known"
         android:singleLine="true"
         android:layout_width="wrap_content"
         android:layout_height="wrap_content"
         android:layout_weight="80" />
   </LinearLayout>

   <ListView
     android:id="@+id/people_listLV"
     android:layout_width="fill_parent"
     android:layout_height="wrap_content" />

</LinearLayout>

Any Clues? Thanks!

Body: Try to set android:layout_width="0dp"


问:
How to fetch a one table from HTML source file using lwp module?
I'm beginner. I want to know how to fetch one table form the source HTML file using LWP module? Is it possible to use Regex with LWP?</p>

答:
You can use LWP to get the HTML source of a web page. Most easily, by using the get() function from LWP::Simple.

```<code>my $html = get('http://example.com/');
</code>```

Now, in $html you have a text string (potentially a very long text string) which contains HTML. You can use any techniques you want to extract data from that string.

(Hint: Using a regex to do this is likely to be a very bad idea. It will be far harder than you expect and probably very fragile. Perhaps use a better tool - like HTML::TableExtract instead.)

Body:
You can use LWP to get the HTML source of a web page. Most easily, by using the get() function from LWP::Simple.

my $html = get('http://example.com/');

Now, in $html you have a text string (potentially a very long text string) which contains HTML. You can use any techniques you want to extract data from that string.

(Hint: Using a regex to do this is likely to be a very bad idea. It will be far harder than you expect and probably very fragile. Perhaps use a better tool - like HTML::TableExtract instead.)


问:
Limit RAM usage to python program
I'm trying to limit the RAM usage from a Python program to half so it doesn't totally freezes when all the RAM is used, for this I'm using the following code which is not working and my laptop is still freezing:

```<code>import sys
import resource

def memory_limit():
    rsrc = resource.RLIMIT_DATA
    soft, hard = resource.getrlimit(rsrc)
    soft /= 2
    resource.setrlimit(rsrc, (soft, hard))

if __name__ == '__main__':
    memory_limit() # Limitates maximun memory usage to half
    try:
        main()
    except MemoryError:
        sys.stderr.write('MAXIMUM MEMORY EXCEEDED')
        sys.exit(-1)
</code>```

I'm using other functions which I call from the main function.

What am I doing wrong?

Thanks in advance.

PD: I already searched about this and found the code I've put but it's still not working...

答:
due to https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/commit/?id=34e431b0ae398fc54ea69ff85ec700722c9da773

it is better to use :

```<code>if str(sline[0]) == 'MemAvailable:':
            free_memory = int(sline[1])
            break
</code>```

the answer code provided me with 8 GB of available mem on a machine with 1TB of RAM

Title: Limit RAM usage to python program

Body:
I'm trying to limit the RAM usage from a Python program to half so it doesn't totally freezes when all the RAM is used, for this I'm using the following code which is not working and my laptop is still freezing:

import sys
import resource

def memory_limit():
    rsrc = resource.RLIMIT_DATA
    soft, hard = resource.getrlimit(rsrc)
    soft /= 2
    resource.setrlimit(rsrc, (soft, hard))

if __name__ == '__main__':
    memory_limit() # Limitates maximun memory usage to half
    try:
        main()
    except MemoryError:
        sys.stderr.write('MAXIMUM MEMORY EXCEEDED')
        sys.exit(-1)

I'm using other functions which I call from the main function.

What am I doing wrong?

Thanks in advance.

PD: I already searched about this and found the code I've put but it's still not working...

Body:
due to https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/commit/?id=34e431b0ae398fc54ea69ff85ec700722c9da773

it is better to use :

if str(sline[0]) == 'MemAvailable:':
            free_memory = int(sline[1])
            break

the answer code provided me with 8 GB of available mem on a machine with 1TB of RAM