问:
JDK 9 unsafe import sun.misc.Launcher
I've recently upgraded to JDK 9 and Eclipse complains that sun.misc.Launcher cannot be imported. It seems that sun.misc.Launcher is unsafe.
I'm looking for an alternative to replace this line of code in my project.

```<code>final URL url = Launcher.class.getResource("/");
</code>```

Any help would be appreciated.

Update: the more complete version of the above block of code is:

```<code>final URL url = Launcher.class.getResource("/");
final File fs = new File(url.toURI());
for (File f : fs.listFiles()) {
     System.out.println(f.getAbsolutePath());
}
</code>```

This is to print all the files in the src folder when program is launched in IDE.

答:
Calling the Class.getResource from any of the class in the module whose classes are being tried to access should work fine.

```<code>final URL url = ClassInTheCurrentModule.class.getResource("/");
</code>```

The reason why the answer by shazin might return null is probably that with ClassLoader being a caller for the getResource call:

returns null when the resource is a non-".class" resource in a package
  that is not open to the caller's module.

Since ClassLoader belongs to the package java.lang in the module java.base to which your module might not be open.

Also, do note the resolution of the getResource is split further for named and unnamed modules.

Title: JDK 9 unsafe import sun.misc.Launcher

Body:
I've recently upgraded to JDK 9 and Eclipse complains that sun.misc.Launcher cannot be imported. It seems that sun.misc.Launcher is unsafe.
I'm looking for an alternative to replace this line of code in my project.

final URL url = Launcher.class.getResource("/");

Any help would be appreciated.

Update: the more complete version of the above block of code is:

final URL url = Launcher.class.getResource("/");
final File fs = new File(url.toURI());
for (File f : fs.listFiles()) {
     System.out.println(f.getAbsolutePath());
}

This is to print all the files in the src folder when program is launched in IDE.

Body:
Calling the Class.getResource from any of the class in the module whose classes are being tried to access should work fine.

final URL url = ClassInTheCurrentModule.class.getResource("/");

The reason why the answer by shazin might return null is probably that with ClassLoader being a caller for the getResource call:

returns null when the resource is a non-".class" resource in a package
  that is not open to the caller's module.

Since ClassLoader belongs to the package java.lang in the module java.base to which your module might not be open.

Also, do note the resolution of the getResource is split further for named and unnamed modules.


来源: stackexchange

问:
Viewing the IL code generated from a compiled expression
Is it possible to view the IL code generated when you call Compile() on an Expression tree?  Consider this very simple example:

```<code>class Program
{
    public int Value { get; set; }

    static void Main(string[] args)
    {
        var param = Expression.Parameter(typeof(Program));
        var con = Expression.Constant(5);
        var prop = Expression.Property(param, typeof(Program).GetProperty("Value"));
        var assign = Expression.Assign(prop, con);
        Action<Program> lambda = Expression.Lambda<Action<Program>>(assign, param).Compile();

        Program p = new Program();
        lambda(p);

        //p.Value = 5;
    }
}
</code>```

Now, the expression tree does what the last line of Main says.  Compile the application, then open it in Reflector.  You can see the IL code of p.Value = 5; that does the assignment.  But the expression tree was made and compiled at runtime.  Is it possible to view the resulting IL code from the compile?

答:
Create a DynamicAssembly, then a DynamicModule, DynamicType and DynamicMethod. Make that method public and static and pass it to the method CompileTo() on the lambda. When you make the assembly flag it as Save. Then call the Save() method and pass a path. It will be written to disk. Pop it open in reflector.

Something like:

```<code>var da = AppDomain.CurrentDomain.DefineDynamicAssembly(
    new AssemblyName("dyn"), // call it whatever you want
    AssemblyBuilderAccess.Save);

var dm = da.DefineDynamicModule("dyn_mod", "dyn.dll");
var dt = dm.DefineType("dyn_type");
var method = dt.DefineMethod(
    "Foo",
    MethodAttributes.Public | MethodAttributes.Static);

lambda.CompileToMethod(method);
dt.CreateType();

da.Save("dyn.dll");
</code>```

ContentLicense: CC BY-SA 2.5

Body:
Is it possible to view the IL code generated when you call Compile() on an Expression tree?  Consider this very simple example:

class Program
{
    public int Value { get; set; }

    static void Main(string[] args)
    {
        var param = Expression.Parameter(typeof(Program));
        var con = Expression.Constant(5);
        var prop = Expression.Property(param, typeof(Program).GetProperty("Value"));
        var assign = Expression.Assign(prop, con);
        Action<Program> lambda = Expression.Lambda<Action<Program>>(assign, param).Compile();

        Program p = new Program();
        lambda(p);

        //p.Value = 5;
    }
}

Now, the expression tree does what the last line of Main says.  Compile the application, then open it in Reflector.  You can see the IL code of p.Value = 5; that does the assignment.  But the expression tree was made and compiled at runtime.  Is it possible to view the resulting IL code from the compile?

Body:
Create a DynamicAssembly, then a DynamicModule, DynamicType and DynamicMethod. Make that method public and static and pass it to the method CompileTo() on the lambda. When you make the assembly flag it as Save. Then call the Save() method and pass a path. It will be written to disk. Pop it open in reflector.

Something like:

var da = AppDomain.CurrentDomain.DefineDynamicAssembly(
    new AssemblyName("dyn"), // call it whatever you want
    AssemblyBuilderAccess.Save);

var dm = da.DefineDynamicModule("dyn_mod", "dyn.dll");
var dt = dm.DefineType("dyn_type");
var method = dt.DefineMethod(
    "Foo",
    MethodAttributes.Public | MethodAttributes.Static);

lambda.CompileToMethod(method);
dt.CreateType();

da.Save("dyn.dll");

ContentLicense: CC BY-SA 3.0


问:
How to create a rectangle inside each grid's column in Extjs?
I have this grid and would like to put all of the values from Box column inside a rectangle using metadata.style , tdCls or CSS. My issue is that I don't want to color the entire column (cell), I only want to color the value inside of it by wrapping it in a rectangle, and if the value of the column is empty then just show an empty rectangle.
Here's an example of what I want for each column (cell) to look like under the Box column:

Here's the working code : FIDDLE

```<code>       switch(recordStatus) {
         case 'Checked-In':
            backgroundColor = "#B4B4D6";
            metadata.style = 'background-color: ' + backgroundColor + ';';
            return val;
            break;
             ...
        }
</code>```

Thank you so much in advance!

答:
This worked for me

```<code>renderer: function (v,meta) {
   meta.tdCls = '***your icon with css***';
     }
</code>```

Body:
I have this grid and would like to put all of the values from Box column inside a rectangle using metadata.style , tdCls or CSS. My issue is that I don't want to color the entire column (cell), I only want to color the value inside of it by wrapping it in a rectangle, and if the value of the column is empty then just show an empty rectangle.
Here's an example of what I want for each column (cell) to look like under the Box column:

Here's the working code : FIDDLE

       switch(recordStatus) {
         case 'Checked-In':
            backgroundColor = "#B4B4D6";
            metadata.style = 'background-color: ' + backgroundColor + ';';
            return val;
            break;
             ...
        }

Thank you so much in advance!

Body:
This worked for me

renderer: function (v,meta) {
   meta.tdCls = '***your icon with css***';
     }


问:
Firebase database with android studio not adding to db correctly
I'm creating this app in android which I have connected to Firebase Auth and Fireabase Database. Below I will post the code. I'm able to auntheticate user and when I try to add to the database it works for each user but only one field.

For example: in my app I have a user and i want to add a child called save location and set the value to the address that is clicked by the user and it works but when i try to save another address it overrides my current address in the database. Its only letting me add one thing... This onclick event is triggered when a user clicks a save button I have on the app.

```<code>public void onClick(DialogInterface dialog,int id)
      {
          FirebaseUser firebaseUser = FirebaseAuth.getInstance().getCurrentUser();
                FirebaseDatabase database = FirebaseDatabase.getInstance();
                DatabaseReference myRef = database.getReference();

       if (firebaseUser != null){
               myRef.child("Users").child(firebaseUser.getUid().toString()).child("Saved Location").setValue(getSelectedItemOfList);

         } else{
             Toast.makeText(getActivity(), "This feature for only registered Users",Toast.LENGTH_LONG).show();
             }

      }
</code>```

答:
Replace your line

```<code>myRef.child("Users").child(firebaseUser.getUid().toString()).child("Saved Location").setValue(getSelectedItemOfList);
</code>```

with this:

```<code>DatabaseReference myRef1 = database.getReference();

myRef1= myRef.child("Users").child(firebaseUser.getUid().toString()).child("Saved Location");

myRef1.push().setValue(getSelectedItemOfList);
</code>```

Body:
I'm creating this app in android which I have connected to Firebase Auth and Fireabase Database. Below I will post the code. I'm able to auntheticate user and when I try to add to the database it works for each user but only one field.

For example: in my app I have a user and i want to add a child called save location and set the value to the address that is clicked by the user and it works but when i try to save another address it overrides my current address in the database. Its only letting me add one thing... This onclick event is triggered when a user clicks a save button I have on the app.

public void onClick(DialogInterface dialog,int id)
      {
          FirebaseUser firebaseUser = FirebaseAuth.getInstance().getCurrentUser();
                FirebaseDatabase database = FirebaseDatabase.getInstance();
                DatabaseReference myRef = database.getReference();

       if (firebaseUser != null){
               myRef.child("Users").child(firebaseUser.getUid().toString()).child("Saved Location").setValue(getSelectedItemOfList);

         } else{
             Toast.makeText(getActivity(), "This feature for only registered Users",Toast.LENGTH_LONG).show();
             }

      }

Body:
Replace your line

myRef.child("Users").child(firebaseUser.getUid().toString()).child("Saved Location").setValue(getSelectedItemOfList);

with this:

DatabaseReference myRef1 = database.getReference();

myRef1= myRef.child("Users").child(firebaseUser.getUid().toString()).child("Saved Location");

myRef1.push().setValue(getSelectedItemOfList);


问:
asp net gridview resets all date fields to null when editing (using SQL Server 2012, c#, VS 2017)
ASP.NET with gridview resets all date fields to null when editing (using SQL Server 2012, c#, VS 2017)

I have looked at the one post regarding this, but the answer does not resolve the problem.

Code Snippet below:

aspx.cs

```<code>protected void Button1_Click(object sender, EventArgs e)
{
    DropDownList DropDownList6 = (DropDownList)GridView1.Rows[GridView1.EditIndex].Cells[2].FindControl("DropDownList6");
    DropDownList DropDownList5 = (DropDownList)GridView1.Rows[GridView1.EditIndex].Cells[3].FindControl("DropDownList5");
    DropDownList DropDownList3 = (DropDownList)GridView1.Rows[GridView1.EditIndex].Cells[4].FindControl("DropDownList3");
    TextBox TextBox4 = (TextBox)GridView1.Rows[GridView1.EditIndex].Cells[5].FindControl("TextBox4");
    TextBox TextBox7 = (TextBox)GridView1.Rows[GridView1.EditIndex].Cells[6].FindControl("TextBox7");
    TextBox TextBox8 = (TextBox)GridView1.Rows[GridView1.EditIndex].Cells[7].FindControl("TextBox8");
    TextBox TextBox9 = (TextBox)GridView1.Rows[GridView1.EditIndex].Cells[8].FindControl("TextBox9");
    TextBox TextBox10 = (TextBox)GridView1.Rows[GridView1.EditIndex].Cells[9].FindControl("TextBox10");
    TextBox TextBox2 = (TextBox)GridView1.Rows[GridView1.EditIndex].Cells[10].FindControl("TextBox2");
    SqlDataMaintenanceTasks.UpdateParameters["Location"].DefaultValue = DropDownList6.SelectedValue;
    SqlDataMaintenanceTasks.UpdateParameters["Phase"].DefaultValue = DropDownList5.SelectedValue;
    SqlDataMaintenanceTasks.UpdateParameters["Periodicity"].DefaultValue = DropDownList3.SelectedValue;
    SqlDataMaintenanceTasks.UpdateParameters["Task"].DefaultValue = TextBox4.Text;
    SqlDataMaintenanceTasks.UpdateParameters["Team"].DefaultValue = txtTeam.SelectedValue;
    SqlDataMaintenanceTasks.UpdateParameters["TimeEstimation"].DefaultValue = TextBox7.Text;
    SqlDataMaintenanceTasks.UpdateParameters["ScheduledDate"].DefaultValue = TextBox8.Text;
    SqlDataMaintenanceTasks.UpdateParameters["DueDate"].DefaultValue = TextBox9.Text;
    SqlDataMaintenanceTasks.UpdateParameters["CompletionDate"].DefaultValue = TextBox10.Text;
    SqlDataMaintenanceTasks.UpdateParameters["Comments"].DefaultValue = TextBox2.Text;
    SqlDataMaintenanceTasks.Update();
}
</code>```

.aspx code:

```<code>                <asp:TemplateField HeaderText="ScheduledDate" SortExpression="ScheduledDate">
                    <EditItemTemplate>
                        <asp:TextBox ID="TextBox8" runat="server" Text='<%# Bind("ScheduledDate") %>' TextMode="Date"></asp:TextBox>
                    </EditItemTemplate>
                    <FooterTemplate>
                        <asp:TextBox ID="txtSchedDate" runat="server" TextMode="Date"></asp:TextBox>
                    </FooterTemplate>
                    <ItemTemplate>
                        <asp:Label ID="Label9" runat="server" Text='<%# Bind("ScheduledDate") %>'></asp:Label>
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="DueDate" SortExpression="DueDate">
                    <EditItemTemplate>
                        <asp:TextBox ID="TextBox9" runat="server" Text='<%# Bind("DueDate") %>' TextMode="Date"></asp:TextBox>
                    </EditItemTemplate>
                    <FooterTemplate>
                        <asp:TextBox ID="txtDueDate" runat="server" TextMode="Date"></asp:TextBox>
                    </FooterTemplate>
                    <ItemTemplate>
                        <asp:Label ID="Label10" runat="server" Text='<%# Bind("DueDate") %>'></asp:Label>
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="CompletionDate" SortExpression="CompletionDate">
                    <EditItemTemplate>
                        <asp:TextBox ID="TextBox10" runat="server" Text='<%# Bind("CompletionDate") %>' TextMode="Date"></asp:TextBox>
                    </EditItemTemplate>
                    <FooterTemplate>
                        <asp:TextBox ID="txtCompDate" runat="server" TextMode="Date"></asp:TextBox>
                    </FooterTemplate>
                    <ItemTemplate>
                        <asp:Label ID="Label11" runat="server" Text='<%# Bind("CompletionDate") %>' TextMode="Date"></asp:Label>
                    </ItemTemplate>
                </asp:TemplateField>
</code>```

答: SOLVED: ASP.NET with gridview resets all date fields to null when editing (using SQL Server 2012, c#, VS 2017). Simply had to change SQL Server date fields to Text. This does mean fiddling with char to date conversion for reports etc. but it is manageable.</p>

Body:
ASP.NET with gridview resets all date fields to null when editing (using SQL Server 2012, c#, VS 2017)

I have looked at the one post regarding this, but the answer does not resolve the problem.

Code Snippet below:

aspx.cs

protected void Button1_Click(object sender, EventArgs e)
{
    DropDownList DropDownList6 = (DropDownList)GridView1.Rows[GridView1.EditIndex].Cells[2].FindControl("DropDownList6");
    DropDownList DropDownList5 = (DropDownList)GridView1.Rows[GridView1.EditIndex].Cells[3].FindControl("DropDownList5");
    DropDownList DropDownList3 = (DropDownList)GridView1.Rows[GridView1.EditIndex].Cells[4].FindControl("DropDownList3");
    TextBox TextBox4 = (TextBox)GridView1.Rows[GridView1.EditIndex].Cells[5].FindControl("TextBox4");
    TextBox TextBox7 = (TextBox)GridView1.Rows[GridView1.EditIndex].Cells[6].FindControl("TextBox7");
    TextBox TextBox8 = (TextBox)GridView1.Rows[GridView1.EditIndex].Cells[7].FindControl("TextBox8");
    TextBox TextBox9 = (TextBox)GridView1.Rows[GridView1.EditIndex].Cells[8].FindControl("TextBox9");
    TextBox TextBox10 = (TextBox)GridView1.Rows[GridView1.EditIndex].Cells[9].FindControl("TextBox10");
    TextBox TextBox2 = (TextBox)GridView1.Rows[GridView1.EditIndex].Cells[10].FindControl("TextBox2");
    SqlDataMaintenanceTasks.UpdateParameters["Location"].DefaultValue = DropDownList6.SelectedValue;
    SqlDataMaintenanceTasks.UpdateParameters["Phase"].DefaultValue = DropDownList5.SelectedValue;
    SqlDataMaintenanceTasks.UpdateParameters["Periodicity"].DefaultValue = DropDownList3.SelectedValue;
    SqlDataMaintenanceTasks.UpdateParameters["Task"].DefaultValue = TextBox4.Text;
    SqlDataMaintenanceTasks.UpdateParameters["Team"].DefaultValue = txtTeam.SelectedValue;
    SqlDataMaintenanceTasks.UpdateParameters["TimeEstimation"].DefaultValue = TextBox7.Text;
    SqlDataMaintenanceTasks.UpdateParameters["ScheduledDate"].DefaultValue = TextBox8.Text;
    SqlDataMaintenanceTasks.UpdateParameters["DueDate"].DefaultValue = TextBox9.Text;
    SqlDataMaintenanceTasks.UpdateParameters["CompletionDate"].DefaultValue = TextBox10.Text;
    SqlDataMaintenanceTasks.UpdateParameters["Comments"].DefaultValue = TextBox2.Text;
    SqlDataMaintenanceTasks.Update();
}

.aspx code:

                <asp:TemplateField HeaderText="ScheduledDate" SortExpression="ScheduledDate">
                    <EditItemTemplate>
                        <asp:TextBox ID="TextBox8" runat="server" Text='<%# Bind("ScheduledDate") %>' TextMode="Date"></asp:TextBox>
                    </EditItemTemplate>
                    <FooterTemplate>
                        <asp:TextBox ID="txtSchedDate" runat="server" TextMode="Date"></asp:TextBox>
                    </FooterTemplate>
                    <ItemTemplate>
                        <asp:Label ID="Label9" runat="server" Text='<%# Bind("ScheduledDate") %>'></asp:Label>
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="DueDate" SortExpression="DueDate">
                    <EditItemTemplate>
                        <asp:TextBox ID="TextBox9" runat="server" Text='<%# Bind("DueDate") %>' TextMode="Date"></asp:TextBox>
                    </EditItemTemplate>
                    <FooterTemplate>
                        <asp:TextBox ID="txtDueDate" runat="server" TextMode="Date"></asp:TextBox>
                    </FooterTemplate>
                    <ItemTemplate>
                        <asp:Label ID="Label10" runat="server" Text='<%# Bind("DueDate") %>'></asp:Label>
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="CompletionDate" SortExpression="CompletionDate">
                    <EditItemTemplate>
                        <asp:TextBox ID="TextBox10" runat="server" Text='<%# Bind("CompletionDate") %>' TextMode="Date"></asp:TextBox>
                    </EditItemTemplate>
                    <FooterTemplate>
                        <asp:TextBox ID="txtCompDate" runat="server" TextMode="Date"></asp:TextBox>
                    </FooterTemplate>
                    <ItemTemplate>
                        <asp:Label ID="Label11" runat="server" Text='<%# Bind("CompletionDate") %>' TextMode="Date"></asp:Label>
                    </ItemTemplate>
                </asp:TemplateField>


问:
.select() javascript function returning error in Angular
Because my previous question was incorrectly marked as a Duplicate here

The top answer for what it was marked as a Duplicate for returns an error when copy pasted into an Angular application.

This is copy pasted exactly from the top answer and the html that was used in the question is also being used exactly copy pasted.

Any insight as to why this is refusing to work would be appreciated because this shouldn't be this much of a hassle to do such a simplistic thing such as copying (but I guess everything in Web always has to be more of a hassle than desktop development :P) I mean because clearly this error isn't happening to the 1000's of people who have likely copy pasted from that answer before so insight would be nice.

答:
Thanks to Artem for his comment which adequately explains why the Javascript found in the other answer doesn't work in TypeScript and how to get it to work in TypeScript.

This is the implementation I used to get it to work in Angular w/ Angular Material.

HTML

```<code><mat-card>
    <mat-form-field>
        <input matInput class="email-input-field" placeholder="Email" value="example@gmail.com">
    </mat-form-field>

    <button mat-raised-button color="primary" class="copy-email-button" style="vertical-align:top;" (click)="copyEmail()">
        Copy
    </button>
</mat-card>
</code>```

Typescript

```<code>copyEmail()
{
    var copyTextareaBtn = document.querySelector('.copy-email-button');

    copyTextareaBtn.addEventListener('click', function(event)
    {
        var copyTextarea = document.querySelector('.email-input-field') as HTMLInputElement;
        copyTextarea.select();
        document.execCommand('copy');
    });
}
</code>```

Body:
Thanks to Artem for his comment which adequately explains why the Javascript found in the other answer doesn't work in TypeScript and how to get it to work in TypeScript.

This is the implementation I used to get it to work in Angular w/ Angular Material.

HTML

<mat-card>
    <mat-form-field>
        <input matInput class="email-input-field" placeholder="Email" value="example@gmail.com">
    </mat-form-field>

    <button mat-raised-button color="primary" class="copy-email-button" style="vertical-align:top;" (click)="copyEmail()">
        Copy
    </button>
</mat-card>

Typescript

copyEmail()
{
    var copyTextareaBtn = document.querySelector('.copy-email-button');

    copyTextareaBtn.addEventListener('click', function(event)
    {
        var copyTextarea = document.querySelector('.email-input-field') as HTMLInputElement;
        copyTextarea.select();
        document.execCommand('copy');
    });
}


问:
What is the keyboard shortcut for method suggestions in Eclipse on Mac OS X?
In Eclipse on Windows can I press myObject.ctrl+space to get a list of all methods for the object. But on Mac OS X this doesn't seem to work. I have tried ctrl+space, cmd+space and alt+space but nothing seems to work.

What is the keyboard shortcut for method suggestions in Eclipse on Mac OS X?

答:
Think its  shift+ctrl+space.

In my installation the equivalent to the auto suggest is unbound, but you can attach a binding in Preferences>General>Keys.  The Command is called 'Content Assist (type: Java Proposals)'.

ContentLicense: CC BY-SA 4.0


问:
Call PCL method in background Xamarin.Forms
im currently working on a xamarin.forms app (only android at the moment). This app should perform some tasks if a bluetooth device is connected (app is not running). The task is to collect some data from sensors and write it do sqlite database.

I managed to catch bluetooth events using broadcastreceivers ...

My question is How should i collect and write those data (GPS) ?

Can i just call them  through some events in PCL ?
Or do i need some services ? Or should i create that funcionality in .android project ?

Im a newbie in xamarin and android so i appreciate any help :)

Thanks

答:
My question is How should i collect and write those data (GPS) ? Can i just call them through some events in PCL ? Or do i need some services ? Or should i create that funcionality in .android project ?

There are several ways to get the sensors data, you could so this in your PCL.

Method 1 :

When you  catch bluetooth events in your BroadcastReceiver, you could get sensors data in the OnReceive method.

Method 2 :

You could use DependencyService to get the device sensors data and then  write it do sqlite database. As the document said :

Xamarin.Forms allows developers to define behavior in platform-specific projects. DependencyService then finds the right platform implementation, allowing shared code to access the native functionality.

About DependencyService usage you could read the document or refer to my answer.

Method 3 :

You could use DeviceMotionPlugin to get these sensors data. When you use this plugin, you can call CrossDeviceMotion.Current from any project or PCL to gain access to APIs.

Update :

You could do implement this function in your PCL. When you use method 2 or method 3, you could get the sensors data in PCL and then you could store these into your sqlite. Still use native Android API to get sensors data in native Android, but you could use these data in PCL.


问:
How to remove some character from string using PHP
I need to remove some character from string search by value using PHP. I am explaining my code below.

Current Data

```<code>$datArr = array(
    array(
        "name" => "Ram",
        "id" => 1,
        "date" => "12/04/2017 05:31:57 AM"
    ),
    array(
        "name" => "Rahim",
        "id" => 5,
        "date" => "12/03/2017 12:31:57 PM"
    ),
    array(
        "name" => "Raj",
        "id" => 4,
        "date" => "12/04/2017 05:31:57 PM"
    )
);
</code>```

Expected Output

```<code>$datArr = array(
    array(
        "name" => "Ram",
        "id" => 1,
        "date" => "12/04/2017 05:31:57"
    ),
    array(
        "name" => "Rahim",
        "id" => 5,
        "date" => "12/03/2017 12:31:57"
    ),
    array(
        "name" => "Raj",
        "id" => 4,
        "date" => "12/04/2017 05:31:57"
    )
);
</code>```

From the above array there is a date field value and I need to remove the AM/PM from all date using PHP.

答:
Just to say my piece, I think you're potentially going to have wrong date times if you're just outright going to remove AM/PM using string functions. If you do that, how will you differentiate 5AM to 5PM? Now you're going to have the wrong data.

If you're taking out the PM in 5, then you'll need to format it to military time (17). To do that, you'll need to convert each time first. You can do that with DateTime:

```<code>$datArr = array_map(function($e){
    $dt = new DateTime($e['date']);
    $e['date'] = $dt->format('m/d/Y H:i:s'); // convert me into correct time

    return $e;
}, $datArr);
</code>```

Sample Output

Body:
I need to remove some character from string search by value using PHP. I am explaining my code below.

Current Data

$datArr = array(
    array(
        "name" => "Ram",
        "id" => 1,
        "date" => "12/04/2017 05:31:57 AM"
    ),
    array(
        "name" => "Rahim",
        "id" => 5,
        "date" => "12/03/2017 12:31:57 PM"
    ),
    array(
        "name" => "Raj",
        "id" => 4,
        "date" => "12/04/2017 05:31:57 PM"
    )
);

Expected Output

$datArr = array(
    array(
        "name" => "Ram",
        "id" => 1,
        "date" => "12/04/2017 05:31:57"
    ),
    array(
        "name" => "Rahim",
        "id" => 5,
        "date" => "12/03/2017 12:31:57"
    ),
    array(
        "name" => "Raj",
        "id" => 4,
        "date" => "12/04/2017 05:31:57"
    )
);

From the above array there is a date field value and I need to remove the AM/PM from all date using PHP.

Body:
Just to say my piece, I think you're potentially going to have wrong date times if you're just outright going to remove AM/PM using string functions. If you do that, how will you differentiate 5AM to 5PM? Now you're going to have the wrong data.

If you're taking out the PM in 5, then you'll need to format it to military time (17). To do that, you'll need to convert each time first. You can do that with DateTime:

$datArr = array_map(function($e){
    $dt = new DateTime($e['date']);
    $e['date'] = $dt->format('m/d/Y H:i:s'); // convert me into correct time

    return $e;
}, $datArr);

Sample Output


问:
EF Code First Model with Properties that Hold Encrypted Data
I've got some encrypted code in a table in the database which I am maintaining. This is circa 2012, so no "Always On" encryption. 3 columns contain encrypted data.

If I reverse engineer an EF domain, the Model which is created for that table contains properties for those columns which have a type byte[]. This is to be expected, as the columns are varbinary. So, it looks like this:

```<code>class Person
{
  public byte[] FirstName { get; set; } // FirstName
}
</code>```

Is there an elegant way to do some kind of EF mapping/configuration such that the FirstName class has a type of string and that it decrypts automagically by the framework? I realize I can just instantiate a Person object using sql, but it would be nice to offload this processing to the framework.

I've seen one of two solutions around where people are basically using a sql query for every property. They decorate the property with an Encrypt attribute and iterate the properties of every property. But with a sql query for every property for every object in a list - that does not exactly scale.

Has anyone "solved" this issue before?

Note: to retrieve the data, you first need to send a sql statement akin to:

```<code>OPEN SYMMETRIC KEY SomeKey DECRYPTION BY CERTIFICATE SomeCertificate
</code>```

Thanks

答:
In this answer I'm going to set out the things you need to do to deal with encrypted columns in EF. So, the columns in question will have a type of VARBINARY(MAX). Lets say you table looks something like this:

```<code>CREATE TABLE dbo.Person
(
    SomeId int NOT NULL,
    CreatedByUserId uniqueidentifier NULL,
    CreatedUtcDate datetimeoffset(7) NULL,
    Rowversion timestamp NULL,
    FirstName varbinary(MAX) NULL,
    LastName varbinary(MAX) NULL
)
</code>```

Step 1 - Create a View which returns the decrypted columns. The view should basically be identical to your table, but for the columns which hold encrypted data, it should return the decrypted data. It would looks something like this:

```<code>CREATE VIEW [dbo].[v_Person]
AS
SELECT [SomeId]
      ,[CreatedByUserId]
      ,[CreatedUtcDate]
      ,[RowVersion]
      ,CONVERT(NVARCHAR(50),DECRYPTBYKEY([FirstName])) [FirstName]
      ,CONVERT(NVARCHAR(50),DECRYPTBYKEY([LastName])) [LastName]
FROM [dbo].[Person]
</code>```

Step 2 - Create your domain model Person class with string as the relevant property type, not byte[] (note the select statement in the View above where we have cast the decrypted columns to NVARCHAR).

```<code>public class Person
{
    public int SomeId { get; set; }
    public string FirstName { get; set; } // string, not binary
    public string LastName { get; set; } // string, not binary
    public Guid CreatedByUserId { get; set; }
    public DateTime CreatedUtcDate { get; set; }
    public int SomeForeignKeyId { get; set; }
}
</code>```

Step 3 - We need to set up a mapping for that Domain class. (The solution I am setting out here is for EF6. I am aware that EF Core does not support separate mapping files yet, so this would need to be done in the OnModelCreating event of you DbContext). Create a mapping class for you domain object which looks like this:

```<code>public class PersonMap : EntityTypeConfiguration<Person>
{
    public PersonConfiguration(string schema)
    {
        ToTable("v_Person", schema); // note we map to the View
        HasKey(x => x.SomeId);

        // ... other properties elided for brevity

        Property(x => x.FirstName)
            .HasColumnName(@"FirstName")
            .HasColumnType("nvarchar")
            .IsOptional()
            .HasMaxLength(50);
        Property(x => x.LastName)
            .HasColumnName(@"LastName")
            .HasColumnType("nvarchar")
            .IsOptional()
            .HasMaxLength(50);

        // Foreign keys
        HasRequired(a => a.LogbookEntry)
            .WithOptional(b => b.Person)
            .WillCascadeOnDelete(false);

        MapToStoredProcedures(p =>
            p.Insert(i => i.HasName("Insert_Person"))
                .Update(u => u.HasName("Update_Person"))
                .Delete(d => d.HasName("Delete_Person")));

    }
}
</code>```

Note how we mapped to the view, v_Person, and not the raw table.

Also note the call to MapToStoredProcedures, which I explain next.

Step 4 - The last step is to create some stored procedures for your Insert, Update and Deletes. When you invoke SaveChanges, these will be invoked by EF and the relevant stored proc will be invoked depending on which EntityState the entity has. I won't set out all 3, but an example of the Update stored proc might look something like:

```<code>SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [dbo].[Update_Person]
    @SomeId INT,
    @CreatedByUserId UNIQUEIDENTIFIER,
    @CreatedUtcDate DATETIME,
    @RowVersion_Original timestamp,
    @FirstName NVARCHAR(50),
    @LastName NVARCHAR(50) = NULL
AS
BEGIN
    SET NOCOUNT ON;

    DECLARE @CertKey NVARCHAR(7) = 'CertKey';

    UPDATE PersonDetail
        SET
            FirstName = ENCRYPTBYKEY(KEY_GUID(@CertKey), @FirstName),
            LastName = ENCRYPTBYKEY(KEY_GUID(@CertKey), @LastName)
    WHERE SomeId = @SomeId

    SELECT SomeId, RowVersion
    FROM PersonDetail
    WHERE SomeId = @SomeId
END
</code>```

Feel free to comment if you have done it a better way.

Cheers

Body:
I've got some encrypted code in a table in the database which I am maintaining. This is circa 2012, so no "Always On" encryption. 3 columns contain encrypted data.

If I reverse engineer an EF domain, the Model which is created for that table contains properties for those columns which have a type byte[]. This is to be expected, as the columns are varbinary. So, it looks like this:

class Person
{
  public byte[] FirstName { get; set; } // FirstName
}

Is there an elegant way to do some kind of EF mapping/configuration such that the FirstName class has a type of string and that it decrypts automagically by the framework? I realize I can just instantiate a Person object using sql, but it would be nice to offload this processing to the framework.

I've seen one of two solutions around where people are basically using a sql query for every property. They decorate the property with an Encrypt attribute and iterate the properties of every property. But with a sql query for every property for every object in a list - that does not exactly scale.

Has anyone "solved" this issue before?

Note: to retrieve the data, you first need to send a sql statement akin to:

OPEN SYMMETRIC KEY SomeKey DECRYPTION BY CERTIFICATE SomeCertificate

Thanks

Body:
In this answer I'm going to set out the things you need to do to deal with encrypted columns in EF. So, the columns in question will have a type of VARBINARY(MAX). Lets say you table looks something like this:

CREATE TABLE dbo.Person
(
    SomeId int NOT NULL,
    CreatedByUserId uniqueidentifier NULL,
    CreatedUtcDate datetimeoffset(7) NULL,
    Rowversion timestamp NULL,
    FirstName varbinary(MAX) NULL,
    LastName varbinary(MAX) NULL
)

Step 1 - Create a View which returns the decrypted columns. The view should basically be identical to your table, but for the columns which hold encrypted data, it should return the decrypted data. It would looks something like this:

CREATE VIEW [dbo].[v_Person]
AS
SELECT [SomeId]
      ,[CreatedByUserId]
      ,[CreatedUtcDate]
      ,[RowVersion]
      ,CONVERT(NVARCHAR(50),DECRYPTBYKEY([FirstName])) [FirstName]
      ,CONVERT(NVARCHAR(50),DECRYPTBYKEY([LastName])) [LastName]
FROM [dbo].[Person]

Step 2 - Create your domain model Person class with string as the relevant property type, not byte[] (note the select statement in the View above where we have cast the decrypted columns to NVARCHAR).

public class Person
{
    public int SomeId { get; set; }
    public string FirstName { get; set; } // string, not binary
    public string LastName { get; set; } // string, not binary
    public Guid CreatedByUserId { get; set; }
    public DateTime CreatedUtcDate { get; set; }
    public int SomeForeignKeyId { get; set; }
}

Step 3 - We need to set up a mapping for that Domain class. (The solution I am setting out here is for EF6. I am aware that EF Core does not support separate mapping files yet, so this would need to be done in the OnModelCreating event of you DbContext). Create a mapping class for you domain object which looks like this:

public class PersonMap : EntityTypeConfiguration<Person>
{
    public PersonConfiguration(string schema)
    {
        ToTable("v_Person", schema); // note we map to the View
        HasKey(x => x.SomeId);

        // ... other properties elided for brevity

        Property(x => x.FirstName)
            .HasColumnName(@"FirstName")
            .HasColumnType("nvarchar")
            .IsOptional()
            .HasMaxLength(50);
        Property(x => x.LastName)
            .HasColumnName(@"LastName")
            .HasColumnType("nvarchar")
            .IsOptional()
            .HasMaxLength(50);

        // Foreign keys
        HasRequired(a => a.LogbookEntry)
            .WithOptional(b => b.Person)
            .WillCascadeOnDelete(false);

        MapToStoredProcedures(p =>
            p.Insert(i => i.HasName("Insert_Person"))
                .Update(u => u.HasName("Update_Person"))
                .Delete(d => d.HasName("Delete_Person")));

    }
}

Note how we mapped to the view, v_Person, and not the raw table.

Also note the call to MapToStoredProcedures, which I explain next.

Step 4 - The last step is to create some stored procedures for your Insert, Update and Deletes. When you invoke SaveChanges, these will be invoked by EF and the relevant stored proc will be invoked depending on which EntityState the entity has. I won't set out all 3, but an example of the Update stored proc might look something like:

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [dbo].[Update_Person]
    @SomeId INT,
    @CreatedByUserId UNIQUEIDENTIFIER,
    @CreatedUtcDate DATETIME,
    @RowVersion_Original timestamp,
    @FirstName NVARCHAR(50),
    @LastName NVARCHAR(50) = NULL
AS
BEGIN
    SET NOCOUNT ON;

    DECLARE @CertKey NVARCHAR(7) = 'CertKey';

    UPDATE PersonDetail
        SET
            FirstName = ENCRYPTBYKEY(KEY_GUID(@CertKey), @FirstName),
            LastName = ENCRYPTBYKEY(KEY_GUID(@CertKey), @LastName)
    WHERE SomeId = @SomeId

    SELECT SomeId, RowVersion
    FROM PersonDetail
    WHERE SomeId = @SomeId
END

Feel free to comment if you have done it a better way.

Cheers


问:
Will an XML sitemap make affect my website's PCI compliance?
I have an ecommerce website that's PCI compliant, and the website does not have an XML sitemap. The previous webmaster stated that he removed the sitemap because it caused the website to fail PCI validation testing. (We use the McAfee SECURE service for automated testing.)  I'd like to restore the sitemap for SEO, but I don't want to jeopardize our compliance.

Assuming that my new sitemap only includes relevant product/information link information, do I have anything to worry about?

答:
t-nez,
I work for a merchant service provider, www.banckardclub.com, as the lead SEO. The XML sitemap will not cause your site to fail PCI compliance. We have an XML sitemap and we submit to google, and other search engines. We pass our compliance test with out a problem.

Have your webmaster look into the problem some more.


答:
If I understand your question correctly, here's one approach using groupByKey, mapValues and reduce to aggregate hours and miles:

```<code>val rdd = sc.parallelize(Seq(
  (13, (49,2643)),
  (13, (56,2553)),
  (13, (60,2539)),
  (14, (40,1500)),
  (14, (50,2500))
))

rdd.groupByKey.mapValues( _.reduce( (a, x) => (a._1 + x._1, a._2 + x._2) ) )
// res1: Array[(Int, (Int, Int))] = Array((13,(165,7735)), (14,(90,4000)))
</code>```

Or as pointed out by commenters, aggregate using reduceByKey directly if you don't need the intermediary result from groupByKey:

```<code>rdd.reduceByKey( (a, x) => (a._1 + x._1, a._2 + x._2) )
</code>```

Title: How to get the sum of two elements from the Spark RDD Iiterable

Body:
I am trying to write a simple program to find the sum of hours-logged and sum of miles-logged by a driver. I have applied groupByKey and the RDD look like this now.

(13,CompactBuffer((49,2643), (56,2553), (60,2539), (55,2553), (45,2762), (53,2699), (46,2519), (60,2719), (56,2760), (51,2731), (57,2671), (47,2604), (58,2510), (51,2649), (56,2559), (59,2604), (47,2613), (49,2585), (58,2749), (50,2756), (57,2596), (54,2517), (48,2554), (47,2576), (58,2528), (60,2765), (54,2689), (51,2739), (51,2698), (47,2739), (51,2546), (54,2647), (60,2504), (48,2536), (51,2602), (47,2651), (53,2545), (48,2665), (55,2670), (60,2524), (48,2612), (60,2712), (60,2583), (47,2773), (57,2589), (51,2512), (57,2607), (57,2576), (53,2604), (59,2702), (51,2687), (10,100)))

Could you suggest me some useful scala functions to get the sum of the 2 elements? Thanks!!

Body:
If I understand your question correctly, here's one approach using groupByKey, mapValues and reduce to aggregate hours and miles:

val rdd = sc.parallelize(Seq(
  (13, (49,2643)),
  (13, (56,2553)),
  (13, (60,2539)),
  (14, (40,1500)),
  (14, (50,2500))
))

rdd.groupByKey.mapValues( _.reduce( (a, x) => (a._1 + x._1, a._2 + x._2) ) )
// res1: Array[(Int, (Int, Int))] = Array((13,(165,7735)), (14,(90,4000)))

Or as pointed out by commenters, aggregate using reduceByKey directly if you don't need the intermediary result from groupByKey:

rdd.reduceByKey( (a, x) => (a._1 + x._1, a._2 + x._2) )


问:
setting up a value for a variable name in thymeleaf
I am new to Thymeleaf and converting my Web page from JSP to Thymeleaf. I have a strut tag like this:

```<code><c:set var="someVariable" value="${someValue}"/>
</code>```

That variable can be used anywhere in JSP. Is there any such alternatives for this in Thymeleaf?

答:
declare with th:with="varName=${'str'}

ref with in src th:src="@{${varName}}"

in more detail:

```

Body:
I am new to Thymeleaf and converting my Web page from JSP to Thymeleaf. I have a strut tag like this:

<c:set var="someVariable" value="${someValue}"/>

That variable can be used anywhere in JSP. Is there any such alternatives for this in Thymeleaf?

Body:
declare with th:with="varName=${'str'}

ref with in src th:src="@{${varName}}"

in more detail:

<head th:with="component =${'/static/component'}, bizJs = ${'/static/js/biz'}">
    <span th:text="${component}"></span>
    <script th:src="@{(${component})}"></script>
    <script th:src="@{${bizJs} + '/static/js'}"></script>
</head>


问:
Pandas groupby indexing
I am a bit confused by an aspect of the groupby in pandas.

```<code>import pandas as pd
df = pd.DataFrame(data=dict(a=[1, 1, 2, 2, 3], b=[1, 1, 1, 2, 3]))
g = df.groupby(by=['a', 'b'])
</code>```

The groups in g are the tuples formed by the values of a and b. As I grouped by the two columns, there are no more columns left.

I would have guessed that the kind of aggregation I can perform are like .size() for getting the group size.

```<code>In [2]: g.groups
Out[2]:
{(1, 1): Int64Index([0, 1], dtype='int64'),
 (2, 1): Int64Index([2], dtype='int64'),
 (2, 2): Int64Index([3], dtype='int64'),
 (3, 3): Int64Index([4], dtype='int64')}
</code>```

What I do not understand is that I can do g['b'].groups.

```<code>In [3]: g.b.groups
Out[3]:
{(1, 1): Int64Index([0, 1], dtype='int64'),
 (2, 1): Int64Index([2], dtype='int64'),
 (2, 2): Int64Index([3], dtype='int64'),
 (3, 3): Int64Index([4], dtype='int64')}
</code>```

What does the key b mean in the groups?

Thanks,
F.

答:
You can see what it means by doing for example:

```<code>>>> g.sum()
Empty DataFrame
Columns: []
Index: []
</code>```

and with the columns selected:

```<code>>>> g.b.sum()
a  b
1  1    2
2  1    1
   2    2
3  3    3
</code>```

The groups are the same but the columns where you apply the computation are different.

Title: Pandas groupby indexing

Body:
I am a bit confused by an aspect of the groupby in pandas.

import pandas as pd
df = pd.DataFrame(data=dict(a=[1, 1, 2, 2, 3], b=[1, 1, 1, 2, 3]))
g = df.groupby(by=['a', 'b'])

The groups in g are the tuples formed by the values of a and b. As I grouped by the two columns, there are no more columns left.

I would have guessed that the kind of aggregation I can perform are like .size() for getting the group size.

In [2]: g.groups
Out[2]:
{(1, 1): Int64Index([0, 1], dtype='int64'),
 (2, 1): Int64Index([2], dtype='int64'),
 (2, 2): Int64Index([3], dtype='int64'),
 (3, 3): Int64Index([4], dtype='int64')}

What I do not understand is that I can do g['b'].groups.

In [3]: g.b.groups
Out[3]:
{(1, 1): Int64Index([0, 1], dtype='int64'),
 (2, 1): Int64Index([2], dtype='int64'),
 (2, 2): Int64Index([3], dtype='int64'),
 (3, 3): Int64Index([4], dtype='int64')}

What does the key b mean in the groups?

Thanks,
F.

Body:
You can see what it means by doing for example:

>>> g.sum()
Empty DataFrame
Columns: []
Index: []

and with the columns selected:

>>> g.b.sum()
a  b
1  1    2
2  1    1
   2    2
3  3    3

The groups are the same but the columns where you apply the computation are different.


问:
no such file to load -- rails (MissingSourceFile)... say what?
I'm having an obnoxious and weird problem while trying to include the ThinkingTank gem into my rails project. When I include gem 'thinkingtank' in my project's Gemfile I get the following error:

```~/.rvm/gems/ree-1.8.7-2010.01/gems/activesupport-2.3.5/lib/active_support/dependencies.rb:156:in `require': no such file to load -- rails (MissingSourceFile)
 from ~/.rvm/gems/ree-1.8.7-2010.01/gems/activesupport-2.3.5/lib/active_support/dependencies.rb:156:in `require'
 from ~/.rvm/gems/ree-1.8.7-2010.01/gems/activesupport-2.3.5/lib/active_support/dependencies.rb:521:in `new_constants_in'
 from ~/.rvm/gems/ree-1.8.7-2010.01/gems/activesupport-2.3.5/lib/active_support/dependencies.rb:156:in `require'
 from ~/.rvm/gems/ree-1.8.7-2010.01/gems/thinkingtank-0.0.5/lib/thinkingtank.rb:1
 from ~/.rvm/gems/ree-1.8.7-2010.01/gems/bundler-1.0.7/lib/bundler/runtime.rb:64:in `require'
 from ~/.rvm/gems/ree-1.8.7-2010.01/gems/bundler-1.0.7/lib/bundler/runtime.rb:64:in `require'
 from ~/.rvm/gems/ree-1.8.7-2010.01/gems/bundler-1.0.7/lib/bundler/runtime.rb:62:in `each'
 from ~/.rvm/gems/ree-1.8.7-2010.01/gems/bundler-1.0.7/lib/bundler/runtime.rb:62:in `require'
 from ~/.rvm/gems/ree-1.8.7-2010.01/gems/bundler-1.0.7/lib/bundler/runtime.rb:51:in `each'
 from ~/.rvm/gems/ree-1.8.7-2010.01/gems/bundler-1.0.7/lib/bundler/runtime.rb:51:in `require'
 from ~/.rvm/gems/ree-1.8.7-2010.01/gems/bundler-1.0.7/lib/bundler.rb:112:in `require'
 from ~/git/myproject/config/boot.rb:121:in `load_environment'
 from ~/.rvm/gems/ree-1.8.7-2010.01/gems/rails-2.3.5/lib/initializer.rb:137:in `process'
 from ~/.rvm/gems/ree-1.8.7-2010.01/gems/rails-2.3.5/lib/initializer.rb:113:in `send'
 from ~/.rvm/gems/ree-1.8.7-2010.01/gems/rails-2.3.5/lib/initializer.rb:113:in `run'
 from ~/git/myproject/config/environment.rb:9
 from ~/.rvm/rubies/ree-1.8.7-2010.01/lib/ruby/1.8/irb/init.rb:254:in `require'
 from ~/.rvm/rubies/ree-1.8.7-2010.01/lib/ruby/1.8/irb/init.rb:254:in `load_modules'
 from ~/.rvm/rubies/ree-1.8.7-2010.01/lib/ruby/1.8/irb/init.rb:252:in `each'
 from ~/.rvm/rubies/ree-1.8.7-2010.01/lib/ruby/1.8/irb/init.rb:252:in `load_modules'
 from ~/.rvm/rubies/ree-1.8.7-2010.01/lib/ruby/1.8/irb/init.rb:21:in `setup'
 from ~/.rvm/rubies/ree-1.8.7-2010.01/lib/ruby/1.8/irb.rb:54:in `start'
 from ~/.rvm/rubies/ree-1.8.7-2010.01/bin/irb:17```

The output from ruby -v is:

```ruby 1.8.7 (2009-12-24 patchlevel 248) [i686-darwin10.6.0], MBARI 0x6770, Ruby Enterprise Edition 2010.01```

And the output from rails -v is:

```Rails 2.3.5```

I've followed the basic guidelines from their documentation and from similar SA questions. But none of issues have the rails gem going missing..

And yes, we are including rails in our Gemfile =)

Thank you in advance.

答: I ended up resolving the the issue by just removing the 'require rails' statement. There were some other gem conflicts that caused problems but I was able to resolve them by making some small changes in the source. Thanks!</p>

Body:
I'm having an obnoxious and weird problem while trying to include the ThinkingTank gem into my rails project. When I include gem 'thinkingtank' in my project's Gemfile I get the following error:

~/.rvm/gems/ree-1.8.7-2010.01/gems/activesupport-2.3.5/lib/active_support/dependencies.rb:156:in `require': no such file to load -- rails (MissingSourceFile)
 from ~/.rvm/gems/ree-1.8.7-2010.01/gems/activesupport-2.3.5/lib/active_support/dependencies.rb:156:in `require'
 from ~/.rvm/gems/ree-1.8.7-2010.01/gems/activesupport-2.3.5/lib/active_support/dependencies.rb:521:in `new_constants_in'
 from ~/.rvm/gems/ree-1.8.7-2010.01/gems/activesupport-2.3.5/lib/active_support/dependencies.rb:156:in `require'
 from ~/.rvm/gems/ree-1.8.7-2010.01/gems/thinkingtank-0.0.5/lib/thinkingtank.rb:1
 from ~/.rvm/gems/ree-1.8.7-2010.01/gems/bundler-1.0.7/lib/bundler/runtime.rb:64:in `require'
 from ~/.rvm/gems/ree-1.8.7-2010.01/gems/bundler-1.0.7/lib/bundler/runtime.rb:64:in `require'
 from ~/.rvm/gems/ree-1.8.7-2010.01/gems/bundler-1.0.7/lib/bundler/runtime.rb:62:in `each'
 from ~/.rvm/gems/ree-1.8.7-2010.01/gems/bundler-1.0.7/lib/bundler/runtime.rb:62:in `require'
 from ~/.rvm/gems/ree-1.8.7-2010.01/gems/bundler-1.0.7/lib/bundler/runtime.rb:51:in `each'
 from ~/.rvm/gems/ree-1.8.7-2010.01/gems/bundler-1.0.7/lib/bundler/runtime.rb:51:in `require'
 from ~/.rvm/gems/ree-1.8.7-2010.01/gems/bundler-1.0.7/lib/bundler.rb:112:in `require'
 from ~/git/myproject/config/boot.rb:121:in `load_environment'
 from ~/.rvm/gems/ree-1.8.7-2010.01/gems/rails-2.3.5/lib/initializer.rb:137:in `process'
 from ~/.rvm/gems/ree-1.8.7-2010.01/gems/rails-2.3.5/lib/initializer.rb:113:in `send'
 from ~/.rvm/gems/ree-1.8.7-2010.01/gems/rails-2.3.5/lib/initializer.rb:113:in `run'
 from ~/git/myproject/config/environment.rb:9
 from ~/.rvm/rubies/ree-1.8.7-2010.01/lib/ruby/1.8/irb/init.rb:254:in `require'
 from ~/.rvm/rubies/ree-1.8.7-2010.01/lib/ruby/1.8/irb/init.rb:254:in `load_modules'
 from ~/.rvm/rubies/ree-1.8.7-2010.01/lib/ruby/1.8/irb/init.rb:252:in `each'
 from ~/.rvm/rubies/ree-1.8.7-2010.01/lib/ruby/1.8/irb/init.rb:252:in `load_modules'
 from ~/.rvm/rubies/ree-1.8.7-2010.01/lib/ruby/1.8/irb/init.rb:21:in `setup'
 from ~/.rvm/rubies/ree-1.8.7-2010.01/lib/ruby/1.8/irb.rb:54:in `start'
 from ~/.rvm/rubies/ree-1.8.7-2010.01/bin/irb:17

The output from ruby -v is:

ruby 1.8.7 (2009-12-24 patchlevel 248) [i686-darwin10.6.0], MBARI 0x6770, Ruby Enterprise Edition 2010.01

And the output from rails -v is:

Rails 2.3.5

I've followed the basic guidelines from their documentation and from similar SA questions. But none of issues have the rails gem going missing..

And yes, we are including rails in our Gemfile =)

Thank you in advance.


问:
Tokenize a String and Keep Delimiters Using Regular Expression in C++
I would like to modify the given regular expression to produce the following list of matches. I am having a hard time describing the problem in words.

I want to use a regular expression to match a set of 'tokens'. Specifically I want &&,||,;,(,) to be matched, and any string that does not contain those characters should be a match.
The problem I am having is distinguishing between one pipe and two pipes. How can i produce the desired matches? Thank you a lot for your help!

Link to this example

The expression:

```<code>((&{2})|(\|{2})|(\()|(\))|(;)|[^&|;()]+)
</code>```

Test String

```<code>a < b | c | d > e >> f && ((g) || h) ; i
</code>```

Expected Matches

```<code>a < b | c | d > e >> f
&&

(
(
g
)

||
 h
)

;
 i
</code>```

Actual Matches

```<code>a < b
|
 c
|
 d > e >> f
&&

(
(
g
)

||
 h
)

;
 i
</code>```

I am trying to implement a custom tokenizer for a program in C++.

Example Code

```<code>std::vector<std::string> Parser::tokenizeInput(std::string s) {
    std::vector<std::string> returnTokens;

    //tokenize correctly using this regex
    std::regex rgx(R"S(((&{2})|(\|{2})|(\()|(\))|(;)|[^&|;()]+))S");

    std::regex_iterator<std::string::iterator> rit ( s.begin(), s.end(), rgx );
    std::regex_iterator<std::string::iterator> rend;

    while (rit!=rend) {

        std::string tokenStr = rit->str();

        if(tokenStr.size() > 0 && tokenStr != " "){
            //assure the token is not blank
            //and push the token
            boost::algorithm::trim(tokenStr);
            returnTokens.push_back(tokenStr);
        }

        ++rit;
    }

    return returnTokens;
}
</code>```

Example Driver Code

```<code>//in main
std::vector<std::string> testVec = Parser::tokenizeInput(inputWithNoComments);
std::cout << "input string: " << inputWithNoComments << std::endl;
std::cout << "tokenized string[";
for(unsigned int i = 0; i < testVec.size(); i++){
    std::cout << testVec[i];
    if ( i + 1 < testVec.size() ) { std::cout << ", "; }
}
std::cout << "]" << std::endl;
</code>```

Produced Output

```<code>input string: (cat file > outFile) || ( ls -l | grep -i )
tokenized string[(, cat file > outFile, ), ||, (, ls -l, grep -i, )]

input string: a && b || c > d >> e < f | g
tokenized string[a, &&, b, ||, c > d >> e < f, g]

input string: foo | bar || foo || bar | foo | bar
tokenized string[foo, bar, ||, foo, ||, bar, foo, bar]
</code>```

What I Want the Output to be

```<code>input string: (cat file > outFile) || ( ls -l | grep -i )
tokenized string[(, cat file > outFile, ), ||, (, ls -l | grep -i, )]

input string: a && b || c > d >> e < f | g
tokenized string[a, &&, b, ||, c > d >> e < f | g]

input string: foo | bar || foo || bar | foo | bar
tokenized string[foo | bar, ||, foo, ||, bar | foo | bar]
</code>```

答:
You haven't specified which language you're using, but most app languages would support splitting a string on this regex:

```<code>" *((?=(\$\$|\|\||[;()])|(?<=\$\$|\|\|)|(?<=[;()])) *"
</code>```

The regex is a look ahead or look behind for your terms, but being look arounds the input is not consumed so the delimiters will be output to the result array.

If you're using python, thing are much simpler; split on this regex:

```<code>" *(\$\$|\|\||[;()]) *"
</code>```

Whatever of the delimiter is captured, becomes part of the output array.

Body:
I would like to modify the given regular expression to produce the following list of matches. I am having a hard time describing the problem in words.

I want to use a regular expression to match a set of 'tokens'. Specifically I want &&,||,;,(,) to be matched, and any string that does not contain those characters should be a match.
The problem I am having is distinguishing between one pipe and two pipes. How can i produce the desired matches? Thank you a lot for your help!

Link to this example

The expression:

((&{2})|(\|{2})|(\()|(\))|(;)|[^&|;()]+)

Test String

a  e >> f && ((g) || h) ; i

Expected Matches

a  e >> f
&&

(
(
g
)

||
 h
)

;
 i

Actual Matches

a  e >> f
&&

(
(
g
)

||
 h
)

;
 i

I am trying to implement a custom tokenizer for a program in C++.

Example Code

std::vector<std::string> Parser::tokenizeInput(std::string s) {
    std::vector<std::string> returnTokens;

    //tokenize correctly using this regex
    std::regex rgx(R"S(((&{2})|(\|{2})|(\()|(\))|(;)|[^&|;()]+))S");

    std::regex_iterator<std::string::iterator> rit ( s.begin(), s.end(), rgx );
    std::regex_iterator<std::string::iterator> rend;

    while (rit!=rend) {

        std::string tokenStr = rit->str();

        if(tokenStr.size() > 0 && tokenStr != " "){
            //assure the token is not blank
            //and push the token
            boost::algorithm::trim(tokenStr);
            returnTokens.push_back(tokenStr);
        }

        ++rit;
    }

    return returnTokens;
}

Example Driver Code

//in main
std::vector<std::string> testVec = Parser::tokenizeInput(inputWithNoComments);
std::cout << "input string: " << inputWithNoComments << std::endl;
std::cout << "tokenized string[";
for(unsigned int i = 0; i < testVec.size(); i++){
    std::cout << testVec[i];
    if ( i + 1 < testVec.size() ) { std::cout << ", "; }
}
std::cout << "]" << std::endl;

Produced Output

input string: (cat file > outFile) || ( ls -l | grep -i )
tokenized string[(, cat file > outFile, ), ||, (, ls -l, grep -i, )]

input string: a && b || c > d >> e < f | g
tokenized string[a, &&, b, ||, c > d >> e < f, g]

input string: foo | bar || foo || bar | foo | bar
tokenized string[foo, bar, ||, foo, ||, bar, foo, bar]

What I Want the Output to be

input string: (cat file > outFile) || ( ls -l | grep -i )
tokenized string[(, cat file > outFile, ), ||, (, ls -l | grep -i, )]

input string: a && b || c > d >> e < f | g
tokenized string[a, &&, b, ||, c > d >> e < f | g]

input string: foo | bar || foo || bar | foo | bar
tokenized string[foo | bar, ||, foo, ||, bar | foo | bar]

Body:
You haven't specified which language you're using, but most app languages would support splitting a string on this regex:

" *((?=(\$\$|\|\||[;()])|(?<=\$\$|\|\|)|(?<=[;()])) *"

The regex is a look ahead or look behind for your terms, but being look arounds the input is not consumed so the delimiters will be output to the result array.

If you're using python, thing are much simpler; split on this regex:

" *(\$\$|\|\||[;()]) *"

Whatever of the delimiter is captured, becomes part of the output array.


问:
How to build a JSON like this using js?
I'm trying to build a JSON like this and send it server via form post. All these json values are from select options in the UI.

```<code> {
   "pages":[
      {
         "id":"messages",
         "name":"yourinbox",
         "value":"ACTIVE"
      },
      {
         "id":"emails",
         "name":"newmail",
         "value":"INACTIVE"
      }
   ]
}
</code>```

I've tried with below code, but i'm not able to get the correct format.
    Any help? Thanks!

```<code>var self = this;
var request = new HttpRequest();
this.form$ = $(selector);
self.form$.find('.loader').hide();

this.onSubmit = function(e){
hideSubmit();
e.preventDefault();
e.stopPropagation();
var parsedata = {};
var data = {};
var selectedOptions = self.form$.find('select');
for (var i = 0, ii = selectedOptions.length; i < ii; ++i) {
var input = selectedOptions[i];
data["name"] = input.id;
data["value"] = input.value;
parsedata.push(data); } };
</code>```

答:
This is the rough approach; Feel free to improvise.

let object = {"pages" : []};

let options = document.getElementsByTagName("option");

for(i=0;i<options.length; i++) {
  object["pages"][i] = {}
  object["pages"][i]["id"] = options[i].getAttribute('id');
  object["pages"][i]["value"] = options[i].getAttribute('value');
  let activeStatus = options[i].getAttribute('selected');
  if(activeStatus == "true") object["pages"][i]["activeStatus"] = activeStatus;
  else object["pages"][i]["activeStatus"] = false;
}

console.log(object)```
<pre class="snippet-code-html lang-html prettyprint-override"><code><select>
<option id="1" value="One" selected=true>One</option>
<option id="2" value="Two">Two</option>
<option id="3" value="Three">Three</option>
<option id="4" value="Four">Four</option>
</select></code>```

Title: How to build a JSON like this using js?

Body:
I'm trying to build a JSON like this and send it server via form post. All these json values are from select options in the UI.

 {
   "pages":[
      {
         "id":"messages",
         "name":"yourinbox",
         "value":"ACTIVE"
      },
      {
         "id":"emails",
         "name":"newmail",
         "value":"INACTIVE"
      }
   ]
}

I've tried with below code, but i'm not able to get the correct format.
    Any help? Thanks!

var self = this;
var request = new HttpRequest();
this.form$ = $(selector);
self.form$.find('.loader').hide();

this.onSubmit = function(e){
hideSubmit();
e.preventDefault();
e.stopPropagation();
var parsedata = {};
var data = {};
var selectedOptions = self.form$.find('select');
for (var i = 0, ii = selectedOptions.length; i < ii; ++i) {
var input = selectedOptions[i];
data["name"] = input.id;
data["value"] = input.value;
parsedata.push(data); } };

Body:
This is the rough approach; Feel free to improvise.

let object = {"pages" : []};

let options = document.getElementsByTagName("option");

for(i=0;i<options.length; i++) {
  object["pages"][i] = {}
  object["pages"][i]["id"] = options[i].getAttribute('id');
  object["pages"][i]["value"] = options[i].getAttribute('value');
  let activeStatus = options[i].getAttribute('selected');
  if(activeStatus == "true") object["pages"][i]["activeStatus"] = activeStatus;
  else object["pages"][i]["activeStatus"] = false;
}

console.log(object)

<select>
<option id="1" value="One" selected=true>One</option>
<option id="2" value="Two">Two</option>
<option id="3" value="Three">Three</option>
<option id="4" value="Four">Four</option>
</select>


问:
Count of records; trying to show related data
I am struggling with a beginners problem in my current application development. I have records containing trainingplans which are related to different syllabi in a another model.

What I try to do, is to show how many trainingplans are active for all the syllabi I have. In my controller i tried it with the following find statement:

$trainingplans = $this->Trainingplans->find('all', array('group' =>'syllabus_id','fields' => array('count(*)','syllabus_id')));

The return looks like:

```<code>Array (
    [0] => Array
        (
            [0] => Array
                (
                    [count(*)] => 5
                )
            [Trainingplans] => Array
                (
                    [syllabus_id] => 1
                )
        )

    [1] => Array
        (
            [0] => Array
                (
                    [count(*)] => 2
                )
            [Trainingplans] => Array
                (
                    [syllabus_id] => 2
                )
        )

    [2] => Array
        (
            [0] => Array
                (
                    [count(*)] => 1
                )
            [Trainingplans] => Array
                (
                    [syllabus_id] => 5
                )
        )
)
</code>```

So this is quite close to what I wanted, but I need syllabus.name with it.

答:
If your tables are correctly joined, add Syllabus.name in the 'fields' param.
If this is not enough, try to raise recursivity before the find</p>

```<code>$this->Trainingplans->recursive = 1
</code>```

Body:
I am struggling with a beginners problem in my current application development. I have records containing trainingplans which are related to different syllabi in a another model.

What I try to do, is to show how many trainingplans are active for all the syllabi I have. In my controller i tried it with the following find statement:

$trainingplans = $this->Trainingplans->find('all', array('group' =>'syllabus_id','fields' => array('count(*)','syllabus_id')));

The return looks like:

Array (
    [0] => Array
        (
            [0] => Array
                (
                    [count(*)] => 5
                )
            [Trainingplans] => Array
                (
                    [syllabus_id] => 1
                )
        )

    [1] => Array
        (
            [0] => Array
                (
                    [count(*)] => 2
                )
            [Trainingplans] => Array
                (
                    [syllabus_id] => 2
                )
        )

    [2] => Array
        (
            [0] => Array
                (
                    [count(*)] => 1
                )
            [Trainingplans] => Array
                (
                    [syllabus_id] => 5
                )
        )
)

So this is quite close to what I wanted, but I need syllabus.name with it.

Body:
If your tables are correctly joined, add Syllabus.name in the 'fields' param.
If this is not enough, try to raise recursivity before the find

$this->Trainingplans->recursive = 1


问:
Make my UIViewController fullscreen in Objective-C
I have an Objective C project which uses XIB files (not storyboards).

I have a UIViewController view that I lunch from my AppDelegate.m file which plays a video.  I want to make it full screen but the title
bar at the top is showing and there is a thin white line down the left hand side of the screen.

How can I make the whole video play full screen.

AppDelegate.m

```<code>- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];

    VideoIntroViewController *videoIntroViewController = [[VideoIntroViewController alloc] initWithNibName:@"VideoIntroViewController" bundle:nil];
    videoIntroViewController.managedObjectContext = self.managedObjectContext;

    self.navigationController = [[UINavigationController alloc] initWithRootViewController:videoIntroViewController];
    self.window.rootViewController = self.navigationController;
    [self.window addSubview:self.navigationController.view];

    [self.window makeKeyAndVisible];

  return YES;
}
</code>```

VideoIntroViewController.m

```<code>- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];

    if (!self.navigationController.toolbarHidden)
    {
        [self.navigationController setToolbarHidden:YES animated:animated];
    }
}

- (void)viewDidLoad
{
    [self createVideoPlayer];

    [super viewDidLoad];
}

- (void)createVideoPlayer
{
    NSString *filePath = [[NSBundle mainBundle] pathForResource:@"welcome_video" ofType:@"mp4"];
    NSURL *url = [NSURL fileURLWithPath:filePath];

    AVPlayerItem *playerItem = [AVPlayerItem playerItemWithURL:url];

    self.player = [AVPlayer playerWithPlayerItem:playerItem];
    self.player.volume = PLAYER_VOLUME;

    AVPlayerLayer *playerLayer = [AVPlayerLayer playerLayerWithPlayer:self.player];
    playerLayer.videoGravity = UIViewContentModeScaleToFill; <-- 'Null passed to a callee that requires a non-null argument'
    playerLayer.frame = self.playerView.layer.bounds;
    [self.playerView.layer addSublayer:playerLayer];

    [self.player play];

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(moviePlayDidEnd:) name:AVPlayerItemDidPlayToEndTimeNotification object:self.player.currentItem];
}
</code>```

答:
Hide navigation bar in AppDelegate itself:</p>

```<code>self.navigationController = [[UINavigationController alloc] initWithRootViewController:videoIntroViewController];
self.navigationController.navigationBar.hidden = YES;
</code>```

Body:
I have an Objective C project which uses XIB files (not storyboards).

I have a UIViewController view that I lunch from my AppDelegate.m file which plays a video.  I want to make it full screen but the title
bar at the top is showing and there is a thin white line down the left hand side of the screen.

How can I make the whole video play full screen.

AppDelegate.m

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];

    VideoIntroViewController *videoIntroViewController = [[VideoIntroViewController alloc] initWithNibName:@"VideoIntroViewController" bundle:nil];
    videoIntroViewController.managedObjectContext = self.managedObjectContext;

    self.navigationController = [[UINavigationController alloc] initWithRootViewController:videoIntroViewController];
    self.window.rootViewController = self.navigationController;
    [self.window addSubview:self.navigationController.view];

    [self.window makeKeyAndVisible];

  return YES;
}

VideoIntroViewController.m

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];

    if (!self.navigationController.toolbarHidden)
    {
        [self.navigationController setToolbarHidden:YES animated:animated];
    }
}

- (void)viewDidLoad
{
    [self createVideoPlayer];

    [super viewDidLoad];
}

- (void)createVideoPlayer
{
    NSString *filePath = [[NSBundle mainBundle] pathForResource:@"welcome_video" ofType:@"mp4"];
    NSURL *url = [NSURL fileURLWithPath:filePath];

    AVPlayerItem *playerItem = [AVPlayerItem playerItemWithURL:url];

    self.player = [AVPlayer playerWithPlayerItem:playerItem];
    self.player.volume = PLAYER_VOLUME;

    AVPlayerLayer *playerLayer = [AVPlayerLayer playerLayerWithPlayer:self.player];
    playerLayer.videoGravity = UIViewContentModeScaleToFill; <-- 'Null passed to a callee that requires a non-null argument'
    playerLayer.frame = self.playerView.layer.bounds;
    [self.playerView.layer addSublayer:playerLayer];

    [self.player play];

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(moviePlayDidEnd:) name:AVPlayerItemDidPlayToEndTimeNotification object:self.player.currentItem];
}

Body:
Hide navigation bar in AppDelegate itself:

self.navigationController = [[UINavigationController alloc] initWithRootViewController:videoIntroViewController];
self.navigationController.navigationBar.hidden = YES;


问:
Multiple file download manager in listview +progress/pause/resume android
i need to make a dynamic download manager for my app in this form :

adding new link to current list

can pause and resume download

deleting complete downloads from custom list

like this

at first i use this site code for thread downloading.

then , i make a custom list view that Every time user click on the Download button,that download link Will be added.

But i have two problem :

after adding new link to list , all of list will be New!

too, previous unfinished download(s) will be new , as list will be new!

Now , The question is:
how i can make a dynamic download manager for my app that , can adding new link to list with pause/resume ability and remove downloaded item from custom list?

Edit - adding Custom-Listview

my custom list-view in this link : https://github.com/saeid-pm/Custom-Listview

答:
use

```<code>dependencies {
compile 'com.mani:ThinDownloadManager:1.4.0'
}
</code>```

but in its github it says the last vesion is 1.3.0 but in fact pause and resume feature is in 1.4.0 version and github readMe is not up to date, pay attention to setDownloadResumable() in the following code

```<code>DownloadRequest downloadRequest = new DownloadRequest(downloadUri)
            .addCustomHeader("Auth-Token", "YourTokenApiKey")
            .setRetryPolicy(new DefaultRetryPolicy())
            .setDownloadResumable(true)
</code>```

and for multipart you should do it in initializing download manager as the following code:

```<code>int availableProcessors = getRuntime().availableProcessors();
downloadManager = new ThinDownloadManager(availableProcessors);
</code>```

Body:
use

dependencies {
compile 'com.mani:ThinDownloadManager:1.4.0'
}

but in its github it says the last vesion is 1.3.0 but in fact pause and resume feature is in 1.4.0 version and github readMe is not up to date, pay attention to setDownloadResumable() in the following code

DownloadRequest downloadRequest = new DownloadRequest(downloadUri)
            .addCustomHeader("Auth-Token", "YourTokenApiKey")
            .setRetryPolicy(new DefaultRetryPolicy())
            .setDownloadResumable(true)

and for multipart you should do it in initializing download manager as the following code:

int availableProcessors = getRuntime().availableProcessors();
downloadManager = new ThinDownloadManager(availableProcessors);


问:
reverse order in R leaflet continuous legend
I am trying to reverse the value display of my leaflet legend in R. This post covers categorical data, but I am working with continuous data. Here's a toy example:

```<code>map <- leaflet() %>% addProviderTiles('Esri.WorldTopoMap')
x <- 1:100
pal <- colorNumeric(c("#d7191c","#fdae61","#ffffbf","#abd9e9", "#2c7bb6"), x)
map %>% addLegend('topright', pal=pal, values=x)
</code>```

I'd like the legend to read 100 at the top and 1 on the bottom with the colors reversed. I can certainly reverse the colors in colorNumeric(), but reversing the order of the labels is harder. I have tried reversing the order of the values in x, and I even fiddled with the labelFormat() parameter for addLegend() to reference a lookup table of reversed values... nothing seems to work. Is there an easy way to do this?

答:
I just found that the built-in labelFormat function has a transform parameter that takes a function. So I passed the sort function in there.
To use the same example,

```<code>map %>% addLegend('topright',
              pal = pal,
              values = x,
              labFormat = labelFormat(transform = function(x) sort(x, decreasing = TRUE)))
</code>```

Body:
I am trying to reverse the value display of my leaflet legend in R. This post covers categorical data, but I am working with continuous data. Here's a toy example:

map <- leaflet() %>% addProviderTiles('Esri.WorldTopoMap')
x <- 1:100
pal <- colorNumeric(c("#d7191c","#fdae61","#ffffbf","#abd9e9", "#2c7bb6"), x)
map %>% addLegend('topright', pal=pal, values=x)

I'd like the legend to read 100 at the top and 1 on the bottom with the colors reversed. I can certainly reverse the colors in colorNumeric(), but reversing the order of the labels is harder. I have tried reversing the order of the values in x, and I even fiddled with the labelFormat() parameter for addLegend() to reference a lookup table of reversed values... nothing seems to work. Is there an easy way to do this?

Body:
I just found that the built-in labelFormat function has a transform parameter that takes a function. So I passed the sort function in there.
To use the same example,

map %>% addLegend('topright',
              pal = pal,
              values = x,
              labFormat = labelFormat(transform = function(x) sort(x, decreasing = TRUE)))


问:
Sort Primefaces DataTable column with two Columns names in sortBy attribute
I would like to sort a dataTable which has column named "CustomerName" which needs to be sorted based on Customer's FirstName & LastName.
So i'd like to pass value to sortBy attribute as shown below
sortBy="CustomerTable.FirstName,CustomerTable.LastName"

When i try this i get a parser error stating that String

I am able to sort a column with one table name & column name as input like shown below
sortBy="CustomerTable.CustomerNumber"

答:
sortBy="CONCAT(CustomerTable.FirstName,' ',CustomerTable.LastName)"
This will sort the column in alphabetical order after concatenating the FirstName and LastName columns of CustomerTable</p>


问:
Is there a "null coalescing" operator in JavaScript?
Is there a null coalescing operator in Javascript?

For example, in C#, I can do this:

```<code>String someString = null;
var whatIWant = someString ?? "Cookies!";
</code>```

The best approximation I can figure out for Javascript is using the conditional operator:

```<code>var someString = null;
var whatIWant = someString ? someString : 'Cookies!';
</code>```

Which is sorta icky IMHO. Can I do better?

答:
If || as a replacement of C#'s ?? isn't good enough in your case, because it swallows empty strings and zeros, you can always write your own function:

```<code> function $N(value, ifnull) {
    if (value === null || value === undefined)
      return ifnull;
    return value;
 }

 var whatIWant = $N(someString, 'Cookies!');
</code>```

OwnerDisplayName: Daniel Schaffer

Body:
Is there a null coalescing operator in Javascript?

For example, in C#, I can do this:

String someString = null;
var whatIWant = someString ?? "Cookies!";

The best approximation I can figure out for Javascript is using the conditional operator:

var someString = null;
var whatIWant = someString ? someString : 'Cookies!';

Which is sorta icky IMHO. Can I do better?

LastEditorDisplayName: Daniel Schaffer

Body:
If || as a replacement of C#'s ?? isn't good enough in your case, because it swallows empty strings and zeros, you can always write your own function:

 function $N(value, ifnull) {
    if (value === null || value === undefined)
      return ifnull;
    return value;
 }

 var whatIWant = $N(someString, 'Cookies!');

OwnerDisplayName: sth


问:
Error _Execution failed for task ':app:mergeDebugResources'
I am new to Android Programming.Recently I have been trying to work on adding a toolbar and tab bar to my existing Recycle view.However, after adding the elements, the Android Studio is suddenly complaining about the problem.

Error.Execution failed for task':app:mergeDebugResources'
AND

Error:java.util.concurrent.ExecutionException: com.android.tools.aapt2.Aapt2Exception: AAPT2 error: check logs for details

This error

After google search for a little bit, I have found most of the solution ,which is to disable the APPT2 in the gradle.properties.However, the solution didn't solve my problem.In fact, it is causing more problem.

After disabling AAPT2

My AndroidMenifest file

Recycler view

Build.grade(Module App)

Build.gradle(Top build level)

答:
You should add Toolbar END TAG. i.e />

```<code> <android.support.v7.widget.Toolbar
    .........
     android:layout_marginTop="14dp"

  />
</code>```

Then Clean-Rebuild-Run.

Body:
You should add Toolbar END TAG. i.e />

 <android.support.v7.widget.Toolbar
    .........
     android:layout_marginTop="14dp"

  />

Then Clean-Rebuild-Run.


答: Check your layout file .xml on line ending with 5 you are missing ending tag /> for toolbar.

Title: Error _Execution failed for task ':app:mergeDebugResources'

Body:
I am new to Android Programming.Recently I have been trying to work on adding a toolbar and tab bar to my existing Recycle view.However, after adding the elements, the Android Studio is suddenly complaining about the problem.

Error.Execution failed for task':app:mergeDebugResources'
AND

Error:java.util.concurrent.ExecutionException: com.android.tools.aapt2.Aapt2Exception: AAPT2 error: check logs for details

This error

After google search for a little bit, I have found most of the solution ,which is to disable the APPT2 in the gradle.properties.However, the solution didn't solve my problem.In fact, it is causing more problem.

After disabling AAPT2

My AndroidMenifest file

Recycler view

Build.grade(Module App)

Build.gradle(Top build level)


问:
How to remove the device's frame on Android Studio's emulators
I am making an android app on Android Studio and I have this emulator for Nexus S.
When the emulator is running, it shows the frame of the device.
I want the emulator to show the screen of the device only.
I've tried looking in the settings but can't help it. Thanks.</p>

答:
Step 1: Open AVD Manager

Step 2: Click Edit in the specific Device emulator

Step 3: Disable device frame option

Step 4: Click Ok and restart the emulator


问:
echo $(command) gets a different result with the output of the command
The Bash command I used:

$ ssh user@myserver.com ps -aux|grep -v \"grep\"|grep "/srv/adih/server/app.js"|awk '{print $2}'

```<code>6373
</code>```

$ ssh user@myserver.com echo $(ps -aux|grep -v \"grep\"|grep "/srv/adih/server/app.js"|awk '{print $2}')

```<code>8630
</code>```

The first result is the correct one and the second one will change echo time I execute it. But I don't know why they are different.

What am I doing?

My workstation has very limited resources, so I use a remote machine to run my Node.js application. I run it using ssh user@remotebox.com "cd /application && grunt serve" in debug mode. When I command Ctrl + C, the grunt task is stopped, but the application is is still running in debug mode. I just want to kill it, and I need to get the PID first.

答:
The command substitution is executed by your local shell before ssh runs.

If your local system's name is here and the remote is there,

```<code>ssh there uname -n
</code>```

will print there whereas

```<code>ssh there echo $(uname -n)  # should have proper quoting, too
</code>```

will run uname -n locally and then send the expanded command line echo here to there to be executed.

As an additional aside, echo $(command) is a useless use of echo unless you specifically require the shell to perform wildcard expansion and whitespace tokenization on the output of command before printing it.

Also, grep x | awk { y } is a useless use of grep; it can and probably should be refactored to awk '/x/ { y }' -- but of course, here you are reinventing pidof so better just use that.

```<code> ssh user@myserver.com pidof /srv/adih/server/app.js
</code>```

If you want to capture the printed PID locally, the syntax for that is

```<code>pid=$(ssh user@myserver.com pidof /srv/adih/server/app.js)
</code>```

Of course, if you only need to kill it, that's

```<code>ssh user@myserver.com pkill /srv/adih/server/app.js
</code>```

Body:
The Bash command I used:

$ ssh user@myserver.com ps -aux|grep -v \"grep\"|grep "/srv/adih/server/app.js"|awk '{print $2}'

6373

$ ssh user@myserver.com echo $(ps -aux|grep -v \"grep\"|grep "/srv/adih/server/app.js"|awk '{print $2}')

8630

The first result is the correct one and the second one will change echo time I execute it. But I don't know why they are different.

What am I doing?

My workstation has very limited resources, so I use a remote machine to run my Node.js application. I run it using ssh user@remotebox.com "cd /application && grunt serve" in debug mode. When I command Ctrl + C, the grunt task is stopped, but the application is is still running in debug mode. I just want to kill it, and I need to get the PID first.

Body:
The command substitution is executed by your local shell before ssh runs.

If your local system's name is here and the remote is there,

ssh there uname -n

will print there whereas

ssh there echo $(uname -n)  # should have proper quoting, too

will run uname -n locally and then send the expanded command line echo here to there to be executed.

As an additional aside, echo $(command) is a useless use of echo unless you specifically require the shell to perform wildcard expansion and whitespace tokenization on the output of command before printing it.

Also, grep x | awk { y } is a useless use of grep; it can and probably should be refactored to awk '/x/ { y }' -- but of course, here you are reinventing pidof so better just use that.

 ssh user@myserver.com pidof /srv/adih/server/app.js

If you want to capture the printed PID locally, the syntax for that is

pid=$(ssh user@myserver.com pidof /srv/adih/server/app.js)

Of course, if you only need to kill it, that's

ssh user@myserver.com pkill /srv/adih/server/app.js


问:
lm75 kernel module available in userspace
I'm using the lm75 kernel module to interact with a sensor on a custom board. Every things works fine, I have my device mounted in /sys/bus/i2c/devices/5-0048. But I would like to let the user set the max temp hysteresis so in other words let the user write into the temp_max_hyst file. The permission for this file is read only except for root

My question is, is there any way to mount my device in /dev?

答:
Mounting isn't the right term here so you won't find anything searching for that.  Block devices with file systems are mounted on directories, which then become mount points.

Here the device 5-0048 is bound to the driver lm75.  You'd find the device is there, assuming it appears in the device tree or board info, whether or not the lm75 driver exists.  If and when the lm75 driver binds to the device, it creates a new device of class hwmon.  It is that device which has attributes, like temp_max_hyst, that you are interested in.

What you see in /dev are known as device nodes.  While many devices, once bound to a driver, will have a device node created to interact with the device, this doesn't have to happen.  There are probably a bunch of devices that appear in /sys/class/regulator or /sys/class/net that have no nodes in /dev associated with them.

Drivers of type hwmon, like lm75, don't normally create any device nodes to provide a char device or block device userspace interface to the hardware.  So there is nothing to appear in dev for this device.  The attributes of the hwmon device are all you get.

But your problem has a simple solution.  As root, just chmod a+w temp_max_hyst or chown user_account temp_max_hyst or (this is probably best) chmod g+w temp_max_hyst ; chgrp hw_access_group temp_max_hyst and add the user to a group hw_access_group.  You could use an existing group, there might be one named wheel or adm that would be used for something like this, or make a new one just for hwmon access.

Of course this won't persist across a reboot, as sysfs is not a real file system on disk.  To make the change persistent, the best way is to create a udev rule that automatically effects the chmod/chown when it detects the hwmon device.  It's the hwmon device you care about here, not the i2c device.  Try running udevadm info -a /sys/class/hwmon/hwmon0.


问:
535-5.7.8 Username and Password not accepted
I have a contact form and after submitting I am getting a Net::SMTPAuthenticationError 535-5.7.8 Username and Password not accepted

It's pointing to the create action in the contacts controller ContactMailer.new_contact(@contact).deliver

I have restarted the server. I tried https://accounts.google.com/DisplayUnlockCaptcha.

I am in development.

Contacts controller:

```<code> def new
      @contact = Contact.new
    end

    def create
      @contact = Contact.new(params[:message])
      if @contact.valid?
        ContactMailer.new_contact(@contact).deliver
        flash[:notice] = "Message sent! Thank you for contacting us."
        redirect_to root_url
      else
        render :action => 'new'
      end
    end
  end
</code>```

Development.rb:

```<code>  config.action_mailer.raise_delivery_errors = true
  config.action_mailer.perform_deliveries = true
  config.action_mailer.delivery_method = :smtp
  config.action_mailer.smtp_settings = {
    address:              'smtp.gmail.com',
    port:                 587,
    domain:               'gmail.com',
    user_name:            'username@gmail.com',
    password:             'password',
    authentication:       'plain',
    enable_starttls_auto: true  }

  config.action_mailer.default_url_options = { :host => "localhost:3000" }
</code>```

答:
If you still cannot solve the problem after you turn on the less secure apps.
The other possible reason which might cause this error is you are not using gmail account.

```<code>-    : user_name  =>  'example@company.com' ,  # It can not be used since it is not a gmail address
+    : user_name  =>  'example@gmail.com' ,  # since it's a gmail address
</code>```

Refer to here.

Also, bear in mind that it might take some times to enable the less secure apps. I have to do it several times (before it works, every time I access the link it will shows that it is off) and wait for a while until it really work.

Body:
I have a contact form and after submitting I am getting a Net::SMTPAuthenticationError 535-5.7.8 Username and Password not accepted

It's pointing to the create action in the contacts controller ContactMailer.new_contact(@contact).deliver

I have restarted the server. I tried https://accounts.google.com/DisplayUnlockCaptcha.

I am in development.

Contacts controller:

 def new
      @contact = Contact.new
    end

    def create
      @contact = Contact.new(params[:message])
      if @contact.valid?
        ContactMailer.new_contact(@contact).deliver
        flash[:notice] = "Message sent! Thank you for contacting us."
        redirect_to root_url
      else
        render :action => 'new'
      end
    end
  end

Development.rb:

  config.action_mailer.raise_delivery_errors = true
  config.action_mailer.perform_deliveries = true
  config.action_mailer.delivery_method = :smtp
  config.action_mailer.smtp_settings = {
    address:              'smtp.gmail.com',
    port:                 587,
    domain:               'gmail.com',
    user_name:            'username@gmail.com',
    password:             'password',
    authentication:       'plain',
    enable_starttls_auto: true  }

  config.action_mailer.default_url_options = { :host => "localhost:3000" }

Body:
If you still cannot solve the problem after you turn on the less secure apps.
The other possible reason which might cause this error is you are not using gmail account.

-    : user_name  =>  'example@company.com' ,  # It can not be used since it is not a gmail address
+    : user_name  =>  'example@gmail.com' ,  # since it's a gmail address

Refer to here.

Also, bear in mind that it might take some times to enable the less secure apps. I have to do it several times (before it works, every time I access the link it will shows that it is off) and wait for a while until it really work.


问:
Pass a value of the factory to the associated one
In the FactoryBot GETTING STARTED page there is the following snippet which explains how to create an association.

```<code>factory :post do
  # ...
  association :author, factory: :user, last_name: "Writely"
end
</code>```

In my case, I need to pass a value of the factory to the associated one.

```<code>factory :post do
  category: ['a','b','c'].sample
  association :author, factory: :user, expertise: ??CATEGORY??
end
</code>```

I have tried several things (mainly putting curly braces) but nothing seems to work: Trait not registered: category.

Is there a way to pass the category selected for the post to its author?

Thanks

答:
You could use an after(:build) callback:

```<code>factory :post do
  category ['a','b','c'].sample
  association :author, factory: :user

  after(:build) do |post|
    post.author.expertise = post.category
  end
end
</code>```

Body:
In the FactoryBot GETTING STARTED page there is the following snippet which explains how to create an association.

factory :post do
  # ...
  association :author, factory: :user, last_name: "Writely"
end

In my case, I need to pass a value of the factory to the associated one.

factory :post do
  category: ['a','b','c'].sample
  association :author, factory: :user, expertise: ??CATEGORY??
end

I have tried several things (mainly putting curly braces) but nothing seems to work: Trait not registered: category.

Is there a way to pass the category selected for the post to its author?

Thanks

Body:
You could use an after(:build) callback:

factory :post do
  category ['a','b','c'].sample
  association :author, factory: :user

  after(:build) do |post|
    post.author.expertise = post.category
  end
end


问:
Swift delegate not calling function in parent

I am trying to get a child view controller, which is displayed in a view container at the bottom part of the main, parent View Controller. When I press the button in the child, "Button pressed from Basic VC" prints to the console, but "Warm button pressed from main VC" does not. I need the function that prints that second message to be called in the main View Controller. Here is the relevant BasicViewController code:

```<code>protocol BasicVCDelegate: class {
    func warmButton()
}

class BasicViewController: UIViewController {
    weak var BasicVCDelegate: BasicVCDelegate?

    @IBOutlet weak var warmButton: UIButton!

    @IBAction func warmButton(sender: AnyObject) {
        print("Button pressed from Basic VC")
        BasicVCDelegate?.warmButton()
    }
}
</code>```

And from ViewController.swift

```<code>class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate, BasicVCDelegate {
    override func viewDidLoad() {
        pauseButton.isEnabled = false

        hideAll();
        self.basicContainer.isUserInteractionEnabled = true;
        self.basicContainer.isHidden = false;

        self.timerLabel.text = String("00:00:00");

        eventTable.dataSource = self
        eventTable.delegate = self

        loadEvents(event: "timer start")
        super.viewDidLoad()
    }

    // CREATE SEGUEs
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if let nav = segue.destination as? UINavigationController, let classBasicVC = nav.topViewController as? BasicViewController {
            classBasicVC.BasicVCDelegate = self
        }
    }

    // FUNCTIONS FOR BASIC VIEW CONTROLLER TO REFERENCE
    func warmButton() {
        print("Warm button pressed from main VC")
    }
}
</code>```

EDIT:
From everyone below, it seems that the following section of code in ViewController is causing the issue (the line within the if statement is never being called):

```<code>override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if let nav = segue.destination as? UINavigationController, let classBasicVC = nav.topViewController as? BasicViewController {
        classBasicVC.basicVCDelegate = self
    }
}
</code>```

This is probably due to my unfamiliarity with delegates and the prepareforsegue function. Need help figuring out what should follow that "if let"

EDIT 2:
Replaced the above code with the following as per some users' suggestion (still not reaching the print statement):

```<code>override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if let nav = segue.destination as? BasicViewController, let classBasicVC = nav.basicVCDelegate {
        print("got here!!")
    }
}
</code>```

FINAL EDIT:
Thank you for your help! After some playing around, the following works (aside from a warning that changes to an error when I address it - I can live with a warning).

```<code>override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if let nav = segue.destination as? BasicViewController, let classBasicVC = nav as? BasicViewController? {
        classBasicVC?.basicVCDelegate = self
    }
}
</code>```

答:
You haven't assigned button's delegate to the ViewController

Add this to your ViewController's viewDidLoad

```<code>    override func viewDidLoad() {
    //other code
    yourButton.BasicVCDelegate = self
    }
</code>```

Also its a good practice to use camel case for delegate variable like this basicVCDDelegate

Body:
I am trying to get a child view controller, which is displayed in a view container at the bottom part of the main, parent View Controller. When I press the button in the child, "Button pressed from Basic VC" prints to the console, but "Warm button pressed from main VC" does not. I need the function that prints that second message to be called in the main View Controller. Here is the relevant BasicViewController code:

protocol BasicVCDelegate: class {
    func warmButton()
}

class BasicViewController: UIViewController {
    weak var BasicVCDelegate: BasicVCDelegate?

    @IBOutlet weak var warmButton: UIButton!

    @IBAction func warmButton(sender: AnyObject) {
        print("Button pressed from Basic VC")
        BasicVCDelegate?.warmButton()
    }
}

And from ViewController.swift

class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate, BasicVCDelegate {
    override func viewDidLoad() {
        pauseButton.isEnabled = false

        hideAll();
        self.basicContainer.isUserInteractionEnabled = true;
        self.basicContainer.isHidden = false;

        self.timerLabel.text = String("00:00:00");

        eventTable.dataSource = self
        eventTable.delegate = self

        loadEvents(event: "timer start")
        super.viewDidLoad()
    }

    // CREATE SEGUEs
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if let nav = segue.destination as? UINavigationController, let classBasicVC = nav.topViewController as? BasicViewController {
            classBasicVC.BasicVCDelegate = self
        }
    }

    // FUNCTIONS FOR BASIC VIEW CONTROLLER TO REFERENCE
    func warmButton() {
        print("Warm button pressed from main VC")
    }
}

EDIT:
From everyone below, it seems that the following section of code in ViewController is causing the issue (the line within the if statement is never being called):

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if let nav = segue.destination as? UINavigationController, let classBasicVC = nav.topViewController as? BasicViewController {
        classBasicVC.basicVCDelegate = self
    }
}

This is probably due to my unfamiliarity with delegates and the prepareforsegue function. Need help figuring out what should follow that "if let"

EDIT 2:
Replaced the above code with the following as per some users' suggestion (still not reaching the print statement):

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if let nav = segue.destination as? BasicViewController, let classBasicVC = nav.basicVCDelegate {
        print("got here!!")
    }
}

FINAL EDIT:
Thank you for your help! After some playing around, the following works (aside from a warning that changes to an error when I address it - I can live with a warning).

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if let nav = segue.destination as? BasicViewController, let classBasicVC = nav as? BasicViewController? {
        classBasicVC?.basicVCDelegate = self
    }
}

Body:
You haven't assigned button's delegate to the ViewController

Add this to your ViewController's viewDidLoad

    override func viewDidLoad() {
    //other code
    yourButton.BasicVCDelegate = self
    }

Also its a good practice to use camel case for delegate variable like this basicVCDDelegate