问:
Inconsitent TypeScript behavior with union and object type
Let's have a following snippet:

```<code>interface A {
  isEmpty(x: any[] | string | object): boolean;
  isEmptyObject(x: object): boolean;
}

const a: A = <A>{};

a.isEmptyObject({});
a.isEmptyObject({a: 1});

a.isEmpty([]);
a.isEmpty('');
a.isEmpty({});
a.isEmpty({a: 1});
</code>```

When I try to compile it, it crashes with this:

```<code>a.ts(14,12): error TS2345: Argument of type '{ a: number; }' is not assignable to parameter of type 'string | object | any[]'.
  Object literal may only specify known properties, and 'a' does not exist in type 'string | object | any[]'.
</code>```

How is this possible, when the union type (string | object | any[]) contains type object for which it works (the isEmptyObject call with {a: 1} is fine)?

Main question: Is this a TypeScript bug, or how one should write that input may be an array of any value or string or object (but not any primitive, I don't want any or Object)?

Tested with TypeScript 2.3.4.

答:
You can easily go around this problem by adding another signature:

```<code>interface A {
    isEmpty(x: any[]): boolean;
    isEmpty(x: string | object): boolean;
    isEmptyObject(x: object): boolean;
}

a.isEmpty({ a: 1 }); // fine now
</code>```

(code in playground)

Edit

I don't think that it's a bug, if anything is a bug it's the error message which isn't very helpful.

What I think that happens is that you can use object in a union with any primitive types without a problem (in your case), but once you introduce a non-primitive type then you'll get the error, for example:

```<code>isEmpty(x: string | object | Map<string, string>): boolean;
</code>```

Will result in the same error.

The union of object (which is anything that isn't primitive) and another non-primitive type probably results in a type that cannot be matched and the compiler gets confused.

You are welcome to open a new issue on this case, if you do please share the link here, I'd like to see what they say.

Body:
Let's have a following snippet:

interface A {
  isEmpty(x: any[] | string | object): boolean;
  isEmptyObject(x: object): boolean;
}

const a: A = {};

a.isEmptyObject({});
a.isEmptyObject({a: 1});

a.isEmpty([]);
a.isEmpty('');
a.isEmpty({});
a.isEmpty({a: 1});

When I try to compile it, it crashes with this:

a.ts(14,12): error TS2345: Argument of type '{ a: number; }' is not assignable to parameter of type 'string | object | any[]'.
  Object literal may only specify known properties, and 'a' does not exist in type 'string | object | any[]'.

How is this possible, when the union type (string | object | any[]) contains type object for which it works (the isEmptyObject call with {a: 1} is fine)?

Main question: Is this a TypeScript bug, or how one should write that input may be an array of any value or string or object (but not any primitive, I don't want any or Object)?

Tested with TypeScript 2.3.4.

Body:
You can easily go around this problem by adding another signature:

interface A {
    isEmpty(x: any[]): boolean;
    isEmpty(x: string | object): boolean;
    isEmptyObject(x: object): boolean;
}

a.isEmpty({ a: 1 }); // fine now

(<a href="https://www.typescriptlang.org/play/#src=interface%20A%20%7B%0D%0A%20%20%20%20isEmpty(x%3A%20any%5B%5D)%3A%20boolean%3B%0D%0A%20%20%20%20isEmpty(x%3A%20string%20%7C%20object)%3A%20boolean%3B%0D%0A%20%20%20%20isEmptyObject(x%3A%20object)%3A%20boolean%3B%0D%0A%7D%0D%0A%0D%0Aconst%20a%3A%20A%20%3D%20%3CA%3E%7B%7D%3B%0D%0A%0D%0Aa.isEmptyObject(%7B%7D)%3B%0D%0Aa.isEmptyObject(%7Ba%3A%201%7D)%3B%0D%0A%0D%0Aa.isEmpty(%5B%5D)%3B%0D%0Aa.isEmpty('')%3B%0D%0Aa.isEmpty(%7B%7D)%3B%0D%0Aa.isEmpty(%7Ba%3A%201%7D)%3B" rel="nofollow noreferrer">code in playground)

Edit

I don't think that it's a bug, if anything is a bug it's the error message which isn't very helpful.

What I think that happens is that you can use object in a union with any primitive types without a problem (in your case), but once you introduce a non-primitive type then you'll get the error, for example:

isEmpty(x: string | object | Map<string, string>): boolean;

Will result in the same error.

The union of object (which is anything that isn't primitive) and another non-primitive type probably results in a type that cannot be matched and the compiler gets confused.

You are welcome to open a new issue on this case, if you do please share the link here, I'd like to see what they say.


来源: stackexchange

问:
Error While Installing Vagrant Plugins in Manjaro Deepin
I am using vagrant version 1.9.4

When trying to install any vagrant plugin one of the two outputs comes out

I run This command:

```<code>vagrant plugin install vagrant-hostmanager
</code>```

Then This comes out at a time:

```<code>Installing the 'vagrant-managed-servers' plugin. This can take a few minutes...
/opt/vagrant/embedded/lib/ruby/2.2.0/rubygems/source.rb:192:in `load': Marshal.load reentered at marshal_load (RuntimeError)
    from /opt/vagrant/embedded/lib/ruby/2.2.0/rubygems/source.rb:192:in `load_specs'
    from /opt/vagrant/embedded/gems/gems/vagrant-1.9.4/lib/vagrant/bundler.rb:335:in `block in validate_configured_sources!'
    from /opt/vagrant/embedded/lib/ruby/2.2.0/rubygems/source_list.rb:97:in `each'
    from /opt/vagrant/embedded/lib/ruby/2.2.0/rubygems/source_list.rb:97:in `each_source'
    from /opt/vagrant/embedded/gems/gems/vagrant-1.9.4/lib/vagrant/bundler.rb:333:in `validate_configured_sources!'
    from /opt/vagrant/embedded/gems/gems/vagrant-1.9.4/lib/vagrant/bundler.rb:268:in `internal_install'
    from /opt/vagrant/embedded/gems/gems/vagrant-1.9.4/lib/vagrant/bundler.rb:106:in `install'
    from /opt/vagrant/embedded/gems/gems/vagrant-1.9.4/lib/vagrant/plugin/manager.rb:62:in `block in install_plugin'
    from /opt/vagrant/embedded/gems/gems/vagrant-1.9.4/lib/vagrant/plugin/manager.rb:72:in `call'
    from /opt/vagrant/embedded/gems/gems/vagrant-1.9.4/lib/vagrant/plugin/manager.rb:72:in `install_plugin'
    from /opt/vagrant/embedded/gems/gems/vagrant-1.9.4/plugins/commands/plugin/action/install_gem.rb:29:in `call'
    from /opt/vagrant/embedded/gems/gems/vagrant-1.9.4/lib/vagrant/action/warden.rb:34:in `call'
    from /opt/vagrant/embedded/gems/gems/vagrant-1.9.4/lib/vagrant/action/builder.rb:116:in `call'
    from /opt/vagrant/embedded/gems/gems/vagrant-1.9.4/lib/vagrant/action/runner.rb:66:in `block in run'
    from /opt/vagrant/embedded/gems/gems/vagrant-1.9.4/lib/vagrant/util/busy.rb:19:in `busy'
    from /opt/vagrant/embedded/gems/gems/vagrant-1.9.4/lib/vagrant/action/runner.rb:66:in `run'
    from /opt/vagrant/embedded/gems/gems/vagrant-1.9.4/plugins/commands/plugin/command/base.rb:14:in `action'
    from /opt/vagrant/embedded/gems/gems/vagrant-1.9.4/plugins/commands/plugin/command/install.rb:32:in `block in execute'
    from /opt/vagrant/embedded/gems/gems/vagrant-1.9.4/plugins/commands/plugin/command/install.rb:31:in `each'
    from /opt/vagrant/embedded/gems/gems/vagrant-1.9.4/plugins/commands/plugin/command/install.rb:31:in `execute'
    from /opt/vagrant/embedded/gems/gems/vagrant-1.9.4/plugins/commands/plugin/command/root.rb:66:in `execute'
    from /opt/vagrant/embedded/gems/gems/vagrant-1.9.4/lib/vagrant/cli.rb:42:in `execute'
    from /opt/vagrant/embedded/gems/gems/vagrant-1.9.4/lib/vagrant/environment.rb:308:in `cli'
    from /opt/vagrant/embedded/gems/gems/vagrant-1.9.4/bin/vagrant:127:in `<main>'
</code>```

And in another time this what comes out:

```<code>/opt/vagrant/embedded/lib/ruby/2.2.0/rubygems/source.rb:192: [BUG]

Segmentation fault at 0x00000000000010
ruby 2.2.5p319 (2016-04-26 revision 54774) [x86_64-linux]

-- Control frame information -----------------------------------------------
c:0026 p:---- s:0148 e:000147 CFUNC  :load
c:0025 p:0163 s:0144 e:000142 METHOD /opt/vagrant/embedded/lib/ruby/2.2.0/rubygems/source.rb:192
c:0024 p:0012 s:0131 e:000130 BLOCK  /opt/vagrant/embedded/gems/gems/vagrant-1.9.4/lib/vagrant/bundler.rb:335 [FINISH]
c:0023 p:---- s:0127 e:000126 CFUNC  :each
c:0022 p:0011 s:0124 e:000123 METHOD /opt/vagrant/embedded/lib/ruby/2.2.0/rubygems/source_list.rb:97
c:0021 p:0015 s:0120 E:001b60 METHOD /opt/vagrant/embedded/gems/gems/vagrant-1.9.4/lib/vagrant/bundler.rb:333
c:0020 p:0168 s:0117 e:000116 METHOD /opt/vagrant/embedded/gems/gems/vagrant-1.9.4/lib/vagrant/bundler.rb:268
c:0019 p:0016 s:0102 e:000101 METHOD /opt/vagrant/embedded/gems/gems/vagrant-1.9.4/lib/vagrant/bundler.rb:106
c:0018 p:0021 s:0097 e:000096 LAMBDA /opt/vagrant/embedded/gems/gems/vagrant-1.9.4/lib/vagrant/plugin/manager.rb:62 [FINISH]
c:0017 p:---- s:0095 e:000094 CFUNC  :call
c:0016 p:0160 s:0092 E:001c70 METHOD /opt/vagrant/embedded/gems/gems/vagrant-1.9.4/lib/vagrant/plugin/manager.rb:72
c:0015 p:0134 s:0081 e:000080 METHOD /opt/vagrant/embedded/gems/gems/vagrant-1.9.4/plugins/commands/plugin/action/install_gem.rb:29
c:0014 p:0081 s:0069 e:000068 METHOD /opt/vagrant/embedded/gems/gems/vagrant-1.9.4/lib/vagrant/action/warden.rb:34
c:0013 p:0013 s:0063 e:000062 METHOD /opt/vagrant/embedded/gems/gems/vagrant-1.9.4/lib/vagrant/action/builder.rb:116
c:0012 p:0010 s:0059 e:000058 BLOCK  /opt/vagrant/embedded/gems/gems/vagrant-1.9.4/lib/vagrant/action/runner.rb:66
c:0011 p:0014 s:0057 e:000056 METHOD /opt/vagrant/embedded/gems/gems/vagrant-1.9.4/lib/vagrant/util/busy.rb:19
c:0010 p:0292 s:0053 E:000598 METHOD /opt/vagrant/embedded/gems/gems/vagrant-1.9.4/lib/vagrant/action/runner.rb:66
c:0009 p:0018 s:0043 e:000042 METHOD /opt/vagrant/embedded/gems/gems/vagrant-1.9.4/plugins/commands/plugin/command/base.rb:14
c:0008 p:0042 s:0038 e:000037 BLOCK  /opt/vagrant/embedded/gems/gems/vagrant-1.9.4/plugins/commands/plugin/command/install.rb:32 [FINISH]
c:0007 p:---- s:0035 e:000034 CFUNC  :each
c:0006 p:0086 s:0032 E:0021d8 METHOD /opt/vagrant/embedded/gems/gems/vagrant-1.9.4/plugins/commands/plugin/command/install.rb:31
c:0005 p:0111 s:0026 e:000025 METHOD /opt/vagrant/embedded/gems/gems/vagrant-1.9.4/plugins/commands/plugin/command/root.rb:66
c:0004 p:0158 s:0022 e:000021 METHOD /opt/vagrant/embedded/gems/gems/vagrant-1.9.4/lib/vagrant/cli.rb:42
c:0003 p:0020 s:0016 e:000015 METHOD /opt/vagrant/embedded/gems/gems/vagrant-1.9.4/lib/vagrant/environment.rb:308
c:0002 p:0680 s:0012 E:0005a0 EVAL   /opt/vagrant/embedded/gems/gems/vagrant-1.9.4/bin/vagrant:127 [FINISH]
c:0001 p:0000 s:0002 E:000ad0 TOP    [FINISH]
</code>```

I Installed vagrant using the normal "yaourt command"
and tried to remove completely and reinstall again
by "pacman" but, still having the same issue.

and of course I have removed the ".vagrant.d" folder in the removing process.

Kernel Version: 4.9.30-1-MANJARO

Manjaro Version: 17.0.1

Ruby Version: ruby 2.4.1p111 (2017-03-22 revision 58053)

If there is no way to fix this now . Is there anyway to download the plugins from github and manually install them into vagrant ?

Please help me cause I can't install any vagrant plugin.
Thanks

答:
I solved the same problem and found out the solution on serverfault.

You have to downgrade package vagrant-substrate. I used AUR package downgrader which offers me all vagrant-substrate packages in archive. I choosed version 599.d7cedfe-2 (according to the link) and now it works like charm. :]

ContentLicense: CC BY-SA 3.0

Body:
I am using vagrant version 1.9.4

When trying to install any vagrant plugin one of the two outputs comes out

I run This command:

vagrant plugin install vagrant-hostmanager

Then This comes out at a time:

Installing the 'vagrant-managed-servers' plugin. This can take a few minutes...
/opt/vagrant/embedded/lib/ruby/2.2.0/rubygems/source.rb:192:in `load': Marshal.load reentered at marshal_load (RuntimeError)
    from /opt/vagrant/embedded/lib/ruby/2.2.0/rubygems/source.rb:192:in `load_specs'
    from /opt/vagrant/embedded/gems/gems/vagrant-1.9.4/lib/vagrant/bundler.rb:335:in `block in validate_configured_sources!'
    from /opt/vagrant/embedded/lib/ruby/2.2.0/rubygems/source_list.rb:97:in `each'
    from /opt/vagrant/embedded/lib/ruby/2.2.0/rubygems/source_list.rb:97:in `each_source'
    from /opt/vagrant/embedded/gems/gems/vagrant-1.9.4/lib/vagrant/bundler.rb:333:in `validate_configured_sources!'
    from /opt/vagrant/embedded/gems/gems/vagrant-1.9.4/lib/vagrant/bundler.rb:268:in `internal_install'
    from /opt/vagrant/embedded/gems/gems/vagrant-1.9.4/lib/vagrant/bundler.rb:106:in `install'
    from /opt/vagrant/embedded/gems/gems/vagrant-1.9.4/lib/vagrant/plugin/manager.rb:62:in `block in install_plugin'
    from /opt/vagrant/embedded/gems/gems/vagrant-1.9.4/lib/vagrant/plugin/manager.rb:72:in `call'
    from /opt/vagrant/embedded/gems/gems/vagrant-1.9.4/lib/vagrant/plugin/manager.rb:72:in `install_plugin'
    from /opt/vagrant/embedded/gems/gems/vagrant-1.9.4/plugins/commands/plugin/action/install_gem.rb:29:in `call'
    from /opt/vagrant/embedded/gems/gems/vagrant-1.9.4/lib/vagrant/action/warden.rb:34:in `call'
    from /opt/vagrant/embedded/gems/gems/vagrant-1.9.4/lib/vagrant/action/builder.rb:116:in `call'
    from /opt/vagrant/embedded/gems/gems/vagrant-1.9.4/lib/vagrant/action/runner.rb:66:in `block in run'
    from /opt/vagrant/embedded/gems/gems/vagrant-1.9.4/lib/vagrant/util/busy.rb:19:in `busy'
    from /opt/vagrant/embedded/gems/gems/vagrant-1.9.4/lib/vagrant/action/runner.rb:66:in `run'
    from /opt/vagrant/embedded/gems/gems/vagrant-1.9.4/plugins/commands/plugin/command/base.rb:14:in `action'
    from /opt/vagrant/embedded/gems/gems/vagrant-1.9.4/plugins/commands/plugin/command/install.rb:32:in `block in execute'
    from /opt/vagrant/embedded/gems/gems/vagrant-1.9.4/plugins/commands/plugin/command/install.rb:31:in `each'
    from /opt/vagrant/embedded/gems/gems/vagrant-1.9.4/plugins/commands/plugin/command/install.rb:31:in `execute'
    from /opt/vagrant/embedded/gems/gems/vagrant-1.9.4/plugins/commands/plugin/command/root.rb:66:in `execute'
    from /opt/vagrant/embedded/gems/gems/vagrant-1.9.4/lib/vagrant/cli.rb:42:in `execute'
    from /opt/vagrant/embedded/gems/gems/vagrant-1.9.4/lib/vagrant/environment.rb:308:in `cli'
    from /opt/vagrant/embedded/gems/gems/vagrant-1.9.4/bin/vagrant:127:in `'

And in another time this what comes out:

/opt/vagrant/embedded/lib/ruby/2.2.0/rubygems/source.rb:192: [BUG]

Segmentation fault at 0x00000000000010
ruby 2.2.5p319 (2016-04-26 revision 54774) [x86_64-linux]

-- Control frame information -----------------------------------------------
c:0026 p:---- s:0148 e:000147 CFUNC  :load
c:0025 p:0163 s:0144 e:000142 METHOD /opt/vagrant/embedded/lib/ruby/2.2.0/rubygems/source.rb:192
c:0024 p:0012 s:0131 e:000130 BLOCK  /opt/vagrant/embedded/gems/gems/vagrant-1.9.4/lib/vagrant/bundler.rb:335 [FINISH]
c:0023 p:---- s:0127 e:000126 CFUNC  :each
c:0022 p:0011 s:0124 e:000123 METHOD /opt/vagrant/embedded/lib/ruby/2.2.0/rubygems/source_list.rb:97
c:0021 p:0015 s:0120 E:001b60 METHOD /opt/vagrant/embedded/gems/gems/vagrant-1.9.4/lib/vagrant/bundler.rb:333
c:0020 p:0168 s:0117 e:000116 METHOD /opt/vagrant/embedded/gems/gems/vagrant-1.9.4/lib/vagrant/bundler.rb:268
c:0019 p:0016 s:0102 e:000101 METHOD /opt/vagrant/embedded/gems/gems/vagrant-1.9.4/lib/vagrant/bundler.rb:106
c:0018 p:0021 s:0097 e:000096 LAMBDA /opt/vagrant/embedded/gems/gems/vagrant-1.9.4/lib/vagrant/plugin/manager.rb:62 [FINISH]
c:0017 p:---- s:0095 e:000094 CFUNC  :call
c:0016 p:0160 s:0092 E:001c70 METHOD /opt/vagrant/embedded/gems/gems/vagrant-1.9.4/lib/vagrant/plugin/manager.rb:72
c:0015 p:0134 s:0081 e:000080 METHOD /opt/vagrant/embedded/gems/gems/vagrant-1.9.4/plugins/commands/plugin/action/install_gem.rb:29
c:0014 p:0081 s:0069 e:000068 METHOD /opt/vagrant/embedded/gems/gems/vagrant-1.9.4/lib/vagrant/action/warden.rb:34
c:0013 p:0013 s:0063 e:000062 METHOD /opt/vagrant/embedded/gems/gems/vagrant-1.9.4/lib/vagrant/action/builder.rb:116
c:0012 p:0010 s:0059 e:000058 BLOCK  /opt/vagrant/embedded/gems/gems/vagrant-1.9.4/lib/vagrant/action/runner.rb:66
c:0011 p:0014 s:0057 e:000056 METHOD /opt/vagrant/embedded/gems/gems/vagrant-1.9.4/lib/vagrant/util/busy.rb:19
c:0010 p:0292 s:0053 E:000598 METHOD /opt/vagrant/embedded/gems/gems/vagrant-1.9.4/lib/vagrant/action/runner.rb:66
c:0009 p:0018 s:0043 e:000042 METHOD /opt/vagrant/embedded/gems/gems/vagrant-1.9.4/plugins/commands/plugin/command/base.rb:14
c:0008 p:0042 s:0038 e:000037 BLOCK  /opt/vagrant/embedded/gems/gems/vagrant-1.9.4/plugins/commands/plugin/command/install.rb:32 [FINISH]
c:0007 p:---- s:0035 e:000034 CFUNC  :each
c:0006 p:0086 s:0032 E:0021d8 METHOD /opt/vagrant/embedded/gems/gems/vagrant-1.9.4/plugins/commands/plugin/command/install.rb:31
c:0005 p:0111 s:0026 e:000025 METHOD /opt/vagrant/embedded/gems/gems/vagrant-1.9.4/plugins/commands/plugin/command/root.rb:66
c:0004 p:0158 s:0022 e:000021 METHOD /opt/vagrant/embedded/gems/gems/vagrant-1.9.4/lib/vagrant/cli.rb:42
c:0003 p:0020 s:0016 e:000015 METHOD /opt/vagrant/embedded/gems/gems/vagrant-1.9.4/lib/vagrant/environment.rb:308
c:0002 p:0680 s:0012 E:0005a0 EVAL   /opt/vagrant/embedded/gems/gems/vagrant-1.9.4/bin/vagrant:127 [FINISH]
c:0001 p:0000 s:0002 E:000ad0 TOP    [FINISH]

I Installed vagrant using the normal "yaourt command"
and tried to remove completely and reinstall again
by "pacman" but, still having the same issue.

and of course I have removed the ".vagrant.d" folder in the removing process.

Kernel Version: 4.9.30-1-MANJARO

Manjaro Version: 17.0.1

Ruby Version: ruby 2.4.1p111 (2017-03-22 revision 58053)

If there is no way to fix this now . Is there anyway to download the plugins from github and manually install them into vagrant ?

Please help me cause I can't install any vagrant plugin.
Thanks


问:
Android open new activity when click link from textview(autolink)
I have a view display textview and enable autolink.

```<code><TextView
   android:id="@+id/txt_contents"
   android:layout_width="match_parent"
   android:layout_height="match_parent"
   android:layout_margin="30dp"
   android:textColor="@color/txt_code_itemlist"
   android:autoLink="web"
   android:textSize="22sp" />
</code>```

Now, when I click link from textview it's will open browser. But I want to find way to open new activity when I click same link.

答:
Use the below code to identify which part of text is clicked

```<code>tv.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
    ClassroomLog.log(TAG, "Textview Click listener ");
    if (tv.getSelectionStart() == -1 && tv.getSelectionEnd() == -1) {
        //This condition will satisfy only when it is not an autolinked text
        //Fired only when you touch the part of the text that is not hyperlinked
    }
}
</code>```

});

and write code to do whatever you want with either case

Body:
I have a view display textview and enable autolink.

<TextView
   android:id="@+id/txt_contents"
   android:layout_width="match_parent"
   android:layout_height="match_parent"
   android:layout_margin="30dp"
   android:textColor="@color/txt_code_itemlist"
   android:autoLink="web"
   android:textSize="22sp" />

Now, when I click link from textview it's will open browser. But I want to find way to open new activity when I click same link.

Body:
Use the below code to identify which part of text is clicked

tv.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
    ClassroomLog.log(TAG, "Textview Click listener ");
    if (tv.getSelectionStart() == -1 && tv.getSelectionEnd() == -1) {
        //This condition will satisfy only when it is not an autolinked text
        //Fired only when you touch the part of the text that is not hyperlinked
    }
}

});

and write code to do whatever you want with either case


问:
MVC 5 Datatable error
I am currently working on a datatable in MVC 5 but when I try to load the content in the datatable I am getting an error.

HomeController

```<code>using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Mvc;
using CMS.Models;
using System.Linq.Dynamic;
using CMS.Models.DatabaseModels;

namespace CMS.Controllers.Home
 {
public class HomeController : Controller
{
    private CMSEntities db = new CMSEntities();

    public ActionResult Index()
    {
        return View();
    }

    public ActionResult loaddata()
    {
        using (CMSEntities dc = new CMSEntities())
        {
            var data = dc.ContentItems.OrderBy(a => a.Name).ToList();
            return Json(new { data = data }, JsonRequestBehavior.AllowGet);
        }
    }

}
}
</code>```

Index.cshtml

```<code>    ViewBag.Title = "Index";
      }

<div style="width:90%; margin:0 auto;">
    <table id="myTable">
        <thead>
            <tr>
                <th>Name</th>
                <th>Title</th>
                <th>Create Date</th>
                <th>Update Date</th>
                <th>Item Content</th>
                <th>Visual Order</th>
                <th></th>
                <th></th>
            </tr>
        </thead>
    </table>
</div>
<style>
    tr.even {
        background-color: #F5F5F5 !important;
    }
</style>
@* Load datatable css *@
<link href="//cdn.datatables.net/1.10.9/css/jquery.dataTables.min.css" rel="stylesheet" />
@* Load datatable js *@
@section Scripts{
    <script src="//cdn.datatables.net/1.10.9/js/jquery.dataTables.min.js"></script>
    <script>
        $(document).ready(function () {
            $('#myTable').DataTable({
                "ajax": {
                    "url": "/home/loaddata",
                    "type": "GET",
                    "datatype": "json"
                },
                "columns" : [
                        { "data": "Name", "autoWidth": true },
                        { "data": "Title", "autoWidth": true },
                        { "data": "CreateDate", "autoWidth": true },
                        { "data": "UpdateDate", "autoWidth": true },
                        { "data": "ItemContent", "autoWidth": true },
                        { "data": "VisualOrder", "autoWidth": true }
                    ]
            });
        });
    </script>
}
</code>```

The error I am getting is: DataTables warning: table id=myTable - Ajax error. For more information about this error, please see http://datatables.net/tn/7.

I went to the website and they said it needed to check the error message.
The code gave me the 404 error message which means that there is a typo in the file name in the ajax option parameter and in your file on the server.

I can't seem to find the error.

Maybe I'm missing something but I don't know what.

答:
pass your data like this </p>

```<code>public ActionResult loaddata()
    {
        using (CMSEntities dc = new CMSEntities())
        {
            var data = dc.ContentItems.select(m=>new{
Name : m.Name,
Title : m.Title,
CreateDate : m.CreateDate,
UpdateDate : m.UpdateDate,
ItemContent : m.ItemContent,
VisualOrder : m.VisualOrder
}).toList()
            return Json(new { data = data }, JsonRequestBehavior.AllowGet);
        }
    }
</code>```

Title: MVC 5 Datatable error

Body:
I am currently working on a datatable in MVC 5 but when I try to load the content in the datatable I am getting an error.

HomeController

using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Mvc;
using CMS.Models;
using System.Linq.Dynamic;
using CMS.Models.DatabaseModels;

namespace CMS.Controllers.Home
 {
public class HomeController : Controller
{
    private CMSEntities db = new CMSEntities();

    public ActionResult Index()
    {
        return View();
    }

    public ActionResult loaddata()
    {
        using (CMSEntities dc = new CMSEntities())
        {
            var data = dc.ContentItems.OrderBy(a => a.Name).ToList();
            return Json(new { data = data }, JsonRequestBehavior.AllowGet);
        }
    }

}
}

Index.cshtml

    ViewBag.Title = "Index";
      }

                Name
                Title
                Create Date
                Update Date
                Item Content
                Visual Order

@* Load datatable css *@
<link href="//cdn.datatables.net/1.10.9/css/jquery.dataTables.min.css" rel="stylesheet" />
@* Load datatable js *@
@section Scripts{

}

The error I am getting is: DataTables warning: table id=myTable - Ajax error. For more information about this error, please see http://datatables.net/tn/7.

I went to the website and they said it needed to check the error message.
The code gave me the 404 error message which means that there is a typo in the file name in the ajax option parameter and in your file on the server.

I can't seem to find the error.

Maybe I'm missing something but I don't know what.

Body:
pass your data like this

public ActionResult loaddata()
    {
        using (CMSEntities dc = new CMSEntities())
        {
            var data = dc.ContentItems.select(m=>new{
Name : m.Name,
Title : m.Title,
CreateDate : m.CreateDate,
UpdateDate : m.UpdateDate,
ItemContent : m.ItemContent,
VisualOrder : m.VisualOrder
}).toList()
            return Json(new { data = data }, JsonRequestBehavior.AllowGet);
        }
    }


问:
Redirect output to a file AND console
Currently I have a script where I want all output to be redirected to both a file and the console.

```<code>#!/bin/bash
touch /mnt/ybdata/ybvwconf.log
{
  ... [Do some script code here]
} 2>&1 | tee -a /mnt/ybdata/ybvwconf.log
</code>```

Above, you can see my current code, which works perfectly fine. It prints all the output to the console as well as piping it to the ybvwconf.log file. However, I was looking for a way to eliminate the curly brackets. Something along the lines of this:

```<code>#!/bin/bash
touch /mnt/ybdata/ybvwconf.log
exec 2>&1 | tee -a /mnt/ybdata/ybvwconf.log

... [Do some script code here]
</code>```

I have tried this approach and sadly it does not work. I don't get any errors but no content appears in my log file. Any ideas what might be wrong?

答:
You can place this at top of your script to redirect both stdout and stderr to a file and show them on terminal as well.</p>

```<code>#!/bin/bash
exec &> >(tee /mnt/ybdata/ybvwconf.log; exit)

# your script code goes here
</code>```

Title: Redirect output to a file AND console

Body:
Currently I have a script where I want all output to be redirected to both a file and the console.

#!/bin/bash
touch /mnt/ybdata/ybvwconf.log
{
  ... [Do some script code here]
} 2>&1 | tee -a /mnt/ybdata/ybvwconf.log

Above, you can see my current code, which works perfectly fine. It prints all the output to the console as well as piping it to the ybvwconf.log file. However, I was looking for a way to eliminate the curly brackets. Something along the lines of this:

#!/bin/bash
touch /mnt/ybdata/ybvwconf.log
exec 2>&1 | tee -a /mnt/ybdata/ybvwconf.log

... [Do some script code here]

I have tried this approach and sadly it does not work. I don't get any errors but no content appears in my log file. Any ideas what might be wrong?

Body:
You can place this at top of your script to redirect both stdout and stderr to a file and show them on terminal as well.

#!/bin/bash
exec &> >(tee /mnt/ybdata/ybvwconf.log; exit)

# your script code goes here


问:
Giving border to
 of table in a table
How do i give a border to the
(t_border).
The inner table shouldnt inherit the style from the outer one

```<code><table>

    <tr>
        <td>A</td>
    </tr>

    <tr>
        <td>
           <table class="t_border">
              <tr>
                 <td>B</td>
              </tr>
        </td>
    </tr>
</tbody>
</code>```

答:
just give style of tr tag

```<code>   <tr>
         <td style="border : 1px solid black">B</td>
      </tr>
</code>```

Title: Giving border to <tr> of table in a table

Body:
How do i give a border to the
(t_border).
The inner table shouldnt inherit the style from the outer one

        A

                 B

Body:
just give style of tr tag

   <tr>
         <td style="border : 1px solid black">B</td>
      </tr>


问:
Fastest method of collection searching by DateTime
I have a Dictionary containing 10 keys, each with a list containing up to 30,000 values. The values contain a DateTime property.

I frequently need to extract a small subset of one of the keys, like a date range of 30 - 60 seconds.

Doing this is easy, but getting it to run fast is not so. What would be the most efficient way to query this in-memory data?

Thanks a lot.

答:
1) Keep the dictionary, but use SortedList instead of a list for value of dictionaries, sorted by DateTime property

2) Implement a binary search to find the upper and lower edges in your range in the sorted list which gives you indexes.

3) Just select values in the range using Sortedlist.Values.Skip(lowerIndex).Take(upperIndex - lowerIndex)

ContentLicense: CC BY-SA 2.5


答:
If you need to style your border, you may use other answers.

But if you only need to use the pure HTML table style, you can use this :

 to give border on your table inside table.

Body:
If you need to style your border, you may use other answers.

But if you only need to use the pure HTML table style, you can use this :

<table border=1> to give border on your table inside table.


问:
log10 of a Vector3f (Eigen Libs)
I need to calculate the log10 of a Vector3f.
I have tried:

```<code>Eigen::Vector3f valsingn = svd.singularValues()/svd.singularValues()(0);
valsingn = valsingn.log10();
</code>```

But it doesn't work.

```<code>main.cpp:145:27: error: ‘Eigen::Vector3f {aka class Eigen::Matrix<float, 3, 1>}’ has no member named ‘log10’; did you mean ‘log’?
     valsingn = valsingn.log10();
</code>```

Is there a way to calculate the log10 with this vector?

Thank you!

答:
The simple way that would allow Eigen to still utilize SIMD (I assume it's enabled) would be to do a simple change of bases:

```<code>valsingn = valsingn.array().log() / log(10.0);
</code>```

Alternatively, you can pass log10 as a unary expression:

```<code> valsingn.unaryExpr(&log10); // You may have to wrap
                             // log10 in a function of
                             // your own depending on
                             // the log10 overloads
</code>```

Title: log10 of a Vector3f (Eigen Libs)

Body:
I need to calculate the log10 of a Vector3f.
I have tried:

Eigen::Vector3f valsingn = svd.singularValues()/svd.singularValues()(0);
valsingn = valsingn.log10();

But it doesn't work.

main.cpp:145:27: error: ‘Eigen::Vector3f {aka class Eigen::Matrix<float, 3, 1>}’ has no member named ‘log10’; did you mean ‘log’?
     valsingn = valsingn.log10();

Is there a way to calculate the log10 with this vector?

Thank you!

Body:
The simple way that would allow Eigen to still utilize SIMD (I assume it's enabled) would be to do a simple change of bases:

valsingn = valsingn.array().log() / log(10.0);

Alternatively, you can pass log10 as a unary expression:

 valsingn.unaryExpr(&log10); // You may have to wrap
                             // log10 in a function of
                             // your own depending on
                             // the log10 overloads


问:
Javafx : TableCell focus lost
I have  TableView and I want to do something when the cell loses the focus.
I have cell selection enabled on this TableView and it doesn't listens to cell focus lost. I tried this way:

```<code>table.getFocusModel().focusedCellProperty().addListener((observable, oldValue, newValue) -> {
        if (newValue != null) {
            //doSomething
        }
        // else doSomethingElse doesn't work
});
</code>```

Simply it doesn't listen when I deselect (Ctrl + click) the cell. What did I wrong or how can I listen to focus lost on a TableCell?

答:
I'm using this:

```<code>TABLEVIEW.focusedProperty().addListener(new ChangeListener<Boolean>() {
    @Override
    public void changed(ObservableValue<? extends Boolean> arg0, Boolean oldPropertyValue, Boolean newPropertyValue) {
        if (newPropertyValue) {
            System.out.println("on focus");
        } else {
            System.out.println("out focus");
        }
     }
});
</code>```

It works only if you select another selectable element (doesn't work e.g clicking on a pane).

Title: Javafx : TableCell focus lost

Body:
I have  TableView and I want to do something when the cell loses the focus.
I have cell selection enabled on this TableView and it doesn't listens to cell focus lost. I tried this way:

table.getFocusModel().focusedCellProperty().addListener((observable, oldValue, newValue) -> {
        if (newValue != null) {
            //doSomething
        }
        // else doSomethingElse doesn't work
});

Simply it doesn't listen when I deselect (Ctrl + click) the cell. What did I wrong or how can I listen to focus lost on a TableCell?

Body:
I'm using this:

TABLEVIEW.focusedProperty().addListener(new ChangeListener<Boolean>() {
    @Override
    public void changed(ObservableValue<? extends Boolean> arg0, Boolean oldPropertyValue, Boolean newPropertyValue) {
        if (newPropertyValue) {
            System.out.println("on focus");
        } else {
            System.out.println("out focus");
        }
     }
});

It works only if you select another selectable element (doesn't work e.g clicking on a pane).


问:
Where to find the warning of `Warnings found during shrinking`?
After adding RxAndroid and Retrofit library to my gradle, and compile, I got the below error, shows in my Android Studio Message panel.

```<code>Error:Execution failed for task
':app:transformClassesWithNewClassShrinkerForProductionDebug'.
> Warnings found during shrinking, please use -dontwarn or -ignorewarnings to suppress them.
</code>```

In my Debug, I use

```<code>        minifyEnabled true
        useProguard false
</code>```

I believe I could use -dontwarn or ignorewarnings to suprress and let the compilation continue. But I would like to know what warnings was that. Where could I find the warning?

答:
Found it. Just need to open the Gradle Console (normally a tab at the right bottom) to look at the Gradle Log.

It is stated

```<code>FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task
':app:transformClassesWithNewClassShrinkerForProductionDebug'.
> Warnings found during shrinking, please use -dontwarn or -ignorewarnings to suppress them.

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output.
</code>```

Optionally, I could just need to run the gradlew on command line with the --debug option.

```<code>./gradlew :app:transformClassesWithNewClassShrinkerForInternalDebug --debug
</code>```

Body:
After adding RxAndroid and Retrofit library to my gradle, and compile, I got the below error, shows in my Android Studio Message panel.

Error:Execution failed for task
':app:transformClassesWithNewClassShrinkerForProductionDebug'.
> Warnings found during shrinking, please use -dontwarn or -ignorewarnings to suppress them.

In my Debug, I use

        minifyEnabled true
        useProguard false

I believe I could use -dontwarn or ignorewarnings to suprress and let the compilation continue. But I would like to know what warnings was that. Where could I find the warning?

Body:
Found it. Just need to open the Gradle Console (normally a tab at the right bottom) to look at the Gradle Log.

It is stated

FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task
':app:transformClassesWithNewClassShrinkerForProductionDebug'.
> Warnings found during shrinking, please use -dontwarn or -ignorewarnings to suppress them.

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output.

Optionally, I could just need to run the gradlew on command line with the --debug option.

./gradlew :app:transformClassesWithNewClassShrinkerForInternalDebug --debug


问:
Promise.reject() continues with then() instead of catch()
I am making myself a library which retries failed promise "chain-parts" - I collect methods to be called and queue next phase only after previous succeeded.

Conceptually rounded up - my problems are more fundamental. This is where I arrived with debugging:

```<code>this.runningPromise
    .then(function() {
        return Promise.reject();
    })
//;
//this.runningPromise
    .then(this.promiseResolver.bind(this))
    .catch(this.promiseRejector.bind(this))
    ;
</code>```

Works, promiseRejector kicks in. When I uncomment out the two lines, works not. promiseResolver gets called.

Can't find anywhere anything. Nodejs 6.10.3 with browserify on Windows, Chrome.

答:
If you uncomment two rows means you are calling this.runningPromise twice and each time it has its own callbacks.

If you keep the rows commented then it will act as a promise (and associated callbacks)

Better you should assign promise to a variable and then you can use it multiple times.

```<code>let newPromise = this.runningPromise
    .then(function() {
        return Promise.reject();
    });

newPromise
    .then(this.promiseResolver.bind(this))
    .catch(this.promiseRejector.bind(this));
</code>```

With above code you can use newPromise multiple times.

Body:
I am making myself a library which retries failed promise "chain-parts" - I collect methods to be called and queue next phase only after previous succeeded.

Conceptually rounded up - my problems are more fundamental. This is where I arrived with debugging:

this.runningPromise
    .then(function() {
        return Promise.reject();
    })
//;
//this.runningPromise
    .then(this.promiseResolver.bind(this))
    .catch(this.promiseRejector.bind(this))
    ;

Works, promiseRejector kicks in. When I uncomment out the two lines, works not. promiseResolver gets called.

Can't find anywhere anything. Nodejs 6.10.3 with browserify on Windows, Chrome.

Body:
If you uncomment two rows means you are calling this.runningPromise twice and each time it has its own callbacks.

If you keep the rows commented then it will act as a promise (and associated callbacks)

Better you should assign promise to a variable and then you can use it multiple times.

let newPromise = this.runningPromise
    .then(function() {
        return Promise.reject();
    });

newPromise
    .then(this.promiseResolver.bind(this))
    .catch(this.promiseRejector.bind(this));

With above code you can use newPromise multiple times.


问:
Generate 6 digit unique number in Firebase
I want to generate 6 digit unique number in Firbase (unique must)

above attendeeCode should be unique on every new attendess entry

I am new in firebase and I have searched alot but could not find

答:
Create a six digit number that corresponds to the nth entry into attendees. And then keep track of that number elsewhere.

You can find in other questions that Firebase still does not support COUNT or LENGTH queries.

Create a path called /meta-data (arbitrary) and save the number of current attendees:

```<code>meta-data: {
    num_of_attendees: "000000" // parse this client side and send back padded string to keep 6 characters
}
</code>```

Grab the value every time you add an attendee, increment it, and send it back. This keeps you from grabbing a list of all attendees and getting the length client-side.

A new option: Firebase Cloud Functions

This is still in beta, but is having fair success. They provided and example of this functionality here:

functions-sample

Body:
Create a six digit number that corresponds to the nth entry into attendees. And then keep track of that number elsewhere.

You can find in other questions that Firebase still does not support COUNT or LENGTH queries.

Create a path called /meta-data (arbitrary) and save the number of current attendees:

meta-data: {
    num_of_attendees: "000000" // parse this client side and send back padded string to keep 6 characters
}

Grab the value every time you add an attendee, increment it, and send it back. This keeps you from grabbing a list of all attendees and getting the length client-side.

A new option: Firebase Cloud Functions

This is still in beta, but is having fair success. They provided and example of this functionality here:

functions-sample


问:
Request Tracker: Notify Previous Owner
I would like to be able to send an e-mail to the previous owner when someone steals a ticket, currently with Request Tracker I can send an e-mail to the new owner but not the previous owner.

There appears to be an extension to allow this however it does not support RT 4.2 (I am using 4.2.1): http://metacpan.org/pod/RT::Extension::NotifyOwners

Any help would be appreciated, if someone has this set up or is using the extension on RT 4.2 that would be great. I am pretty sure you can do this with a custom action but I do not have enough knowledge in this area.

Error from the log:

```
root@WEBSVR01:/home/steven# cpanm RT::Extension::NotifyOwners
--> Working on RT::Extension::NotifyOwners
Fetching http://www.cpan.org/authors/id/I/ID/IDN/RT-Extension-NotifyOwners-0.02.tar.gz ... OK
Configuring RT-Extension-NotifyOwners-0.02 ... N/A
! Configure failed for RT-Extension-NotifyOwners-0.02. See /root/.cpanm/work/1390880978.19447/build.log for details.
root@WEBSVR01:/home/steven# tail /root/.cpanm/work/1390880978.19447/build.log
Unpacking RT-Extension-NotifyOwners-0.02.tar.gz
Entering RT-Extension-NotifyOwners-0.02
Checking configure dependencies from META.yml
Checking if you have ExtUtils::MakeMaker 6.42 ... Yes (6.82)
Configuring RT-Extension-NotifyOwners-0.02
Running Makefile.PL
Cannot find the location of RT.pm that defines $RT::LocalPath in: inc /etc/perl /usr/local/lib/perl/5.14.2 /usr/local/sh                     are/perl/5.14.2 /usr/lib/perl5 /usr/share/perl5 /usr/lib/perl/5.14 /usr/share/perl/5.14 /usr/local/lib/site_perl . /opt/                     rt3/lib /opt/lib/rt3 /opt/lib /usr/local/rt3/lib /usr/local/lib/rt3 /usr/local/lib /home/rt3/lib /home/lib/rt3 /home/lib                      /usr/rt3/lib /usr/lib/rt3 /usr/lib /sw/rt3/lib /sw/lib/rt3 /sw/lib
Path to directory containing your RT.pm:
-> N/A
-> FAIL Configure failed for RT-Extension-NotifyOwners-0.02. See /root/.cpanm/work/1390880978.19447/build.log for details.
```

答:
You can achieve that by a script and a template. Scrip On Steal Notify Old Owner should be like this:

```<code>my $field = $self->TransactionObj->Field;
my $type = $self->TransactionObj->Type;

return 0 unless defined($field);
return 0 unless $field eq 'Owner';
return 0 unless $type eq 'Set';
return 0 if $self->TransactionObj->OldValue == $self->TransactionObj->Creator;

return 1 if $self->TransactionObj->OldValue != RT::Nobody()->id();

return 0;
</code>```

Condition of the scrip should be User defined, Action should be Notify Other Recipients, Template for example Stolen Ticket.

Perl template Stolen Ticket will be then for example this one:

```<code>To: {my $user = new RT::User($RT::SystemUser);
$user->Load($Transaction->OldValue); $user->EmailAddress() || $Transaction->OldValue}
Subject: [{$rtname } #{ $Ticket->Id() }] Stolen: { $Ticket->Subject() }

URL: https://rt.example.com/rt/Ticket/Display.html?id={ $Ticket->id }

A ticket you owned:
  { $Ticket->Subject() }

has been taken by {$Ticket->OwnerObj->RealName} <{$Ticket->OwnerObj->EmailAddress}>.
</code>```

Title: Request Tracker: Notify Previous Owner

Body:
I would like to be able to send an e-mail to the previous owner when someone steals a ticket, currently with Request Tracker I can send an e-mail to the new owner but not the previous owner.

There appears to be an extension to allow this however it does not support RT 4.2 (I am using 4.2.1): http://metacpan.org/pod/RT::Extension::NotifyOwners

Any help would be appreciated, if someone has this set up or is using the extension on RT 4.2 that would be great. I am pretty sure you can do this with a custom action but I do not have enough knowledge in this area.

Error from the log:

root@WEBSVR01:/home/steven# cpanm RT::Extension::NotifyOwners
--> Working on RT::Extension::NotifyOwners
Fetching http://www.cpan.org/authors/id/I/ID/IDN/RT-Extension-NotifyOwners-0.02.tar.gz ... OK
Configuring RT-Extension-NotifyOwners-0.02 ... N/A
! Configure failed for RT-Extension-NotifyOwners-0.02. See /root/.cpanm/work/1390880978.19447/build.log for details.
root@WEBSVR01:/home/steven# tail /root/.cpanm/work/1390880978.19447/build.log
Unpacking RT-Extension-NotifyOwners-0.02.tar.gz
Entering RT-Extension-NotifyOwners-0.02
Checking configure dependencies from META.yml
Checking if you have ExtUtils::MakeMaker 6.42 ... Yes (6.82)
Configuring RT-Extension-NotifyOwners-0.02
Running Makefile.PL
Cannot find the location of RT.pm that defines $RT::LocalPath in: inc /etc/perl /usr/local/lib/perl/5.14.2 /usr/local/sh                     are/perl/5.14.2 /usr/lib/perl5 /usr/share/perl5 /usr/lib/perl/5.14 /usr/share/perl/5.14 /usr/local/lib/site_perl . /opt/                     rt3/lib /opt/lib/rt3 /opt/lib /usr/local/rt3/lib /usr/local/lib/rt3 /usr/local/lib /home/rt3/lib /home/lib/rt3 /home/lib                      /usr/rt3/lib /usr/lib/rt3 /usr/lib /sw/rt3/lib /sw/lib/rt3 /sw/lib
Path to directory containing your RT.pm:
-> N/A
-> FAIL Configure failed for RT-Extension-NotifyOwners-0.02. See /root/.cpanm/work/1390880978.19447/build.log for details.

Body:
You can achieve that by a script and a template. Scrip On Steal Notify Old Owner should be like this:

my $field = $self->TransactionObj->Field;
my $type = $self->TransactionObj->Type;

return 0 unless defined($field);
return 0 unless $field eq 'Owner';
return 0 unless $type eq 'Set';
return 0 if $self->TransactionObj->OldValue == $self->TransactionObj->Creator;

return 1 if $self->TransactionObj->OldValue != RT::Nobody()->id();

return 0;

Condition of the scrip should be User defined, Action should be Notify Other Recipients, Template for example Stolen Ticket.

Perl template Stolen Ticket will be then for example this one:

To: {my $user = new RT::User($RT::SystemUser);
$user->Load($Transaction->OldValue); $user->EmailAddress() || $Transaction->OldValue}
Subject: [{$rtname } #{ $Ticket->Id() }] Stolen: { $Ticket->Subject() }

URL: https://rt.example.com/rt/Ticket/Display.html?id={ $Ticket->id }

A ticket you owned:
  { $Ticket->Subject() }

has been taken by {$Ticket->OwnerObj->RealName} <{$Ticket->OwnerObj->EmailAddress}>.


问:
How do I use vector values as variables in R
I have a dataframe called repay and I have created a vector for the variables names of the variables I am interested in called variables.

```<code>variables<-names(repay)[22:36]
</code>```

I want to write a for loop that does some univariate analysis on each of the variables in variables. For example:

```<code>for (i in 1:length(variables))
{
model<-glm(Successful~ variables[i]
,data=repay
,family=binomial(link='logit'))
}
</code>```

However it doesn't recognize variables[i] as a variable, giving the following error message:

Error in model.frame.default(formula = Successful ~ variables[i], data
  = repay,  : variable lengths differ (found for 'variables[i]')

答:
Alternatively you can use assign yielding in as many models as the variables.
Let us consider

```<code>repay<-data.table(Successful=runif(10),a=sample(10),b=sample(10),c=runif(10))
variables<-names(repay)[2:4]
</code>```

yielding:

```<code>>repay
    Successful  a  b         c
 1:  0.8457686  7  9 0.2930537
 2:  0.4050198  6  6 0.5948573
 3:  0.1994583  2  8 0.4198423
 4:  0.1471735  1  5 0.5906494
 5:  0.7765083  8 10 0.7933327
 6:  0.6503692  9  4 0.4262896
 7:  0.2449512  4  1 0.7311928
 8:  0.6754966  3  3 0.4723299
 9:  0.7792951 10  7 0.9101495
10:  0.6281890  5  2 0.9215107
</code>```

Then you can perform the loop

for (i in 1:length(variables)){
 assign(paste0("model",i),eval(parse(text=paste("glm(Successful~",variables[i],",data=repay,family=binomial(link='logit'))"))))
}

resulting in 3 objects: model1,model2 and model3.

```<code> >model1
 Call:  glm(formula = Successful ~ a, family = binomial(link = "logit"),
 data = repay)
 Coefficients:
 (Intercept)            a
   -0.36770      0.05501
 Degrees of Freedom: 9 Total (i.e. Null);  8 Residual
 Null Deviance:     5.752
 Residual Deviance: 5.69    AIC: 17.66
</code>```

Idem for model2, model3 et.c.

Body:
I have a dataframe called repay and I have created a vector for the variables names of the variables I am interested in called variables.

variables<-names(repay)[22:36]

I want to write a for loop that does some univariate analysis on each of the variables in variables. For example:

for (i in 1:length(variables))
{
model<-glm(Successful~ variables[i]
,data=repay
,family=binomial(link='logit'))
}

However it doesn't recognize variables[i] as a variable, giving the following error message:

Error in model.frame.default(formula = Successful ~ variables[i], data
  = repay,  : variable lengths differ (found for 'variables[i]')

Body:
Alternatively you can use assign yielding in as many models as the variables.
Let us consider

repay<-data.table(Successful=runif(10),a=sample(10),b=sample(10),c=runif(10))
variables<-names(repay)[2:4]

yielding:

>repay
    Successful  a  b         c
 1:  0.8457686  7  9 0.2930537
 2:  0.4050198  6  6 0.5948573
 3:  0.1994583  2  8 0.4198423
 4:  0.1471735  1  5 0.5906494
 5:  0.7765083  8 10 0.7933327
 6:  0.6503692  9  4 0.4262896
 7:  0.2449512  4  1 0.7311928
 8:  0.6754966  3  3 0.4723299
 9:  0.7792951 10  7 0.9101495
10:  0.6281890  5  2 0.9215107

Then you can perform the loop

for (i in 1:length(variables)){
 assign(paste0("model",i),eval(parse(text=paste("glm(Successful~",variables[i],",data=repay,family=binomial(link='logit'))"))))
}

resulting in 3 objects: model1,model2 and model3.

 >model1
 Call:  glm(formula = Successful ~ a, family = binomial(link = "logit"),
 data = repay)
 Coefficients:
 (Intercept)            a
   -0.36770      0.05501
 Degrees of Freedom: 9 Total (i.e. Null);  8 Residual
 Null Deviance:     5.752
 Residual Deviance: 5.69    AIC: 17.66

Idem for model2, model3 et.c.


问:
IntelliJ IDEA - "Imported project refers to unknown jdks JavaSE-1.8" while import Eclipse projects
I tried to import Eclipse project to IntelliJ IDEA, but I got this error:

答:
The eclipse project description contains a reference to a "manually" defined JDK (named JavaSE-1.8).

Just go forward and define an SDK for your project within IntelliJ yourself. See here for the necessary steps:

To define a JDK and a mobile SDK in IntelliJ IDEA

Open the Project Structure dialog (e.g. Ctrl+Shift+Alt+S).

In the leftmost pane, under Platform Settings, click SDKs.

Above the pane to the right, click ￼ and select JDK.

In the dialog that opens, select the installation directory of the JDK to be used and click OK.

... (obviously you don't need the Java ME mobile specific things listed in the original link)


问:
Is there any difference between "json" and "tojson" filters in jinja for saltstack?
According to saltstack documentation it's "json":
https://docs.saltstack.com/en/latest/ref/renderers/all/salt.renderers.jinja.html

But in jinja doc
http://jinja.pocoo.org/docs/2.9/templates/#builtin-filters - there is not "json", but "tojson".

Does anybody know why?

答:
While I can't say absolutely for sure, I have an impression that Salt Renderers are built-in for Salt only. For example, there are also yaml and python renderers, but there is no corresponding filter for Jinja.

So, json renderer and tojson filter just happened to have similar names because of their purpose. And you won't be able to use json renderer outside of Salt.


问:
Can't center divs HTML CSS
i'm having a small issue getting my divs to sit inline with each other and in the center of the parent div. So I have one parent "page" then 6 other divs inside of that the "pageName" which sits above "bg_01", "bg_02", "bg_03", "bg_04", "bg_05", "bg_06" which all sit inline with each other. However it works when the window is quite small however i'm trying to get it to work when the window is any size, can anyone see where I'm going wrong?

Thanks again guys.

p {
  margin: 0;
}

#page {
  border: 2px solid #e1dfe1;
  border-radius: 5px;
  background-color: #fff;
  width: 100%;
  height: 200px;
  margin-top: 50px;
  font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;
}

#pageName {
  background-color: #f5f0f5;
  border-bottom: 2px solid #e1dfe1;
}

#pageName p {
  padding-top: 15px;
  padding-bottom: 15px;
  padding-left: 15px;
  color: #565656;
  font-weight: bold;
}

#bg_01 {
  background-color: #80b3ff;
  width: 80px;
  height: 80px;
  border: 3px solid #666;
  border-radius: 20px;
  margin: 4%;
  float: left;
}

#bg_02 {
  background-color: #afe9af;
  width: 80px;
  height: 80px;
  border: 3px solid #666;
  border-radius: 20px;
  margin: 4%;
  float: left;
}

#bg_03 {
  background-color: #ffb380;
  width: 80px;
  height: 80px;
  border: 3px solid #666;
  border-radius: 20px;
  margin: 4%;
  float: left;
}

#bg_04 {
  background-color: #ffaaaa;
  width: 80px;
  height: 80px;
  border: 3px solid #666;
  border-radius: 20px;
  margin: 4%;
  float: left;
}

#bg_05 {
  background-color: #eeaaff;
  width: 80px;
  height: 80px;
  border: 3px solid #666;
  border-radius: 20px;
  margin: 4%;
  float: left;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="page">
  <div id="pageName" }>
    <p>Colour</p>
  </div>
  <div id="bg_01">
  </div>

  <div id="bg_02">
  </div>

  <div id="bg_03">
  </div>

  <div id="bg_04">
  </div>

  <div id="bg_05">
  </div>
</div></code>```

答:
Just add text-align: center; to #page and replace float:left; width display: inline-block and it should work.

Something as follows:

```<code><div id="page">
  <div id="pageName" }>
    <p>Colour</p>
  </div>
  <div id="bg_01">
  </div>

  <div id="bg_02">
  </div>

  <div id="bg_03">
  </div>

  <div id="bg_04">
  </div>

  <div id="bg_05">
  </div>
</div>
</code>```

And the css:

```<code>p {
  margin: 0;
}

#page {
  border: 2px solid #e1dfe1;
  border-radius: 5px;
  background-color: #f00;
  width: 100%;
  height: 100%;
  margin-top: 50px;
  font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;
  text-align: center;
}

#pageName {
  background-color: #f5f0f5;
  border-bottom: 2px solid #e1dfe1;
}

#pageName p {
  padding-top: 15px;
  padding-bottom: 15px;
  padding-left: 15px;
  color: #565656;
  font-weight: bold;
}

#bg_01 {
  background-color: #80b3ff;
  width: 80px;
  height: 80px;
  border: 3px solid #666;
  border-radius: 20px;
  margin: 4%;
  display: inline-block;
}

#bg_02 {
  background-color: #afe9af;
  width: 80px;
  height: 80px;
  border: 3px solid #666;
  border-radius: 20px;
  margin: 4%;
  display: inline-block;
}

#bg_03 {
  background-color: #ffb380;
  width: 80px;
  height: 80px;
  border: 3px solid #666;
  border-radius: 20px;
  margin: 4%;
  display: inline-block;
}

#bg_04 {
  background-color: #ffaaaa;
  width: 80px;
  height: 80px;
  border: 3px solid #666;
  border-radius: 20px;
  margin: 4%;
  display: inline-block;
}

#bg_05 {
  background-color: #eeaaff;
  width: 80px;
  height: 80px;
  border: 3px solid #666;
  border-radius: 20px;
  margin: 4%;
  display: inline-block;
}
</code>```

Here is the fiddle.

Title: Can't center divs HTML CSS

Body:
i'm having a small issue getting my divs to sit inline with each other and in the center of the parent div. So I have one parent "page" then 6 other divs inside of that the "pageName" which sits above "bg_01", "bg_02", "bg_03", "bg_04", "bg_05", "bg_06" which all sit inline with each other. However it works when the window is quite small however i'm trying to get it to work when the window is any size, can anyone see where I'm going wrong?

Thanks again guys.

p {
  margin: 0;
}

#page {
  border: 2px solid #e1dfe1;
  border-radius: 5px;
  background-color: #fff;
  width: 100%;
  height: 200px;
  margin-top: 50px;
  font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;
}

#pageName {
  background-color: #f5f0f5;
  border-bottom: 2px solid #e1dfe1;
}

#pageName p {
  padding-top: 15px;
  padding-bottom: 15px;
  padding-left: 15px;
  color: #565656;
  font-weight: bold;
}

#bg_01 {
  background-color: #80b3ff;
  width: 80px;
  height: 80px;
  border: 3px solid #666;
  border-radius: 20px;
  margin: 4%;
  float: left;
}

#bg_02 {
  background-color: #afe9af;
  width: 80px;
  height: 80px;
  border: 3px solid #666;
  border-radius: 20px;
  margin: 4%;
  float: left;
}

#bg_03 {
  background-color: #ffb380;
  width: 80px;
  height: 80px;
  border: 3px solid #666;
  border-radius: 20px;
  margin: 4%;
  float: left;
}

#bg_04 {
  background-color: #ffaaaa;
  width: 80px;
  height: 80px;
  border: 3px solid #666;
  border-radius: 20px;
  margin: 4%;
  float: left;
}

#bg_05 {
  background-color: #eeaaff;
  width: 80px;
  height: 80px;
  border: 3px solid #666;
  border-radius: 20px;
  margin: 4%;
  float: left;
}

Colour

Body:
Just add text-align: center; to #page and replace float:left; width display: inline-block and it should work.

Something as follows:

<div id="page">
  <div id="pageName" }>
    <p>Colour</p>
  </div>
  <div id="bg_01">
  </div>

  <div id="bg_02">
  </div>

  <div id="bg_03">
  </div>

  <div id="bg_04">
  </div>

  <div id="bg_05">
  </div>
</div>

And the css:

p {
  margin: 0;
}

#page {
  border: 2px solid #e1dfe1;
  border-radius: 5px;
  background-color: #f00;
  width: 100%;
  height: 100%;
  margin-top: 50px;
  font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;
  text-align: center;
}

#pageName {
  background-color: #f5f0f5;
  border-bottom: 2px solid #e1dfe1;
}

#pageName p {
  padding-top: 15px;
  padding-bottom: 15px;
  padding-left: 15px;
  color: #565656;
  font-weight: bold;
}

#bg_01 {
  background-color: #80b3ff;
  width: 80px;
  height: 80px;
  border: 3px solid #666;
  border-radius: 20px;
  margin: 4%;
  display: inline-block;
}

#bg_02 {
  background-color: #afe9af;
  width: 80px;
  height: 80px;
  border: 3px solid #666;
  border-radius: 20px;
  margin: 4%;
  display: inline-block;
}

#bg_03 {
  background-color: #ffb380;
  width: 80px;
  height: 80px;
  border: 3px solid #666;
  border-radius: 20px;
  margin: 4%;
  display: inline-block;
}

#bg_04 {
  background-color: #ffaaaa;
  width: 80px;
  height: 80px;
  border: 3px solid #666;
  border-radius: 20px;
  margin: 4%;
  display: inline-block;
}

#bg_05 {
  background-color: #eeaaff;
  width: 80px;
  height: 80px;
  border: 3px solid #666;
  border-radius: 20px;
  margin: 4%;
  display: inline-block;
}

Here is the fiddle.


问:
Issue connecting composer to Blockchain on Bluemix - identity or token does not match
I have fabric composer 0.72 installed on my mac, and I was able to follow this thread to get it connected to my Blockchain (v.61 of Fabric) on Bluemix.

fabric-composer-integration-with-bluemix-blockchain-service

Now I am trying to build an ubuntu (16.04) docker container and run composer-rest-server there.  When I try to connect to my blockchain service from my docker container (using the same id, WebAppAdmin, that I used on my mac) I get an error:

```<code>Discovering types from business network definition ...
Connection fails: Error: Identity or token does not match.
It will be retried for the next request.
{ Error: Identity or token does not match.
     at /home/composer/.nvm/versions/node/v6.10.3/lib/node_modules  /composer-rest-server/node_modules/grpc/src/node/src/client.js:417:17 code: 2, metadata: Metadata { _internal_repr: {} } }
</code>```

I tried copying the cert from my mac to my docker container:

```<code>/home/composer/.composer-credentials/member.WebAppAdmin
</code>```

but when I did that I got a different error that says "signature does not verify".  I did some additional testing, and I discovered that if I used an id that I had not previously used with composer (i.e. user_type1_0) then I could connect, and I could see a new cert in my .composer-credentials directory.

I tried deleting that container and building a new one (I dorked something else up) I could not use that same userid again.

Does anybody know how security and these certs are supposed to work?  It would seem as though something to do with certificate generation/validation is tied to the client (i.e. hardware address), such that if I try to re-use an id on a different machine, the certs or keys or something don't match.  I have a way to make things work, but it doesn't seem like it's the right way if I can't use the same id from different machines.

Thanks!

答:
Hi i tried to recreate this by having blockchain running on a unix machine and then i copied my connection profile and certificate to my mac and then edited my connection profile to update the ip address and key store. I then did a composer network ping and it worked fine.

I am using composer v0.7.4 so you could try that?

Body:
I have fabric composer 0.72 installed on my mac, and I was able to follow this thread to get it connected to my Blockchain (v.61 of Fabric) on Bluemix.

fabric-composer-integration-with-bluemix-blockchain-service

Now I am trying to build an ubuntu (16.04) docker container and run composer-rest-server there.  When I try to connect to my blockchain service from my docker container (using the same id, WebAppAdmin, that I used on my mac) I get an error:

Discovering types from business network definition ...
Connection fails: Error: Identity or token does not match.
It will be retried for the next request.
{ Error: Identity or token does not match.
     at /home/composer/.nvm/versions/node/v6.10.3/lib/node_modules  /composer-rest-server/node_modules/grpc/src/node/src/client.js:417:17 code: 2, metadata: Metadata { _internal_repr: {} } }

I tried copying the cert from my mac to my docker container:

/home/composer/.composer-credentials/member.WebAppAdmin

but when I did that I got a different error that says "signature does not verify".  I did some additional testing, and I discovered that if I used an id that I had not previously used with composer (i.e. user_type1_0) then I could connect, and I could see a new cert in my .composer-credentials directory.

I tried deleting that container and building a new one (I dorked something else up) I could not use that same userid again.

Does anybody know how security and these certs are supposed to work?  It would seem as though something to do with certificate generation/validation is tied to the client (i.e. hardware address), such that if I try to re-use an id on a different machine, the certs or keys or something don't match.  I have a way to make things work, but it doesn't seem like it's the right way if I can't use the same id from different machines.

Thanks!


答:
Small workaround that might help</p>

```<code> for (i in 22:36)
{
  ivar <- repay[i] #choose variable for running the model
  repay2 <- data.frame(Successful= repay$Successful, ivar) #create new data frame with 2 variables only for running the model

  #run model for new data frame repay2
  model<-glm(Successful~ ivar
             ,data=repay2
             ,family=binomial(link='logit'))
}
</code>```

Title: How do I use vector values as variables in R

Body:
Small workaround that might help

 for (i in 22:36)
{
  ivar <- repay[i] #choose variable for running the model
  repay2 <- data.frame(Successful= repay$Successful, ivar) #create new data frame with 2 variables only for running the model

  #run model for new data frame repay2
  model<-glm(Successful~ ivar
             ,data=repay2
             ,family=binomial(link='logit'))
}


问:
Android layout editor background color gets ignored
The following layout xml snippet works fine. But if I make any attempt to remove the Floating Action Button in it, the background color of "@color/green" in main Layout element gets ignored by the IDEA/Android Studio Layout Editor.

```<code><?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    tools:ignore="RtlHardcoded"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/green"
    android:fitsSystemWindows="true">

<android.support.design.widget.FloatingActionButton
        android:id="@+id/fab"
        android:onClick="callDirector"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="bottom|end"
        android:layout_margin="@dimen/fab_margin"
        android:src="@android:drawable/ic_dialog_alert"/>

<RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:paddingLeft="@dimen/activity_horizontal_margin"
        android:paddingRight="@dimen/activity_horizontal_margin"
        android:paddingTop="@dimen/activity_vertical_margin"
        android:paddingBottom="@dimen/activity_vertical_margin"
        android:background="@color/green"
        tools:context="org.drachenschloss.bidzclient.MainActivity">
</code>```

I'm perfectly content to remove both the FAB AND the CoordinatorLayout (if memory serves, I only put in the CoordinatorLayout for the FAB), thus moving all of the xmlns elements to the RelativeLayout as that would become the root layout element for the activity but that doesn't help either.

Again the green background color works fine in the app. It's just not shown in the IDE layout editor display. I've even tried adding

```<code>tools:background="@color/green"
</code>```

in order to cause the root layout element (whichever it is) to make the layout display in IDEA get the clue, but nothing changes. The moment the FAB goes away, the background color for the activity does too.

答:
Seems this is a difficult to reproduce issue in both IJ and Android Studio.

https://issuetracker.google.com/issues/62334380

Body:
The following layout xml snippet works fine. But if I make any attempt to remove the Floating Action Button in it, the background color of "@color/green" in main Layout element gets ignored by the IDEA/Android Studio Layout Editor.

<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    tools:ignore="RtlHardcoded"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/green"
    android:fitsSystemWindows="true">

<android.support.design.widget.FloatingActionButton
        android:id="@+id/fab"
        android:onClick="callDirector"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="bottom|end"
        android:layout_margin="@dimen/fab_margin"
        android:src="@android:drawable/ic_dialog_alert"/>

<RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:paddingLeft="@dimen/activity_horizontal_margin"
        android:paddingRight="@dimen/activity_horizontal_margin"
        android:paddingTop="@dimen/activity_vertical_margin"
        android:paddingBottom="@dimen/activity_vertical_margin"
        android:background="@color/green"
        tools:context="org.drachenschloss.bidzclient.MainActivity">

I'm perfectly content to remove both the FAB AND the CoordinatorLayout (if memory serves, I only put in the CoordinatorLayout for the FAB), thus moving all of the xmlns elements to the RelativeLayout as that would become the root layout element for the activity but that doesn't help either.

Again the green background color works fine in the app. It's just not shown in the IDE layout editor display. I've even tried adding

tools:background="@color/green"

in order to cause the root layout element (whichever it is) to make the layout display in IDEA get the clue, but nothing changes. The moment the FAB goes away, the background color for the activity does too.


问:
Spring boot h2-console not working
Hello I am not able to open h2-console with spring boot

```<code><parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>1.3.0.RC1</version>
</parent>

<dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-devtools</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-security</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-thymeleaf</artifactId>
    </dependency>
    <dependency>
        <groupId>org.thymeleaf.extras</groupId>
        <artifactId>thymeleaf-extras-springsecurity4</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-jpa</artifactId>
    </dependency>
    <dependency>
        <groupId>com.h2database</groupId>
        <artifactId>h2</artifactId>
        <scope>runtime</scope>
    </dependency>
</code>```

SpringSecurity Cfg:

```<code>@Configuration
</code>```

@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

```<code>@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
    auth.inMemoryAuthentication()
        .withUser("admin").password("admin").roles("ADMIN").and()
        .withUser("user").password("user").roles("USER");
}

@Override
protected void configure(HttpSecurity httpSecurity) throws Exception {
    httpSecurity.authorizeRequests()
    .anyRequest().authenticated()
    .and()
        .formLogin().loginPage("/login").permitAll()
    .and()
        .logout().permitAll()
    .and()
        .exceptionHandling().accessDeniedPage("/Access_Denied")
    .and()
        .csrf();
}
</code>```

}

```<code>@SpringBootApplication
</code>```

public class SpringBootWebSecureApplication {

```<code>@Bean
public Java8TimeDialect java8TimeDialect() {
    return new Java8TimeDialect();
}

public static void main(String[] args) {
    SpringApplication.run(SpringBootWebSecureApplication.class);
}
</code>```

}

I am starting boot with:

```<code>-Dserver.port=8090
-Dspring.h2.console.enabled=true
-Dspring.datasource.url=jdbc:h2:mem:testdb
-Dspring.datasource.username=sa
-Dspring.datasource.driverClassName=org.h2.Driver
</code>```

Logs:

```<code>2015-11-13 17:37:47 [restartedMain] DEBUG c.m.a.SpringBootWebSecureApplication - Running with Spring Boot v1.3.0.RC1, Spring v4.2.2.RELEASE
2015-11-13 17:37:49 [restartedMain] INFO  o.s.b.c.e.t.TomcatEmbeddedServletContainer - Tomcat initialized with port(s): 8090 (http)
2015-11-13 17:37:50 [localhost-startStop-1] INFO  o.s.b.c.e.ServletRegistrationBean - Mapping servlet: 'webServlet' to [/h2-console/*]
2015-11-13 17:37:51 [localhost-startStop-1] INFO  o.s.s.web.DefaultSecurityFilterChain - Creating filter chain: Ant [pattern='/h2-console/**'], [org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter@11ffd6f0, org.springframework.security.web.context.SecurityContextPersistenceFilter@615c57c5, org.springframework.security.web.header.HeaderWriterFilter@6b2cbcbf, org.springframework.security.web.authentication.logout.LogoutFilter@af7bece, org.springframework.security.web.authentication.www.BasicAuthenticationFilter@17d03ab2, org.springframework.security.web.savedrequest.RequestCacheAwareFilter@613197b, org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter@8d48442, org.springframework.security.web.authentication.AnonymousAuthenticationFilter@7fa13240, org.springframework.security.web.session.SessionManagementFilter@9f16a1c, org.springframework.security.web.access.ExceptionTranslationFilter@1f3f02ef, org.springframework.security.web.access.intercept.FilterSecurityInterceptor@115de1f6]
</code>```

But when I open browser with my app
console not appearing

```<code>http://localhost:8090/h2-console/
</code>```

Any hints?

Thank you

Title: Spring boot h2-console not working

Body:
Hello I am not able to open h2-console with spring boot

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>1.3.0.RC1</version>
</parent>

<dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-devtools</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-security</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-thymeleaf</artifactId>
    </dependency>
    <dependency>
        <groupId>org.thymeleaf.extras</groupId>
        <artifactId>thymeleaf-extras-springsecurity4</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-jpa</artifactId>
    </dependency>
    <dependency>
        <groupId>com.h2database</groupId>
        <artifactId>h2</artifactId>
        <scope>runtime</scope>
    </dependency>

SpringSecurity Cfg:

@Configuration

@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
    auth.inMemoryAuthentication()
        .withUser("admin").password("admin").roles("ADMIN").and()
        .withUser("user").password("user").roles("USER");
}

@Override
protected void configure(HttpSecurity httpSecurity) throws Exception {
    httpSecurity.authorizeRequests()
    .anyRequest().authenticated()
    .and()
        .formLogin().loginPage("/login").permitAll()
    .and()
        .logout().permitAll()
    .and()
        .exceptionHandling().accessDeniedPage("/Access_Denied")
    .and()
        .csrf();
}

}

@SpringBootApplication

public class SpringBootWebSecureApplication {

@Bean
public Java8TimeDialect java8TimeDialect() {
    return new Java8TimeDialect();
}

public static void main(String[] args) {
    SpringApplication.run(SpringBootWebSecureApplication.class);
}

}

I am starting boot with:

-Dserver.port=8090
-Dspring.h2.console.enabled=true
-Dspring.datasource.url=jdbc:h2:mem:testdb
-Dspring.datasource.username=sa
-Dspring.datasource.driverClassName=org.h2.Driver

Logs:

2015-11-13 17:37:47 [restartedMain] DEBUG c.m.a.SpringBootWebSecureApplication - Running with Spring Boot v1.3.0.RC1, Spring v4.2.2.RELEASE
2015-11-13 17:37:49 [restartedMain] INFO  o.s.b.c.e.t.TomcatEmbeddedServletContainer - Tomcat initialized with port(s): 8090 (http)
2015-11-13 17:37:50 [localhost-startStop-1] INFO  o.s.b.c.e.ServletRegistrationBean - Mapping servlet: 'webServlet' to [/h2-console/*]
2015-11-13 17:37:51 [localhost-startStop-1] INFO  o.s.s.web.DefaultSecurityFilterChain - Creating filter chain: Ant [pattern='/h2-console/**'], [org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter@11ffd6f0, org.springframework.security.web.context.SecurityContextPersistenceFilter@615c57c5, org.springframework.security.web.header.HeaderWriterFilter@6b2cbcbf, org.springframework.security.web.authentication.logout.LogoutFilter@af7bece, org.springframework.security.web.authentication.www.BasicAuthenticationFilter@17d03ab2, org.springframework.security.web.savedrequest.RequestCacheAwareFilter@613197b, org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter@8d48442, org.springframework.security.web.authentication.AnonymousAuthenticationFilter@7fa13240, org.springframework.security.web.session.SessionManagementFilter@9f16a1c, org.springframework.security.web.access.ExceptionTranslationFilter@1f3f02ef, org.springframework.security.web.access.intercept.FilterSecurityInterceptor@115de1f6]

But when I open browser with my app
console not appearing

http://localhost:8090/h2-console/

Any hints?

Thank you

Body: http.headers().frameOptions().disable();


问:
Proper way to handle ACTION_MANAGE_WRITE_SETTINGS activity
I want write settings permission in order to start portable WLAN hotspot...

this is what i got,

```<code>if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (!Settings.System.canWrite(getApplicationContext())) {
                Intent intent = new Intent(Settings.ACTION_MANAGE_WRITE_SETTINGS, Uri.parse("package:" + getPackageName()));
                startActivityForResult(intent, 200);
            }
        }
</code>```

this works fine until i press back button after i grant permission.

after pressing back button resultCode is 0 always, therefore further code is not working properly.

答:
after pressing back button resultCode is 0 always

An ACTION_MANAGE_WRITE_SETTINGS is not documented to return a result. Most activities do not return a result.

Do not call startActivityForResult() — just use startActivity(). When needed, call Settings.System.canWrite(this) to see if you have permission.

Body:
I want write settings permission in order to start portable WLAN hotspot...

this is what i got,

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (!Settings.System.canWrite(getApplicationContext())) {
                Intent intent = new Intent(Settings.ACTION_MANAGE_WRITE_SETTINGS, Uri.parse("package:" + getPackageName()));
                startActivityForResult(intent, 200);
            }
        }

this works fine until i press back button after i grant permission.

after pressing back button resultCode is 0 always, therefore further code is not working properly.


问:
Procfile start processes in their own working directory
I have this simple Procfile

```<code>web: myapp
</code>```

myapp is in the path, but the processes home directory should be ./directory/. How can I specify in the Procfile where the process is to be started?

https://github.com/ddollar/foreman/pull/101 doesn't help because it assumes, that this working directory should be the same for every process specified by the Procfile

答:
You can chain a set of shell commands together. With the current version of Foreman, you do not need to wrap this in a shell command as in @JohnDoe's answer.

```<code>web: cd server_dir && start web_service
clk: cd clock_tower && start timers
</code>```

These would start the necessary processes from their respective folders and track them independently.

Body:
I have this simple Procfile

web: myapp

myapp is in the path, but the processes home directory should be ./directory/. How can I specify in the Procfile where the process is to be started?

https://github.com/ddollar/foreman/pull/101 doesn't help because it assumes, that this working directory should be the same for every process specified by the Procfile

Body:
You can chain a set of shell commands together. With the current version of Foreman, you do not need to wrap this in a shell command as in @JohnDoe's answer.

web: cd server_dir && start web_service
clk: cd clock_tower && start timers

These would start the necessary processes from their respective folders and track them independently.


答:
the fastest way will be to organize the data so it is indexed by the thing you want to search on.  Currently you have it indexed by key, but you want to search by date.  I think you would be best indexing it by date, if that is what you want to be able to search on.

I would keep 2 dictionaries, one indexed as you do now and one where the items are indexed by date.  i would decide on a time frame (say 1 minute) and add each object to a list based on the minute it happens in and then add each list to the dictionary under the key of that minute.  then when you want the data for a particular time frame, generate the relevant minute(s) and get the list(s) from the dictionary.  This relies on you being able to know the key in the other dictionary from the objects though.

Title: Fastest method of collection searching by DateTime

Body:
I have a Dictionary containing 10 keys, each with a list containing up to 30,000 values. The values contain a DateTime property.

I frequently need to extract a small subset of one of the keys, like a date range of 30 - 60 seconds.

Doing this is easy, but getting it to run fast is not so. What would be the most efficient way to query this in-memory data?

Thanks a lot.


问:
Changing the entire string in a string builder object
I have the following code:

```<code>using System;
using System.Text;

public class Program
{
    private static StringBuilder mystrb = new StringBuilder("hello");
    public static void Main()
    {
        mystrb.Clear();
        mystrb.Append("chau");
    }
}
</code>```

is there any other way of entirly replacing the string in the string builder, i am looking for a one sentence way of doing it if it exist.

答:
The best option is not to instantiate with a default at all. Since you are immediately replacing it with something else, just leave it empty (new StringBuilder()) or null.

```<code>private static StringBuilder mystrb;
</code>```

If you have oversimplified your sample code, then just create a new instance:

```<code>mystrb = new StringBuilder("chau");
</code>```

Body:
I have the following code:

using System;
using System.Text;

public class Program
{
    private static StringBuilder mystrb = new StringBuilder("hello");
    public static void Main()
    {
        mystrb.Clear();
        mystrb.Append("chau");
    }
}

is there any other way of entirly replacing the string in the string builder, i am looking for a one sentence way of doing it if it exist.

Body:
The best option is not to instantiate with a default at all. Since you are immediately replacing it with something else, just leave it empty (new StringBuilder()) or null.

private static StringBuilder mystrb;

If you have oversimplified your sample code, then just create a new instance:

mystrb = new StringBuilder("chau");


问:
php - unable to split a string by new lines from database
I'm receiving data from a MSSQL database with PHP (using PDO sqlsrv driver).

I need to split the string by new line.

In the DB the string looks like this:

I tried the following with no success:

```<code>$text = explode("\n\n",$text);
$text = preg_split("/\n\n/",$text);
</code>```

Or

```<code>$text = explode("\n",$text);
$text = preg_split("/\n/",$text);
</code>```

When i debug the code and when i print the text to the browser the string appears as one line.

But if i inspect the element in chrome, it is displayed exactly like in the database:

I copied the text from the inspector to a regex tester and the newlines were found successfully! But the "echoed" text was in one line.

答:
Try replacing new line character with comma (,) or something other special char.

```<code>preg_replace("/((\r?\n)|(\r\n?))/", ',', $input);
</code>```

Then try to explode like this explode(',', $input);

or
if result set is file go through this post

```<code>explode(PHP_EOL, $input);
</code>```

https://stackoverflow.com/a/29471912/4895810

Body:
I'm receiving data from a MSSQL database with PHP (using PDO sqlsrv driver).

I need to split the string by new line.

In the DB the string looks like this:

I tried the following with no success:

$text = explode("\n\n",$text);
$text = preg_split("/\n\n/",$text);

Or

$text = explode("\n",$text);
$text = preg_split("/\n/",$text);

When i debug the code and when i print the text to the browser the string appears as one line.

But if i inspect the element in chrome, it is displayed exactly like in the database:

I copied the text from the inspector to a regex tester and the newlines were found successfully! But the "echoed" text was in one line.

Body:
Try replacing new line character with comma (,) or something other special char.

preg_replace("/((\r?\n)|(\r\n?))/", ',', $input);

Then try to explode like this explode(',', $input);

or
if result set is file go through this post

explode(PHP_EOL, $input);

https://stackoverflow.com/a/29471912/4895810


问:
How do I get the parent's class name in Ruby
Let assume I have a classes A and B where B inherits A. How do I print parent class name in B

```<code>class A
end

class B < A
end
</code>```

Some things I have tried

```<code>>> B.new.class #=> B   #which is correct
>> B.new.parent  #=> Undefined method `parent`
>> B.parent   #=> Object
>> B.parent.class #=> Class
</code>```

Thanks :)

答:
Inheritance is a relation between two classes. Inheritance create a
  parent child relationship between classes. It is a mechanism for code
  reuse and to allow independent extensions of the original software via
  public classes and interfaces.The benefit of inheritance is that
  classes lower down the hierarchy get the features of those higher up,
  but can also add specific features of their own.

In Ruby, a class can only inherit from a single other class. (i.e. a class can inherit from a class that inherits from another class which inherits from another class, but a single class can not inherit from many classes at once). The BasicObject class is the parent class of all classes in Ruby. Its methods are therefore available to all objects unless explicitly overridden.

Ruby overcome the single class inheritance at once by using the mixin.

I will try to explain with an example.

```<code>module Mux
 def sam
  p "I am an module"
 end
end
class A
  include Mux
end
class B < A
end
class C < B
end
class D < A
end
</code>```

You can trace by using class_name.superclass.name and do this process unless you found BasicOject in this hierarchy. BasicObject is super class o every classes. lets see suppose we want to see class C hierarchy tree.

```<code> C.superclass
   => B
 B.superclass
  => A
 A.superclass
  => Object
 Object.superclass
  => BasicObject
</code>```

You can see the whole hierarchy of class C. Point to note using this approach you will not find modules that are included or prepended in the parent classes.

There is another approach to find complete hierarchy including modules. According to Ruby doc ancestors. Returns a list of modules included/prepended in mod (including mod itself).

```<code>C.ancestors
 => [C, B, A, Mux, Object, Kernel, BasicObject]
</code>```

Here, Mux and Kernel are Modules.

http://rubylearning.com/satishtalim/ruby_inheritance.html
https://en.wikipedia.org/wiki/Inheritance_(object-oriented_programming)

Body:
Let assume I have a classes A and B where B inherits A. How do I print parent class name in B

class A
end

class B < A
end

Some things I have tried

>> B.new.class #=> B   #which is correct
>> B.new.parent  #=> Undefined method `parent`
>> B.parent   #=> Object
>> B.parent.class #=> Class

Thanks :)

Body:
Inheritance is a relation between two classes. Inheritance create a
  parent child relationship between classes. It is a mechanism for code
  reuse and to allow independent extensions of the original software via
  public classes and interfaces.The benefit of inheritance is that
  classes lower down the hierarchy get the features of those higher up,
  but can also add specific features of their own.

In Ruby, a class can only inherit from a single other class. (i.e. a class can inherit from a class that inherits from another class which inherits from another class, but a single class can not inherit from many classes at once). The BasicObject class is the parent class of all classes in Ruby. Its methods are therefore available to all objects unless explicitly overridden.

Ruby overcome the single class inheritance at once by using the mixin.

I will try to explain with an example.

module Mux
 def sam
  p "I am an module"
 end
end
class A
  include Mux
end
class B < A
end
class C < B
end
class D < A
end

You can trace by using class_name.superclass.name and do this process unless you found BasicOject in this hierarchy. BasicObject is super class o every classes. lets see suppose we want to see class C hierarchy tree.

 C.superclass
   => B
 B.superclass
  => A
 A.superclass
  => Object
 Object.superclass
  => BasicObject

You can see the whole hierarchy of class C. Point to note using this approach you will not find modules that are included or prepended in the parent classes.

There is another approach to find complete hierarchy including modules. According to Ruby doc ancestors. Returns a list of modules included/prepended in mod (including mod itself).

C.ancestors
 => [C, B, A, Mux, Object, Kernel, BasicObject]

Here, Mux and Kernel are Modules.

http://rubylearning.com/satishtalim/ruby_inheritance.html
https://en.wikipedia.org/wiki/Inheritance_(object-oriented_programming)


问:
Looping queue with jQuery
I've got some very simple code below that I want to use as a starting point for a bigger jQuery solution. I need for the count() function to loop, but am not able to achieve this with the code below which only runs once and then stops. Would appreciate some pointers.</p>

```<code>$(function() {
    count();
});

function count(){
    var $count = parseInt($("#count").text());
    $("#count").text($count).delay(2000).queue(function() {
        $(this).text($count+1);
        count();
    });
}
</code>```

答:
You need to call the next function in the queue, like this:

```<code>$(count);

function count(){
    var $count = parseInt($("#count").text());
    $("#count").text($count).delay(2000).queue(function(n) {
        $(this).text($count+1);
        count();
        n();
    });
}
</code>```

You can test it out here. Alternatively, you could replace n() with $(this).dequeue(), either way works.  If it helps, you could also slim it down a bit, like this:

```<code>$(count);
function count(){
    $("#count").delay(2000).queue(function(n) {
        count();
        $(this).text(function(i, t) { return parseInt(t, 10)+1; }).dequeue();
    });
}
</code>```

You can test that version here.

Title: Looping queue with jQuery

Body:
I've got some very simple code below that I want to use as a starting point for a bigger jQuery solution. I need for the count() function to loop, but am not able to achieve this with the code below which only runs once and then stops. Would appreciate some pointers.

$(function() {
    count();
});

function count(){
    var $count = parseInt($("#count").text());
    $("#count").text($count).delay(2000).queue(function() {
        $(this).text($count+1);
        count();
    });
}

Body:
You need to call the next function in the queue, like this:

$(count);

function count(){
    var $count = parseInt($("#count").text());
    $("#count").text($count).delay(2000).queue(function(n) {
        $(this).text($count+1);
        count();
        n();
    });
}

You can test it out here. Alternatively, you could replace n() with $(this).dequeue(), either way works.  If it helps, you could also slim it down a bit, like this:

$(count);
function count(){
    $("#count").delay(2000).queue(function(n) {
        count();
        $(this).text(function(i, t) { return parseInt(t, 10)+1; }).dequeue();
    });
}

You can test that version here.