问:
IBDesignable View - need ViewController at design time
I'm creating an IBDesignable component so that I can see the component render live in the Xcode storyboard.  The component is simply a composition of other components.  Unfortunately, one of those components requires a UIViewController to function properly.  Yes, bad, but I have no control over it.

The component works fine running in the app, but does not render properly at design time because the UIViewController for that scene is not available.  I have tried

marching up the responder chain looking for a UIViewController

creating an IBOutlet on the component and connecting it to the View
Controller in the storyboard

Neither of these has worked; the View Controller is always nil.  Any suggestions?

答:
A UIViewController can not be render in IBDesignable Mode.
You just can IBDesignable in a view staff.

sample:

```<code>import UIKit

@IBDesignable
class SMButton: UIButton {

    override func layoutSubviews() {
        super.layoutSubviews()

        layer.cornerRadius = 6
        layer.borderColor = UIColor.baseInstagram.cgColor
        layer.borderWidth = 0.66

        titleLabel?.font = UIFont.systemFont(ofSize: 15)
        titleLabel?.textColor = UIColor.baseInstagram

    }

}
</code>```

The sample is a round button with border.

Body:
A UIViewController can not be render in IBDesignable Mode.
You just can IBDesignable in a view staff.

sample:

import UIKit

@IBDesignable
class SMButton: UIButton {

    override func layoutSubviews() {
        super.layoutSubviews()

        layer.cornerRadius = 6
        layer.borderColor = UIColor.baseInstagram.cgColor
        layer.borderWidth = 0.66

        titleLabel?.font = UIFont.systemFont(ofSize: 15)
        titleLabel?.textColor = UIColor.baseInstagram

    }

}

The sample is a round button with border.


来源: stackexchange

问:
Login is not working unless I remove the "." from ".config"
I am having trouble with my app. When my app.js is the same as below I get an error alert with undefined but if I remove the "." and leave it as config the login function works fine and returns a response. What am I doing wrong?

app.js

```<code>angular.module('app',['angular-jwt','angular-storage', 'ngRoute', 'ui.router'])
    .config(function  ($stateProvider, $urlRouterProvider, jwtInterceptorProvider, $httpProvider) {
    $urlRouterProvider.otherwise('/');
    $stateProvider
        .state("login", {
            url:"/login",
            controller: "loginController",
            templateUrl: "login.html"
        })

        .state("signup", {
            url:"/signup",
            controller: "/Controllers/signupController",
            templateUrl: "register.html"
        });

    jwtInterceptorProvider.tokenGetter = function (store) {
        return store.get('jwt');
    };

    $httpProvider.interceptors.push('jwtInterceptor');

})
    .run(function($rootScope, $state, store, jwtHelper) {
    $rootScope.$on('$stateChangeStart', function(e, to) {
        if (to.data && to.data.requiresLogin) {
            if (!store.get('jwt') || jwtHelper.isTokenExpired(store.get('jwt'))) {
                e.preventDefault();
                $state.go('login');
            }
        }
    });
});
</code>```

loginController.js

```<code>'use strict';

angular.module('app')
    .controller('loginController', function ($scope, $http, $state, store) {
    $scope.user = {};
    $scope.login = function() {
        $http({
            url: '',
            method: 'POST',
            data: $scope.user
        }).then(function(response) {
            console.log("res", response.data.token);
            store.set('jwt', response.data.token);
            var test1 = store.get('jwt');
            console.log("get", test1);
            //$state.go('login');
        }, function(error) {
            console.log();
            alert(error.data);
        });
    }
});
</code>```

login.html

```<code><body class="main" ng-app="app" ng-controller="loginController">
  <div class="form" data-ix="new-interaction-2">
    <label class="field-label" for="Name-2">Email</label>
      <input class="text-field-2 w-input" data-name="name" id="Name-2" maxlength="256" name="name" placeholder="Email" required="required" type="email" ng-model="user.email">
    <label for="Password-2">Password:</label>
      <input class="text-field w-input" data-name="Password" id="Password-2" maxlength="256" name="Password" placeholder="Password" required="required" type="password" ng-model="user.password">
  </div>
</div>

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js" type="text/javascript"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.4/angular.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/angular-ui-router/1.0.3/angular-ui-router.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/angular-messages/1.6.4/angular-messages.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/angular-storage/0.0.15/angular-storage.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.1/angular-route.js"></script>
    <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular-resource.js" type="text/javascript"></script>
    <script src="/app.js"></script>
    <script src="/node_modules/angular-jwt/dist/angular-jwt.js"></script>
    <script src="/Controllers/loginController.js"></script>
    <script src="/Controllers/testController.js"></script>
</code>```

My file structure

答:
Fixed it. Had to whitelist my domain in app.js by adding</p>

```<code>jwtOptionsProvider.config({
    whiteListedDomains: ['api.api', 'localhost']
});
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am having trouble with my app. When my app.js is the same as below I get an error alert with undefined but if I remove the "." and leave it as config the login function works fine and returns a response. What am I doing wrong?

app.js

angular.module('app',['angular-jwt','angular-storage', 'ngRoute', 'ui.router'])
    .config(function  ($stateProvider, $urlRouterProvider, jwtInterceptorProvider, $httpProvider) {
    $urlRouterProvider.otherwise('/');
    $stateProvider
        .state("login", {
            url:"/login",
            controller: "loginController",
            templateUrl: "login.html"
        })

        .state("signup", {
            url:"/signup",
            controller: "/Controllers/signupController",
            templateUrl: "register.html"
        });

    jwtInterceptorProvider.tokenGetter = function (store) {
        return store.get('jwt');
    };

    $httpProvider.interceptors.push('jwtInterceptor');

})
    .run(function($rootScope, $state, store, jwtHelper) {
    $rootScope.$on('$stateChangeStart', function(e, to) {
        if (to.data && to.data.requiresLogin) {
            if (!store.get('jwt') || jwtHelper.isTokenExpired(store.get('jwt'))) {
                e.preventDefault();
                $state.go('login');
            }
        }
    });
});

loginController.js

'use strict';

angular.module('app')
    .controller('loginController', function ($scope, $http, $state, store) {
    $scope.user = {};
    $scope.login = function() {
        $http({
            url: '',
            method: 'POST',
            data: $scope.user
        }).then(function(response) {
            console.log("res", response.data.token);
            store.set('jwt', response.data.token);
            var test1 = store.get('jwt');
            console.log("get", test1);
            //$state.go('login');
        }, function(error) {
            console.log();
            alert(error.data);
        });
    }
});

login.html

    Email
      <input class="text-field-2 w-input" data-name="name" id="Name-2" maxlength="256" name="name" placeholder="Email" required="required" type="email" ng-model="user.email">
    Password:
      <input class="text-field w-input" data-name="Password" id="Password-2" maxlength="256" name="Password" placeholder="Password" required="required" type="password" ng-model="user.password">

My file structure

Body:
Fixed it. Had to whitelist my domain in app.js by adding

jwtOptionsProvider.config({
    whiteListedDomains: ['api.api', 'localhost']
});


问:
In jquery, what's the difference between '.add()' and ',' (comma)?
I know that many things can be done in different ways, none of which necessarily and always better than others; So, having multiple ways to do the same is generally good: but, the jQuery '.add()' method and the jQuery comma selector are just two ways to do the same thing or differ from one another (in this particular use as selector)?

```<code> $("p").add("span").css("background", "yellow");
 $("p, span").css("background", "yellow");
</code>```

https://jsfiddle.net/rudijuri/gg3vfmcp/3/

(sorry for the external link to jsfiddle, but the snippet doesn't work using touch device, like mine now)

答:
In this case use it as a parallel selector or both p and span objects, if you want to select the spans that are in the p objects you have to insert:

```<code>$("p > span").css("background", "yellow");
</code>```

or

```<code>$("p").find("span").css("background", "yellow");
</code>```

Body:
I know that many things can be done in different ways, none of which necessarily and always better than others; So, having multiple ways to do the same is generally good: but, the jQuery '.add()' method and the jQuery comma selector are just two ways to do the same thing or differ from one another (in this particular use as selector)?

 $("p").add("span").css("background", "yellow");
 $("p, span").css("background", "yellow");

https://jsfiddle.net/rudijuri/gg3vfmcp/3/

(sorry for the external link to jsfiddle, but the snippet doesn't work using touch device, like mine now)

Body:
In this case use it as a parallel selector or both p and span objects, if you want to select the spans that are in the p objects you have to insert:

$("p > span").css("background", "yellow");

or

$("p").find("span").css("background", "yellow");


问:
Docker Cannot link to a non running container
I need to create Rails and Mysql containers with docker-compose. When I try to create links between containers with docker-compose up, I get

Cannot start container
  9b271c58cf6aecaf017dadaf5b Cannot link to a non running container:
  /puma_db_1 AS /puma_web_1/db

Files

Dockerfile

```<code>FROM ubuntu:14.04

RUN apt-get -y update
RUN apt-get -y install git curl zlib1g-dev build-essential libssl-dev libreadline-dev libyaml-dev libsqlite3-dev sqlite3 libxml2-dev libxslt1-dev libcurl4-openssl-dev python-software-properties libffi-dev

RUN apt-get -y install libmysqlclient-dev
RUN git clone https://github.com/sstephenson/rbenv.git /root/.rbenv
RUN git clone https://github.com/sstephenson/ruby-build.git /root/.rbenv/plugins/ruby-build
RUN echo 'eval "$(rbenv init -)"' >> $HOME/.profile
RUN echo 'eval "$(rbenv init -)"' >> $HOME/.bashrc

RUN rbenv install 2.1.5
RUN rbenv global 2.1.5
RUN gem install rails -v 4.0.11

ADD app.tar.gz /home/
WORKDIR /home/app

RUN bundle install
EXPOSE 3000
CMD ["rails", "server", "-b", "0.0.0.0"]
</code>```

docker-compose.yml

```<code>db:
  image: mysql:latest
  environment:
    MYSQL_DATABASE: app_development
    MYSQL_USER: mysql
    DATABASE_PASSWORD: onetwo
    ROOT_PASSWORD: onetwo
web:
  build: .
  command: bundle exec rails s -p 3000 -b '0.0.0.0'
  ports:
    - "4000:3000"
  links:
    - db
</code>```

答:
Issue:

I have gotten this error whenever docker-compose successfully
builds a set of Images, but one of those Imagesfails to
run (e.g. launch into its own Container).

In this case, I suspect the Image, underlying your
puma_db_1 Container, is failing to run. You can
find the name of this Image by running docker ps -a. That said, its name is most likely puma_db

Solution:

To get at the cause, you can try docker-compose up
<service_name> or docker-compose up db

Alternatively, I find the error message by running docker run
<image_name> more useful. In this case, that would be docker
run puma_db

ContentLicense: CC BY-SA 4.0

Body:
I need to create Rails and Mysql containers with docker-compose. When I try to create links between containers with docker-compose up, I get

Cannot start container
  9b271c58cf6aecaf017dadaf5b Cannot link to a non running container:
  /puma_db_1 AS /puma_web_1/db

Files

Dockerfile

FROM ubuntu:14.04

RUN apt-get -y update
RUN apt-get -y install git curl zlib1g-dev build-essential libssl-dev libreadline-dev libyaml-dev libsqlite3-dev sqlite3 libxml2-dev libxslt1-dev libcurl4-openssl-dev python-software-properties libffi-dev

RUN apt-get -y install libmysqlclient-dev
RUN git clone https://github.com/sstephenson/rbenv.git /root/.rbenv
RUN git clone https://github.com/sstephenson/ruby-build.git /root/.rbenv/plugins/ruby-build
RUN echo 'eval "$(rbenv init -)"' >> $HOME/.profile
RUN echo 'eval "$(rbenv init -)"' >> $HOME/.bashrc

RUN rbenv install 2.1.5
RUN rbenv global 2.1.5
RUN gem install rails -v 4.0.11

ADD app.tar.gz /home/
WORKDIR /home/app

RUN bundle install
EXPOSE 3000
CMD ["rails", "server", "-b", "0.0.0.0"]

docker-compose.yml

db:
  image: mysql:latest
  environment:
    MYSQL_DATABASE: app_development
    MYSQL_USER: mysql
    DATABASE_PASSWORD: onetwo
    ROOT_PASSWORD: onetwo
web:
  build: .
  command: bundle exec rails s -p 3000 -b '0.0.0.0'
  ports:
    - "4000:3000"
  links:
    - db


问:
Why does $.getJSON() block the browser?
I have a page where I list hardware devices we monitor for customers. Each row displayed also shows the status of the device i.e. whether it's running, paused, starting up etc.

To improve page load times I list the devices but don't query for their status until the page is rendered. This is because some queries such as via SNMP or other API's can take as much as 5-10 seconds to respond. So for a list of say ten devices it could take well over a minute of the user looking at a blank page. So I do the following instead -

On the device list page I have the following script:

```<code>$(document).ready(function () {

  var devices = $('div[name="runStatus"]');
  devices.each(function () {

    // Get device ID (I embed this using the HTML5 data-* attributes/annotations)
    var deviceId = $(this).attr("data-deviceid");
    var url = "/devmanager/status/" + deviceId;

    $.getJSON(url, function (response) {
      // Not actually important to the question...set text status, colours etc
      $('div[data-deviceid="' + deviceId + '"]').text(response);
      //...
    });
  });
});
</code>```

What I'm finding is that if I allow this script to run, all links on the page become unresponsive.

I'm guessing this is because I've quite a few almost parallel async requests blocking until they get a response from the server and somehow the "UI thread" is being blocked by this?

However I thought this wasn't supposed to happen with AJAX.

I find this 'blocking' behaviour to happen in IE8, Chrome 8.0 and Firefox 3.6. Chrome in fact shows the arrow cursor + spinning-toilet-bowl-of-death (I'm using Windows 7) as if the page isn't completely rendered.

How can I fix this?

答:
Turns out this isn't a problem with the client side:

Would multiple calls to the same ASP.NET MVC action cause the browser to block?

Would multiple calls to the same ASP.NET MVC action cause the browser to block? - Answer

This was being caused by a "by-design" feature of ASP.NET where multiple requests made in the same session are serialised.

ContentLicense: CC BY-SA 2.5

Title: Why does $.getJSON() block the browser?

Body:
I have a page where I list hardware devices we monitor for customers. Each row displayed also shows the status of the device i.e. whether it's running, paused, starting up etc.

To improve page load times I list the devices but don't query for their status until the page is rendered. This is because some queries such as via SNMP or other API's can take as much as 5-10 seconds to respond. So for a list of say ten devices it could take well over a minute of the user looking at a blank page. So I do the following instead -

On the device list page I have the following script:

$(document).ready(function () {

  var devices = $('div[name="runStatus"]');
  devices.each(function () {

    // Get device ID (I embed this using the HTML5 data-* attributes/annotations)
    var deviceId = $(this).attr("data-deviceid");
    var url = "/devmanager/status/" + deviceId;

    $.getJSON(url, function (response) {
      // Not actually important to the question...set text status, colours etc
      $('div[data-deviceid="' + deviceId + '"]').text(response);
      //...
    });
  });
});

What I'm finding is that if I allow this script to run, all links on the page become unresponsive.

I'm guessing this is because I've quite a few almost parallel async requests blocking until they get a response from the server and somehow the "UI thread" is being blocked by this?

However I thought this wasn't supposed to happen with AJAX.

I find this 'blocking' behaviour to happen in IE8, Chrome 8.0 and Firefox 3.6. Chrome in fact shows the arrow cursor + spinning-toilet-bowl-of-death (I'm using Windows 7) as if the page isn't completely rendered.

How can I fix this?


问:
Update to 1.11: TypeError build_attrs() takes at most 2 arguments (3 given)
I a updating from 1.10.7 to 1.11.0 and I am getting the following error when viewing a form. I cannot fathom what is wrong with my form at all. Other forms work in the same way. I suspect that it could be an interaction with either select2 or markdownx but there is no indication that those are incompatible with 1.11.

How can I debug this further?

```<code>File "/home/usr/.virtualenvs/intranet/lib/python2.7/site-packages/django/core/handlers/exception.py" in inner
  41.             response = get_response(request)

File "/home/usr/.virtualenvs/intranet/lib/python2.7/site-packages/django/core/handlers/base.py" in _get_response
  187.                 response = self.process_exception_by_middleware(e, request)

File "/home/usr/.virtualenvs/intranet/lib/python2.7/site-packages/django/core/handlers/base.py" in _get_response
  185.                 response = wrapped_callback(request, *callback_args, **callback_kwargs)

File "/home/usr/.virtualenvs/intranet/lib/python2.7/site-packages/django/contrib/auth/decorators.py" in _wrapped_view
  23.                 return view_func(request, *args, **kwargs)

File "/home/usr/.virtualenvs/intranet/lib/python2.7/site-packages/django/contrib/auth/decorators.py" in _wrapped_view
  23.                 return view_func(request, *args, **kwargs)

File "/home/usr/repos/intranet/isotek_intranet_site/order_book/views.py" in create
  161.     return render(request, 'order_book/create.html', context)

File "/home/usr/.virtualenvs/intranet/lib/python2.7/site-packages/django/shortcuts.py" in render
  30.     content = loader.render_to_string(template_name, context, request, using=using)

File "/home/usr/.virtualenvs/intranet/lib/python2.7/site-packages/django/template/loader.py" in render_to_string
  68.     return template.render(context, request)

File "/home/usr/.virtualenvs/intranet/lib/python2.7/site-packages/django/template/backends/django.py" in render
  66.             return self.template.render(context)

File "/home/usr/.virtualenvs/intranet/lib/python2.7/site-packages/django/template/base.py" in render
  207.                     return self._render(context)

File "/home/usr/.virtualenvs/intranet/lib/python2.7/site-packages/django/template/base.py" in _render
  199.         return self.nodelist.render(context)

File "/home/usr/.virtualenvs/intranet/lib/python2.7/site-packages/django/template/base.py" in render
  990.                 bit = node.render_annotated(context)

File "/home/usr/.virtualenvs/intranet/lib/python2.7/site-packages/django/template/base.py" in render_annotated
  957.             return self.render(context)

File "/home/usr/.virtualenvs/intranet/lib/python2.7/site-packages/django/template/loader_tags.py" in render
  177.             return compiled_parent._render(context)

File "/home/usr/.virtualenvs/intranet/lib/python2.7/site-packages/django/template/base.py" in _render
  199.         return self.nodelist.render(context)

File "/home/usr/.virtualenvs/intranet/lib/python2.7/site-packages/django/template/base.py" in render
  990.                 bit = node.render_annotated(context)

File "/home/usr/.virtualenvs/intranet/lib/python2.7/site-packages/django/template/base.py" in render_annotated
  957.             return self.render(context)

File "/home/usr/.virtualenvs/intranet/lib/python2.7/site-packages/django/template/loader_tags.py" in render
  72.                 result = block.nodelist.render(context)

File "/home/usr/.virtualenvs/intranet/lib/python2.7/site-packages/django/template/base.py" in render
  990.                 bit = node.render_annotated(context)

File "/home/usr/.virtualenvs/intranet/lib/python2.7/site-packages/django/template/base.py" in render_annotated
  957.             return self.render(context)

File "/home/usr/.virtualenvs/intranet/lib/python2.7/site-packages/django/template/base.py" in render
  1046.         return render_value_in_context(output, context)

File "/home/usr/.virtualenvs/intranet/lib/python2.7/site-packages/django/template/base.py" in render_value_in_context
  1024.     value = force_text(value)

File "/home/usr/.virtualenvs/intranet/lib/python2.7/site-packages/django/utils/encoding.py" in force_text
  78.                 s = six.text_type(s)

File "/home/usr/.virtualenvs/intranet/lib/python2.7/site-packages/django/utils/html.py" in <lambda>
  376.         klass.__unicode__ = lambda self: mark_safe(klass_unicode(self))

File "/home/usr/.virtualenvs/intranet/lib/python2.7/site-packages/django/forms/boundfield.py" in __str__
  41.         return self.as_widget()

File "/home/usr/.virtualenvs/intranet/lib/python2.7/site-packages/django/forms/boundfield.py" in as_widget
  120.             **kwargs

File "/home/usr/.virtualenvs/intranet/lib/python2.7/site-packages/django/forms/widgets.py" in render
  220.         context = self.get_context(name, value, attrs)

File "/home/usr/.virtualenvs/intranet/lib/python2.7/site-packages/django/forms/widgets.py" in get_context
  665.         context = super(Select, self).get_context(name, value, attrs)

File "/home/usr/.virtualenvs/intranet/lib/python2.7/site-packages/django/forms/widgets.py" in get_context
  626.         context = super(ChoiceWidget, self).get_context(name, value, attrs)

File "/home/usr/.virtualenvs/intranet/lib/python2.7/site-packages/django/forms/widgets.py" in get_context
  211.             'attrs': self.build_attrs(self.attrs, attrs),

Exception Type: TypeError at /order_book/create/
Exception Value: build_attrs() takes at most 2 arguments (3 given)
</code>```

The template:

```<code><form action="/order_book/invoice/create/" method="post">
{% csrf_token %}
<input type='hidden' name='action' value='create'>

<table>
    <tr>
        <td>{{ form.active.label }}</td>
        <td>{{ form.active }}</td>
    </tr>
    <!-- other entries like the one above… -->
    <tr>
        <td>
            <button type="submit" value="Add"><img src="/static/images/tick.png" alt="Set">
                Create new project code</button>
        </td>
    </tr>
</table>
</code>```

The view:

```<code>def create_code(request):  # pragma: no cover
    context = {}
    if request.method == 'POST':
        form = MyForm(request.POST)
        if form.is_valid():
            pass  # Clearly for testing…
    form = MyForm()
    context['form'] = form
    return render(request, 'order_book/create_code.html', context)
</code>```

The form:

```<code>class MyForm(forms.ModelForm):

    class Meta:
        model = MyModel
        fields = '__all__'
        widgets = {
           'manager': Select2Widget(attrs={'style': 'min-width:400px'}),
        }
</code>```

答:
In the Django 1.11 update, they change the build_attrs class to use only 2 arguments, where all your extra arguments should now be passed in a dict.

So when you use a custom widget that uses the build_attrs function, you need to change the build_attrs call from:

```<code>build_attrs(attrs, foo='bizz', bar='baz')
</code>```

to:

```<code>build_attrs(attrs, {'foo':'bizz', 'bar':'baz'})
</code>```

Thus the culprit is the Select2 class. You can fix it yourself by super-classing and overwriting the render function with the new method or you can check if the author has an update.

Body:
I a updating from 1.10.7 to 1.11.0 and I am getting the following error when viewing a form. I cannot fathom what is wrong with my form at all. Other forms work in the same way. I suspect that it could be an interaction with either select2 or markdownx but there is no indication that those are incompatible with 1.11.

How can I debug this further?

File "/home/usr/.virtualenvs/intranet/lib/python2.7/site-packages/django/core/handlers/exception.py" in inner
  41.             response = get_response(request)

File "/home/usr/.virtualenvs/intranet/lib/python2.7/site-packages/django/core/handlers/base.py" in _get_response
  187.                 response = self.process_exception_by_middleware(e, request)

File "/home/usr/.virtualenvs/intranet/lib/python2.7/site-packages/django/core/handlers/base.py" in _get_response
  185.                 response = wrapped_callback(request, *callback_args, **callback_kwargs)

File "/home/usr/.virtualenvs/intranet/lib/python2.7/site-packages/django/contrib/auth/decorators.py" in _wrapped_view
  23.                 return view_func(request, *args, **kwargs)

File "/home/usr/.virtualenvs/intranet/lib/python2.7/site-packages/django/contrib/auth/decorators.py" in _wrapped_view
  23.                 return view_func(request, *args, **kwargs)

File "/home/usr/repos/intranet/isotek_intranet_site/order_book/views.py" in create
  161.     return render(request, 'order_book/create.html', context)

File "/home/usr/.virtualenvs/intranet/lib/python2.7/site-packages/django/shortcuts.py" in render
  30.     content = loader.render_to_string(template_name, context, request, using=using)

File "/home/usr/.virtualenvs/intranet/lib/python2.7/site-packages/django/template/loader.py" in render_to_string
  68.     return template.render(context, request)

File "/home/usr/.virtualenvs/intranet/lib/python2.7/site-packages/django/template/backends/django.py" in render
  66.             return self.template.render(context)

File "/home/usr/.virtualenvs/intranet/lib/python2.7/site-packages/django/template/base.py" in render
  207.                     return self._render(context)

File "/home/usr/.virtualenvs/intranet/lib/python2.7/site-packages/django/template/base.py" in _render
  199.         return self.nodelist.render(context)

File "/home/usr/.virtualenvs/intranet/lib/python2.7/site-packages/django/template/base.py" in render
  990.                 bit = node.render_annotated(context)

File "/home/usr/.virtualenvs/intranet/lib/python2.7/site-packages/django/template/base.py" in render_annotated
  957.             return self.render(context)

File "/home/usr/.virtualenvs/intranet/lib/python2.7/site-packages/django/template/loader_tags.py" in render
  177.             return compiled_parent._render(context)

File "/home/usr/.virtualenvs/intranet/lib/python2.7/site-packages/django/template/base.py" in _render
  199.         return self.nodelist.render(context)

File "/home/usr/.virtualenvs/intranet/lib/python2.7/site-packages/django/template/base.py" in render
  990.                 bit = node.render_annotated(context)

File "/home/usr/.virtualenvs/intranet/lib/python2.7/site-packages/django/template/base.py" in render_annotated
  957.             return self.render(context)

File "/home/usr/.virtualenvs/intranet/lib/python2.7/site-packages/django/template/loader_tags.py" in render
  72.                 result = block.nodelist.render(context)

File "/home/usr/.virtualenvs/intranet/lib/python2.7/site-packages/django/template/base.py" in render
  990.                 bit = node.render_annotated(context)

File "/home/usr/.virtualenvs/intranet/lib/python2.7/site-packages/django/template/base.py" in render_annotated
  957.             return self.render(context)

File "/home/usr/.virtualenvs/intranet/lib/python2.7/site-packages/django/template/base.py" in render
  1046.         return render_value_in_context(output, context)

File "/home/usr/.virtualenvs/intranet/lib/python2.7/site-packages/django/template/base.py" in render_value_in_context
  1024.     value = force_text(value)

File "/home/usr/.virtualenvs/intranet/lib/python2.7/site-packages/django/utils/encoding.py" in force_text
  78.                 s = six.text_type(s)

File "/home/usr/.virtualenvs/intranet/lib/python2.7/site-packages/django/utils/html.py" in <lambda>
  376.         klass.__unicode__ = lambda self: mark_safe(klass_unicode(self))

File "/home/usr/.virtualenvs/intranet/lib/python2.7/site-packages/django/forms/boundfield.py" in __str__
  41.         return self.as_widget()

File "/home/usr/.virtualenvs/intranet/lib/python2.7/site-packages/django/forms/boundfield.py" in as_widget
  120.             **kwargs

File "/home/usr/.virtualenvs/intranet/lib/python2.7/site-packages/django/forms/widgets.py" in render
  220.         context = self.get_context(name, value, attrs)

File "/home/usr/.virtualenvs/intranet/lib/python2.7/site-packages/django/forms/widgets.py" in get_context
  665.         context = super(Select, self).get_context(name, value, attrs)

File "/home/usr/.virtualenvs/intranet/lib/python2.7/site-packages/django/forms/widgets.py" in get_context
  626.         context = super(ChoiceWidget, self).get_context(name, value, attrs)

File "/home/usr/.virtualenvs/intranet/lib/python2.7/site-packages/django/forms/widgets.py" in get_context
  211.             'attrs': self.build_attrs(self.attrs, attrs),

Exception Type: TypeError at /order_book/create/
Exception Value: build_attrs() takes at most 2 arguments (3 given)

The template:

<form action="/order_book/invoice/create/" method="post">
{% csrf_token %}
<input type='hidden' name='action' value='create'>

        {{ form.active.label }}
        {{ form.active }}

            <button type="submit" value="Add">
                Create new project code</button>

The view:

def create_code(request):  # pragma: no cover
    context = {}
    if request.method == 'POST':
        form = MyForm(request.POST)
        if form.is_valid():
            pass  # Clearly for testing…
    form = MyForm()
    context['form'] = form
    return render(request, 'order_book/create_code.html', context)

The form:

class MyForm(forms.ModelForm):

    class Meta:
        model = MyModel
        fields = '__all__'
        widgets = {
           'manager': Select2Widget(attrs={'style': 'min-width:400px'}),
        }

Body:
In the Django 1.11 update, they change the build_attrs class to use only 2 arguments, where all your extra arguments should now be passed in a dict.

So when you use a custom widget that uses the build_attrs function, you need to change the build_attrs call from:

build_attrs(attrs, foo='bizz', bar='baz')

to:

build_attrs(attrs, {'foo':'bizz', 'bar':'baz'})

Thus the culprit is the Select2 class. You can fix it yourself by super-classing and overwriting the render function with the new method or you can check if the author has an update.


问:
copy bytes without memcpy()
It's a home work. I want to implement memcpy(). I was told memory area must not overlap. Actually I don't understand what that means, because this code works fine, but there is a possibility of memory overlap. How to prevent it?

```<code>void *mem_copy(void *dest, const void *src, unsigned int n) {
    assert((src != NULL) && (n > 0));
    int i = 0;
    char *newsrc = (char*)src;
    char *newdest = (char*)dest;
    while (i < n) {
        newdest[i] = newsrc[i];
        i++;
    }
    newdest[i]='\0';
    return newdest;
}
</code>```

答:
There are some issues in your re-implementation of memcpy():

The size argument n should have type size_t.  The index variable i should have the same type as the size argument.

It is OK to pass a count of 0. Indeed your code would behave correctly in this case, remove the test from the assert().

Avoid casting away the const qualifier unless absolutely necessary.

Do not tack a '\0' at the end of the destination, it is incorrect and will cause buffer overruns.

Here is a corrected version:

```<code>void *mem_copy(void *dest, const void *src, size_t n) {
    assert(n == 0 || (src != NULL && dest != NULL));
    size_t i = 0;
    const char *newsrc = (const char *)src;
    char *newdest = (char *)dest;
    while (i < n) {
        newdest[i] = newsrc[i];
        i++;
    }
    return dest;
}
</code>```

Regarding the potential overlap between the source area and the destination area, your code's behavior will be surprising if the destination pointer is greater than the source, but within the source area:

```<code>char buffer[10] = "12345";
printf("before: %s\n", buffer);
mem_copy(buffer + 1, buffer, 5);
printf("after: %s\n", buffer);
</code>```

Will output:

```<code>before: 12345
after: 111111
</code>```

There is no completely portable way to test for such overlap, but it is quite easy on non exotic architectures at some small cost in execution time and code size.  The semantics of memcpy() is that no such test is assumed to be performed by the library, so the programmer should only call this function if there is no possibility for source and destination areas to overlap.  When in doubt, use memmove() that handles overlapping areas correctly.

If you wish to add an assert for this, here is a mostly portable one:

```<code>assert(n == 0 || newdest + n <= newsrc || newdest >= newsrc + n);
</code>```

Here is a simple rewrite of memmove(), albeit not completely portable:

```<code>void *mem_move(void *dest, const void *src, size_t n) {
    assert(n == 0 || (src != NULL && dest != NULL));
    const char *newsrc = (const char *)src;
    char *newdest = (char *)dest;
    if (newdest <= newsrc || newdest >= newsrc + n) {
        /* Copying forward */
        for (size_t i = 0; i < n; i++) {
            newdest[i] = newsrc[i];
        }
    } else {
        /* Copying backwards */
        for (size_t i = n; i-- > 0;) {
            newdest[i] = newsrc[i];
        }
    }
    return dest;
}
</code>```

Title: copy bytes without memcpy()

Body:
It's a home work. I want to implement memcpy(). I was told memory area must not overlap. Actually I don't understand what that means, because this code works fine, but there is a possibility of memory overlap. How to prevent it?

void *mem_copy(void *dest, const void *src, unsigned int n) {
    assert((src != NULL) && (n > 0));
    int i = 0;
    char *newsrc = (char*)src;
    char *newdest = (char*)dest;
    while (i < n) {
        newdest[i] = newsrc[i];
        i++;
    }
    newdest[i]='\0';
    return newdest;
}

Body:
There are some issues in your re-implementation of memcpy():

The size argument n should have type size_t.  The index variable i should have the same type as the size argument.

It is OK to pass a count of 0. Indeed your code would behave correctly in this case, remove the test from the assert().

Avoid casting away the const qualifier unless absolutely necessary.

Do not tack a '\0' at the end of the destination, it is incorrect and will cause buffer overruns.

Here is a corrected version:

void *mem_copy(void *dest, const void *src, size_t n) {
    assert(n == 0 || (src != NULL && dest != NULL));
    size_t i = 0;
    const char *newsrc = (const char *)src;
    char *newdest = (char *)dest;
    while (i < n) {
        newdest[i] = newsrc[i];
        i++;
    }
    return dest;
}

Regarding the potential overlap between the source area and the destination area, your code's behavior will be surprising if the destination pointer is greater than the source, but within the source area:

char buffer[10] = "12345";
printf("before: %s\n", buffer);
mem_copy(buffer + 1, buffer, 5);
printf("after: %s\n", buffer);

Will output:

before: 12345
after: 111111

There is no completely portable way to test for such overlap, but it is quite easy on non exotic architectures at some small cost in execution time and code size.  The semantics of memcpy() is that no such test is assumed to be performed by the library, so the programmer should only call this function if there is no possibility for source and destination areas to overlap.  When in doubt, use memmove() that handles overlapping areas correctly.

If you wish to add an assert for this, here is a mostly portable one:

assert(n == 0 || newdest + n <= newsrc || newdest >= newsrc + n);

Here is a simple rewrite of memmove(), albeit not completely portable:

void *mem_move(void *dest, const void *src, size_t n) {
    assert(n == 0 || (src != NULL && dest != NULL));
    const char *newsrc = (const char *)src;
    char *newdest = (char *)dest;
    if (newdest <= newsrc || newdest >= newsrc + n) {
        /* Copying forward */
        for (size_t i = 0; i < n; i++) {
            newdest[i] = newsrc[i];
        }
    } else {
        /* Copying backwards */
        for (size_t i = n; i-- > 0;) {
            newdest[i] = newsrc[i];
        }
    }
    return dest;
}


问:
How to implement interface from a different package in golang?
I am beginner in golang and was trying interfaces. I want to keep interfaces in a separate packages so that I can use it to implement this in various other packages, also provide it to other teams (.a file) so that they can implement custom plugins. Please see example below on what I would like to achieve.

```<code>--- Folder structure ---
gitlab.com/myproject/
                  interfaces/
                            shaper.go
                  shapes/
                        rectangle.go
                        circle.go

---- shaper.go ---
package interfaces

type Shaper interface{

    Area() int

}
</code>```

How do I ensure that the rectangle.go implements shaper interface?
I understand that go implements interfaces implicitly, does this mean rectangle.go automatically implements shaper.go even though it is in a different package?

I tried it like below, but when I run gofmt tool, it removes the import because it is unused.

```<code>--- rectangle.go ---
package shapes

import "gitlab.com/myproject/interfaces"

type rectangle struct{

  length int
  width int
}

func (r rectangle) Area() int {
 return r.length * r.width
}
</code>```

Thanks in advance.

答:
Let's say you have a function that uses a Shaper. You can test the function with a rectangle, and by doing so ensuring the implementation:

```<code>func DoStuff(s Shaper) {
    s.Area()
}

func TestDoStuff(t *testing.T) {
    var s Shaper = rectangle{length: 5, width: 3}
    DoStuff(s)
    // assertion
}
</code>```

If rectangle does not implement Shaper, you'll get an error like this:

```<code>cannot use rectangle literal (type rectangle) as type Shaper in assignment:
rectangle does not implement Shaper (missing Area method)
</code>```

Effective Go:

Interfaces in Go provide a way to specify the behavior of an object: if something can do this, then it can be used here.

Body:
I am beginner in golang and was trying interfaces. I want to keep interfaces in a separate packages so that I can use it to implement this in various other packages, also provide it to other teams (.a file) so that they can implement custom plugins. Please see example below on what I would like to achieve.

--- Folder structure ---
gitlab.com/myproject/
                  interfaces/
                            shaper.go
                  shapes/
                        rectangle.go
                        circle.go

---- shaper.go ---
package interfaces

type Shaper interface{

    Area() int

}

How do I ensure that the rectangle.go implements shaper interface?
I understand that go implements interfaces implicitly, does this mean rectangle.go automatically implements shaper.go even though it is in a different package?

I tried it like below, but when I run gofmt tool, it removes the import because it is unused.

--- rectangle.go ---
package shapes

import "gitlab.com/myproject/interfaces"

type rectangle struct{

  length int
  width int
}

func (r rectangle) Area() int {
 return r.length * r.width
}

Thanks in advance.

Body:
Let's say you have a function that uses a Shaper. You can test the function with a rectangle, and by doing so ensuring the implementation:

func DoStuff(s Shaper) {
    s.Area()
}

func TestDoStuff(t *testing.T) {
    var s Shaper = rectangle{length: 5, width: 3}
    DoStuff(s)
    // assertion
}

If rectangle does not implement Shaper, you'll get an error like this:

cannot use rectangle literal (type rectangle) as type Shaper in assignment:
rectangle does not implement Shaper (missing Area method)

Effective Go:

Interfaces in Go provide a way to specify the behavior of an object: if something can do this, then it can be used here.


问:
Chrome Background-size not accurate?
I am having an issue with background images not scaling correctly in Chrome. I have included my code below as well a codepen link. You will notice that despite being set to 20% width, the background image does fit in perfectly 5 times. Does any one have a fix or workaround for this?

CSS

```<code>    #vsb-screen-preview {
    background-image: url(/screen-builder-screen.png);
    background-size: 20% 25%;
    background-position: top left;
    float: left;
    width: 454px;
    height: 316px;}

    .vsb-screen-preview-bg {
    float: left;
    overflow: hidden;
    width: auto;
    height: auto;
    box-shadow: 0px 0px 10px 5px rgba(0,0,0,1);
    background-image: url(/pexels-photo-361951.jpeg);
    background-size: cover;
    background-position: center center;
    position: relative;}
</code>```

HTML

```<code>    <div class="vsb-screen-preview-bg">
    <div id="vsb-screen-preview">
    </div>
    </div>
</code>```

Any assistance would be greatly appreciated.

https://codepen.io/anon/pen/BWMGrz

答:
The reason for this is a Chrome bug.  When you set the background size, it only repeats and multiplies in integers and not decimal numbers. So if your value is a float, scale or percentage, it will be wrong in Chrome.

I've just discovered that after 2 hours of trying to figure out why chrome spacing is different.

I haven't found a fix yet apart asking for as many people as possible to report the bug so they fix it.

Title: Chrome Background-size not accurate?

Body:
I am having an issue with background images not scaling correctly in Chrome. I have included my code below as well a codepen link. You will notice that despite being set to 20% width, the background image does fit in perfectly 5 times. Does any one have a fix or workaround for this?

CSS

    #vsb-screen-preview {
    background-image: url(/screen-builder-screen.png);
    background-size: 20% 25%;
    background-position: top left;
    float: left;
    width: 454px;
    height: 316px;}

    .vsb-screen-preview-bg {
    float: left;
    overflow: hidden;
    width: auto;
    height: auto;
    box-shadow: 0px 0px 10px 5px rgba(0,0,0,1);
    background-image: url(/pexels-photo-361951.jpeg);
    background-size: cover;
    background-position: center center;
    position: relative;}

HTML

Any assistance would be greatly appreciated.

https://codepen.io/anon/pen/BWMGrz


问:
where to get the pre-trained models for "Show and Tell: A Neural Image Caption Generator"?
I have no resource to train the training datasets for Show and Tell: A Neural Image Caption Generator, so where to get the pre-trained models?

答:
I haven't tried this, but it seems what you want: https://github.com/KranthiGV/Pretrained-Show-and-Tell-model

I have followed the great Readme at https://github.com/tensorflow/models/tree/master/research/im2txt and am able to build such a model in a few hours on my computer with GTX 1070, the details of which is described in my blog https://jeffxtang.github.io/deep/learning,/hardware,/gpu,/performance/2017/02/14/deep-learning-machine.html in case you're interested in the future.


问:
"Element not found 0x80070490" when installing ASP .Net Core tooling
I'm using Visual studio 2015 Update 3, I'm trying to install asp .net core Tooling package(DotNetCore.1.0.1-VS2015Tools.Preview2.0.3.exe)

I get this by either downloading it separately or when clicking at the
"ASP .NET 5 RC" template when creating a new ASP Net Web Application in VS.
After a while during the installation I get the error

"Element not found 0x80070490"

(also see log file at bottom)

After some searching:

I have tried starting it from cmd (as admin) with flag SKIP_VSU_CHECK=1
and I have tried to reinstall VC++ Distributables, these just gives me more errors when creating projects from templates. I have english as my VS language. I have also tried downloaded the v1.1, it installs ok but I can't see any difference in Visual studio

This is the end of the log file after my installation has failed:

[1E4C:1E48][2017-01-17T09:58:01]i360: Creating a system restore point.

[1E4C:1E48][2017-01-17T09:58:01]i361: Created a system restore point.

[1E4C:1E48][2017-01-17T09:58:01]i371: Updating session, registration
  key:
  SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall{da280276-4f5b-4918-8d40-20ca56dfa535},
  resume: Active, restart initiated: No, disable resume: No

[1E4C:1FD0][2017-01-17T09:58:02]i305: Verified acquired payload:
  SetupBlocked_Install at path: C:\ProgramData\Package
  Cache.unverified\SetupBlocked_Install, moving to:
  C:\ProgramData\Package
  Cache\f727b670-667c-3e6f-aafb-e48a72a2dea2\SetupBlocked_69.exe.

[1E4C:1E48][2017-01-17T09:58:02]i301: Applying execute package:
  SetupBlocked_Install, action: Install, path: C:\ProgramData\Package
  Cache\f727b670-667c-3e6f-aafb-e48a72a2dea2\SetupBlocked_69.exe,
  arguments: '"C:\ProgramData\Package
  Cache\f727b670-667c-3e6f-aafb-e48a72a2dea2\SetupBlocked_69.exe"'

[1E4C:1FD0][2017-01-17T09:58:02]i305: Verified acquired payload:
  Preparation_Uninstall_ASPNET at path: C:\ProgramData\Package
  Cache.unverified\Preparation_Uninstall_ASPNET, moving to:
  C:\ProgramData\Package
  Cache\50e2672c-aefb-300c-8301-d8ebba628476\Preparation_69.exe.

[1E4C:1FD0][2017-01-17T09:58:02]i304: Verified existing payload:
  ANCM_IISExpress_x64 at path: C:\ProgramData\Package
  Cache{C2BB4C41-59DC-487E-9CCF-1E21C3AC9139}v1.0.1967\packages\ancm_iis_express_x64_en_69.msi.

[0D30:1FB0][2017-01-17T09:58:02]w343: Prompt for source of package:
  DotNetCLI_x64, payload: DotNetCLI_x64, path:
  C:\Users\MYACCOUNTNAME\Downloads\packages\DotNetCore.1.0.1-SDK.1.0.0.Preview2-003131-x64.exe

[0D30:1FB0][2017-01-17T09:58:02]i338: Acquiring package:
  DotNetCLI_x64, payload: DotNetCLI_x64, download from:
  https://download.microsoft.com/download/F/6/E/F6ECBBCC-B02F-424E-8E03-D47E9FA631B7/packages/DotNetCore.1.0.1-SDK.1.0.0.Preview2-003131-x64.exe

[1E4C:1FD0][2017-01-17T09:58:09]i305: Verified acquired payload:
  DotNetCLI_x64 at path: C:\ProgramData\Package
  Cache.unverified\DotNetCLI_x64, moving to: C:\ProgramData\Package
  Cache\8B4ACC662D4A8759AB418CA5F92FE4721D21B190\packages\DotNetCore.1.0.1-SDK.1.0.0.Preview2-003131-x64.exe.

[0D30:1FB0][2017-01-17T09:58:09]w343: Prompt for source of package:
  DotNetVersionManager_x64, payload: DotNetVersionManager_x64, path:
  C:\Users\MYACCOUNTNAME\Downloads\packages\DotNetVersionManager-x64_rc1.msi

[0D30:1FB0][2017-01-17T09:58:09]i338: Acquiring package:
  DotNetVersionManager_x64, payload: DotNetVersionManager_x64, download
  from:
  https://download.microsoft.com/download/F/6/E/F6ECBBCC-B02F-424E-8E03-D47E9FA631B7/packages/DotNetVersionManager-x64_rc1.msi

[1E4C:1FD0][2017-01-17T09:58:10]i305: Verified acquired payload:
  DotNetVersionManager_x64 at path: C:\ProgramData\Package
  Cache.unverified\DotNetVersionManager_x64, moving to:
  C:\ProgramData\Package
  Cache{4EC36977-42B9-3C18-A692-B9DEE7404484}v1.0.11123.0\packages\DotNetVersionManager-x64_rc1.msi.

[0D30:1FB0][2017-01-17T09:58:10]w343: Prompt for source of package:
  AspNetCoreLocalFeed, payload: AspNetCoreLocalFeed, path:
  C:\Users\MYACCOUNTNAME\Downloads\packages\AspNetCoreLocalFeed_69.msi

[0D30:1FB0][2017-01-17T09:58:10]i338: Acquiring package:
  AspNetCoreLocalFeed, payload: AspNetCoreLocalFeed, download from:
  https://download.microsoft.com/download/F/6/E/F6ECBBCC-B02F-424E-8E03-D47E9FA631B7/packages/AspNetCoreLocalFeed_69.msi

[0D30:1E1C][2017-01-17T09:58:15]i319: Applied execute package:
  SetupBlocked_Install, result: 0x0, restart: None

[1E4C:1E48][2017-01-17T09:58:15]i301: Applying execute package:
  Preparation_Uninstall_ASPNET, action: Install, path:
  C:\ProgramData\Package
  Cache\50e2672c-aefb-300c-8301-d8ebba628476\Preparation_69.exe,
  arguments: '"C:\ProgramData\Package
  Cache\50e2672c-aefb-300c-8301-d8ebba628476\Preparation_69.exe" /d'

[0D30:1E1C][2017-01-17T09:58:15]i319: Applied execute package:
  Preparation_Uninstall_ASPNET, result: 0x0, restart: None

[1E4C:1E48][2017-01-17T09:58:15]i301: Applying execute package:
  ANCM_IISExpress_x64, action: Repair, path: C:\ProgramData\Package
  Cache{C2BB4C41-59DC-487E-9CCF-1E21C3AC9139}v1.0.1967\packages\ancm_iis_express_x64_en_69.msi,
  arguments: ' ARPSYSTEMCOMPONENT="1" MSIFASTINSTALL="7"'

[1E4C:1E48][2017-01-17T09:58:18]e000: Error 0x80070652: Failed to run
  maintanance mode for MSI package.

[1E4C:1E48][2017-01-17T09:58:18]e000: Error 0x80070652: Failed to
  execute MSI package.

[0D30:1E1C][2017-01-17T09:58:18]e000: Error 0x80070652: Failed to
  configure per-machine MSI package.

[0D30:1E1C][2017-01-17T09:58:18]w348: Application requested retry of
  package: ANCM_IISExpress_x64, encountered error: 0x80070652.
  Retrying...

[1E4C:1E48][2017-01-17T09:58:21]i301: Applying execute package:
  ANCM_IISExpress_x64, action: Repair, path: C:\ProgramData\Package
  Cache{C2BB4C41-59DC-487E-9CCF-1E21C3AC9139}v1.0.1967\packages\ancm_iis_express_x64_en_69.msi,
  arguments: ' ARPSYSTEMCOMPONENT="1" MSIFASTINSTALL="7"'

[1E4C:1FD0][2017-01-17T09:58:24]i305: Verified acquired payload:
  AspNetCoreLocalFeed at path: C:\ProgramData\Package
  Cache.unverified\AspNetCoreLocalFeed, moving to:
  C:\ProgramData\Package
  Cache{37BEAEAD-FEB0-3B82-9B32-710E0776FFAD}v1.0.20907.0\packages\AspNetCoreLocalFeed_69.msi.

[1E4C:1FD0][2017-01-17T09:58:24]i304: Verified existing payload:
  NuGetVS14 at path: C:\ProgramData\Package
  Cache{08D9540E-77B1-37B3-909A-813DAA5523D0}v3.5.0.1484\packages\NuGetVisualStudio14_69.msi.

[1E4C:1FD0][2017-01-17T09:58:24]i304: Verified existing payload:
  cabFB5D09005B6CCD7291B309F84DC6E0E2 at path: C:\ProgramData\Package
  Cache{08D9540E-77B1-37B3-909A-813DAA5523D0}v3.5.0.1484\packages\nuget14_VisualStudio.cab.

[0D30:1FB0][2017-01-17T09:58:24]w343: Prompt for source of package:
  WebToolsExtensionsVS14, payload: WebToolsExtensionsVS14, path:
  C:\Users\MYACCOUNTNAME\Downloads\packages\WebToolsExtensionsVS14_69.msi

[0D30:1FB0][2017-01-17T09:58:24]i338: Acquiring package:
  WebToolsExtensionsVS14, payload: WebToolsExtensionsVS14, download
  from:
   https://download.microsoft.com/download/F/6/E/F6ECBBCC-B02F-424E-8E03-D47E9FA631B7/packages/WebToolsExtensionsVS14_69.msi

[0D30:1E1C][2017-01-17T09:58:27]i319: Applied execute package:
  ANCM_IISExpress_x64, result: 0x0, restart: None

[1E4C:1E48][2017-01-17T09:58:27]i325: Registering dependency:
  {da280276-4f5b-4918-8d40-20ca56dfa535} on package provider:
  IISExpress_AspNetCore_Module,x64, package: ANCM_IISExpress_x64

[1E4C:1E48][2017-01-17T09:58:27]i301: Applying execute package:
  DotNetCLI_x64, action: Install, path: C:\ProgramData\Package
  Cache\8B4ACC662D4A8759AB418CA5F92FE4721D21B190\packages\DotNetCore.1.0.1-SDK.1.0.0.Preview2-003131-x64.exe,
  arguments: '"C:\ProgramData\Package
  Cache\8B4ACC662D4A8759AB418CA5F92FE4721D21B190\packages\DotNetCore.1.0.1-SDK.1.0.0.Preview2-003131-x64.exe"
  /quiet /norestart'

[1E4C:1FD0][2017-01-17T09:58:39]i305: Verified acquired payload:
  WebToolsExtensionsVS14 at path: C:\ProgramData\Package
  Cache.unverified\WebToolsExtensionsVS14, moving to:
  C:\ProgramData\Package
  Cache{BFC344B0-DCDE-36EB-AB05-CB194F2BE946}v14.1.21111.0\packages\WebToolsExtensionsVS14_69.msi.

[0D30:1FB0][2017-01-17T09:58:39]w343: Prompt for source of package:
  DotNetToolsVS14, payload: DotNetToolsVS14, path:
  C:\Users\MYACCOUNTNAME\Downloads\packages\DotNetToolsVS14_69.msi

[0D30:1FB0][2017-01-17T09:58:39]i338: Acquiring package:
  DotNetToolsVS14, payload: DotNetToolsVS14, download from:
  https://download.microsoft.com/download/F/6/E/F6ECBBCC-B02F-424E-8E03-D47E9FA631B7/packages/DotNetToolsVS14_69.msi

[1E4C:1FD0][2017-01-17T09:58:40]i305: Verified acquired payload:
  DotNetToolsVS14 at path: C:\ProgramData\Package
  Cache.unverified\DotNetToolsVS14, moving to: C:\ProgramData\Package
  Cache{0DFDFA4C-B434-3535-95DA-C5DAFDD5B1CF}v14.1.21111.0\packages\DotNetToolsVS14_69.msi.

[1E4C:1FD0][2017-01-17T09:58:40]i305: Verified acquired payload:
  Preparation_ASPNET at path: C:\ProgramData\Package
  Cache.unverified\Preparation_ASPNET, moving to:
  C:\ProgramData\Package
  Cache\4f0b7b02-eb23-3261-a713-a05662eaa53e\Preparation_69.exe.

[1E4C:1E48][2017-01-17T09:58:45]e000: Error 0x80070490: Process
  returned error: 0x490

[1E4C:1E48][2017-01-17T09:58:45]e000: Error 0x80070490: Failed to
  execute EXE package.

[0D30:1E1C][2017-01-17T09:58:45]e000: Error 0x80070490: Failed to
  configure per-machine EXE package.

[0D30:1E1C][2017-01-17T09:58:45]i319: Applied execute package:
  DotNetCLI_x64, result: 0x80070490, restart: None

[0D30:1E1C][2017-01-17T09:58:45]e000: Error 0x80070490: Failed to
  execute EXE package.

[1E4C:1E48][2017-01-17T09:58:45]i351: Removing cached package:
  DotNetCLI_x64, from path: C:\ProgramData\Package
  Cache\8B4ACC662D4A8759AB418CA5F92FE4721D21B190\

[1E4C:1E48][2017-01-17T09:58:45]i372: Session end, registration key:
  SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall{da280276-4f5b-4918-8d40-20ca56dfa535},
  resume: ARP, restart: None, disable resume: No

[1E4C:1E48][2017-01-17T09:58:45]i371: Updating session, registration
  key:
  SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall{da280276-4f5b-4918-8d40-20ca56dfa535},
  resume: ARP, restart initiated: No, disable resume: No

[0D30:1E1C][2017-01-17T09:58:46]i399: Apply complete, result:
  0x80070490, restart: None, ba requested restart:  No

答:
I had a exact same problem but i have found a solution, hope it will help you or somebody else.

First i download all packages needed to install DotNetCore.1.0.1-VS2015Tools.Preview2.0.3 using commad (in cmd):

```<code>DotNetCore.1.0.1-VS2015Tools.Preview2.0.3.exe /layout
</code>```

It creates packages directory with a bunch of .msi files.
First error in log is about DotNetToolsVS14_69.msi, so I have install it.
Then I tried to install DotNetCore.1.0.1-SDK.1.0.0.Preview2-003131-x64.exe,
but error appeard "Element not found 0x80070490" regarding Visual C++ 2015 Redistributable 14.0.24215. I couldn't install it beceause i already have version 14.10 (from VS 2017). So I uninstall version 14.10 install 14.0.24215 and then i was able to install DotNetCore.1.0.1-SDK.1.0.0.Preview2-003131-x64.exe.

Next step was to try again with DotNetCore.1.0.1-VS2015Tools.Preview2.0.3.exe and it install successfully.

Body:
I had a exact same problem but i have found a solution, hope it will help you or somebody else.

First i download all packages needed to install DotNetCore.1.0.1-VS2015Tools.Preview2.0.3 using commad (in cmd):

DotNetCore.1.0.1-VS2015Tools.Preview2.0.3.exe /layout

It creates packages directory with a bunch of .msi files.
First error in log is about DotNetToolsVS14_69.msi, so I have install it.
Then I tried to install DotNetCore.1.0.1-SDK.1.0.0.Preview2-003131-x64.exe,
but error appeard "Element not found 0x80070490" regarding Visual C++ 2015 Redistributable 14.0.24215. I couldn't install it beceause i already have version 14.10 (from VS 2017). So I uninstall version 14.10 install 14.0.24215 and then i was able to install DotNetCore.1.0.1-SDK.1.0.0.Preview2-003131-x64.exe.

Next step was to try again with DotNetCore.1.0.1-VS2015Tools.Preview2.0.3.exe and it install successfully.


问:
Merge HTML Element object with a custom object
I'm trying to figure out why I can't merge 2 or more objects when one of them is an HTML Element.

EDIT:

Why when i merged with Object.assign 2 "normal" objects like obj1 and obj2 i get the values from obj2 on common properties, but when i do the same with root which is an HTML element i don't get its values (for example the value of id property)

const root = document.getElementById("root");
const obj1 = { id: "obj1", textContent: "i am obj1" };
const obj2 = { id: "obj2", textContent: "i am obj2"};
const merged1 = Object.assign({}, obj1, obj2); // the new object got the id and textContent from obj2
const merged2 = Object.assign({}, obj1, root); // the new object got the id and textContent from obj1. why not from root?
console.log(merged1);
console.log(merged2);
console.log(root.id);
console.log(root.textContent);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="root">i am root</div></code>```

答:
Pass root as first parameter to Object.assign()

const root = document.getElementById("root");
const obj1 = { id: "obj1", textContent: "i am obj1" };
const obj2 = { textContent: "i am obj2"}
const merged = Object.assign(root, obj1, obj2);
console.log(merged);
console.log(root.id);
console.log(root.textContent);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="root">i am root</div></code>```

i don't want to override root, i want a new object and get the
  relevant values from the root object.

const root = document.getElementById("root");
const obj1 = { id: "obj1", textContent: "i am obj1" };
const obj2 = { textContent: "i am obj2"};
const {id, textContent} = root;
const merged = Object.assign({}, obj1, obj2, {id, textContent});
console.log(merged);
console.log(root.id);
console.log(root.textContent);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="root">i am root</div></code>```

EDIT: Why when i merged with Object.assign 2 "normal" objects like
  obj1 and obj2 i get the values from obj2 on common properties, but
  when i do the same with root which is an HTML element i don't get its
  values (for example the value of id property)

Object.assign() can copy enumerable properties of an object. HTMLDivElement id and textContent properties are not enumerable.

Object.assign()

The Object.assign() method is used to copy the values of all
  enumerable own properties from one or more source objects to a target
  object. It will return the target object.

const root = document.getElementById("root");
const props = ["textContent", "id"];

for (const prop of props) console.log(Object.propertyIsEnumerable(root, prop));```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="root">i am root</div></code>```

Body:
I'm trying to figure out why I can't merge 2 or more objects when one of them is an HTML Element.

EDIT:

Why when i merged with Object.assign 2 "normal" objects like obj1 and obj2 i get the values from obj2 on common properties, but when i do the same with root which is an HTML element i don't get its values (for example the value of id property)

const root = document.getElementById("root");
const obj1 = { id: "obj1", textContent: "i am obj1" };
const obj2 = { id: "obj2", textContent: "i am obj2"};
const merged1 = Object.assign({}, obj1, obj2); // the new object got the id and textContent from obj2
const merged2 = Object.assign({}, obj1, root); // the new object got the id and textContent from obj1. why not from root?
console.log(merged1);
console.log(merged2);
console.log(root.id);
console.log(root.textContent);

i am root

Body:
Pass root as first parameter to Object.assign()

const root = document.getElementById("root");
const obj1 = { id: "obj1", textContent: "i am obj1" };
const obj2 = { textContent: "i am obj2"}
const merged = Object.assign(root, obj1, obj2);
console.log(merged);
console.log(root.id);
console.log(root.textContent);

<div id="root">i am root</div>

i don't want to override root, i want a new object and get the
  relevant values from the root object.

const root = document.getElementById("root");
const obj1 = { id: "obj1", textContent: "i am obj1" };
const obj2 = { textContent: "i am obj2"};
const {id, textContent} = root;
const merged = Object.assign({}, obj1, obj2, {id, textContent});
console.log(merged);
console.log(root.id);
console.log(root.textContent);

<div id="root">i am root</div>

EDIT: Why when i merged with Object.assign 2 "normal" objects like
  obj1 and obj2 i get the values from obj2 on common properties, but
  when i do the same with root which is an HTML element i don't get its
  values (for example the value of id property)

Object.assign() can copy enumerable properties of an object. HTMLDivElement id and textContent properties are not enumerable.

Object.assign()

The Object.assign() method is used to copy the values of all
  enumerable own properties from one or more source objects to a target
  object. It will return the target object.

const root = document.getElementById("root");
const props = ["textContent", "id"];

for (const prop of props) console.log(Object.propertyIsEnumerable(root, prop));

<div id="root">i am root</div>


问:
How to implement consistent approach for detecting mouse button being hold
I'm trying to implement Mouse class to handle any related issues to mouse actions. Everything works fine except detecting a mouse button being hold. The library doesn't provide this functionality for the mouse yet there is an option for keyboard event (i.e. through REPEAT flag). I have to implement it manually. The first and simple approach is to set a flag for press and release button

```<code>bool Mouse::isRightDown()
{
    if (m_button == GLFW_MOUSE_BUTTON_RIGHT && m_action == GLFW_PRESS){
        m_isRightHold = true;
        ...
}

bool Mouse::isRightUp()
{
    if (m_button == GLFW_MOUSE_BUTTON_RIGHT && m_action == GLFW_RELEASE ){
        m_isRightHold = false;
        ...
}

bool Mouse::isRightHold()
{
    if ( g_RightFlag ){
        ...
        return true;
    }
    return false;
}
</code>```

Now in rendering loop, I can do the following

```<code>while(!glfwWindowShouldClose(window)){
    glfwPollEvents();
    ...
    // Handle Right Button Mouse
    if ( Mouse::Instance()->isRightHold() ){
        std::cout << "Right Mouse Button is hold..." << std::endl;
    }
    ...
    glfwSwapBuffers(window);
}
</code>```

But the problem with this approach is the fact that while-loop is faster than human's reaction for releasing the button, therefore, single click will be considered as a hold event. I've considered another approach by updating a global Boolean variable (i.e. g_RightFlag). The variable will be updated every 900 second in an independent thread as follows

```<code>while (true){

        //std::this_thread::sleep_for(delay);

        std::chrono::duration<int, std::ratio<1, 1000>> delay(900);

        bool sleep = true;
        auto start = std::chrono::system_clock::now();
        while(sleep)
        {
            auto end = std::chrono::system_clock::now();
            auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(end - start);
            if ( elapsed.count() > delay.count() ){
                sleep = false;
            }
        }

        mtx.lock();
        g_RightFlag = m_isRightHold;
        g_LefFlag   = m_isLeftHold;
        mtx.unlock();
    }
</code>```

This solution is better than the first approach but still inconsistent because threads are not synchronized. At some moments, when I do just a single click, the hold event is detected (i.e. in milliseconds). How can I improve my approach to handle Hold Mouse Event?

main.cpp

```<code>#include <iostream>
#include <GL/glew.h>
#include <GLFW/glfw3.h>
#include "mouse.h"

int main(void)
{
    glfwInit();
    glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR,3);
    glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR,3);
    glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
    glfwWindowHint(GLFW_RESIZABLE, GL_FALSE);

    GLFWwindow* window = glfwCreateWindow(800,600,"LearnOpenGL",nullptr,nullptr);
    if( window == nullptr ){
        std::cout << "Failed to create GLFW window" << std::endl;
        glfwTerminate();
        return -1;
    }
    glfwMakeContextCurrent(window);
    glewExperimental = GL_TRUE;
    if( glewInit() != GLEW_OK ){
        std::cout << "Failed to initialize GLEW" << std::endl;
        return -1;
    }

    int width, height;
    glfwGetFramebufferSize(window, &width, &height);
    glViewport(0,0, width, height);

    // callback events
    //Keyboard Event;
    Mouse::Instance();
    Mouse::Instance()->init(window);

    while(!glfwWindowShouldClose(window)){
        glfwPollEvents();

        glClearColor(0.2f, 0.3f, 0.3f, 1.0f);
        glClear(GL_COLOR_BUFFER_BIT);

        // Handle Right Button Mouse
        if ( Mouse::Instance()->isRightDown() ){
            std::cout << "Right Mouse Button is pressed..." << std::endl;
        }

        if ( Mouse::Instance()->isRightUp() ){
            std::cout << "Right Mouse Button is released..." << std::endl;
        }

        if ( Mouse::Instance()->isRightHold() ){
            std::cout << "Right Mouse Button is hold..." << std::endl;
        }

        // Handle Left Button Mouse
        if ( Mouse::Instance()->isLeftDown() ){
            std::cout << "Left Mouse Button is pressed..." << std::endl;
        }

        if ( Mouse::Instance()->isLeftUp() ){
            std::cout << "Left Mouse Button is released..." << std::endl;
        }

        if ( Mouse::Instance()->isLeftHold() ){
            std::cout << "Left Mouse Button is hold..." << std::endl;
        }

        glfwSwapBuffers(window);
    }

    glfwTerminate();
    return 0;
}
</code>```

mouse.h

```<code>#ifndef MOUSE_H
#define MOUSE_H

#include <thread>
#include <atomic>
#include <chrono>
#include <GLFW/glfw3.h>

class Mouse
{
public:

    static Mouse* Instance(){
        if(s_pInstance == NULL)
            s_pInstance = new Mouse;
        return s_pInstance;
    }
    void init(GLFWwindow* window);
    bool isRightDown();
    bool isRightUp();
    bool isRightHold();

    bool isLeftDown();
    bool isLeftUp();
    bool isLeftHold();

    std::atomic<int> m_button, m_action, m_mode;
private:
    static void mouse_button_callback(GLFWwindow* window, int button, int action, int mods);

    bool m_isRightHold, m_isLeftHold;

    GLFWwindow* m_pWindow;
    Mouse();
    static Mouse* s_pInstance;
    std::thread m_OnHoldThread;
    void initThread();
    void updateThread();
    void update(int b, int a, int m);

};

#endif
</code>```

mouse.cpp

```<code>#include "mouse.h"
#include <iostream>
#include <mutex> // std::mutex

std::mutex mtx;

Mouse* Mouse::s_pInstance = NULL;
bool g_LefFlag(false);
bool g_RightFlag(false);

Mouse::Mouse()
    : m_button(-1), m_action(-1), m_mode(-1),
      m_isRightHold(false), m_isLeftHold(false)
{
    initThread();
}

void Mouse::init(GLFWwindow* window)
{
    m_pWindow = window;
    glfwSetMouseButtonCallback(window, mouse_button_callback);
}

void Mouse::mouse_button_callback(GLFWwindow* window, int button, int action, int mods)
{
    Mouse::Instance()->update(button, action, mods);
}

void Mouse::initThread()
{
    m_OnHoldThread = std::thread(&Mouse::updateThread,this);
}

void Mouse::updateThread()
{
    //std::chrono::milliseconds delay(1100);

    while (true){

        //std::this_thread::sleep_for(delay);

        std::chrono::duration<int, std::ratio<1, 1000>> delay(900);

        bool sleep = true;
        auto start = std::chrono::system_clock::now();
        while(sleep)
        {
            auto end = std::chrono::system_clock::now();
            auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(end - start);
            if ( elapsed.count() > delay.count() ){
                sleep = false;
            }
        }

        mtx.lock();
        g_RightFlag = m_isRightHold;
        g_LefFlag   = m_isLeftHold;
        mtx.unlock();
    }
}

bool Mouse::isRightDown()
{
    if (m_button == GLFW_MOUSE_BUTTON_RIGHT && m_action == GLFW_PRESS){

        m_isRightHold = true;
        m_button   = -1;
        m_action   = -1;
        m_mode     = -1;
        return true;
    }

    return false;
}

bool Mouse::isRightUp()
{
    if (m_button == GLFW_MOUSE_BUTTON_RIGHT && m_action == GLFW_RELEASE ){
        m_isRightHold = false;

        mtx.lock();
        g_RightFlag = m_isRightHold;
        mtx.unlock();

        m_button   = -1;
        m_action   = -1;
        m_mode     = -1;
        return true;
    }

    return false;
}

bool Mouse::isRightHold()
{
    if ( g_RightFlag ){
        m_button   = -1;
        m_action   = -1;
        m_mode     = -1;

        return true;
    }

    return false;
}

bool Mouse::isLeftDown()
{
    if (m_button == GLFW_MOUSE_BUTTON_LEFT && m_action == GLFW_PRESS){

        m_isLeftHold = true;
        m_button   = -1;
        m_action   = -1;
        m_mode     = -1;
        return true;
    }

    return false;
}
bool Mouse::isLeftUp()
{
    if (m_button == GLFW_MOUSE_BUTTON_LEFT && m_action == GLFW_RELEASE ){
        m_isLeftHold = false;

        mtx.lock();
        g_LefFlag = m_isLeftHold;
        mtx.unlock();

        m_button   = -1;
        m_action   = -1;
        m_mode     = -1;
        return true;
    }

    return false;
}
bool Mouse::isLeftHold()
{
    if ( g_LefFlag ){
        m_button   = -1;
        m_action   = -1;
        m_mode     = -1;

        return true;
    }

    return false;
}

void Mouse::update(int b, int a, int m)
{
    m_button   = b;
    m_action   = a;
    m_mode     = m;
}
</code>```

答: Why don't you just get a high-resolution time of m_isRightHold = true; event and compare time period elapsed since then at every main loop iteration while m_isRightHold continues to be true to determine that mouse button has been held for long enough to consider a click or hold to happen?

Body:
I'm trying to implement Mouse class to handle any related issues to mouse actions. Everything works fine except detecting a mouse button being hold. The library doesn't provide this functionality for the mouse yet there is an option for keyboard event (i.e. through REPEAT flag). I have to implement it manually. The first and simple approach is to set a flag for press and release button

bool Mouse::isRightDown()
{
    if (m_button == GLFW_MOUSE_BUTTON_RIGHT && m_action == GLFW_PRESS){
        m_isRightHold = true;
        ...
}

bool Mouse::isRightUp()
{
    if (m_button == GLFW_MOUSE_BUTTON_RIGHT && m_action == GLFW_RELEASE ){
        m_isRightHold = false;
        ...
}

bool Mouse::isRightHold()
{
    if ( g_RightFlag ){
        ...
        return true;
    }
    return false;
}

Now in rendering loop, I can do the following

while(!glfwWindowShouldClose(window)){
    glfwPollEvents();
    ...
    // Handle Right Button Mouse
    if ( Mouse::Instance()->isRightHold() ){
        std::cout << "Right Mouse Button is hold..." << std::endl;
    }
    ...
    glfwSwapBuffers(window);
}

But the problem with this approach is the fact that while-loop is faster than human's reaction for releasing the button, therefore, single click will be considered as a hold event. I've considered another approach by updating a global Boolean variable (i.e. g_RightFlag). The variable will be updated every 900 second in an independent thread as follows

while (true){

        //std::this_thread::sleep_for(delay);

        std::chrono::duration<int, std::ratio<1, 1000>> delay(900);

        bool sleep = true;
        auto start = std::chrono::system_clock::now();
        while(sleep)
        {
            auto end = std::chrono::system_clock::now();
            auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(end - start);
            if ( elapsed.count() > delay.count() ){
                sleep = false;
            }
        }

        mtx.lock();
        g_RightFlag = m_isRightHold;
        g_LefFlag   = m_isLeftHold;
        mtx.unlock();
    }

This solution is better than the first approach but still inconsistent because threads are not synchronized. At some moments, when I do just a single click, the hold event is detected (i.e. in milliseconds). How can I improve my approach to handle Hold Mouse Event?

main.cpp

#include <iostream>
#include <GL/glew.h>
#include <GLFW/glfw3.h>
#include "mouse.h"

int main(void)
{
    glfwInit();
    glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR,3);
    glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR,3);
    glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
    glfwWindowHint(GLFW_RESIZABLE, GL_FALSE);

    GLFWwindow* window = glfwCreateWindow(800,600,"LearnOpenGL",nullptr,nullptr);
    if( window == nullptr ){
        std::cout << "Failed to create GLFW window" << std::endl;
        glfwTerminate();
        return -1;
    }
    glfwMakeContextCurrent(window);
    glewExperimental = GL_TRUE;
    if( glewInit() != GLEW_OK ){
        std::cout << "Failed to initialize GLEW" << std::endl;
        return -1;
    }

    int width, height;
    glfwGetFramebufferSize(window, &width, &height);
    glViewport(0,0, width, height);

    // callback events
    //Keyboard Event;
    Mouse::Instance();
    Mouse::Instance()->init(window);

    while(!glfwWindowShouldClose(window)){
        glfwPollEvents();

        glClearColor(0.2f, 0.3f, 0.3f, 1.0f);
        glClear(GL_COLOR_BUFFER_BIT);

        // Handle Right Button Mouse
        if ( Mouse::Instance()->isRightDown() ){
            std::cout << "Right Mouse Button is pressed..." << std::endl;
        }

        if ( Mouse::Instance()->isRightUp() ){
            std::cout << "Right Mouse Button is released..." << std::endl;
        }

        if ( Mouse::Instance()->isRightHold() ){
            std::cout << "Right Mouse Button is hold..." << std::endl;
        }

        // Handle Left Button Mouse
        if ( Mouse::Instance()->isLeftDown() ){
            std::cout << "Left Mouse Button is pressed..." << std::endl;
        }

        if ( Mouse::Instance()->isLeftUp() ){
            std::cout << "Left Mouse Button is released..." << std::endl;
        }

        if ( Mouse::Instance()->isLeftHold() ){
            std::cout << "Left Mouse Button is hold..." << std::endl;
        }

        glfwSwapBuffers(window);
    }

    glfwTerminate();
    return 0;
}

mouse.h

#ifndef MOUSE_H
#define MOUSE_H

#include <thread>
#include <atomic>
#include <chrono>
#include <GLFW/glfw3.h>

class Mouse
{
public:

    static Mouse* Instance(){
        if(s_pInstance == NULL)
            s_pInstance = new Mouse;
        return s_pInstance;
    }
    void init(GLFWwindow* window);
    bool isRightDown();
    bool isRightUp();
    bool isRightHold();

    bool isLeftDown();
    bool isLeftUp();
    bool isLeftHold();

    std::atomic<int> m_button, m_action, m_mode;
private:
    static void mouse_button_callback(GLFWwindow* window, int button, int action, int mods);

    bool m_isRightHold, m_isLeftHold;

    GLFWwindow* m_pWindow;
    Mouse();
    static Mouse* s_pInstance;
    std::thread m_OnHoldThread;
    void initThread();
    void updateThread();
    void update(int b, int a, int m);

};

#endif

mouse.cpp

#include "mouse.h"
#include <iostream>
#include <mutex> // std::mutex

std::mutex mtx;

Mouse* Mouse::s_pInstance = NULL;
bool g_LefFlag(false);
bool g_RightFlag(false);

Mouse::Mouse()
    : m_button(-1), m_action(-1), m_mode(-1),
      m_isRightHold(false), m_isLeftHold(false)
{
    initThread();
}

void Mouse::init(GLFWwindow* window)
{
    m_pWindow = window;
    glfwSetMouseButtonCallback(window, mouse_button_callback);
}

void Mouse::mouse_button_callback(GLFWwindow* window, int button, int action, int mods)
{
    Mouse::Instance()->update(button, action, mods);
}

void Mouse::initThread()
{
    m_OnHoldThread = std::thread(&Mouse::updateThread,this);
}

void Mouse::updateThread()
{
    //std::chrono::milliseconds delay(1100);

    while (true){

        //std::this_thread::sleep_for(delay);

        std::chrono::duration<int, std::ratio<1, 1000>> delay(900);

        bool sleep = true;
        auto start = std::chrono::system_clock::now();
        while(sleep)
        {
            auto end = std::chrono::system_clock::now();
            auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(end - start);
            if ( elapsed.count() > delay.count() ){
                sleep = false;
            }
        }

        mtx.lock();
        g_RightFlag = m_isRightHold;
        g_LefFlag   = m_isLeftHold;
        mtx.unlock();
    }
}

bool Mouse::isRightDown()
{
    if (m_button == GLFW_MOUSE_BUTTON_RIGHT && m_action == GLFW_PRESS){

        m_isRightHold = true;
        m_button   = -1;
        m_action   = -1;
        m_mode     = -1;
        return true;
    }

    return false;
}

bool Mouse::isRightUp()
{
    if (m_button == GLFW_MOUSE_BUTTON_RIGHT && m_action == GLFW_RELEASE ){
        m_isRightHold = false;

        mtx.lock();
        g_RightFlag = m_isRightHold;
        mtx.unlock();

        m_button   = -1;
        m_action   = -1;
        m_mode     = -1;
        return true;
    }

    return false;
}

bool Mouse::isRightHold()
{
    if ( g_RightFlag ){
        m_button   = -1;
        m_action   = -1;
        m_mode     = -1;

        return true;
    }

    return false;
}

bool Mouse::isLeftDown()
{
    if (m_button == GLFW_MOUSE_BUTTON_LEFT && m_action == GLFW_PRESS){

        m_isLeftHold = true;
        m_button   = -1;
        m_action   = -1;
        m_mode     = -1;
        return true;
    }

    return false;
}
bool Mouse::isLeftUp()
{
    if (m_button == GLFW_MOUSE_BUTTON_LEFT && m_action == GLFW_RELEASE ){
        m_isLeftHold = false;

        mtx.lock();
        g_LefFlag = m_isLeftHold;
        mtx.unlock();

        m_button   = -1;
        m_action   = -1;
        m_mode     = -1;
        return true;
    }

    return false;
}
bool Mouse::isLeftHold()
{
    if ( g_LefFlag ){
        m_button   = -1;
        m_action   = -1;
        m_mode     = -1;

        return true;
    }

    return false;
}

void Mouse::update(int b, int a, int m)
{
    m_button   = b;
    m_action   = a;
    m_mode     = m;
}


问:
Angular: how to make a configurable filter
Is it possible to create a configurable filter the way you can create configurable services:

```<code>angular.module('app', [])
       .provider('resourceUrl', function($filterProvider) {

    var base = '/';

    this.setPrefix = function(prefix) {base = prefix};

    $filterProvider.register('resourceUrl', resourceUrlFilter);

    this.$get = ??

    function resourceUrlFilter(url) { /* returns the new url */ }
})
</code>```

I wan't to create a filter that adds a base url prefix to a path string and the url prefix should be configurable.

Currently I achieve this by injecting a constant in the filter

```<code>angular.module('app', [])
       .constant('baseUrl', '...')
       .filter('resourceUrl', ['baseUrl', function(baseUrl) {

       return function resourceUrlFilter(url) { /* returns the new url */ }
}]
</code>```

答:
I had a reminder of this question today, and recently I had to use some filters in a service, and this crossed my mind:

Since to inject a filter into a service let's say I have created the customDate filter, I have to provide the name customDateFilter in order to inject it

```<code> myModule.factory('MyData', function(customDateFilter) { /* code */ });
</code>```

So I thought:

Maybe I can register a filter the same way I register a service but then append Filter to the name, and it worked.

I don't know if it is considered legal to register a filter in this way, or whether it won't be dropped in the future
but this is a way that allows you to register a filter with a provider

The short version:

You can register a configurable filter, by creating a ServiceProvider the way usual configurable services are created -> https://docs.angularjs.org/guide/providers#provider-recipe
But when you register the ServiceProvider append Filter to the service name:

JS

```<code>var module = angular.module('app', [])
var customDate = function filterProvider() { /* ServiceProvider definition */ };
myModule.provider('customDateFilter', customDate);
</code>```

HTML

```<code><p>Some date: <span>{{ $ctrl.date | customDate }}</span> </p>
</code>```

Working plunk example

This plunk shows an example of a baseUrl filter that can be configured with
a prefix in a module's config block
https://plnkr.co/edit/RkTkKM?p=preview

Other Options

You can always create a service that performs the filtering and then expose it through a filter by injecting it to the filter factory. And this service can be a configurable service using the Provider Recipe

```<code>class FilteringServiceProvider {

    $get() { return new FilteringService(this.configuration) }

    configure(params) { /* some config logic */ }
}

class FilteringService {

  constructor(configuration) {}

  filterDate(date) { /* some filtering on the date and return a value */ }
}

const myModule = angular.module('app.filters', []);

myModule
  .provider('filteringService', FilteringServiceProvider)
  .filter('customDate', (filteringService) => filteringService.filterDate);
</code>```

Body:
Is it possible to create a configurable filter the way you can create configurable services:

angular.module('app', [])
       .provider('resourceUrl', function($filterProvider) {

    var base = '/';

    this.setPrefix = function(prefix) {base = prefix};

    $filterProvider.register('resourceUrl', resourceUrlFilter);

    this.$get = ??

    function resourceUrlFilter(url) { /* returns the new url */ }
})

I wan't to create a filter that adds a base url prefix to a path string and the url prefix should be configurable.

Currently I achieve this by injecting a constant in the filter

angular.module('app', [])
       .constant('baseUrl', '...')
       .filter('resourceUrl', ['baseUrl', function(baseUrl) {

       return function resourceUrlFilter(url) { /* returns the new url */ }
}]

Body:
I had a reminder of this question today, and recently I had to use some filters in a service, and this crossed my mind:

Since to inject a filter into a service let's say I have created the customDate filter, I have to provide the name customDateFilter in order to inject it

 myModule.factory('MyData', function(customDateFilter) { /* code */ });

So I thought:

Maybe I can register a filter the same way I register a service but then append Filter to the name, and it worked.

I don't know if it is considered legal to register a filter in this way, or whether it won't be dropped in the future
but this is a way that allows you to register a filter with a provider

The short version:

You can register a configurable filter, by creating a ServiceProvider the way usual configurable services are created -> https://docs.angularjs.org/guide/providers#provider-recipe
But when you register the ServiceProvider append Filter to the service name:

JS

var module = angular.module('app', [])
var customDate = function filterProvider() { /* ServiceProvider definition */ };
myModule.provider('customDateFilter', customDate);

HTML

<p>Some date: <span>{{ $ctrl.date | customDate }}</span> </p>

Working plunk example

This plunk shows an example of a baseUrl filter that can be configured with
a prefix in a module's config block
https://plnkr.co/edit/RkTkKM?p=preview

Other Options

You can always create a service that performs the filtering and then expose it through a filter by injecting it to the filter factory. And this service can be a configurable service using the Provider Recipe

class FilteringServiceProvider {

    $get() { return new FilteringService(this.configuration) }

    configure(params) { /* some config logic */ }
}

class FilteringService {

  constructor(configuration) {}

  filterDate(date) { /* some filtering on the date and return a value */ }
}

const myModule = angular.module('app.filters', []);

myModule
  .provider('filteringService', FilteringServiceProvider)
  .filter('customDate', (filteringService) => filteringService.filterDate);


问:
How to do variable interpolation on domain property in Grails?
I am new to Grails and have been looking into doing variable interpolation on a domain property which I am calling from a service.

My Domain looks like this:

```<code>class MonthlyResult {

FilterType type
String typeId
Integer year
Integer january = 0
Integer february = 0
Integer march = 0
Integer april = 0
Integer may = 0
Integer june = 0
Integer july = 0
Integer august = 0
Integer september = 0
Integer october = 0
Integer november = 0
Integer december = 0
</code>```

And I am trying to do this on my MonthlyResult monthlyResult:
monthlyResult.${monthName}
where monthName is a String with the name of the month that I want.

答:
As simple as

```<code>String monthName = 'january'
assert 42 == new MonthlyResult( january:42 )[ monthName ]
</code>```

Also, I'd rather use a map in such domain class, keyed by some enum values:

```<code>class MonthlyResult {

  Enum Month { january, february, .... }

  Map<Month,Integer> months
}
</code>```

Body:
I am new to Grails and have been looking into doing variable interpolation on a domain property which I am calling from a service.

My Domain looks like this:

class MonthlyResult {

FilterType type
String typeId
Integer year
Integer january = 0
Integer february = 0
Integer march = 0
Integer april = 0
Integer may = 0
Integer june = 0
Integer july = 0
Integer august = 0
Integer september = 0
Integer october = 0
Integer november = 0
Integer december = 0

And I am trying to do this on my MonthlyResult monthlyResult:
monthlyResult.${monthName}
where monthName is a String with the name of the month that I want.

Body:
As simple as

String monthName = 'january'
assert 42 == new MonthlyResult( january:42 )[ monthName ]

Also, I'd rather use a map in such domain class, keyed by some enum values:

class MonthlyResult {

  Enum Month { january, february, .... }

  Map<Month,Integer> months
}


问:
How can I center the loading div before load() with jQuery?
I have this code:

```<code>$("#result").html('<div class="loading">Loading results...</div>');
$("#result").load('<?php bloginfo('template_directory'); ?>/GetResults.php?' + $.cookie('nw-query'));
</code>```

It shows the loading div until the load is done. What I want to do here, I want the loading div exactly in the center of the page/document?

That's extra but could be nice - can I also fade the document until the load is done so that the loading div stands out?

Any jquery/css suggestions are welcome.

Thank you :)

答:
Have you looked at jQueryUI?  You could use a modal dialog for this.  jQueryUi automatically centers the modal dialog and you can make the dialog disappear after it's finished loading.  There is a way to remove the title bar from the dialog:
http://www.comanswer.com/question/jquery-ui-dialog-how-to-initialize-without-a-title-bar

I don't know if this is what you're looking for, but it might avoid some headaches for you later down the road (and it's pretty and you can have custom themes).

Body:
I have this code:

$("#result").html('
Loading results...
');
$("#result").load('<?php bloginfo('template_directory'); ?>/GetResults.php?' + $.cookie('nw-query'));

It shows the loading div until the load is done. What I want to do here, I want the loading div exactly in the center of the page/document?

That's extra but could be nice - can I also fade the document until the load is done so that the loading div stands out?

Any jquery/css suggestions are welcome.

Thank you :)


问:
Understanding Basic Python Logic and Flow of Operations (a, b = b, a+b)
I am trying to understand the code provided on the Python.org tutorial in section 3.2

```<code>a, b = 0, 1
>>> while b < 10:
...     print(b)
...     a, b = b, a+b
</code>```

The code above results in the sequence as follows:

```<code>1
1
2
3
5
8
</code>```

My questions are as follows:

Why do the numbers appear vertically and not horizontally like a print statement generally does?  I know you can force the numbers to appear horizontally but want to understand why that is not the default.

Most importantly, how is the python logic working?  I understand its the fibonacci sequence but you're only asking the code to print "b".  It should just print a+b over and over again, should it not (resulting in 1 being printed over and over again)?  I don't understand how the logic within python progresses the sequence.

Any help is much appreciated.  Thank you.

答:
First of all your code would be quite simple if you used parentheses. The code a,b is a tupel:
(a,b)=(0,1)
Let's interpret the code line per line:

```<code>While b<10: #b=1
    print(b) #output:1
    (a,b) = (a,a+b) # a=1, b=1
</code>```

Now the next iteration:

```<code>While b<10: #b=1
    print(b) #output:1
    (a,b) = (a,a+b) # a=1, b=2
</code>```

And the next:

```<code>While b<10: #b=1
    print(b) #output:2
    (a,b) = (a,a+b) # a=2, b=3
</code>```

And so on....
You will get
1
1
2
3
5
8
But each number in a separate line because print function add '\n'. So the output is "vertical".

Body:
I am trying to understand the code provided on the Python.org tutorial in section 3.2

a, b = 0, 1
>>> while b < 10:
...     print(b)
...     a, b = b, a+b

The code above results in the sequence as follows:

1
1
2
3
5
8

My questions are as follows:

Why do the numbers appear vertically and not horizontally like a print statement generally does?  I know you can force the numbers to appear horizontally but want to understand why that is not the default.

Most importantly, how is the python logic working?  I understand its the fibonacci sequence but you're only asking the code to print "b".  It should just print a+b over and over again, should it not (resulting in 1 being printed over and over again)?  I don't understand how the logic within python progresses the sequence.

Any help is much appreciated.  Thank you.

Body:
First of all your code would be quite simple if you used parentheses. The code a,b is a tupel:
(a,b)=(0,1)
Let's interpret the code line per line:

While b<10: #b=1
    print(b) #output:1
    (a,b) = (a,a+b) # a=1, b=1

Now the next iteration:

While b<10: #b=1
    print(b) #output:1
    (a,b) = (a,a+b) # a=1, b=2

And the next:

While b<10: #b=1
    print(b) #output:2
    (a,b) = (a,a+b) # a=2, b=3

And so on....
You will get
1
1
2
3
5
8
But each number in a separate line because print function add '\n'. So the output is "vertical".


问:
How to push to gitlab with java api with ssh
I am using gitlab of version GitLab Community Edition 9.1.1 d3123f6.

I am able to push my code to gitlab with http protocol but when I am trying with git protocol it is showing following error.

```<code>Exception in thread "main"
org.eclipse.jgit.errors.UnsupportedCredentialItem:
ssh://git@192......:
org.eclipse.jgit.transport.CredentialItem$YesNoType:The authenticity
of host '192......' can't be established.

RSA key fingerprint is
99:...............
Are you sure you want to continue connecting?
at org.eclipse.jgit.transport.UsernamePasswordCredentialsProvider.get(UsernamePasswordCredentialsProvider.java:119)
at org.eclipse.jgit.transport.CredentialsProviderUserInfo.promptYesNo(CredentialsProviderUserInfo.java:124)
at com.jcraft.jsch.Session.checkHost(Session.java:785)
at com.jcraft.jsch.Session.connect(Session.java:342)
at org.eclipse.jgit.transport.JschConfigSessionFactory.getSession(JschConfigSessionFactory.java:117)
at org.eclipse.jgit.transport.SshTransport.getSession(SshTransport.java:137)
at org.eclipse.jgit.transport.TransportGitSsh$SshFetchConnection.<init>(TransportGitSsh.java:264)
at org.eclipse.jgit.transport.TransportGitSsh.openFetch(TransportGitSsh.java:162)
at org.eclipse.jgit.transport.FetchProcess.executeImp(FetchProcess.java:136)
at org.eclipse.jgit.transport.FetchProcess.execute(FetchProcess.java:122)
at org.eclipse.jgit.transport.Transport.fetch(Transport.java:1201)
at org.eclipse.jgit.api.FetchCommand.call(FetchCommand.java:128)
at org.eclipse.jgit.api.CloneCommand.fetch(CloneCommand.java:203)
at org.eclipse.jgit.api.CloneCommand.call(CloneCommand.java:136)
at org.dstadler.jgit.unfinished.PushToRemoteRepository.main(PushToRemoteRepository.java:100)
</code>```

and my code is

```<code>private static final String REMOTE_URL = "git@192.....:ash/test.git";
File localPath = new File("/home/user/Git", "");
localPath.getParentFile().mkdirs();
localPath.createNewFile();
if(!localPath.delete()) {
    throw new IOException("Could not delete temporary file " + localPath);
}

Git git = Git.cloneRepository()
        .setURI( REMOTE_URL )
        .setDirectory(localPath)
        .setCredentialsProvider( cp )
        .call();
System.out.println("Cloning from " + REMOTE_URL + " to " + localPath);

System.out.println("please edit the file and then press \"Enter\" here to push ");
System.in.read();

File file = new File( git.getRepository().getWorkTree(), "file" + new Object().hashCode() );

git.add().addFilepattern( file.getName() ).call();

git.commit().setAll(true).setMessage("a message").call();

git.push() .setCredentialsProvider( cp ) .call();

System.out.println("Pushed from repository: " + localPath + " to remote repository at " + REMOTE_URL);
</code>```

答:
Try to establish a connection from command line first:

```<code>ssh git@...
</code>```

That should ask you the same question: answer 'y'.

Once that is done, meaning once the ~/.ssh/known_hosts has been updated by the key scan of the remote server, you can try your same Java JGit program again.

I posted before (5 years ago) a solution, but for EGit, not JGit.

See more at "JGit Authentication Explained"

JGit provides an abstract JSchConfigSessionFactory that uses JSch to establish SSH connections and requires its configure() to be overridden

The OP Ash adds in the comments:

The problem was in .ssh/config file where needed lines are commented including private key identity.

Body:
I am using gitlab of version GitLab Community Edition 9.1.1 d3123f6.

I am able to push my code to gitlab with http protocol but when I am trying with git protocol it is showing following error.

Exception in thread "main"
org.eclipse.jgit.errors.UnsupportedCredentialItem:
ssh://git@192......:
org.eclipse.jgit.transport.CredentialItem$YesNoType:The authenticity
of host '192......' can't be established.

RSA key fingerprint is
99:...............
Are you sure you want to continue connecting?
at org.eclipse.jgit.transport.UsernamePasswordCredentialsProvider.get(UsernamePasswordCredentialsProvider.java:119)
at org.eclipse.jgit.transport.CredentialsProviderUserInfo.promptYesNo(CredentialsProviderUserInfo.java:124)
at com.jcraft.jsch.Session.checkHost(Session.java:785)
at com.jcraft.jsch.Session.connect(Session.java:342)
at org.eclipse.jgit.transport.JschConfigSessionFactory.getSession(JschConfigSessionFactory.java:117)
at org.eclipse.jgit.transport.SshTransport.getSession(SshTransport.java:137)
at org.eclipse.jgit.transport.TransportGitSsh$SshFetchConnection.<init>(TransportGitSsh.java:264)
at org.eclipse.jgit.transport.TransportGitSsh.openFetch(TransportGitSsh.java:162)
at org.eclipse.jgit.transport.FetchProcess.executeImp(FetchProcess.java:136)
at org.eclipse.jgit.transport.FetchProcess.execute(FetchProcess.java:122)
at org.eclipse.jgit.transport.Transport.fetch(Transport.java:1201)
at org.eclipse.jgit.api.FetchCommand.call(FetchCommand.java:128)
at org.eclipse.jgit.api.CloneCommand.fetch(CloneCommand.java:203)
at org.eclipse.jgit.api.CloneCommand.call(CloneCommand.java:136)
at org.dstadler.jgit.unfinished.PushToRemoteRepository.main(PushToRemoteRepository.java:100)

and my code is

private static final String REMOTE_URL = "git@192.....:ash/test.git";
File localPath = new File("/home/user/Git", "");
localPath.getParentFile().mkdirs();
localPath.createNewFile();
if(!localPath.delete()) {
    throw new IOException("Could not delete temporary file " + localPath);
}

Git git = Git.cloneRepository()
        .setURI( REMOTE_URL )
        .setDirectory(localPath)
        .setCredentialsProvider( cp )
        .call();
System.out.println("Cloning from " + REMOTE_URL + " to " + localPath);

System.out.println("please edit the file and then press \"Enter\" here to push ");
System.in.read();

File file = new File( git.getRepository().getWorkTree(), "file" + new Object().hashCode() );

git.add().addFilepattern( file.getName() ).call();

git.commit().setAll(true).setMessage("a message").call();

git.push() .setCredentialsProvider( cp ) .call();

System.out.println("Pushed from repository: " + localPath + " to remote repository at " + REMOTE_URL);

Body:
Try to establish a connection from command line first:

ssh git@...

That should ask you the same question: answer 'y'.

Once that is done, meaning once the ~/.ssh/known_hosts has been updated by the key scan of the remote server, you can try your same Java JGit program again.

I posted before (5 years ago) a solution, but for EGit, not JGit.

See more at "JGit Authentication Explained"

JGit provides an abstract JSchConfigSessionFactory that uses JSch to establish SSH connections and requires its configure() to be overridden

The OP Ash adds in the comments:

The problem was in .ssh/config file where needed lines are commented including private key identity.