text:
Q: Using Needspace within paragraph provides too much space I am trying to implement the solution provided in Equation tag in twoside-mode outer. It seems the solution provides too much space above the align environment. The following code reproduces the problem, and you can also view the attached picture. Compare the first paragraph to the second paragraph.
\documentclass{article}
\usepackage{amsmath}
\usepackage{needspace}

\begin{document}

\setbox0=\hbox{%
\begin{minipage}{\linewidth}%
\begin{align}
a^2=b^2+c^2, \\ d^2 = e^2 + f^2.
\end{align}
\end{minipage}%
}

Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa:
\Needspace{\ht0}
\begin{align}
a^2=b^2+c^2, \\ d^2 = e^2 + f^2.
\end{align}
Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus.

Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa:
\begin{align}
a^2=b^2+c^2, \\ d^2 = e^2 + f^2.
\end{align}
Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus.

\end{document}

The manual of the Needspace package does make a note that \Needspace should not be used within paragraphs; this might be causing the issue. I would like the spacing within both paragraphs to be identical. How can I achieve this?
Remark. Initially, I thought the problem was caused by Extra space above boxed multi-line equation, but the solution to add
\setlength\abovedisplayskip{0pt}

within the minipage had no effect. This suggests the issue occurs because of the \Needspace command.

A: I can confirm that the problem is that \Needspace (once it parses for starred or unstarred invocation) issues a \par as its opening macro (see \makeatletter\meaning\@needsp@).  SO the extra space is essentially the result of a new paragraph being inserted prior to the align environment.
Thus, here, before the \Needspace invocation, I issue a \vspace{\dimexpr-\baselineskip-\parskip\relax}.  In this MWE, I alter \parskip, just to confirm its proper use in my solution.
Whether this will work for you in general, I could not say.
Per David's comment, I have also invoked the minipage with the [b] option, so that box depth does not come into play.
\documentclass{article}
\usepackage{amsmath}
\usepackage{needspace}
\parskip 3em
\begin{document}

\setbox0=\hbox{%
\begin{minipage}[b]{\linewidth}%
\begin{align}
a^2=b^2+c^2, \\ d^2 = e^2 + f^2.
\end{align}
\end{minipage}%
}

Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa:%
\vspace{\dimexpr-\baselineskip-\parskip\relax}\Needspace{\ht0}%
\begin{align}
a^2=b^2+c^2, \\ d^2 = e^2 + f^2.
\end{align}
Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus.

Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa:
\begin{align}
a^2=b^2+c^2, \\ d^2 = e^2 + f^2.
\end{align}
Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus.

\end{document}


text:
Q: Why does this node CL generate multiple prompts? I'm noticing a strange behavior in node when working on the command line directly with stdin/stdout.  This program should prompt you to enter some text, appends the text to a file fp.txt, then prompt you to do it again ad infinitum
var fs = require('fs'), stdin = process.stdin, stdout = process.stdout;

function prompt() {
  stdout.write('Enter text: ');
  stdin.resume();
  stdin.setEncoding('utf8');
  stdin.on('data', enter);
}

function enter(data) {
  stdin.pause(); // this should terminate stdin
  fs.open('fp.txt', 'a', 0666, function (error, fp) {
    fs.write(fp, data, null, 'utf-8', function() {
        fs.close(fp, function(error) {
            prompt();
        });
      });
  });
}

prompt();

After the second entry, the prompt will fire twice, then four times.  (more than that I get a warning)
Enter text: foo
Enter text: bar
Enter text: Enter text: baz
Enter text: Enter text: Enter text: Enter text: qux

fp.txt shows 1 foo, 2 bar, 4 baz and 8 qux.  Is there a way to keep a single text-entry loop going using just process.stdin and process.stdout?

A: Every time you call prompt() you're adding a new event listener to stdin. Then, every time you're entering something new on the stdin stream, it's calling all the event listeners you've previously added.
You should call it once at the very start of your script instead (you might as well put setEncoding there too):
var fs = require('fs'), stdin = process.stdin, stdout = process.stdout;

stdin.setEncoding('utf8');
stdin.on('data', enter);

function prompt() {
  stdout.write('Enter text: ');
  stdin.resume();
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: Indexer does not find printf/exit/fprintf (Eclipse + Qt + MinGW integration regarding stuff in stdio.h / stdlib.h / etc.) I have a Qt Project and Eclipse started with the Qt Eclipse integration program.
I am using the newest version of Qt (4.3.4), Eclipse and MinGW.
My problem is, that the Eclipse Indexer does not find stuff like printf()/fprintf()/exit()! The code compiles fine and the program runs normally!
e.g:
static void mouseHandler(int event, int x, int y, int flags, void *param)
{
switch(event) {
/* left button down */
case CV_EVENT_LBUTTONDOWN:
    MousePointerPosition = cvPoint(x,y);
    leftClicks = 1;
    break;

    /* right button down */
case CV_EVENT_RBUTTONDOWN:
    fprintf(stdout, "Right button down (%d, %d).\n", x, y);
    break;

    /* mouse move */
case CV_EVENT_MOUSEMOVE:
    break;
}
}

I included a screenshot of the directories and files I included (note: I used Qt 4.7.3 in the screenshot, shouldn't make a difference)!
Any suggestions?
Here's a link to the screenshot (I am a new user..):
screenshot


text:
Q: VSCode debug move breakpoint back to previous In Visual Studio usually I take the current break point and move it back to the previous line but in vscode I don't know how to do it.
Please advise.

A: There are two possible commands that may help you - they don't work that well for me but you may have better luck.
I believe you are looking for the debug.jumpToCursor command which doesn't have a default keybinding.  Put your cursor on the previous line and trigger the command.
It doesn't show up in the command palette for some reason so you will have to set your own keybinding for it to work.  In keybindings.jon:
 {
    "key": "ctrl+alt+'",
    "command": "debug.jumpToCursor"
  },

Your language server may not support this functionality though yet, it is fairly new.  See also github issues: jump to cursor.
There is also a Run to cursor command.  Move your cursor where you want and right-click, "run to Cursor" is in the context menu.  See the link above for the differences between these two commands:

"Move to line" can be used to set the PC (Program Counter) to any
  location without executing the code between the current location and
  the destination. So you can even go backward with this. "Run To
  Cursor" can only go forward and executes everything in between.


text:
Q: Using Font Awesome with Petite Vue I am trying to use Font Awesome with Petite Vue. As it is a lightweight version of Vue with no build step, I cannot use the Font Awesome Vue Component.
I am using a Font Awesome Pro Kit (web fonts to avoid CORS issues) and importing Font Awesome and Petite Vue in a


text:
Q: Convert Postman Collection to PDF I've developed a pretty extense API, and I have it on Postman, which works pretty nice. Now I have to generate an html doc to keep it versioned inside /docs along with my sources.
Is there a tool or a way to achieve this? I really don't want to write all this documentation.I don't want to use Postman publish docs also. Sharing the postman collection is not an option
How can we convert Postman Collection to PDF/Word document?

A: The best I've found is Postman to HTML (properly, not file > save)

*

*Install this anywhere in your PATH: https://github.com/aubm/postmanerator

*Right click on your collection in Postman and click export, which will give you a JSON file

*Run postmanerator -output=/var/www/public/api.html -collection=/var/www/my-collection.json in cli

You can create your own themes too which collectively is what we all want to be able to do straight out of Postman

A: You can publish the documentation of your collection through postman :

*

*Click on the ... -> Publish Docs.

This will open a new page to postman website in which you can preview your documentation.

*Click on Preview Documentation, it will open a new page as the html version of the documentation.

*Right click to display chrome option Print it

This will provide you the option to save it as a pdf

This answer was inspired from here for Creating html doc from postman collection.

A: For newer versions of postman try this

*

*Go to your collection

*Right click the collection and go to "View Documentation"

*Then top right hand corner, press "Publish"

A: You can also get the PDF version by clicking :


text:
Q: In Angularjs can a controller nested inside a directive set the ng-model of the directive? I have a directive that uses ng-model controller and gets it model value from the controller it's inside, "myController". I'm using transclude=true and ng-transclude. This is a general purpose directive that I want to allow my colleagues to re-use.  I want to let the consumer click the button and it set ngModel value to whatever value they want but basically always some object. How do I properly set that up? I realize inside the directive I can call ngModel.$setValue or $setViewValue etc... Sorry I am still new to angularjs, specifically directives. Also should I be using a controller inside the directive? I know the object definition for directives has that ability although I don't really know how or when to leverage that. Lastly is it ok to transclude controllers into directives, as in "nestedInDirController"? Thanks for any tips, tricks, examples, or advice.
jsfiddle here

           <various-controls-in-here />

angular.module('myApp', [])
 .directive('fooDirective', function(){

    var template = '

 <button ng-click="someFunc()">I want to update ng-model in the directive, which in turn will update myController $scope.viewModel.foo</button>
';
   return {
      transclude: true,
      require: '?ngModel',
      template: template,
      compile: function(tElement, tAttrs, transclude){

         return function(scope, element, attrs, ngModel){

         }
      }
    };
 });

function myController($scope){

  $scope.viewModel = { foo : { bar: 'baz'}};
 }

function nestedInDirController($scope){

  $scope.someFunc = function(){
      alert('I was called');
      //how can I set ng-model in foo-directive from this controller?
  }

}

A: http://jsfiddle.net/jSEba/
This is one way to satisfy your need by using event emission.
i.e. letting directive to $broadcast event into its child scope,
so that transcluded child scope can catch via $on to react to the
button click.
angular.module('myApp', [])
.directive('fooDirective', function(){
    var template = '

 <button ng-click="someFunc()">I want to update ng-model in the directive, which in turn will update myController $scope.viewModel.foo</button>
';
    return {
        transclude: true,
        template: template,
        link: function(scope, elem, attrs) {
            scope.someFunc = function() {
                scope.$broadcast('buttonclick', { valname: attrs.fooDirective });
            };
        }
    };
});

function myController($scope){
    $scope.viewModel = { foo : { bar: 'baz'}};
}

function nestedInDirController($scope){
    $scope.$on('buttonclick', function(event, arg) {
        $scope.$eval( arg.valname + " = 'new value'");
    });
}

I'm suspecting there may be a better way, though.

A: This is another solution using a Shared service between the directive and the controllers.
(You could create a better service to enforce the required data structure to be shared between the controllers in that specific case, instead of the general example.)
Here is a jsfiddle http://jsfiddle.net/PguFh/15/ (a little updated after I wrote the code below).
index.html

{{viewModel.foo|json}}

app.js
angular.module('myApp', [])

.factory('Shared', function() {
    var shared = {};

    return {
        set: function(value) {
            shared = value;
        },
        get: function() {
            return shared;
       }
    }
})

.directive('fooDirective', function(Shared){

    var template = '

 <button ng-click="shared.someFunc()">I want to update ng-model in the directive, which in turn will update myController $scope.viewModel.foo</button>
';
    return {
        transclude: true,
        require: '?ngModel',
        template: template,
        compile: function(tElement, tAttrs, transclude){

            return function(scope, element, attrs, ngModel) {
                scope.shared = Shared.get();
            }
        }
    };
});

function myController($scope, Shared){

    $scope.viewModel = { foo : { bar: 'baz'}};
    Shared.set({
        viewModel: $scope.viewModel,
        someFunc: function() { alert('default?'); }
    });
}

function nestedInDirController($scope, Shared){
    var shared = Shared.get();
    shared.someFunc = function(){
        alert('I was called');
        //how can I set ng-model in foo-directive from this controller?
        shared.viewModel.foo.bar = "baz.modified";
    }

}


text:
Q: Redirect http access of a program in Windows 7 My Eclipse is trying to contact fixed http urls (to get m2e connectors). These addresses are unavailable due to some proxy settings that I cannot change.
Is there a way to redirect the calls of Eclipse to some other address, i.e. is there a way to tell Windows 7 to redirect http accesses that programs try to make?

A: If you know the name of the server you can cancel them as the attached picture.
Create entries in the file C:\WINDOWS\System32\Drivers\Etc\hosts
In the example image, I redirected the address www.google.com to the IP of my own computer, 127.0.0.1
In your case maybe you can replace www.google.com to the address you want to inhibit.


text:
Q: Visual Studio Ctrl+ Comma equivalent in Intellij I am trying to find that Navigate To command just like in Visual Studio.
In VS 2013 Ctrl + ,(Comma) opens a search bar and then it searches the related objects properties classes all the related stuff and when you press enter it will navigate you easily.
What is the equivalent of Ctrl + ,(Comma) in IntelliJ?

A: I have found out that double pressing ↑(Shift) button has the pretty much same command for IntelliJ


text:
Q: Правильно построить замыкание Создаю некоторый класс, который при инициализации получает список ключей полей и должен принять из базы редис по этим ключам некоторые данные, которые надлежит хранить в классе до его отработки. Делаю так:
heap =  function(arr) {
        var self = this;
        this.list = {};

        for(var key in arr){
             clientRedis.hgetall("heap:"+arr[key], function(err,obj){
                 (function(i){
                     self.list[i] = obj;
                 })(arr[key]);
             });
        }
};

Однако, после создания new heap(data) в heap.list сидит один объект -- последний из обрабатываемых. Где я ошибся в построении функции замыкания?..

ДОПОЛНЕНИЕ:функции вызова методов библиотеки clientRedis -- асинхронные, может мне коллбек нужен вместе с замыканием?
A: (function(arg){

}(my_arg));

Так понятнее? =)
Если я все правильно понимаю, то закрывающая скобка у вас не на месте. Соответственно, i у вас всегда 0, оно не задается через my_arg, который у вас arr[key]
A: внимание, правильный ответ!

heap =  function(arr) {
    var self = this;
    this.list = {};

    for(var key in arr){
         (function(i) {
             clientRedis.hgetall("heap:"+i, function(err,obj){
                 self.list[i] = obj;
             });
         })(arr[key]);
    }
};

т.е., одеть в функцию-анонимку нужно было всю логику, теперь все ОК, создаются все объекты. ВСем спасибо за внимание!


text:
Q: Align multiple equations IEEEeqnarray I am trying to align multiple equations left in a two column environment.
The equal signs are aligned properly, but are more centered in the column, rahter than aligned on the left side of the column. Could one help me out with proper alignment? Please excuse me for the messy third line equation, but since I am using a two column environment I had to break this equation line as well.
\documentclass[twoside,twocolumn,9pt]{article}
\usepackage{IEEEtrantools}

\begin{document}

    \begin{IEEEeqnarray}{ll}
    P  &= \sum_{i,j; i<j} \left\{ 4\varepsilon_{ij} \left[ \left( \frac{\epsilon_{ij}}{r_{ij}} \right)^{12} - \left(\frac{\epsilon_{ij}}{r_{ij}} \right)^{6} \right] + \frac{q_{i}q_{j}e^{2}}{r_{ij}} \right\} \nonumber\\
       &+ \sum_{i} k_{b,i} (r_{i} - r_{0,i})^{2} + \sum_{i} k_{\theta,i} (\theta_{i} - \theta_{0,i})^{2}  \nonumber\\
       &+ \sum_{i} \frac{1}{2} \left[ k_{\varsigma_{1},i}(1+cos \varsigma) + k_{\varphi_{2},i}(1+cos \varsigma) + \ldots \right. \nonumber\\
    \left. \quad k_{\varsigma_{3},i}(1+cos \varphi) + k_{\varphi_{4},i}(1+cos \varphi)  \right]
    \end{IEEEeqnarray}

\end{document}

Thanks for the help.
John.

A: I'd use rCl for the specification.
\documentclass[twoside,twocolumn]{article}
\usepackage{amsmath}
\usepackage{IEEEtrantools}

\begin{document}

\begin{IEEEeqnarray}{rCl}
P &=& \sum_{\substack{i,j \\ i<j}}
      \biggl\{
        4\varepsilon_{ij} \biggl[
          \left( \frac{\epsilon_{ij}}{r_{ij}} \right)^{\!12} -
          \left(\frac{\epsilon_{ij}}{r_{ij}} \right)^{\!6}
        \biggr]
        + \frac{q_{i}q_{j}e^{2}}{r_{ij}}
      \biggr\}
\nonumber\\
  &+& \sum_{i} k_{b,i} (r_{i} - r_{0,i})^{2} +
      \sum_{i} k_{\theta,i} (\theta_{i} - \theta_{0,i})^{2}
\nonumber\\
  &+& \sum_{i} \frac{1}{2}
      \bigl[ k_{\varsigma_{1},i}(1+\cos \varsigma) +
        k_{\varphi_{2},i}(1+\cos \varsigma)
\nonumber\\
  & &\hphantom{\sum} + k_{\varsigma_{3},i}(1+\cos \varphi) + k_{\varphi_{4},i}(1+\cos \varphi)
     \bigr]
\end{IEEEeqnarray}

\end{document}

Points to note:

*

*\substack under the first summation to save horizontal space and get alignment in the subsequent lines

*sparing use of \left and \right, that make oversized fences

*\! in the exponents to the large parentheses

*\cos and not cos

*a phantom in the last line to achieve better spacing
With align:
\documentclass[twoside,twocolumn]{article}
\usepackage{amsmath}

\begin{document}

\begin{align}
P &= \sum_{\substack{i,j \\ i<j}}
     \biggl\{
       4\varepsilon_{ij} \biggl[
         \left( \frac{\epsilon_{ij}}{r_{ij}} \right)^{\!12} -
         \left(\frac{\epsilon_{ij}}{r_{ij}} \right)^{\!6}
       \biggr]
       + \frac{q_{i}q_{j}e^{2}}{r_{ij}}
     \biggr\}
\nonumber\\
  &+ \sum_{i} k_{b,i} (r_{i} - r_{0,i})^{2} +
     \sum_{i} k_{\theta,i} (\theta_{i} - \theta_{0,i})^{2}
\nonumber\\
  &+ \sum_{i} \frac{1}{2}
     \bigl[ k_{\varsigma_{1},i}(1+\cos \varsigma) +
        k_{\varphi_{2},i}(1+\cos \varsigma)
\nonumber\\
  & \qquad\quad + k_{\varsigma_{3},i}(1+\cos \varphi) + k_{\varphi_{4},i}(1+\cos \varphi)
     \bigr]
\end{align}

\end{document}


text:
Q: ModelMapper - Failed to convert inner class to dto I have a error using modelmapper when try convert entity to dto.
My java classes are:
User class:
@Data
@NoArgsConstructor
@Document("user")
public class User{
    @Id
    private String id;
    private String lastname;
    private String name;
    private Rol rol;
    private City city;
    private App app;

}

Rol class:
@Data
@NoArgsConstructor
@Document("rol")
public class Rol{
    @Id
    private String id;
    private String name;
    private String description;
    private boolean state;

}

UserDTO class:
@Data
public class UserDTO {

    private String id;
    private String lastname;
    private String name;
    private RolDTO rol;

    @Data
    public class RolDTO {
        private String id;
        private String nombre;
    }

}

When i try to map User.class to UserDTO.class when modelmapper i have the next error:
ModelMapper modelMapper = new ModelMapper();
modelMapper.map(user, UserDTO.class)

Also, i try using this modelmapper configuration:
ModelMapper modelMapper = new ModelMapper();
modelMapper.getConfiguration()
                .setMatchingStrategy(MatchingStrategies.LOOSE)
                .setFieldMatchingEnabled(true)
                .setFieldAccessLevel(Configuration.AccessLevel.PACKAGE_PRIVATE)
                .setMethodAccessLevel(AccessLevel.PACKAGE_PRIVATE);
modelMapper.map(user, UserDTO.class)

Error:
Failed to instantiate instance of destination com.gh360.rest.dto.UserDTO$RolDTO. Ensure that com.gh360.rest.dto.UserDTO$RolDTO has a non-private no-argument constructor.

1 error] with root cause

java.lang.NoSuchMethodException: com.gh360.rest.dto.UserDTO$RolDTO.<init>()
at java.base/java.lang.Class.getConstructor0(Class.java:3427) ~[na:na]
    at java.base/java.lang.Class.getDeclaredConstructor(Class.java:2631) ~[na:na]
    at org.modelmapper.internal.MappingEngineImpl.instantiate(MappingEngineImpl.java:332) ~[modelmapper-2.3.0.jar:na]
    at org.modelmapper.internal.MappingEngineImpl.createDestinationViaGlobalProvider(MappingEngineImpl.java:367) ~[modelmapper-2.3.0.jar:na]
    at org.modelmapper.internal.MappingContextImpl.getParentDestination(MappingContextImpl.java:316) ~[modelmapper-2.3.0.jar:na]
    at org.modelmapper.internal.MappingEngineImpl.setDestinationValue(MappingEngineImpl.java:226) ~[modelmapper-2.3.0.jar:na]
    at org.modelmapper.internal.MappingEngineImpl.propertyMap(MappingEngineImpl.java:187) ~[modelmapper-2.3.0.jar:na]
    at org.modelmapper.internal.MappingEngineImpl.typeMap(MappingEngineImpl.java:151) ~[modelmapper-2.3.0.jar:na]
    at org.modelmapper.internal.MappingEngineImpl.map(MappingEngineImpl.java:114) ~[modelmapper-2.3.0.jar:na]
    at org.modelmapper.internal.MappingEngineImpl.map(MappingEngineImpl.java:71) ~[modelmapper-2.3.0.jar:na]
    at org.modelmapper.ModelMapper.mapInternal(ModelMapper.java:573) ~[modelmapper-2.3.0.jar:na]
    at org.modelmapper.ModelMapper.map(ModelMapper.java:406) ~[modelmapper-2.3.0.jar:na]
    at com.gh360.rest.mapper.ColaboradorMapper.toColaboradorBuscarDTO(ColaboradorMapper.java:29) ~[classes/:na]
    at com.gh360.rest.controller.ColaboradorController.buscarPorId(ColaboradorController.java:48) ~[classes/:na]
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:na]
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:na]
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:na]
    at java.base/java.lang.reflect.Method.invoke(Method.java:564) ~[na:na]
    at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:190) ~[spring-web-5.2.6.RELEASE.jar:5.2.6.RELEASE]
    at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:138) ~[spring-web-5.2.6.RELEASE.jar:5.2.6.RELEASE]
    at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:105) ~[spring-webmvc-5.2.6.RELEASE.jar:5.2.6.RELEASE]
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:879) ~[spring-webmvc-5.2.6.RELEASE.jar:5.2.6.RELEASE]
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:793) ~[spring-webmvc-5.2.6.RELEASE.jar:5.2.6.RELEASE]
    at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87) ~[spring-webmvc-5.2.6.RELEASE.jar:5.2.6.RELEASE]
    at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1040) ~[spring-webmvc-5.2.6.RELEASE.jar:5.2.6.RELEASE]
    at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:943) ~[spring-webmvc-5.2.6.RELEASE.jar:5.2.6.RELEASE]
    at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1006) ~[spring-webmvc-5.2.6.RELEASE.jar:5.2.6.RELEASE]
    at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:898) ~[spring-webmvc-5.2.6.RELEASE.jar:5.2.6.RELEASE]
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:634) ~[tomcat-embed-core-9.0.35.jar:9.0.35]
    at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:883) ~[spring-webmvc-5.2.6.RELEASE.jar:5.2.6.RELEASE]
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:741) ~[tomcat-embed-core-9.0.35.jar:9.0.35]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231) ~[tomcat-embed-core-9.0.35.jar:9.0.35]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.35.jar:9.0.35]
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53) ~[tomcat-embed-websocket-9.0.35.jar:9.0.35]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-9.0.35.jar:9.0.35]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.35.jar:9.0.35]
    at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:100) ~[spring-web-5.2.6.RELEASE.jar:5.2.6.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119) ~[spring-web-5.2.6.RELEASE.jar:5.2.6.RELEASE]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-9.0.35.jar:9.0.35]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.35.jar:9.0.35]
    at org.springframework.web.filter.FormContentFilter.doFilterInternal(FormContentFilter.java:93) ~[spring-web-5.2.6.RELEASE.jar:5.2.6.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119) ~[spring-web-5.2.6.RELEASE.jar:5.2.6.RELEASE]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-9.0.35.jar:9.0.35]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.35.jar:9.0.35]
    at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:201) ~[spring-web-5.2.6.RELEASE.jar:5.2.6.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119) ~[spring-web-5.2.6.RELEASE.jar:5.2.6.RELEASE]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-9.0.35.jar:9.0.35]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.35.jar:9.0.35]
    at org.springframework.web.filter.CorsFilter.doFilterInternal(CorsFilter.java:92) ~[spring-web-5.2.6.RELEASE.jar:5.2.6.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119) ~[spring-web-5.2.6.RELEASE.jar:5.2.6.RELEASE]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-9.0.35.jar:9.0.35]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.35.jar:9.0.35]
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:202) ~[tomcat-embed-core-9.0.35.jar:9.0.35]
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96) ~[tomcat-embed-core-9.0.35.jar:9.0.35]
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:541) ~[tomcat-embed-core-9.0.35.jar:9.0.35]
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:139) ~[tomcat-embed-core-9.0.35.jar:9.0.35]
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92) ~[tomcat-embed-core-9.0.35.jar:9.0.35]
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:74) ~[tomcat-embed-core-9.0.35.jar:9.0.35]
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:343) ~[tomcat-embed-core-9.0.35.jar:9.0.35]
    at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:373) ~[tomcat-embed-core-9.0.35.jar:9.0.35]
    at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:65) ~[tomcat-embed-core-9.0.35.jar:9.0.35]
    at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:868) ~[tomcat-embed-core-9.0.35.jar:9.0.35]
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1590) ~[tomcat-embed-core-9.0.35.jar:9.0.35]
    at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49) ~[tomcat-embed-core-9.0.35.jar:9.0.35]
    at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1130) ~[na:na]
    at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:630) ~[na:na]
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) ~[tomcat-embed-core-9.0.35.jar:9.0.35]
    at java.base/java.lang.Thread.run(Thread.java:832) ~[na:na]

If RolDTO class is externalized, modelmapper works fine. I hope can you help me with this problem.
Thanks.

A: Nested Classes
Serialization of inner classes, including local and anonymous classes, is strongly discouraged. When the Java compiler compiles certain constructs, such as inner classes, it creates synthetic constructs; these are classes, methods, fields, and other constructs that do not have a corresponding construct in the source code.

A: Use @NoArgsConstructor in both UserDTO and RolDTO. And create RolDTO class outside of UserDTO.


text:
Q: What is the convention in Rails (with asset pipeline) for internationalization inside CSS? I know CSS isn't supposed to have content, but it does, like this nice box (below) extracted from the Twitter Bootstrap documentation CSS:

/* Echo out a label for the example */
.bs-docs-example:after {
  content: "Example";
}

I don't care for "Example", I use something like that as a mixin:
.box (@legend) {
  /* Echo out a label for the example */
  &:after {
    content: @legend;
  }
}

Then I don't need really dynamic CSS, I can easily include the mixin in a class, but instead of passing "Observation" I need to pass t 'box.observation':
.observation {
  .box("<%= t 'box.observation' =>");
}

Rails is supposed to follow Conventions over Configuration, it is very easy to just add a static CSS/LESS/SCSS and it is already included in all pages in a single minified CSS. What is the convention for internationalized CSS? For example, where I am supposed to put declarations like that of .observation?

A: I could generate one CSS per locale as suggested in this answer, but since the CSS is the same except by the I18n bits, I would have either of:

*

*A folder with a multitude of static CSS/LESS with the locale inlined, e.g.:
/* en */
.observation {
  .box("Observation");
}

*Lots of exactly identical dynamic CSS's, e.g.
/* en */
html[lang=en] {
  .observation {
    .box("Observation")
  }
}

Instead I choose to create a CSS and ERB view and deliver using using page caching with the locale code in the URL, this way there is no duplication. See code below.
config/routes.rb
X::Application.routes.draw do
  get 'index.:locale.:format' => 'css#index',
    constraints: { locale: /[a-z]{2}(-[A-Z]{2})?/,
                   format: 'css' }
end

app/controllers/css_controller.rb
class CssController < ActionController::Base
  caches_page :index
  def index
    @locale = params[:locale]
  end
end

app/views/css/index.css.less.erb
@import "mixins";
.observation {
  .box("<%= t 'box.observation', locale: @locale %>");
}

app/assets/stylesheets/mixins.less
.box (@legend) {
  /* Echo out a label for the example */
  &:after {
    content: @legend;
  }
}

This example would work as is if it was a simple ERB view, but since it is using Less, I have to parse the ERB and LESS manually as of rails 4:
class CssController < ActionController::Base
  caches_page :index

  def index
    @locale = params[:locale]
    erb_source  = find_template.source
    less_source = Tilt::ERBTemplate.new { erb_source }.render(self)
    css_source  = Less::Parser.new(paths: Rails.application.config.less.paths).parse(less_source).to_css
    render text: css_source
  end

  private

  def find_template(_action_name = action_name)
    lookup_context.disable_cache { lookup_context.find_template(_action_name, lookup_context.prefixes) }
  end
end

A: You don't need to generate a new CSS file for each locale - that borders on madness.  Why does your CSS care about the text content of your website?
I think your best bet would be to use a data-attribute to grab the value...
<div class='bs-docs-example' data-before-content='<%= t.css_example %>'>
  <!-- html here -->
</div>

And then in your css:
.bs-docs-example:after {
  content: attr(data-before-content);
}

You could probably find a way to extract this into a partial (or helper), so that your erb file ends up like this:
<%= docs_example do %>
  <!-- html here -->
<% end %>

And a helper method:
def docs_example
  content_tag(:div, class: "bs-docs-example", "data-before-content" => t.css_example) do
    yield
  end
end


text:
Q: Error while configuring Node Canvas module with jpeg support on Windows 2016 I'm trying to build an application with fabric.js on node server. I followed the documented steps and i was able to set the canvas and fabric modules.
When i tried to include support for jpeg files by updating the binding.gyp file, the node.canvas breaks.
Current Configuration
v8: '5.1.281.83'
node@6.6.0
node-gyp@3.8.0
npm: '6.4.0-next.0'

Canvas pre-requisite versions
GTK - gtk+-bundle_2.22.1-20101229_win64
jpeglib - libjpeg-turbo-2.0.0-vc64

Installation Steps
npm i canvas

canvas project builds successfully without any errors
I updated binding.gyp in "node_modules/canvas" folder with the following
'with_jpeg%': 'true',
'libjpeg_root%': 'C:/libjpeg-turbo64',

updated the condition
['with_jpeg=="true"', {
  'defines': [
    'HAVE_JPEG'
  ],
  'conditions': [
    ['OS=="win"', {
     'copies': [{
        'destination': '<(PRODUCT_DIR)',
        'files': [
          '<(libjpeg_root)/bin/jpeg62.dll',
        ]
      }],
      'libraries': [
         '-l<(libjpeg_root)/lib/jpeg.lib'
      ],
      'include_dirs': [
        '<(libjpeg_root)/include'
      ]
    }, {
      'libraries': [
        '-ljpeg'
      ]
    }]
  ]
}]

after updating the binding file node-gyp rebuild works fine without any issues and once done if i run the test
Test Canvas Code
var Canvas = require('canvas');

On running the test code i get the following error
Error: The specified module could not be found.
\\?\C:\<AppPath>\node_modules\canvas\build\Release\canvas.node
    at Error (native)

If i set with_jpeg variable to false and rebuild the test code works fine without any issue. I'm not quite sure about where i'm going wrong. Can somebody please help me to get this issue resolved.

A: JPEG support on Windows requires node-canvas 2.x, and fabric.js uses 1.6.x currently. There are other source code changes required besides the build config changes that you made (see https://github.com/Automattic/node-canvas/pull/841/files#diff-b92a52ffb02b7fb42c340919b0f983d6).
You can save as a PNG until fabric.js upgrades, possibly using another tool to convert the PNG to a JPEG if you really want a JPEG.


text:
Q: Add vertical line in a DT datatable in a shiny app with custom container I want to add a vertical line between groups of columns. Here is a desired outcome:
---------
g1  | g2
---------
a b | a b
---------
1 2 | 3 4
---------

and a shiny app to start with:
library(shiny)
library(DT)
library(htmltools)

runApp(shinyApp(
  ui <- basicPage(
    DT::dataTableOutput('table1')
  ),
  server = function(input, output) {
    output$table1 <- DT::renderDataTable({
      datatable(data.frame(a1 = 1, b1 = 2, a2 = 3, b2 = 4), rownames = FALSE,
                container = withTags(table(
                  class = 'display',
                  thead(
                    tr(
                      th(colspan = 2, 'g1'),
                      th(colspan = 2, 'g2')
                    ),
                    tr(
                      lapply(rep(c('a', 'b'), 2), th)
                    )
                  )
                ))
      )
    })
  }
))

Current output from shiny app above:

A: You could add a css class that adds a border on the right of the cells and apply it to the relevant columns using the columnDefs options. For the header, you can set the class using the initComplete callback.
Here's an example:
library(shiny)
library(DT)
library(htmltools)

runApp(shinyApp(
  ui <- basicPage(
    tags$head(
      tags$style(HTML(".cell-border-right{border-right: 1px solid #000}"))),
    DT::dataTableOutput('table1')
  ),
  server = function(input, output) {
    output$table1 <- DT::renderDataTable({
      datatable(data.frame(a1 = 1, b1 = 2, a2 = 3, b2 = 4), rownames = FALSE,
                container = withTags(table(
                  class = 'display',
                  thead(
                    tr(
                      th(colspan = 2, 'g1'),
                      th(colspan = 2, 'g2')
                    ),
                    tr(
                      lapply(rep(c('a', 'b'), 2), th)
                    )
                  )
                )),options = list(initComplete = JS(
                  "function(settings, json) {",
                  "var headerBorder = [0,1];",
                  "var header = $(this.api().table().header()).find('tr:first > th').filter(function(index) {return $.inArray(index,headerBorder) > -1 ;}).addClass('cell-border-right');",
                  "}"),columnDefs=list(list(className="dt-right cell-border-right",targets=1))
      ))
    })
  }
))

The jquery selectors are used to select the first row of the header and the first th tag, so that the border is only added to the g1 cell.


text:
Q: Dismissing AlertDialog in Flutter I have simple Flutter app with list of items that are loaded from Firebase database (Cloud Firestore).

As you can see - there is button for adding items and each item can be deleted or edited. When I press edit button for selected item, AlertDialog with TextField appears, in this TextField user can see current item name and edit it.  I have problems only with dismissing dialog after editing.
   new IconButton(
      icon: new Icon(Icons.edit, color: Colors.white),
      onPressed: (){ showItemUpdateDialog(context, document); }
   )
   .......

void showItemUpdateDialog(BuildContext context, DocumentSnapshot item) {

  String itemName = "";
  var textContoller = new TextEditingController();
  textContoller.text = item['name'];

  var dialog = new AlertDialog(
    title: new Text("item name"),
    content: new TextField(
      controller: textContoller,
      onChanged: (value) {newName = value;},
    ),
    actions: <Widget>[
      new FlatButton(
        child: Text("cancel"),
        onPressed: (){
          Navigator.pop(context);
        },
      ),
      new FlatButton(
          child: Text("Update"),
          onPressed: () {
            updateItemOnServer(item, newName);
            Navigator.pop(context);
          }
      )
    ],
  );

  showDialog(context: context, child: dialog);
}

Value is updating correctly but AlertDialog is not dismissed. Error code is below. I think that it is due to that is was called by item that was modified and updated from server.

flutter: The following assertion was thrown while handling a gesture:
  flutter: Looking up a deactivated widget's ancestor is unsafe.
  flutter: At this point the state of the widget's element tree is no
  longer stable. To safely refer to a flutter: widget's ancestor in its
  dispose() method, save a reference to the ancestor by calling flutter:
  inheritFromWidgetOfExactType() in the widget's didChangeDependencies()
  method.

A: With the latest Flutter use:
Navigator.of(context).pop();

instead of
Navigator.pop(context);

For some reason it pops twice from the stack when popping Dialog
Do let me know if this solves the problem!

A: Try this,
 Navigator.of(context, rootNavigator: true).pop(),

A: Try This,
Navigator.popUntil(context, ModalRoute.withName('/login'));


text:
Q: What does 'processor synchronizes I/O instruction execution with external bus activity' mean? The following excerpt is from Intel® 64 and IA-32 Architectures Software Developer's Manual, Volume 1: Basic Architecture (p.432, http://www.intel.com/Assets/PDF/manual/253665.pdf)

When the I/O address space is used instead of memory-mapped I/O, the situation is
different in two respects:
• The processor never buffers I/O writes. Therefore, strict ordering of I/O
operations is enforced by the processor. (As with memory-mapped I/O, it is
possible for a chip set to post writes in certain I/O ranges.)
• The processor synchronizes I/O instruction execution with external bus activity
(see Table 14-1).
Table 14-1. I/O Instruction Serialization

------------------+----------------------------------+----------------------------------
                  | Processor Delays Execution of …  | Until Completion of …
                  +---------------+------------------+-----------------+----------------
Instruction Being | Current       | Next             |                 |
Executed          | Instruction?  | Instruction?     | Pending Stores? | Current Store?
------------------+---------------+------------------+-----------------+----------------
IN                |     Yes       |                  |      Yes        |
INS               |     Yes       |                  |      Yes        |
REP INS           |     Yes       |                  |      Yes        |
OUT               |               |       Yes        |      Yes        |       Yes
OUTS              |               |       Yes        |      Yes        |       Yes
REP OUTS          |               |       Yes        |      Yes        |       Yes
------------------+---------------+------------------+-----------------+----------------

Can anyone explain me what this table means? Especially, I have no idea what this 'pending stores' or  'current store' means.

A: The processor has a write queue, so when store something to memory, the data just goes into the queue. The instruction is considered complete as soon as the data goes into the queue -- you can start executing the next instruction without waiting for the data to go from the queue to the destination memory.
I/O space is not the same though. If you're reading from I/O space, your read won't even begin until all data in the memory write queue at that time has been written to memory. If you're writing to I/O space, the instruction starts to execute immediately, but the next instruction can't execute until all the data in the write queue has been written out and the data being written by the current instruction has been written.
The reason for this is fairly simple: when you're dealing with memory, the processor knows about all the address mapping, so if (for example) you write something to memory, and (almost) immediately read it back in, the processor can/will detect that the data is actually in the write queue, and and ensure that your read gets the current data.
With I/O space, however, the processor doesn't know how a read/write from/to a particular address might be related to a previous read/write in the memory space. For example, you might be sending some data to memory, and then telling your graphics card to use that data as a texture. You might not be as well, but the CPU has no real way to tell, so it has to make the pessimistic assumption, and wait for the data you wrote to memory to actually get there (or at least leave the CPU) before it tells the graphics card to use that data.


text:
Q: RUST Borrowing issue on custom concurrentMap Struct Hello Im a RUST begginer Im dealing with some Borrowing issues that I can't solve
I want to make a Concurrent Map, I saw some examples to do it where I need it and it works, but now I want to generalize the solution writing my own mod.
Here it is
use std::collections::HashMap;
use std::hash::Hash;
use std::sync::Mutex;

pub struct ConcurrentMap<K, V> {
    elems: Mutex<HashMap<K, V>>,
}

impl<K: Hash + Eq, V> ConcurrentMap<K, V> {
    pub fn new() -> ConcurrentMap<K, V> {
        let map: HashMap<K, V> = HashMap::new();
        ConcurrentMap {
            elems: Mutex::new(map),
        }
    }

    pub fn get(&self, k: &K) -> Option<&V> {
        let map = self.elems.lock();
        match map {
            Ok(t) => {
                return match t.get(k) {
                    None => None,
                    Some(v) => Some(v),
                }
            }
            Err(e) => panic!("GET Concurrent Map Error: {}", e),
        }
    }
}

My problem is in Some(v) => Some(v) line, I dont know how to copy the value.
If I make that V implement Copy trait then I can't use this Map to store String because String does not implement Copy trait.
Maybe the last matching is not necessary but is the last thing I tried.

A: As @loganfsmyth suggested, I implemented Clone insted of Copy trait in V(alue) type.
Also, as I mention, I changed last matching with a simple Map combinator
So this is how it looks now
use std::collections::HashMap;
use std::hash::Hash;
use std::sync::Mutex;

pub struct ConcurrentMap<K, V> {
    elems: Mutex<HashMap<K, V>>,
}

impl<K: Hash + Eq, V: Clone> ConcurrentMap<K, V> {
    pub fn new() -> ConcurrentMap<K, V> {
        let map: HashMap<K, V> = HashMap::new();
        ConcurrentMap {
            elems: Mutex::new(map),
        }
    }

    pub fn insert(&self, k: K, v: V) {
        let map = self.elems.lock();
        match map {
            Ok(mut t) => t.insert(k, v),
            Err(e) => panic!("INSERT Concurrent Map Error: {}", e),
        };
    }

    pub fn get(&self, k: K) -> Option<V> {
        let map = self.elems.lock();
        match map {
            Ok(t) => t.get(&k).map(|v| v.clone()),
            Err(e) => panic!("GET Concurrent Map Error: {}", e),
        }
    }
}

Usage example:
lazy_static! {
    static ref PROPERTIES: ConcurrentMap<String, String> = ConcurrentMap::new();
}

PROPERTIES.insert("Key".to_string(), "val".to_string());
PROPERTIES.get("Key".to_string()).unwrap().to_string();


text:
Q: image drawable is not showing in imageview i am working with svgs in my app. the issue is that my svgs are not loading when i create image view of size 1500px x 500px. i have to keep size of image view in pixels and it is fixed. but when i decrease the size of image view to 950px x 430px, the svg is showing properly. i am keeping svgs in my assets.
i am working on oppo and my device has android version 4.2
(P.S. i have checked the same svg with same dimensions of image view on other device and it is working alright)
please help


text:
Q: SwiftUI text wrapping disabled on click interaction using `.textSelection(.enabled)` I'm creating an error message dialog in swiftUI and I'd like the user to be able to copy and paste the error message from the dialog. I use Text like this to achieve that:
ScrollView {
    Text(debugMessage)
        .padding(.horizontal, 20)
        .padding(.top, 10)
        .textSelection(.enabled)
}.padding(.bottom, 20)

And it looks fine at first (placeholder error message):

But once the user clicks on the error message it collapses and looks like this:

This is not a problem functionally since the user can still select all of the text and paste it into google or our GitHub issues. However it looks ridiculous and feels unpolished so I'd really like to get to the bottom of this. Any ideas??


text:
Q: Questions closed as duplicates without second thoughts ok, I found that funny: both questions are marked as duplicate of each other!
Why are most marketing tags (Omniture, XE, etc) written with document.write()?
Why use document.write?
Generally speaking, I find that people tagging duplicates should give it more thought. I recently had a question closed because a similar question with an accepted but inaccurate answer was posted... 4 years ago!
svg on older IE browsers
Not sure how this could work, but I just wish there was a safeguard to prevent people from jumping too fast on the close button, and maybe give the OP a chance to explain the difference. The points I wanted to make with my examples:

*

*it's strange to mark a question as duplicate of a more recent question

*people should understand that 4 years are a lot in the programming world and that the older answer is possibly outdated

*accepted answer doesn't necessarily mean correct answer

A: It's an odd edge case.  Both questions were being closed at right around the same time, they each had some votes to close as a duplicate of the other before either was actually closed.
If memory serves, there has since been a code change to prevent this from happening in the future.
In any case, you can simply flag one of the post stating that there's a circular duplicate closure and a mod will handle it.
To your edited points:

*

*There is nothing wrong with marking a question as a duplicate of a newer question.  Whatever question is better or has more valuable content should be the canonical question that is left open, regardless of when it's asked.

*If the answers to a question are outdated then either post updated answers to the canonical question, or ensure that the new question differentiates itself from the existing question; make it clear that the answer(s) to that question do not work, and explain why.  Then the questions are no longer duplicates.

*Again, if there isn't a good answer on the duplicate question than one can always be added.  If you really need to you can always add a bounty to the question to look for better answers.


text:
Q: Can you yield from a lambda function? I have a generator function in a class:
self.s = [['a',1],['b',2],['c',3]

def generator(self):
  for r in self.s:
    yield r

In another function I initalize it as a variable:
var = self.generator()

And it's yielded as necessary:
>>> next(var) # returns ['a',1]
>>> next(var) # returns ['b',2]
>>> next(var) # returns ['c',3]

Can defining the generator be done in one line, however? I've considered the below:
var = lambda: [(yield r) for r in self.s]
>>> next(var) # SyntaxError: 'yield' inside list comprehension

Here's a minimal code I'm working with:
class Foo():
  def __init__(self):
    self.s = {}

  def generator(self):
    for r in self.s:
      yield r

  def fetch(self):
    if not self.s:
      self.fetch_gen = self.generator()
      self.s['a'] = 1
      self.s['b'] = 2
      self.s['c'] = 3
    try:
      var = self.s.get(next(self.fetch_gen))
    except StopIteration:
      return None
    return var

BAR = Foo()
while True:
  OUT = BAR.fetch()
  if OUT is None:
    break
  print(OUT)

Output is below:
1
2
3

I just wanted to see if I could get rid of Foo.generator and instead declare the generator in one line.

A: You are returning a list comprehension. You can just do:
var = (r for r in self.s)

that will generate a generator with the values you want. You test it later with next(var) is in your code.


text:
Q: How does self.textField.delegate = self work in swift? I am working with keyboard resign features in iPhone app development. I would like to know why
self.textField.delegate = self

needs to be included into the viewDidLoad of a viewController. I have tried to find reasons of this but no explanation has been clear so far.

A: A few points

*

*The reason you need to set the delegate is because without it the view doesn't know about the view controller. So it wouldn't know about your method textFieldDidEndEditing and it would never be called.

*That is the basic premise of delegate, you are telling that object, "here is an object that I want you to call methods on"

*It doesn't have to be set in viewDidLoad - but it's often the most convient place to set up delegates for views.

*The delegate doesn't have to be the view controller (self), in your case it's the simplest way, but with a UITableView its common to have another class be the delegate so that all the logic isn't in one place and so it can be changed.

A:
The UITextFieldDelegate protocol defines methods that you use to manage the editing and validation of text in a UITextField object. All of the methods of this protocol are optional.
A text field calls the methods of its delegate in response to important changes. You use these methods to validate text that was typed by the user, to respond to specific interactions with the keyboard, and to control the overall editing process. Editing begins shortly before the text field becomes the first responder and displays the keyboard (or its assigned input view).

From more info. check apple doc.
Its not necessary to use self.textField.delegate = self if you don't want to manage the editing and validation of text in a UITextField object as all the methods of UITextFieldDelegate is optional.
For your other questions like what does .delegate = self do??
When you "set the delegate," what you are doing is saying where you want the messages to go.
Hence,

blah.delegate = amazingPlace will send the messages to "amazingPlace".
blah.delegate = somewhereElse will send the messages to "somewhereElse".
blah.delegate = self will send the messages to you.

... check this source link for details

A: Delegates are key concepts in iOS development so I'd suggest taking a good look at the documentation for them. It can be particularly useful to create your own custom delegates in certain situations too so understanding and using them in the right places can really help improve the structure of your projects.
There are a couple of key reasons for using them. Firstly, they allow safe communication between classes. In your example, the textField object that you're using is communicating back to your view controller. This is why you need to set your view controller as its delegate. Otherwise the text field doesn't have a delegate object (your view controller) to communicate with. The text field fires certain methods at certain times, such as textFieldDidBeginEditing, and calls these on its delegate object if it has one. When you register your view controller as the text view's delegate you can tap into these callbacks.
The other benefit is that delegates allow you to separate concerns and encapsulate or abstract responsibilities. It might be that the main concern for the text view is how to handle text in its view but not necessarily what to do when has been entered, or when the return button in the keyboard is pressed, or how to validate text that has been input. It's better that these tasks are handed over to something else, such as a delegate (in Obj-C parlance), and that is why in your example you have to register one class as the delegate for another.

A: As stated before, UITextfield delegation allows you to control events on your textfield.
You ll have the ability to edit functions like
textFieldShoulEndEditing

or
textFieldDidEndEditing

in order to add custom rules, for example : text validation.
Take a look at  Apple doc.
If you don't need it, you can delete this line and UITextfieldDelegate on your class declaration.

A: You need to either set the delegate of a UITextField in code with self.textField.delegate = self
or make your viewcontroller (or any other class) a delegate with class MyViewController: UITextFieldDelegate and set the delegate of the UITextField in the storyboard by control dragging from the textfield to the viewController.


text:
Q: running delphi application on non delphi pc I'm building an application using delphi 7 with ms access 2007 as the database for a client. it runs normally on my laptop (asus) but after I copy the whole project folder and run the Project.exe, it gives me an error "Disk write error".
I've tried googling about "disk write error delphi application" but only found about I/O errors. my application only opens a file after a button click in a form that is called when I click on a submenu, so I'm guessing it's not about I/O..
what is the solution?
thanks in advance
P.S.:
in the project options, the checkbox for building application using runtime packages is already unchecked.
my PC and my client's PC are both using windows 7 32bit (I haven't actually confirmed this with him but I'm guessing he's also using 32bit version because he's not a techy guy)
his PC doesn't have delphi installed
UPDATE :
I forgot that the exact error message was "Disk or network error" instead of "Disk write error".
after googling for the correct error message, I've found out that the problem is that I use a full path for the DataSource in the ADOs' connection string. after I change connection string into "DataSource=.\db\my_db.mdb", the application works perfectly.
even though this question has a negative mark, I'll just leave this solution here in case someone needs it in the future...

A: Here are some different questions.
The "Disk write error" probably is that you need permissions to write in the folder. A simple test is that you execute your application with "admin permissions" to test this.
Different question is the "using runtime packages" check in project options.
If you compile your application with this check, you need to copy the BPL's needed for your application with the executable.
If you compile with this option unchecked, your exe file include all the libraries for execute (not included DLL's or external dependencies).


text:
Q: Alternative of #include in C++ Why is is necessary to use iostream library while writing a program in C++. If i don't want to include this library, so what is the alternative of this iostream library.
Here is my code without including iostream. I tried to use include stdio.h but it does not work.
#include<conio.h>

using namespace std;

void biodata ();

main()
{
    biodata ();
}

void biodata()
{
    cout << "Name: Ijlal Hussain.\nFather Name: Iftikhar Hussin.\nAge: 18. \nStudent of Comsats University Islamabad (Attock Campus)";
}

A: You can use <cstdio> instead of <iostream>, if you just need to output text.
To print a string without formatting, you can use puts. Use printf to print with format and conversion specifiers.
#include<cstdio>

void biodata ();

int main()
{
  biodata ();
  return 0;
}

void biodata()
{
   //using puts
   puts("Name: Ijlal Hussain.\nFather Name: Iftikhar Hussin.\nAge: 18. \nStudent of Comsats University Islamabad (Attock Campus)");

   //using printf
    const char* name = "Ijlal Hussain";
    const char* fathername = "Iftikhar Hussin";
    int age = 18;
    printf("Name: %s.\nFather Name: %s.\nAge: %d. \nStudent of Comsats University Islamabad (Attock Campus)", name, fathername, age);

}

A: You cannot use std::cout without  header so use printf instead with cstdio header .
#include<cstdio>
void biodata ();
main()
{
    biodata ();
}
void biodata()
{
    printf("Name: Ijlal Hussain.\nFather Name: Iftikhar Hussin.\nAge: 18. \nStudent of Comsats University Islamabad (Attock Campus)");
}


text:
Q: Update with switch and inner join I am given a table for a range of option codes, models and availability from someone else. Currently these are updated by hand in the back-end (I know...) and take a whopping 3 months. I want to automate the process, I tried using CASE WHEN but it seems Access cannot handle it. I ran a query that updated based on one clause and it worked fine, see below. Table 1 is in my db, Table 2 is the data I am given translated in to a usable format. It is just a table with 2 columns; option codes and availability (relevant to a specific model)
UPDATE Table1
SET Table1.Availability = 'Y'
WHERE
(
    SELECT Table1.Availability
    FROM Table1
    INNER JOIN Table2
    ON Table1.Code = Table2.Code
    WHERE Table2.Availability='OPT'
)

This works but would require a new query for every availability type. Below is my attempt at updating for each availability type. It says there is a syntax error @ Switch(...
UPDATE Table1
SET Table1.Availability =
Switch(
        Table2.Availability = 'OPT', 'Y',
        Table2.Availability = 'STD', 'S',
        Table2.Availability = 'DEL', 'N'
    )
FROM Table1
INNER JOIN Table2
ON Table1.Code = Table2.Code
WHERE ModelCode = '1234'
;

I'm not sure if I am using switch correctly here, help appreciated. If it isn't clear pretty much what I want is If Table2.Availability = OPT, UPDATE Table1.Availability to 'Y' where Code is the same and Model = specific model
I have to specify a model code as the availability for a given option code (Code) is unique. The data I am given is a mess and it is easiest to sort it in to model specific data.
Thanks in advance :)

A: Consider the following tested and working syntax:
UPDATE Table1
INNER JOIN Table2
ON Table1.Code = Table2.Code
SET Table1.Availability =
Switch(
        Table2.Availability = 'OPT', 'Y',
        Table2.Availability = 'STD', 'S',
        Table2.Availability = 'DEL', 'N'
    )
WHERE ModelCode = '1234'
;


text:
Q: Using waitForKeyElements, is it possible to prevent the key element from being displayed, and only display it after it's modified by my code? I have this userscript (written with a great help from Stack Overflow) for the site metal-archives.com.
Its structure is like this:
function appendColumn(...) {
    // code for appending column
    // code for making the table sortable
}

waitForKeyElements ("table", appendColumn);

The script works okay except for a visual glitch/delay as you switch sub-tabs (tables).
When switching, the extra (6th) column is initially shown as expected. But then, the table is displayed momentarily in its original form, and then finally with the 6th column as it should be.
To see this, install the script, visit this typical target page, and then switch the sub-tabs (Between Complete Discography, Main, Lives, Demos, Misc, etc.).
It looks like this:

I've tried to make it so that the initial table does not appear by adding:
GM_addStyle(".display.discog {display: none;} ");

to the beginning of appendColumn() and:
GM_addStyle(".display.discog {display: inline !important;} ");

to the end of appendColumn().
But it didn't make any difference.

I used Firefox Network Monitor on that page and it seems that when you switch tabs:

*

*The code immediately modifies the table (which is loaded from cache?? -- because there's no entry in Network Monitor).

*Then the table (the relevant HTML file) is loaded from the server.

*Then the table is modified one last time.

How can I change the code (while using waitForKeyElements) to prevent the key element from being displayed, and only display it after it's modified by my code?
Or how do I speed up the response?
Thank you.

A: I loaded your script, added timing lines, and tested it.  The time elapsed from AJAX-complete until the table was fixed and finished was only 400 to 500 milliseconds!  That's plenty fast for most people and situations.
But, for those times when you absolutely want to squeeze out the milliseconds, you can switch to MutationObservers.  These are finicky, brittle, and less cross-browser portable, but they are fast.
In this case, MutationObservers took the AJAX-to-fixed-table time down to the 20 to 40 millisecond range.
I recommend using a library like Mutation Summary to take some of the pain out of the process.
To convert from a simple waitForKeyElements() implementation to Mutation Summary:

*

*Add
@require https://raw.githubusercontent.com/rafaelw/mutation-summary/master/src/mutation-summary.js

to your metadata block.

*Plug your waitForKeyElements callback and simple selector into this structure:
var muteObserver = new MutationSummary ( {
    callback: handleDiscographyChanges,
    rootNode: $( {ANY-JQUERY-SELECTOR} )[0],
    queries: [ {element: {A-SIMPLE-SELECTOR}} ]
} );

function handleDiscographyChanges (muteSummaries) {
    var mSummary    = muteSummaries[0];
    if (mSummary.added.length) {
        {YOUR-CALLBACK} ( $(mSummary.added[0]) );
    }
}

For example in this case, change:
waitForKeyElements (".display.discog", appendColumn);

To:
var muteObserver = new MutationSummary ( {
    callback: handleDiscographyChanges,
    rootNode: $("#band_disco")[0],
    queries: [ {element: ".discog"} ]
} );

function handleDiscographyChanges (muteSummaries) {
    var mSummary    = muteSummaries[0];
    if (mSummary.added.length) {
        appendColumn ( $(mSummary.added[0]) );
    }
}

Where the rootNode was determined by examining the page structure.

For reference, a complete script with 3 optional approaches and timing logging is below.  It was only tested on Firefox, but should work with Tampermonkey too (maybe).
See the //OPTION n lines just above each line to optionally comment out.
// ==UserScript==
// @name        Metal Archives (discography pages) - Reviews column split and sortable tables
// @include     http://www.metal-archives.com/bands/*
// @include     http://www.metal-archives.com/band/*
// @grant       none
// @require     http://code.jquery.com/ui/1.9.1/jquery-ui.min.js
// @require     https://greasyfork.org/scripts/2199-waitforkeyelements/code/waitForKeyElements.js?version=6349
// @require     https://greasyfork.org/scripts/5844-tablesorter/code/TableSorter.js?version=21758
// @require     https://raw.githubusercontent.com/rafaelw/mutation-summary/master/src/mutation-summary.js
// ==/UserScript==

function appendColumn(jNode) {
    logTime ("Table fixed");

    // STEP 1+2: SPLIT THE 'REVIEWS' COLUMN INTO A 'REVIEWS' COLUMN AND A 'RATINGS' COLUMN
    var tbl = jNode[0];     // table reference

    // If the current sub-table has no data, then stop the execution of the function
    if (tbl.rows[1].cells[0].innerHTML == '<em>Nothing entered yet. Please add the releases, if applicable. </em>') {
        return;
    }

    var newCell, newText;

    const cols = tbl.rows[0].cells.length - 1;

    var tr = tbl.tHead.children[0],
    th = document.createElement('th');

    th.innerHTML = "Ratings";
    th.className = "ratingsCol";
    tr.appendChild(th);

    for (i = 1; i < tbl.rows.length; i++) {
        k = tbl.rows[i].cells[cols].innerHTML;    // Retrieve the content of the current cell of the Review column and store it to variable k

        re1 = /<a [^>]*>[^(]*[(]([^)]+)/ ;        // (RegEx which matches the 'Ratings' percentage(incl.the % symbol)
        l = re1.exec(k);                          // (Execute the RegEx and store it to variable l)

        newCell = tbl.rows[i].insertCell(-1);     // Add a new cell (for the new 'Ratings' column ) -for each row-

        if (re1.test(k) != 0){                    // If the RegEx has matches, (only) then create new cells with...

            re0 = /(<a [^>]*>)[0-9]*[^(]/ ;       // (RegEx which matches the reviews URL)
            url = re0.exec(k);                    // (Execute the RegEx and store it to variable url)

            newCell.innerHTML = url[1] + l[1] + '</url>'; // ...the Ratings percentage (which is also a link to the Reviews)...

            re2 = /<a [^>]*>([0-9]*)[^(]/ ;       // (RegEx which matches the 'Reviews' number)
            m = re2.exec(k);                      // (Execute the RegEx and store it to variable m)

            newCell = tbl.rows[i].cells[cols];    //
            newCell.innerHTML = url[1] + m[1] + '</url>'; // ...and the Reviews number (which is also a link to the Reviews)
        }
    }

    //  STEP 3: MAKE THE DISCOGRAPHY TABLE SORTABLE  (using the jQuery plugin "tablesorter")
    $(tbl).tablesorter ( {
        cssAsc: 'up',
        cssDesc: 'down',
        headers: {
              0: {sorter: false}
        }
    } );
}

//OPTION 1
//waitForKeyElements (".display.discog", appendColumn);

$(document).ajaxComplete (function (e, xhr, config){
    logTime ("Ajax complete");
    //OPTION 2
    return; //-- For compare test

    if (config.url.indexOf ('/tab/') != -1){
        $(".display.discog").each ( function () {
            appendColumn ( $(this) );
        } );
    }
} );

$("#band_disco > ul > li").on ("click", "a.ui-tabs-anchor", function (zEvent) {
    logTime (zEvent.target.textContent + " tab was clicked.");
} );

function logTime (lableTxt) {
    var tNow    = new Date ();
    console.log (tNow.toLocaleFormat ('%H:%M:%S') + "." + tNow.getMilliseconds (), " <== " + lableTxt);
}

//OPTION 3
//*--- Remove leading slash, from this line, to comment out block, below.
var muteObserver = new MutationSummary ( {
    callback: handleDiscographyChanges,
    rootNode: $("#band_disco")[0],
    queries: [ {element: ".discog"} ]
} );
//*/ -- Tail end of optional comment block

function handleDiscographyChanges (muteSummaries) {
    var mSummary    = muteSummaries[0];
    if (mSummary.added.length) {
        appendColumn ( $(mSummary.added[0]) );
    }
}

Note that styling code, and some original comments, were omitted from this example.

A: waitForKeyElements is a slow way to insert your content. This is one reason you're seeing the rendering behavior that you are seeing.
The reason the tab is rendered appropriately when you first switch is because it is hidden and correctly adjusted while hidden. When the tab is shown the content is updated to reflect the latest from the server, which has not been adjusted. waitForKeyElements then notices the change and fires again to correct.
Using ajaxComplete you can hide the panel when the content is first loaded.
Hiding the panel when data first returns:
$(document).ajaxComplete(function(e, xhr, config){
   if(config.url.indexOf('/tab/') != -1){                     // Because the tables URLs are like `www.metal-archives.com/band/discography/id/xxx/tab/lives`
       $('.ui-tabs-panel').css('visibility', 'hidden');
   }
});

Showing the panel in your appendColumn function:
function appendColumn(...) {
    // code for appending column
    // code for making the table sortable
    $('.ui-tabs-panel').css('visibility', 'visible');
}

Happy coding!


text:
Q: Python - slice array until certain condition is met I need to slice an array from a given index until a certain condition is met.
>>> a = numpy.zeros((10), dtype='|S1')
>>> a[2] = 'A'
>>> a[4] = 'X'
>>> a[8] = 'B'
>>> a
array(['', '', 'A', '', 'X', '', '', '', 'B', ''], dtype='|S1')

For instance, for the above array I want a subset from a given index until first non-zero values in both directions. For example, for index values 2, 4, 8 the results would be:
['', '', A, '']      # 2
['', X, '', '', '']  # 4
['', '', '', B, '']  # 8

Any suggestions on the simplest way to do this using the numpy API? Learning python and numpy, would appreciate any help. Thanks!

A: If you set up your problem like this:
import numpy
a = numpy.zeros((10), dtype=str)
a[2] = 'A'
a[4] = 'X'
a[8] = 'B'

You can easily get the indices of non-empty strings like so:
i = numpy.where(a!='')[0]  # array([2, 4, 8])

Alternatively, numpy.argwhere(..) also works well.
Then you can slice away using this array:
out2 = a[:i[1]]        # 2   ['' '' 'A' '']
out4 = a[i[0]+1:i[2]]  # 4   ['' 'X' '' '' '']

etc.

A: this is a work for masked arrays, numpy.ma has lots of functions for working with subsets.
a = np.zeros((10), dtype=str)
a[2] = 'A'
a[4] = 'X'
a[8] = 'B'

let's mask out not empty elements:
am=np.ma.masked_where(a!='', a)

np.ma.notmasked_contiguous goes through the array (very efficiently) and finds all the slices of contiguous elements where the array is not masked:
slices = np.ma.notmasked_contiguous(am)
[slice(0, 1, None), slice(3, 3, None), slice(5, 7, None), slice(9, 9, None)]

so, the array is continuously empty between element 5 and 7 for example.
Now you only have to join the slices you are interested in, first you get the starting index of each slice:
slices_start = np.array([s.start for s in slices])

then you get the location of the index you are looking for:
slices_start.searchsorted(4) #4
Out: 2

So you want slice 1 and 2:
    a[slices[1].start:slices[2].stop+1]
    array(['', 'X', '', '', ''],
      dtype='|S1')
or let's try 8:
i = slices_start.searchsorted(8)
a[slices[i-1].start:slices[i].stop+1]
Out: array(['', '', '', 'B', ''],
  dtype='|S1')

If should probably play a bit with this in ipython for understanding it better.

A: Note that this could be cleanly done in pure python using itertools and functools.
import functools, itertools
arr = ['', '', 'A', '', 'X', '', '', '', 'B', '']

f = functools.partial(itertools.takewhile, lambda x: not x)
def g(a, i):
    return itertools.chain(f(reversed(a[:i])), [a[i]], f(a[i+1:]))

We define f as the sub-iterator found by looking until the element evaluates as true, and g as the combination of applying this on the reversed area of the list before the index and the list after the index.
This returns generators which can be casted to lists that contain our results.
>>> list(g(arr, 2))
['', '', 'A', '']
>>> list(g(arr, 4))
['', 'X', '', '', '']
>>> list(g(arr, 8))
['', '', '', 'B', '']

A: Two loops are the first thing that comes to mind.  Something like this would work:
'''Given an array and an index...'''
def getNoneSlice(a, i):

    # get the first non-None index before i
    start = 0
    for j in xrange(i - 1, -1, -1):
        if a[j] is not None: # or whatever condition
            start = j + 1
            break

    # get the first non-None index after i
    end = len(a) - 1
    for j in xrange(i + 1, len(a)):
        if a[j] is not None: # or whatever condition
            end = j - 1
            break

    # return the slice
    return a[start:end + 1]

A: def getSlice(a, n):
    try:
        startindex = a[:n].nonzero()[0][-1]
    except IndexError:
        startindex = 0
    try:
        endindex = a[(n+1):].nonzero()[0][0] + n+1
    except IndexError:
        endindex = len(a)
    return a[startindex: endindex]


text:
Q: How to run a quote search on a paragraph, and return the specific sentence containing the quote I'm completely new to regular expressions, and I've run into a problem.
$paragraph = '<text start="90" dur="4">hello world</text><text start="94" dur="5">hello humans</text>

$quote = 'hello world';

I want to check that $paragraph contains $quote, then return the quote's parent element node. In this case, the result would be:
<text start="90" dur="4">hello world</text>

Any ideas on how should I go about solving this?

A: You can merely include $quote in the regex string, and type the opening/closing tags literally like this:
$regex = "<text start=\"[0-9]+\" dur=\"[0-9]+\">" . $quote . "<\\/text>";

A: $paragraph = '<text start="90" dur="4">hello world</text><text start="94" dur="5">hello humans</text>';
$quote = 'hello world';

preg_match ("/<.*?$quote.*?>/", $paragraph, $return);
$to_print = print_r($return, true);
echo htmlspecialchars($to_print);

What this does is it captures everything from '<' to $quote to '>'. This means that if your quote is between p, div, span, etc. It will capture them as well.
.*? is lazy, meaning it'll capture everything until it reads the first instance of $quote, then it captures everything else until it captures the first instance of '>', after which it returns.


text:
Q: jquery dialog zindex setting won't work in second open subscribeDialog = $('#metrics-subscribe-popup').dialog({
        autoOpen: false,
        width: 600,
        modal: true,
        zIndex: 20,
        buttons: {
            "OK": function() {

                $(this).dialog("close");
            }
        }
    });

subscribeDialog.dialog('open')

When I use subscribeDialog.dialog('open') to open the dialog at second time, the zIndex is not work.

A: It works fine. Dialog open and close has nothing to do with the z-index property of dialog.
But you can also set explicitly the z-index on second open like this
subscribeDialog.dialog({
     zIndex: 100
});
subscribeDialog.dialog('open');


text:
Q: Android Camera Capture Live Preview (cwac) I'm using the cwac camera android library in my app. I'm using single shot mode, so when I call 'takePicture' the preview freezes as it should. However when the fragment is paused (I've extended cameraFragment), and resumed, the preview is restarted.
I understand that is an intended feature, and that the camera does need to be given up in these situations, but I have cases where when the fragment is resumed, I want the frozen preview to still be there.
Things I've tried :

*

*waiting for saveImage to be called, where I'm given the bytes of the captured image, and then  I populate an  image view. - works but there is significant delay between freezing the image and when saveImage Is called, making it very unattractive feeling.

*capturing the preview screen as a bitmap (or other data format)  and showing that in an image view immediately  so that it appears the preview is frozen but it's just a image view. -  mechanism is in place but I cannot for the life of me get the preview image (in another post, it was said that the preview frames are not exposed).
I was wondering if anyone had suggestions on how to tackle this issue? I've been at this for a while. Thanks!


text:
Q: HIDManager Wierd CFRunLoop Termination I've created device matching and device removal callbacks, And need to run CFRunLoop to get those callbacks invoked whenever device plugged in and removed.
But the problem is, DeviceMatching callback takes a lot of processing time and depends on device to be attached, So I want to detect if device is removed by running the CFRunLoop for a limited time, and With that the device removal callback happens.
But, It works for 2 times and then it throws exe_bad_access.

  IOHIDManagerSetDeviceMatching( tIOHIDManagerRef, matchingCFDictRef );
  if( matchingCFDictRef ) {
        CFRelease( matchingCFDictRef );
  }
  IOHIDManagerRegisterDeviceMatchingCallback(tIOHIDManagerRef,
                                                 Handle_DeviceMatchingCallback,NULL);
  IOHIDManagerRegisterDeviceRemovalCallback(tIOHIDManagerRef, Handle_RemovalCallback, NULL);

  IOHIDManagerScheduleWithRunLoop(tIOHIDManagerRef, CFRunLoopGetCurrent(), kCFRunLoopDefaultMode);
      CFRunLoopRun();

Device Add Callback
static void Handle_DeviceMatchingCallback(void* inContext, IOReturn inResult,
                             void* inSender, IOHIDDeviceRef  inIOHIDDeviceRef) {
      //DO SOME HEAVY PROCESSING

      //NOW WE NEED TO CHECK IF DEVICE IS STILL CONNECTED
     [[NSRunLoop currentRunLoop]  runUntilDate:[NSDate dateWithTimeIntervalSinceNow:1]];

      //DO POST PROCESSING

}

Device Removal Callback:
static void Handle_RemovalCallback( void* inContext,IOReturn  inResult,
                        void*  inSender, IOHIDDeviceRef inIOHIDDeviceRef) {
     //NOW THIS GET's INVOKED, after keeping in run loop

}

Following is the code for generating matchingCFDictRef
CFMutableDictionaryRef matchDict = CFDictionaryCreateMutable(kCFAllocatorDefault, 0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks);

    CFNumberRef vendorIDCFNumRef  = CFNumberCreate( kCFAllocatorDefault, kCFNumberIntType, &vendorId );
    CFNumberRef productIDCFNumRef = CFNumberCreate( kCFAllocatorDefault, kCFNumberIntType, &productId );

    CFDictionarySetValue( matchDict, CFSTR( kIOHIDVendorIDKey  ), vendorIDCFNumRef );
    CFDictionarySetValue( matchDict, CFSTR( kIOHIDProductIDKey ), productIDCFNumRef );

    CFRelease( vendorIDCFNumRef );
    CFRelease( productIDCFNumRef );

A: How do you generate matchingCFDictRef? Though normal conventions would suggest that IOHIDManager should retain or copy it, it's possible that it isn't. I would try taking out the CFRelease for now and see if that improves things.
The crash in CFGetTypeID indicates that it is trying to work with a CF object that has been freed. A few things you can do to try to debug which one it is:

*

*Turn on NSZombie. It might work, even though this is a CF object (many CF objects are toll free bridged and will still work).

*In the debugger, check the parameter to CFGetType. See Inspecting Obj-C parameters in gdb for the correct register depending on your processor. (It doesn't matter that this page is for ObjC; you just want the entires related to arg0.)

A: Following is the code for generating matchingCFDictRef
CFMutableDictionaryRef matchDict = CFDictionaryCreateMutable(kCFAllocatorDefault, 0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks);

    CFNumberRef vendorIDCFNumRef  = CFNumberCreate( kCFAllocatorDefault, kCFNumberIntType, &vendorId );
    CFNumberRef productIDCFNumRef = CFNumberCreate( kCFAllocatorDefault, kCFNumberIntType, &productId );

    CFDictionarySetValue( matchDict, CFSTR( kIOHIDVendorIDKey  ), vendorIDCFNumRef );
    CFDictionarySetValue( matchDict, CFSTR( kIOHIDProductIDKey ), productIDCFNumRef );

    CFRelease( vendorIDCFNumRef );
    CFRelease( productIDCFNumRef );

Now, I see different stack trace, called from CFRunLoop, Though I still see the GetTypeID in the symbols
0x00007fff8534407a  <+0023>  jne    0x7fff8534409f <IOHIDDeviceScheduleWithRunLoop+60>
0x00007fff8534407c  <+0025>  mov    0x18(%rdi),%rdi
0x00007fff85344080  <+0029>  mov    (%rdi),%rax
0x00007fff85344083  <+0032>  lea    0x58(%r12),%rsi
0x00007fff85344088  <+0037>  callq  *0x40(%rax)
0x00007fff8534408b  <+0040>  test   %eax,%eax
0x00007fff8534408d  <+0042>  jne    0x7fff85344148 <IOHIDDeviceScheduleWithRunLoop+229>
0x00007fff85344093  <+0048>  cmpq   $0x0,0x58(%r12)
0x00007fff85344099  <+0054>  je     0x7fff85344148 <IOHIDDeviceScheduleWithRunLoop+229>
0x00007fff8534409f  <+0060>  mov    0x58(%r12),%rdi
0x00007fff853440a4  <+0065>  callq  0x7fff85368f36 <dyld_stub_CFGetTypeID>
0x00007fff853440a9  <+0070>  mov    %rax,%rbx
0x00007fff853440ac  <+0073>  callq  0x7fff85369008 <dyld_stub_CFRunLoopSourceGetTypeID>
0x00007fff853440b1  <+0078>  cmp    %rax,%rbx
0x00007fff853440b4  <+0081>  jne    0x7fff853440cc <IOHIDDeviceScheduleWithRunLoop+105>

I see that it is breaking at 0x00007fff85344080  <+0029>  mov    (%rdi),%rax, for IOHIDDeviceScheduleWithRunLoop ( Please search with 0x00007fff85344080)
With the help of reference document, I see it is the first argument which means tIOHIDManagerRef, which I create IOHIDManagerRef tIOHIDManagerRef = IOHIDManagerCreate( kCFAllocatorDefault, kIOHIDOptionsTypeNone );
But, How to see the address of it, from above stack trace ?


text:
Q: Adding Psychopath Xpath2 processor as a dependency in a maven project I want to use Psychopath Xpath processor in a project(IDE :Intellij Idea) which uses Apache maven for building which is not available at maven central repo. Psychopath jar is available here . And also I know the fact that the psychopath XPath2 engine is available through the P2 repositories too.
What do I have to put in my pom.xml to make Maven downloading the .jar + the java source + the javadoc, and eventually the other dependencies (actually IBM ICU, Xerces, JavaCup).
If its available through p2 repositories how to add it in the pom.xml as a dependency.Some where it was suggested to use tycho and add the dependency from the p2 repository. Still needs a better guidance.
Here "Get a Hudson build with Maven " also this issue was discussed but couldn't get something positive out of it.

A: You can configure Maven to download dependencies directly from P2 repositories. Here's a sample setup for Psychopath:
<project>
 ...

 <repositories>
  <repository>
   <id>kepler</id>
   <layout>p2</layout>
   <url>http://download.eclipse.org/releases/kepler/201306260900</url>
  </repository>
 </repositories>

 <dependencies>
  <dependency>
   <groupId>osgi.bundle</groupId>
   <artifactId>org.eclipse.wst.xml.xpath2.processor</artifactId>
   <version>2.1.100.v201211261519</version>
  </dependency>
  <dependency>
   <groupId>osgi.bundle</groupId>
   <artifactId>java_cup.runtime</artifactId>
   <version>0.10.0.v201005080400</version>
  </dependency>
 </dependencies>

 <build>
  <extensions>
   <extension>
    <groupId>com.github.veithen.cosmos</groupId>
    <artifactId>p2-maven-connector</artifactId>
    <version>0.3</version>
   </extension>
  </extensions>
 </build>
</project>


text:
Q: Photoshop px size is different from CSS px size I have a mockup in photoshop which has a font at 60px. I set the font in the browser to be the same, at the same size of 60px, but in the browser the font is smaller. Any ideas why this is?

A: You have anti-aliasing on for your text in Photoshop?  Most browsers don't have that.
There is quite a bit of difference between how Photoshop renders text compared to how browsers render it (every browser has their own rendering engine, which might even vary depending on the OS).  It is impossible to replicate a Photoshop mockup pixel for pixel in a browser when there's text involved.

A: Try using this tool, i am sure that would help you...
http://www.endmemo.com/sconvert/pixelpoint.php
From this it states that:- 1px = 0.75pt


text:
Q: 'chromium-browser' is not recognized as an internal or external command, operable program or batch file I have used this code in AIML file
<category>
      <pattern>OPEN GOOGLE</pattern>
      <template>
           <random>

Sure thing!

Right away, sir!

On it!

          </random>
          <system> chromium-browser "http://www.google.com"</system>
      </template>
  </category>

but i am getting the error that chromium-browser is not an external command.
P.S- I am running it with Python 3.7

A: if you are on mac download chrome and try this
<system> open -a "Google Chrome" http://google.com</system>

A: Assuming your interpreter supports AIML 2, you can do this using the <link> tag.
<category>
    <pattern>OPEN GOOGLE</pattern>
    <template>
        <link>
            <text>
                <random>

Sure thing!

Right away, sir!

On it!

                </random>
            </text>
            <url>http://www.google.com</url>
         </link>
    </template>
</category>


text:
Q: Boost 1.45 dataset workaround I'm making an attempt at setting boost's unit test framework up for myself, but due to having to use C++98, I also have to use boost 1.45. Due to this, I find I can't make use of datasets the way I'd like (have test cases that have an arity of 2 and a dataset of pairs (input_val,expected_val)). It's looking like I'll be able to get an approximation going using a global fixture (The fixtures would have to be global if I want to not have it reset every test case. This issue is documented in another post), but I dislike the idea of throwing all that into global. Does anybody know a better, possibly more elegant solution?

A: @ provided the info I needed. If anybody else is looking for a good unit testing framework for C++98, Catch seems great so far!


text:
Q: How to inject NLog using Autofac in ASP.NET Webforms I have an ASP.NET Webforms project that I've been recently converting to use Dependency Injection via Autofac. It has all been going well, that is until I tried to inject my NLog instances. I can't work out how to perform the equivalent of the static GetCurrentClassLogger() method calls with the property injected Logger object.
Here is my sample code illustrating the problem:
Global.asax.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

using Autofac;
using Autofac.Integration.Web;

public class Global : HttpApplication, IContainerProviderAccessor
{
  private static IContainerProvider containerProvider;

  public IContainerProvider ContainerProvider
  {
    get { return containerProvider; }
  }

  void Application_Start(object sender, EventArgs e)
  {
    var builder = new ContainerBuilder();
    Bootstrapper.RegisterInstances(builder);
    containerProvider = new ContainerProvider(builder.Build());
  }
}

Bootstrapper.cs
using Autofac;

public static class Bootstrapper
{
  public static void RegisterInstances(ContainerBuilder builder)
  {
    builder.RegisterType<Logger>().As<ILogger>().InstancePerRequest();
    builder.RegisterType<MyTestModule>().As<IMyTestModule>().InstancePerRequest();
  }
}

MyTestModule.cs
using System;

public class MyTestModule : IMyTestModule
{
   // was previously: protected static readonly ILogger Logger = LogManager.GetCurrentClassLogger();

  private ILogger _logger;

  public MyTestModule(ILogger logger)
  {
    _logger = logger;
  }

  public void DoSomethingBad()
  {
    try
    {
        int z = 5 / 0;
    }
    catch (Exception ex)
    {
        _logger.Error("Error!", ex);
    }
  }
}

public interface IMyTestModule
{
  void DoSomethingBad();
}

PageBase.cs
public abstract class PageBase : Page
{
  // was previously: protected static readonly ILogger Logger = LogManager.GetCurrentClassLogger();

  public ILogger Logger { get; set; }

  public IMyTestModule MyTestModuleInstance { get; set; }
}

Default.aspx
<%@ Page Title="Home" Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

Default.aspx.cs
using System;

public partial class _Default : PageBase
{
  protected void Page_Load(object sender, EventArgs e)
  {
    MyTestModuleInstance.DoSomethingBad();
  }
}

You can see in PageBase.cs and MyTestModule.cs I have commented out the previous static calls to create the NLog instance:
protected static readonly ILogger Logger = LogManager.GetCurrentClassLogger();

They are now simply replaced with the Autofac dependency injected property like this:
public ILogger Logger { get; set; }

This works in so much that the Logger object gets initialised to an instance of the logger.
How do I perform the equivalent of LogManager.GetCurrentClassLogger() ?
Is there something I need to do with NLog modules to achieve this? If there is I've not been able to find any specific examples. Any help would be much appreciated!

A: Override the AttachTocomponentRegistaration of your Module:
public class AutofacLogInjectionModule : Module
{
    protected override void AttachToComponentRegistration(IComponentRegistry registry, IComponentRegistration registration)
    {
        registration.Preparing += OnComponentPreparing;
    }

    static void OnComponentPreparing(object sender, PreparingEventArgs e)
    {
        e.Parameters = e.Parameters.Union(new[]
    {
        new ResolvedParameter((p, i) => p.ParameterType == typeof(ILogger), (p, i) => LogManager.GetCurrentClassLogger())
    });
    }

}

And Register this module in your bootstrap:
builder.RegisterModule(new AutofacLogInjectionModule());


text:
Q: save sign up view controller text values on the server through php web service call using post method in iOS i have sign up form in which i have the fields like first name,last name,gender,email,password,user image,age. i want to make save this user information on the server through php webservice call.how can i pass these parameters to service url? will i use the http request using post method to save the user info to server and when that user wants to log in iOS app , i may match the credencial for that user. in shore, i need a log in and sign up screen for my iOS app, please suggest me any tutorial
Thanks in advance to all of you

A: First you need nto create php script and then transfer data through NSURL.
NSURL * url=[NSURL URLWithString:[NSString stringWithFormat:@"http://192.168.0.6/savedevicedata.php?Udid=%@&Flag=%d&DateTime=%@",uniqueIdentifier,Flag,FinalDate]];

    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    NSLog(@"%@",request);
    [request setHTTPMethod:@"POST"];
    //[request setHTTPBody:[NSString stringWithFormat:@"%@",rawStr]];

    NSURLResponse *response;
    NSError *err;
    NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&err];
    NSLog(@"responseData: %@", responseData);

Try this Code just replaces the your field.


text:
Q: server did not respond with an encrypted session key within the specified time-out period I am attempting to auto pause a SQL DW within Azure Automation runbook with the following workflow:
workflow SuspendOrPauseAzureSQLDataWarehouse
{
    Param(
        [Parameter(Mandatory=$true)]
        [string]$ConnectionName = "AzureRunAsConnection",
        [Parameter(Mandatory=$true)]
        [string]$SQLActionAccountName,
        [Parameter(Mandatory=$true,
        HelpMessage="ServerName must be the fully qualified name.")]
        [string]$ServerName,
        [Parameter(Mandatory=$true)]
        [string]$DWName,
        [int]$RetryCount = 4,
        [int]$RetryTime = 15
    )
        #Pulling in credentials used in the process
        $credSQL = Get-AutomationPSCredential -Name $SQLActionAccountName
        $AutomationConnection = Get-AutomationConnection -Name $ConnectionName
        $null = Add-AzureRmAccount -ServicePrincipal -TenantId $AutomationConnection.TenantId -ApplicationId $AutomationConnection.ApplicationId -CertificateThumbprint $AutomationConnection.CertificateThumbprint
        $DWDetail = (Get-AzureRmResource | Where-Object {$_.Kind -like "*datawarehouse*" -and $_.Name -like "*/$DWName"})
        if ($null -ne $DWDetail) {
            $DWDetail = $DWDetail.ResourceId.Split("/")
            $SQLUser = $credSQL.Username
            $SQLPass = $credSQL.GetNetworkCredential().Password

            #Checking to see if the ADW exists and is online
            $cRetry = 0
            do {
                if ($cRetry -ne 0) {Start-Sleep -Seconds $RetryTime}
                $DWStatus = (Get-AzureRmSqlDatabase -ResourceGroup $DWDetail[4] -ServerName $DWDetail[8] -DatabaseName $DWDetail[10]).Status
                Write-Verbose "Test $cRetry status is $DWStatus looking for Online"
                $cRetry++
            } while ($DWStatus -ne "Online" -and $cRetry -le $RetryCount )
            if ($DWStatus -eq "Online") {
                Write-Verbose "Querying data warehouse for activity"
                $CanPause = InLineScript {
                    $testquery = @"
                    with test as
                    (
                        select
                        (select @@version) version_number
                        ,(select count(*) from sys.dm_pdw_exec_requests where status in ('Running', 'Pending', 'CancelSubmitted') and session_id != SESSION_ID()) active_query_count
                        ,(select count(*) from sys.dm_pdw_exec_sessions where is_transactional = 1) as session_transactional_count
                        ,(select count(*) from sys.dm_pdw_waits where type = 'Exclusive') as pdw_waits
                    )
                    select
                        case when
                                version_number like 'Microsoft Azure SQL Data Warehouse%'
                                and active_query_count = 0
                                and session_transactional_count = 0
                                and pdw_waits = 0
                                then 1
                        else 0
                        end as CanPause
                    from test
"@
                    $DBConnection = New-Object System.Data.SqlClient.SqlConnection("Server=$($Using:ServerName); Database=$($Using:DWName);User ID=$($Using:SQLUser);Password=$($Using:SQLPass);")
                    $DBConnection.Open()
                    $DBCommand = New-Object System.Data.SqlClient.SqlCommand($testquery, $DBConnection)
                    $DBAdapter = New-Object -TypeName System.Data.SqlClient.SqlDataAdapter
                    $DBDataSet = New-Object -TypeName System.Data.DataSet
                    $DBAdapter.SelectCommand = $DBCommand
                    $DBAdapter.Fill($DBDataSet) | Out-Null
                    # Returning result to CanPause
                    if ($DBDataSet.Tables[0].Rows[0].CanPause) {$true} else {$false}
                    try{$DBConnection.Close()} catch {}
                }
                Write-Verbose "Activity request is $CanPause"
                if ($CanPause) {
                    Write-Verbose "Calling suspend/pause"
                    Get-AzureRmSqlDatabase -ResourceGroup $DWDetail[4] -ServerName $DWDetail[8] -DatabaseName $DWDetail[10] | Suspend-AzureRmSqlDatabase
                } else {
                    Write-Error "Azure SQL Data Warehouse $DWName on server $ServerName has outstanding request and will not be paused at this time."
                }
            }
        }
        else {
            Write-Error "No Azure SQL Data Warehouse named $DWName exist on SQL Server $ServerName."
        }
}

Called within the same runbook as:
SuspendOrPauseAzureSQLDataWarehouse -ConnectionName "AzureRunAsConnection" -SQLActionAccountName "namedCredential" -ServerName "server2.database.windows.net" -DWName "DW" -RetryCount 0 -RetryTime 0

However, the error always notes:

How can this be alleviated?