text:
Q: Initializing a static field vs. returning a value in static property get? A) In the following code, will the method DataTools.LoadSearchList() only be called once, or every time the property is being accessed?
public static IEnumerable<string> SearchWordList
{
    get
    {
        return DataTools.LoadSearchList();
    }
}

B) Is there any difference to this?
public static IEnumerable<string> SearchWordList = DataTools.LoadSearchList();

A: In your first example, LoadSearchList() will be called each time the property is accessed.
In the second, LoadSearchList() will only be called once (but it will be called whether you use it or not since it is now a field rather than a property).
A better option might be:
private static IEnumerable<string> _searchWordList;

public static IEnumerable<string> SearchWordList
{
    get
    {
        return _searchWordList ??
            ( _searchWordList = DataTools.LoadSearchList());
    }
}

Or if you're using .NET 4.0 and want something thread-safe you can use Lazy<T>, as Jon Skeet mentioned (I think the syntax should be correct, but don't hold me to it):
private static Lazy<IEnumerable<string>> _searchWordList =
    new Lazy<IEnumerable<string>>(() => DataTools.LoadSearchList());

public static IEnumerable<string> SearchWordList
{
    get { return _searchWordList.Value; }
}

A: Yes, the property will call DataTools.LoadSearchList() every time access. The static field will only call the method once.

A: In the first case the method will be called every time the property is accessed. When it's set as a field, it will be run exactly once - when the type it initialized - whether or not it's ever accessed.
If you want a lazily-initialized value, I'd recommend Lazy<T> from .NET 4.


text:
Q: Angular grunt build (from yeoman) breaks my app after running the build from the /dist folder I get:
Uncaught Error: [$injector:modulerr] http://errors.angularjs.org/1.2.1/$injector/modulerr?p0=ourname&p1=Error%3A…(http%3A%2F%2Flocalhost%3A8085%2Flib%2Fangular%2Fangular.min.js%3A32%3A462)

nothing I do seems to solve this problem
this is the grunt task flow - adapted 1 to 1 from yeoman angular-generator:
module.exports = function(grunt){
    require('load-grunt-tasks')(grunt);
    require('time-grunt')(grunt);

    grunt.initConfig({
        //pkg: grunt.file.readJSON('package.json'),
        yeoman: {
            // configurable paths
            app: require('./bower.json').appPath || 'app',
            dist: 'dist'
        },
        coveralls:{
        options:{
          coverage_dir:'coverage'
        }
         },
        jshint:{
            files:['app/js/**/*.js', 'Gruntfile.js'],
            options:grunt.file.readJSON('.jshintrc')

        },
        watch:{
            styles: {
                files: ['<%= yeoman.app %>/css/{,*/}*.css'],
                tasks: ['copy:css', 'autoprefixer']
            },
            livereload: {
                options: {
                    livereload: '<%= connect.options.livereload %>'
                },
                files: [
                    '<%= yeoman.app %>/{,*/}*.html',
                    '.tmp/css/{,*/}*.css',
                    '{.tmp,<%= yeoman.app %>}/js/{,*/}*.js',
                    '<%= yeoman.app %>/img/{,*/}*.{png,jpg,jpeg,gif,webp,svg}'
                ]
            }
        },
        autoprefixer: {
            options: ['last 1 version'],
            dist: {
                files: [{
                    expand: true,
                    cwd: '.tmp/styles/',
                    src: '{,*/}*.css',
                    dest: '.tmp/styles/'
                }]
            }
        },
        connect: {
            options: {
                port: 9000,
                // Change this to '0.0.0.0' to access the server from outside.
                hostname: 'localhost',
                livereload: 35729
            },
            livereload: {
                options: {
                    open: true,
                    base: [
                        '.tmp',
                        '<%= yeoman.app %>'
                    ]
                }
            },
            test: {
                options: {
                    port: 9001,
                    base: [
                        '.tmp',
                        'test',
                        '<%= yeoman.app %>'
                    ]
                }
            },
            dist: {
                options: {
                    base: '<%= yeoman.dist %>'
                }
            }
        },
        clean: {
            dist: {
                files: [{
                    dot: true,
                    src: [
                        '.tmp',
                        '<%= yeoman.dist %>/*',
                        '!<%= yeoman.dist %>/.git*'
                    ]
                }]
            },
//            server: '.tmp'
        },
            rev: {
                dist: {
                    files: {
                        src: [
                            '<%= yeoman.dist %>/js/{,*/}*.js',
                            '<%= yeoman.dist %>/css/{,*/}*.css',
                            '<%= yeoman.dist %>/img/{,*/}*.{png,jpg,jpeg,gif,webp,svg}',
                            '<%= yeoman.dist %>/css/fonts/*'
                        ]
                    }
                }
            },
            useminPrepare: {
                html: '<%= yeoman.app %>/index.html',
                options: {
                    dest: '<%= yeoman.dist %>',
                    html: {
                        steps: {'js': ['concat','ngmin']},
                        post: {}
                    }
                }
            },
            usemin: {
                html: ['<%= yeoman.dist %>/{,*/}*.html'],
                css: ['<%= yeoman.dist %>/css/{,*/}*.css'],
                options: {
                    assetsDirs: ['<%= yeoman.dist %>']
                }
            },
            imagemin: {
                dist: {
                    files: [{
                        expand: true,
                        cwd: '<%= yeoman.app %>/img',
                        src: '{,*/}*.{png,jpg,jpeg}',
                        dest: '<%= yeoman.dist %>/img'
                    }]
                }
            },
            svgmin: {
                dist: {
                    files: [{
                        expand: true,
                        cwd: '<%= yeoman.app %>/img',
                        src: '{,*/}*.svg',
                        dest: '<%= yeoman.dist %>/img'
                    }]
                }
            },
            cssmin: {
                // By default, your `index.html` <!-- Usemin Block --> will take care of
                // minification. This option is pre-configured if you do not wish to use
                // Usemin blocks.
                // dist: {
                //   files: {
                //     '<%= yeoman.dist %>/styles/main.css': [
                //       '.tmp/styles/{,*/}*.css',
                //       '<%= yeoman.app %>/styles/{,*/}*.css'
                //     ]
                //   }
                // }
            },
            htmlmin: {
                dist: {
                    options: {
                        /*removeCommentsFromCDATA: true,
                         // https://github.com/yeoman/grunt-usemin/issues/44
                         //collapseWhituseminPrepareespace: true,
                         collapseBooleanAttributes: true,
                         removeAttributeQuotes: true,
                         removeRedundantAttributes: true,
                         useShortDoctype: true,
                         removeEmptyAttributes: true,
                         removeOptionalTags: true*/
                    },
                    files: [{
                        expand: true,
                        cwd: '<%= yeoman.app %>',
                        src: ['*.html', 'partials/*.html'],
                        dest: '<%= yeoman.dist %>'
                    }]
                }
            },
        copy: {
            dist: {
                files: [{
                    expand: true,
                    dot: true,
                    cwd: '<%= yeoman.app %>',
                    dest: '<%= yeoman.dist %>',
                    src: [
                        '*.{ico,png,txt}',
                        'lib/**/*',
                        'img/{,*/}*.{gif,webp}',
                        'fonts/*',
                        'languages/*'
                    ]
                }, {
                    expand: true,
                    cwd: '.tmp/img',
                    dest: '<%= yeoman.dist %>/img',
                    src: [
                        'generated/*'
                    ]
                }]
            },
            styles: {
                expand: true,
                cwd: '<%= yeoman.app %>/css',
                dest: '.tmp/css/',
                src: '{,*/}*.css'
            }
        },
        concurrent: {
            server: [
                'copy:styles'
            ],
            test: [
                'copy:styles'
            ],
            dist: [
                'copy:styles',
                'imagemin',
                'svgmin',
                'htmlmin'
            ]
        },
//        cdnify: {
//            dist: {
//                html: ['<%= yeoman.dist %>/*.html']
//            }
//        },
        ngmin: {
            dist: {
                files: [{
                    expand: true,
                    cwd: '.tmp/concat/js',
                    src: '*.js',
                    dest: '.tmp/concat/js'
                }]
            }
        },
        uglify: {
            dist: {
                options:{
                    compress:false,
                    mangle:false
                },
                files: {
                    '<%= yeoman.dist %>/js/scripts.js': [
                        '<%= yeoman.dist %>/js/scripts.js'
                    ]
                }
            }
        },

//        concat:{
//            options:{
//                seperator:';'
//            },
//            dist:{
//                src :['app/js/**/*.js', 'app/lib/**/*.js'],
//                dest :'dist/app/js/<%pkg.name%>.js'
//
//            }
//        },
        exec:{
            instrument:{
                cmd: function(){
                    return 'istanbul instrument app/js -o app/instrumentjs';
                }

            },
            djangoUp:{
              cmd: function(){
                  var command = 'workon stokeet-api  && cd ../stokeet-api/ && python manage.py runserver> /dev/null 2>&1 && cd ../angular/ & ';
                  return command;
              }
            },

            webserverUp:{
              cmd: function(){
                  var command = 'cd ../angular/ && node ./scripts/web-server.js > /dev/null 2>&1 &';
                  return command;
              }

            }
        },
        karma:{
            unit:{
                configFile:'config/karma.conf.js',
                autoWatch:true,
                browsers:['PhantomJS']
            },
            ci:{
                configFile:'config/karma.conf.js',
                singleRun:true,
                autoWatch:false,
                browsers:['Firefox','PhantomJS']
            },
            buildTest:{
                configFile:'config/karma.conf.js',
                singleRun:true,
                autoWatch:false,
                browsers:['PhantomJS']
            }

        }

    });
    grunt.registerTask('coverage',['coveralls']);
    grunt.registerTask('default',['jshint']);
    grunt.registerTask('instrument',['exec: instrument']);
//    grunt.registerTask('concat',['concat']);
    grunt.registerTask('dev_up',['exec:djangoUp', 'exec:webserverUp']);
    grunt.registerTask('test',[
                            'clean:server',
                            'concurrent:test',
                            'autoprefixer',
                            'connect:test',
                            'karma:buildTest']),
    grunt.registerTask('build', [
                            'clean:dist',
                            'useminPrepare',
                            'concurrent:dist',
                            'autoprefixer',
                            'concat',

                            'copy:dist',
                            'ngmin',
                            'cssmin',
                            'uglify',
                            'rev',
                            'usemin'
    ]);
    grunt.registerTask('server', function (target) {
        if (target === 'dist') {
            return grunt.task.run(['build', 'connect:dist:keepalive']);
        }

        grunt.task.run([
            'clean:server',
            'concurrent:server',
            'autoprefixer',
            'connect:livereload',
            'watch'
        ]);
    });

};

You can see I tried overriding the usemin default flow, but that didn't help
I suspect this has to do with the known angular minification problem, but since ngmin is running here, and all my code (Not sure about the plugins) does respect the angular minification safe array notation I'm not sure .
any ideas? I'll be glad for any help with this

A: I will try to be brief explaining the problem when building with usemin 2.0.x and ngmin in Angularjs (according my experience, I may be wrong in something, if yes please correct me):
The normal flow in the Build grunt task is that ngmin is executed before usemin and others, to let the code with injections like this:
...
angular.module("Config",[])
    .config(["$httpProvider","CONSTANTS","ERRORS","HEADERS",function(a,b,c,d){var
...

usemin 0.1.x was using only 'concat', but the version 2.0.x is using 'concat' and 'uglifyjs' so, after concatenate the code, it changes the javascript code again, this corrupts the ngmin, as you can see in the following example:
...
angular.module("Config",[])
    .config(function(a,b,c,d){var
...

So you have to stop it defining the flow in useminPrepare, like the following:
useminPrepare: {
        html: '<%= yeoman.app %>/index.html',
        options: {
            dest: '<%= yeoman.dist %>',
            flow: {
                steps: {'js': ['concat']},
                post: {}
            }
        }
    },

Edit
You can add the task in the grunt tasks:
grunt.registerTask('build', [
    'clean:dist',
    'jshint',
    'useminPrepare',
    'imagemin',
    'cssmin',
    'ngmin',
    'uglify',
    'rev',
    'usemin'
])

Hope it helps!

A: I was also facing the same issue after yo angular setup without any modifications.
The following discussion helped me resolve it:
https://github.com/DaftMonk/generator-angular-fullstack/issues/164
In a nutshell:
Search for
<!-- build:js scripts/vendor.js -->

and change it to
<!-- build:js(app/..) scripts/vendor.js -->

A: I think the default GruntFile.js has changed a bit in Yeoman since this question was answered.
This worked for me:
Uncommented out the following uglify block and added the mangle:false option.
uglify: {
   options:{mangle:false},
   dist: {
     files: {
       '<%= yeoman.dist %>/scripts/scripts.js': [
         '<%= yeoman.dist %>/scripts/scripts.js'
       ]
     }
   }
},

Then I commented out the ngmin line (which took forever to run anyway).
The result is non-mangled js which is considerably larger, but runs my angular code well. Eventually I suppose ngmin will be smart enough to handle things more seamlessly, but until then I'm okay with the extra bytes.

A: Is everything working if you only serve the files (grunt server)?
So: No problem with angular this way?
Have your read the linked error page?
http://docs.angularjs.org/error/$injector:modulerr?p0=ourname&p1=Error:%E2%80%A6(http:%2F%2Flocalhost:8085%2Flib%2Fangular%2Fangular.min.js:32:462)
It tells you, that there is a problem with our "ourname" module.
Do you have some code for us?
I am not quite sure, what this changes, but you can also define it like:
useminPrepare: {
            html: '<%= yeoman.app %>/index.html',
            options: {
                dest: '<%= yeoman.dist %>',
                flow: {
                    steps: {'js': ['concat','ngmin']},
                    post: {}
                }
            }
        },

https://github.com/yeoman/grunt-usemin#flow
Did you missed the "flow"?
Maybe one of the questions helps to find the solution ;)

A: if you are using Yeoman for building your angular application.
Simply type
yo doctor

This will help you to identify what all issues are present with your application.
Yeoman Doctor
Running sanity checks on your system

✔ Global configuration file is valid
✔ NODE_PATH matches the npm root
✖ Node.js version

Your Node.js version is outdated.
Upgrade to the latest version: https://nodejs.org

✔ No .bowerrc file in home directory
✔ No .yo-rc.json file in home directory
✔ npm version

Found potential issues on your machine :(

redpajama_set_name: RedPajamaStackExchange


text:
Q: Chrono library gives 0 as elapsed time - wrong code? Good evening fellow coders,
I'm a newbie in C++ and after searching for an answer I have not come to find a helpful answer. I'm testing #pragma pack right now and want to compare access speeds with unaligned memory, therefore I have a few structs I want to test elapsed time with.
struct ReallySlowStruct {
    char c : 6;
    __int64 d : 64;
    int b : 32;
    char a : 8;
};

And
int main() {
    struct ReallySlowStruct s;

    std::chrono::steady_clock::time_point begin = std::chrono::high_resolution_clock::now();
    s.a = 'c';
    s.d = 100;
    s.b = 50;
    s.a = 'a';
    std::chrono::steady_clock::time_point end = std::chrono::high_resolution_clock::now();
    std::cout << std::chrono::duration_cast<std::chrono::milliseconds>(end - begin).count() << std::endl;
    system("pause");
    return 0;
}

This is what I found how to measure elapsed time with using the Chrono library. However, the output is always 0 and I don't know why. I've tried the different clocks, as well as different time units, but it's always zero. Can anyone explain what's wrong with it? I'm using VS 2013.


text:
Q: Variable Not Showing When Function Called Early In Script Any help is appreciated. I cannot seem to get the value of $sum if I call showSum() before the function...
EXAMPLE 1: (this works fine)
[main code here]

$sum = $valueObtainedAfterWhileLoop;

function showSum(){
global $sum;

return $sum;
}
echo getSum();

EXAMPLE 2: (this does not work - no error is returned, but no value is printed to the screen)
echo getSum();

[main code here]

$sum = $valueObtainedAfterWhileLoop;

function showSum(){
global $sum;

return $sum;
}

I need to use the value of $sum at the top of the page. What can I do?

A: Absolutely nothing. The variable has not been assigned to yet, so there's no value to use. Try calculating it in the function instead.


text:
Q: How to show independence and interpret the result
If $X$ is symmetrically distributed  about zero , then show that $U=|X|$ and
  $$V = \left\{
        \begin{array}{}
           +1, & X \geq0 \\
           -1, & X<0
        \end{array}
   \right .$$
  are independently distributed and interpret the result.

Here distribution is not given only it is known that it symmetrically distributed . I think this result holds for continuous and discrete distribution . How can I show independence and interpret the result . Please help
Edit: Here independence means statistical independence.

Defn1: Two random variables $X$ and $Y$ are independent if and only if
   $$ F_{XY}(x,y)=F_X(x).F_Y(y) \forall x,y \in R$$
    where $ F_{XY}(x,y)$ is their joint distribution function and $F_X(x)$ and $F_Y(y)$ are their marginal distribution functions.

I also know the independence with PDF/PMF.

Defn2: Two random variables $X$ and $Y$ , forming an absolutely continuous random vector,are independent if and only if
  $$f_{XY}(x,y)=f_X(x).f_Y(y) \forall x,y \in R$$
   where $ f_{XY}(x,y)$ is their joint probability density function and $f_X(x)$ and $f_Y(y)$ are their marginal probability density functions.

For discrete case $f$ is replaced by $p$ .

A: The result "sign and magnitude are independently distributed" is certainly true for continuous distributions symmetric about zero. Notably, it can be applied in the derivation of the test statistic in Wilcoxon's signed-rank test for symmetry.
Assume $X$ is continuous with distribution function $F$.
Then for every $t$,
\begin{align}
P(|X|<t\mid \text{sgn}(X)=1)&=\small\frac{P(-t<X<t\,,\,X> 0)}{P(\text{sgn}(X)=1)}
\\&=\small\frac{P(0<X<t)}{P(X> 0)}
\\&=\small\frac{F(t)-F(0)}{1-F(0)}
\\&=2F(t)-1 & \small[\,\because F(0)=1/2\,]
\\&=F(t)-(1-F(t))
\\&=F(t)-F(-t) & \small[\,\because F(t)+F(-t)=1\,]
\\&=P(|X|<t)
\end{align}
Similarly, it holds that $P(|X|<t\mid \text{sgn}(X)=-1)=P(|X|<t)$
Thus the distribution of $|X|$ is independent of $\text{sgn}(X)$.


text:
Q: How to write query to get count occurences of events of different types? I have a table named EventHistory which has fields as shown in the table. A and B together constitutes primary key for the table. For every ke, I want to calculate how many events are of schedule and manual_schedule and displays its count and how many are of cancel type in seperate columns for particular key?
Sample Data:
  A        B                 createdAt         createdBy  eventType
249106  1956901101  2020-01-24 12:01:21.8300000 MOC000  manual_schedule
249106  1956901101  2019-12-11 04:44:42.0000000 VSSUBR  schedule
249106  1956901101  2019-12-10 13:12:32.6980000 VSSUBR  cancel
249128  1956904001  2020-01-27 10:14:23.8930000 MOC000  manual_schedule
249128  1956904001  2020-01-23 09:45:20.7450000 MOC000  manual_schedule
249128  1956904001  2019-12-17 08:41:25.0000000 VSSUBR  schedule
249128  1956904001  2019-11-28 11:46:40.4930000 VSSUBR  hold
249128  1956904001  2019-11-28 11:46:15.8160000 VSSUBR  cancel
249240  1956932501  2020-01-06 10:44:46.7620000 YUG000  manual_schedule
249240  1956932501  2020-01-02 21:09:05.0000000 A9SRI3  schedule
249240  1956932501  2019-12-31 06:41:01.3300000 KRSRIP  cancel
249240  1956932501  2019-12-17 08:35:35.7490000 VSSUBR  manual_schedule
249240  1956932501  2019-12-17 08:30:09.0000000 External    reschedule
249240  1956932501  2019-12-17 05:56:31.0000000 VSSUBR  reschedule
249240  1956932501  2019-12-17 05:55:03.8030000 VSSUBR  manual_schedule
249240  1956932501  2019-12-17 05:16:04.0000000 VSSUBR  reschedule
249240  1956932501  2019-12-17 05:14:46.9600000 VSSUBR  manual_schedule
249240  1956932501  2019-12-17 05:14:43.0000000 VSSUBR  reschedule
249240  1956932501  2019-12-17 05:13:21.2890000 VSSUBR  manual_schedule
249240  1956932501  2019-12-17 05:11:51.5050000 VSSUBR  manual_schedule
249240  1956932501  2019-12-13 10:02:49.7800000 KRSRIP  manual_schedule
249240  1956932501  2019-12-13 10:02:49.7760000 KRSRIP  manual_schedule
249240  1956932501  2019-12-12 04:20:04.1620000 VSSUBR  cancel
249240  1956932501  2019-12-05 12:30:42.2630000 VSSUBR  manual_schedule
249240  1956932501  2019-12-05 12:23:52.3480000 VSSUBR  manual_schedule
249240  1956932501  2019-12-05 09:49:37.0000000 External    reschedule
249240  1956932501  2019-12-05 09:48:42.0000000 External    reschedule
249240  1956932501  2019-12-04 13:16:10.0000000 External    reschedule
249240  1956932501  2019-12-04 12:59:00.0000000 External    reschedule
249240  1956932501  2019-12-04 07:29:43.0000000 External    schedule

A: I think you need conditional aggregation here. I typically do this with CASE statements. The select statement at the bottom demonstrates how I do this with a subset of your example data.
  IF OBJECT_ID('TEMPDB..#TEMP') IS NOT NULL
        DROP TABLE #TEMP

    CREATE TABLE #TEMP (
        A                       INT
        ,B                      INT
        ,event_type             NVARCHAR(50)
    )
    INSERT INTO #TEMP (A,B,event_type)
    VALUES
         ('249106','1956901101','manual_schedule')
        ,('249106','1956901101','schedule')
        ,('249106','1956901101','manual_schedule')
        ,('249128','1956904001','manual_schedule')
        ,('249128','1956904001','schedule')
        ,('249128','1956904001','manual_schedule')
        ,('249128','1956904001','manual_schedule')
        ,('249128','1956904001','schedule')
        ,('249240','1956932501','manual_schedule')
        ,('249240','1956932501','schedule')

    SELECT A
        ,B
        ,SUM(CASE WHEN event_type = 'manual_schedule' THEN 1 ELSE 0 END) [manual_schedule]
        ,SUM(CASE WHEN event_type = 'schedule' THEN 1 ELSE 0 END) [schedule]
    FROM #TEMP
    GROUP BY A
        ,B

SAMPLE DATA OUTPUT AND SELECT STATEMENT OUTPUT:


text:
Q: How to get innerHeight of fullscreen browser I know that I can get browser height in fullscreen without windows taskbar with winodw.availHeight. But I want to know the height without scrollbar, adress bar etc. too. I cant use innerHeight because if browser is not fullscreen, I still want to get fullscreen inner height.
thank you (and sorry for my English)

A: window.innerHeight works perfectly. It gave me 455 when it was full screen and 340 when not full screen.
Check for yourself - Type window.innerHeight when normal and then click F11 and then do the same. You'll see different value. So it does differ.


text:
Q: Mongoose pull object from array inside array I am currently using Node.js with Mongoose to manipulate an MongoDB database. I would like remove an object from an array itself inside an array.
var newTable = new module.Table({
  "_id": ObjectId("1"),
  "name": "Table1",
  "items": [
    {
      "_id": ObjectId("11"),
      "name": "Item1",
      "subscribers": [
        {
          "itemId": "111"
        },
        {
          "itemId": "112"
        }
      ]
    }
  ]
}).save();

I've tried this query but it has no effect:
module.Table.update(
  { "items._id": "11" },
  { $pull: { "items.$.subscribers": { "itemId": "112" } } },
  { "safe": true },
  function (err, obj) {
    if (err) console.log(filename + " @ module.Table.update(): " + err);
  }
);

Please help me how to query.

Note1: ObjectId("xxx") are simplified references for this example.
Note2: I found the bug, it's a mistake of my part, the query need the id as string (not as ObjectId).

A: While jack blank is partially right in the comments, I wanted to clarify this answer further as I had trouble with it.
In my case, the solution was the following:

*

*Import mongoose in your script (note the way it is imported).

const mongoose = require('mongoose');

*Then make sure you that in the case you are updating many documents you use updateMany()

await Order.updateMany({},{
  $pull: {
    'products': mongoose.Types.ObjectId(req.params.id)
  },
}).exec();

Note that the ObjectId is NOT new mongoose.mongo.ObjectId() but rather mongoose.Types.ObjectId().


text:
Q: Commenting/ Excluding commands for Latex 2 HTML with Pandoc The Following Latex Item ends with the Runaway Argument, as apparently the begin/end soln need to be on separate lines.
What I am trying to test is if there is a way to steer out certain commands for different outputs. I have a really long beautiful Latex Document, with all the wonderful packages etc. Now unfortunately two packages which make the PDF really beautiful create big problems in the Pandoc-HTML part, and it would be then just convenient to edit out these parts for the compilation of the HTML. Like the \ref, which is another item Pandoc cannot properly deal with. Any idea on how to design such an inline comment out function?
\documentclass[a4paper, 10pt, twoside]{memoir}
\usepackage{graphicx}
\usepackage{comment}
\includecomment{soln}
\title{ABC}
\author{ABC}
\begin{document}
\section{ABC}\label{se:ABC}
Let us go to section DEF
\begin{soln}%I want this into one line begin ref end
\ref{se:DEF}
\end{soln}
\section{DEF}\label{se:DEF}
Let us go to section ABC
\begin{soln} %I want this into one line begin ref end
\ref{se:ABC}
\end{soln}
\end{document}


text:
Q: my Bootstrap4 Flip Card not work correctly in iphone browsers I have created css3 Flip Card on bootstrap4. it works fine in desktop browser and android but in iphone devices when flip occurs the card will disappear suddenly.
``

http://codepen.io/salehi186/pen/ObdmBX?editors=1100


text:
Q: Returning the results of a LINQ query as a complex model I have the following LINQ query that I want to return as a model with related joins etc all in place.
      var query = (from wi in context.WorkItems
                     join mi in context.MaintenanceItems
                         on new { Id = wi.MaintenanceItemID }
                         equals new { Id = mi.MaintenanceItemID }
                     join p in context.Properties
                         on new { Id = mi.PropertyID }
                         equals new { Id = p.PropertyID }
                     join l in context.Locations
                          on new { Id = p.LocationID }
                          equals new { Id = l.LocationID }
                     join c in context.Categories
                          on new { Id = mi.CategoryID }
                          equals new { Id = c.CategoryID }
                     join sc in context.SubCategories
                          on new { Id = mi.SubCategoryID }
                          equals new { Id = sc.SubCategoryID }
                     join pl in context.PickLists
                          on new { Id = wi.PriorityFlag, V = "Priority" }
                          equals new { Id = pl.ValueKey, V = pl.ValueType }
                     where wi.AssignedTo1 == username
                    orderby wi.PriorityFlag descending, wi.PriorityIndex, wi.WorkItemID
                    select new {
                        wi.WorkItemID,
                        wi.PriorityFlag,
                        wi.PriorityIndex,
                        wi.CompletionDateTime,
                        l.LocationName,
                        p.PropertyFullName ,
                        wi.AssignedTo1,
                        wi.AssignedTo2,
                        wi.AssignedTo3,
                        c.CategoryName,
                        sc.SubCategoryName,
                        PriorityDesc = pl.ValueTitle
                    });

My model consists of a WorkItem entity which the query can return multiples of, with then related entities filling in the descriptive values for all the foreign keys etc.
Obviously using the query I have created an anonymous type, but I am not sure how to turn it back into the fully fleshed out known types I need?

A:
I have created an anonymous type, but I am not sure how to turn it back into the fully fleshed out known types I need?

Instead of projecting selected elements into a new type, use Eager Loading to Include() the full related entities in your result.
Also instead of projecting individual scalar properties in your anonymous type, you can project whole entities.


text:
Q: A responsive two-column layout using flexbox I have a small layout of sections

.collection {
  display: flex;
  flex-direction: column;
  flex-wrap: wrap;
}
.collection section {
  width: 50%;
}

bar

baz

FOO

Then everything is positioned in one column. I'd expect such a layout
___________
| h2 |    |
|____| h1 |
|_h3_|____|

I know that the layout would wrap if I set max-width. But I don't know the div size in advance. My intent is to wrap in such a way that both columns have equal height.
How can I achieve it?

A: By giving the h1 section a 100% height, it will be forced into a new column.

* {
    margin: 0;
    box-sizing: border-box;
}

html, body {
    height: 100%;
}

.collection {
    display: flex;
    flex-direction: column;
    flex-wrap: wrap;
    height: 100%;
}

.collection section {
    width: 50%;
    flex: 1;
    border: 1px dashed black;
}

.collection section:last-child {
    flex-basis: 100%;
}

@media ( max-width: 700px ) {
    .collection section { width: 100%; }
    .collection section:last-child { flex-basis: auto; }
}

bar

baz

FOO

jsFiddle


text:
Q: Assign a value to an rvalue reference returned from function #include <utility>
template <typename Container>
decltype(auto) index(Container &&arr, int n) {
    return std::forward<Container>(arr)[n];
}

Make a function call :
#include <vector>
index(std::vector {1, 2, 3, 4, 5}, 2) = 0;

When function calling finished, the object std::vector {1, 2, 3, 4, 5} will be destroyed, assigning a value to a deallocated address would cause undefined behaviour. But the above code works well and valgrind detected nothing. Maybe the compile helps me make another invisible variable like
auto &&invisible_value {index(std::vector {1, 2, 3, 4, 5}, 2)};
invisible_value = 9;

If my guess is incorrect, I want to know why assigning a value to an rvalue reference returned from function is worked and when the temporary object index(std::vector {1, 2, 3, 4, 5}, 2) will be destroyed.
This idea originated from 《Effective Modern C++》, Item3 : Understand decltype.

A: You said "When function calling finished, the object vector {1, 2, 3, 4, 5} will be destroyed" but that is untrue. The temporary created for the function call is not deleted until the statement ends, i.e. the next line of code. Otherwise imagine how much code would break that passes c_str() of a temporary string.

A: invisible_value = 9; is completely legal assignment as 9 is indeed a temporary. rvalue references can be assigned with a temporary but not bound to an lvalue (for example a variable; but you can achieve this like below:
int a =10;
invisible_value=std::move(a);

https://godbolt.org/z/iTNGFr. Mode detailed explanation in this question C++ Double Address Operator? (&&).

edit:
the assignment is only legal if it is in the same scope. invisible_value in this case refers to something that was in the scope of index function and it's behavior is undefined if you have a reference to it.


text:
Q: Proper way to author Jquery plugins with style rules I have been long battling this, and I would like to know if any others have feedback. I am about to make a customized library for building web apps quickly, and I want to make sure I use the right approach. I WANT to use this method:
$.fn.someSlider = function(){
var coreStyle = '.slider ul { white-space: nowrap; } .slider ul li {display: inline-block}', coreStyleTemplate = '<style><\/style>';
}

But I feel like hard coding the base CSS into the widget is always frowned upon - instead I see SO users recommending the use of CSS style rules instead of this option. I really really really want that 'it just works' feel, and having to force my users to use a separate style sheet just to get my plugins working... well is annoying!
Just to clarify: I would like to include all base style rules needed for the widgets proper/base functionality to be included inside the script. The user would easily modify the base look of the widget by writing a style rule in their own style sheet.
Example:
Instead of having to look through all the base styles trying to find the font color like this... .slider {display: inline-block;  color: #000; someotherconfusingrule : blahblah; }
The user simply starts a new rule with the classes name/selector being used - and then just write the changes to make to the default script styles
They would just write
.slider {color: #000};
Thanks for the help in advance SO!

A: Nice question! Although I'm not sure what the preferred solution to this would be, I was thinking of the following approach:

*

*Use a IIFE to define your jQuery plugin and enable you to define some private, global variables and functions.
$.fn.pluginName = (function() {
    return function() {
       ...your regular plugins code...
    };
}();

*Define your plugins CSS as a list of style rules in your plugins code
var rules = [
    '.box {' +
    '  width: 100px;' +
    '  background-color: #f99;' +
    '  margin: 10px;' +
    '  padding: 10px;' +
    '  font-family: Helvetica, Arial;' +
    '  text-align: center;' +
    '}'
];

*Create a private variable that remembers if your stylesheet has already been added to the document
var styleSheetExists = false;

*Create a private function that creates a stylesheet using the style rules above and that adds it as the first <style> element in the <head> allowing the user to override styles in their own CSS. See http://davidwalsh.name/add-rules-stylesheets for a good tutorial on how to do this properly
var createStyleSheet = function() {
    var style = document.createElement("style");
    style.appendChild(document.createTextNode(""));

    $('head').prepend(style);

    for (var i = 0; i < rules.length; i++) {
        style.sheet.insertRule(rules[i], i);
    }
};

*The first time your plugin is applied to an element check if the stylesheet has already been created and if not create the stylesheet.
var $elements = $(this);

if (!styleSheetExists) {
    createStyleSheet();
    styleSheetExists = true;
}

$elements.each(function() {
    $(this).addClass('box');
});

return $elements;

See http://codepen.io/ckuijjer/pen/FkgsJ for this example. It creates a jQuery plugin called box which simply adds the class box to an element. The class box has a default pink background color defined in its stylesheet which gets overridden by a user defined blue background color.
But please do make this configurable in your jQuery plugin. You want to enable developers to bundle all their css, including your plugins, to optimize resource delivery to the client. Plus injecting stylesheets might be a small performance hit.

A: It may seem annoying but separating the model, view, and controller is the correct way. You're using jQuery so why not consider how jQuery would approach the situation: a jQuery UI widget like the Accordion comes with several stylesheets, the most important being the base stylesheet and a separate 'theme' stylesheet that (if done correctly) is nondestructive and can be modified without risking the integrity of the widget. You may also want to consider how your favorite plugins are authored and what makes them appeal to you. It's my personal opinion CSS should never be present in JavaScript files however if you've made up your mind, the solution @ckuijjer provided is sound. Hope this helps!


text:
Q: Teensy 3.2 Hellokeypad sketch compile errors I'm getting a compiler error when I try and compile the HelloKeypad demo sketch.
I'm on a Windows 7 machine using a Teensy 3.2 board.
I bought a keypad like this one: https://www.adafruit.com/products/1824
I downloaded the keypad.zip file from here:
https://www.pjrc.com/teensy/td_libs_Keypad.html
and I'm using the example sketch from the same web page:
/* @file HelloKeypad.pde
|| @version 1.0
|| @author Alexander Brevig
|| @contact alexanderbrevig@gmail.com
||
|| @description
|| | Demonstrates the simplest use of the matrix Keypad library.
|| #
*/
#include <Keypad.h>

const byte ROWS = 4; //four rows
const byte COLS = 3; //three columns
char keys[ROWS][COLS] = {
  {'1','2','3'},
  {'4','5','6'},
  {'7','8','9'},
  {'*','0','#'}
};
byte rowPins[ROWS] = {5, 4, 3, 2}; //connect to the row pinouts of the keypad
byte colPins[COLS] = {8, 7, 6}; //connect to the column pinouts of the keypad

Keypad keypad = Keypad( makeKeymap(keys), rowPins, colPins, ROWS, COLS );

void setup(){
  Serial.begin(9600);
}

void loop(){
  char key = keypad.getKey();

  if (key){
    Serial.println(key);
  }
}

Here is the compiler message.
Arduino: 1.6.6 (Windows 7), TD: 1.26, Board: "Teensy 3.2 / 3.1, Serial + Keyboard + Mouse + Joystick, 96 MHz optimized (overclock), US English"

In file included from C:\Users\FRESH1~1\AppData\Local\Temp\arduino_827e3ed6878980f03915bd59f832243c\HelloKeypad.ino:10:0:
C:\Users\fresh1011\Documents\Arduino\libraries\Keypad/Keypad.h:80:27: error: expected class-name before '{' token
class Keypad : public Key {
^
C:\Users\fresh1011\Documents\Arduino\libraries\Keypad/Keypad.h:90:2: error: 'Key' does not name a type
Key key[LIST_MAX];
^
C:\Users\fresh1011\Documents\Arduino\libraries\Keypad/Keypad.h:95:2: error: 'KeyState' does not name a type
KeyState getState();
^
C:\Users\fresh1011\Documents\Arduino\libraries\Keypad/Keypad.h:119:28: error: 'KeyState' has not been declared
void transitionTo(byte n, KeyState nextState);
^
Multiple libraries were found for "Keypad.h"
 Used: C:\Users\fresh1011\Documents\Arduino\libraries\Keypad
 Not used: C:\Program Files (x86)\Arduino\hardware\teensy\avr\libraries\Keypad
exit status 1
Error compiling.

Is the Keypad.zip file out of date?
Thanks for any help.

A: Maybe use Arduino IDE 1.6.3 instead of 1.6.6.
According to the following post in the pjrc forum it solves the problem for the library support.


text:
Q: Validation of Models in rails, implicit linking I'm trying to validate two models in rails.
Dismissal has a condition that says "if you have a dismissal type that is "bowled", then you must have a "BowlingRecord".
class Dismissal < ActiveRecord::Base

  include DismissalHelper

  belongs_to :bowling_record

  validate :dismissal_bowling_record_combo_is_appropriate

  def dismissal_bowling_record_combo_is_appropriate
    return if !dismissal_type.present?
    if bowling_record.present?
      return if DismissalHelper::BOWLING_DISMISSAL_TYPES.include?(dismissal_type)
      errors.add(:dismissal_type, "#{dismissal_type} can't have a bowler!")
    else
      return if !DismissalHelper::BOWLING_DISMISSAL_TYPES.include?(dismissal_type)
      errors.add(:dismissal_type, "#{dismissal_type} must have a bowler!")
    end
  end

end

BowlingRecord has a condition that says "if you have some dismissals, then they must be of a certain dismissal type" (of which bowled is one).
class BowlingRecord < ActiveRecord::Base

  include DismissalHelper

  has_many :dismissals

  validate :dismissals_go_against_bowler

  def dismissals_go_against_bowler
    dismissals.each do |dismissal|
      if !DismissalHelper::BOWLING_DISMISSAL_TYPES.include?(dismissal.dismissal_type)
        errors.add(:dismissal, "can't be #{dismissal.dismissal_type} if registered against a bowler")
      end
    end
  end

end

I'm having trouble constructing this, realistically I want to do something like:
BowlingRecord.create!(
  extra_balls: 5,
  maidens: 3,
  runs: 56,
  dismissals: [ Dismissal.create!(dismissal_type: :bowled) ]
)

But this blows up, because when we create the dismissal, it quite rightly says "I need a bowling record, if you want your type to be bowled". But all the information is here, I want the Dismissal creating to be lazy, so that it has the context that it's being created belonging to a bowling record.
Of course I say create the bowling record up front, and then add the dismissals one-by-one. But this seems to be dirtier code and so I was wondering if there was any way to do it in this manner...
Thanks

A: You could .build the associated dismissal:
record = BowlingRecord.new(
  extra_balls: 5,
  maidens: 3,
  runs: 56
)

record.dismissals.build dismissal_type: :bowled

record.save!

.build:

Returns a new object of the collection type that has been instantiated with attributes and linked to this object, but have not yet been saved.

See ActiveRecord::Associations::CollectionProxy for more info.
Through ActiveRecord::AutosaveAssociation, the dismissal is saved automatically when the parent BowlingRecord is saved. This happens within a transaction, so you don't end up in an inconsistent state if one of the two fails to save.


text:
Q: Help understanding second derivative and how they tell us about the features of the original function To aid in sketching graphs:

*

*We can find axial intercepts, asymptotes

*The first derivative can give us the function's stationary points by evaluating $f'(x) = 0$
I know that second derivative give the rate of change of the first derivative
But, what does the second derivative do to help us sketch the original function?
Lets take an example:

*

*$f(x) = -x^2$

*$f'(x) = -2x$

*$f''(x) = -2$
By evaluating $-2x=0$, we get a turning point at $x = 0$.
Now, what can I do with $f''(x)$ in this case, considering that it is just a constant?

A: one of the important things that the second derivative tells us is the property of turning point. For example, if the second derivative of the zero of the first derivative is bigger than $0$, then the turning point is the minimal value locally.
As the function $y=x^2$, whose second derivative of $0$ is $2>0$. Hence, $0$ is the minimal point of the original function locally (of course, in this function, it's actually the globally minimal)


text:
Q: R - Calculate totals using a parent-child relation table I am working with a dataset which contains two tables: one that gives the value of a number of variables at the lowest level, and one that shows all child-parent relations which I should use to calculate the totals.
My data looks something like this:
> # table that shows child-parent relation
> ID <- c(5, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100)
> PARENT_ID <- c(NA, 5, 10, 10, 5, 5, 5, 60, 60, 60, 60)
> df_relation <- data.frame(ID, PARENT_ID)
> df_relation
    ID PARENT_ID
1    5        NA
2   10         5
3   20        10
4   30        10
5   40         5
6   50         5
7   60         5
8   70        60
9   80        60
10  90        60
11 100        60
> # For instance, ID 70 + 80 + 90 + 100 gives the value for ID 60
>
> # table that contains values at the lowest level
> ID <- c(20, 30, 40, 50, 70, 80, 90, 100)
> VALUE <- c(14, 1, 4329, 98503, 272, 667, 712, 55)
> df_value <- data.frame(ID, VALUE)
> df_value
   ID VALUE
1  20    14
2  30     1
3  40  4329
4  50 98503
5  70   272
6  80   667
7  90   712
8 100    55
>
> # add values to relation table
> df <- left_join(df_relation, df_value, by = "ID")
> df
    ID PARENT_ID VALUE
1    5        NA    NA
2   10         5    NA
3   20        10    14
4   30        10     1
5   40         5  4329
6   50         5 98503
7   60         5    NA
8   70        60   272
9   80        60   667
10  90        60   712
11 100        60    55
>
> # compute totals (ID = 5, 10 & 60)
> # ID 60 = 70 + 80 + 90 + 100
> # ID 10 = 20 = 30
> # ID 5 = 10 + 40 + 50 + 60

Off course, I can do this manually, but I also have a number of additional tables which have even more child-parent levels. So I would rather have a function which could do the job.
Would anyone know how to do this?

A: It looks like you need to use recursion here:
sum_children <- function(ID, data)
{
  result <- 0;
  children <- which(data$PARENT_ID == ID)
  if(length(children) == 0)
    return(data$VALUE[which(data$ID == ID)])
  else
    for(i in seq_along(children))
      result <- result + sum_children(data$ID[children[i]], data)
  return(result)
}

This function will take an ID whose child sums you wish to calculate and return the result.
sum_children(60, df)
#> [1] 1706

It will work to any depth. For example, each node with a value in your example is ultimately descended from ID 5. Therefore the child sum of 5 should be the same as the total of VALUE
sum(df$VALUE, na.rm = T)
#> [1] 104553

sum_children(5, df)
#> [1] 104553

And in fact, you can quickly get the result for all descendants for each ID by doing:
df$child_sum <- sapply(df$ID, sum_children, df)

df
#>     ID PARENT_ID VALUE child_sum
#> 1    5        NA    NA    104553
#> 2   10         5    NA        15
#> 3   20        10    14        14
#> 4   30        10     1         1
#> 5   40         5  4329      4329
#> 6   50         5 98503     98503
#> 7   60         5    NA      1706
#> 8   70        60   272       272
#> 9   80        60   667       667
#> 10  90        60   712       712
#> 11 100        60    55        55

A: I am not sure if I understood this correctly, but if it's just about to sum up the ID column which have the same PARENT_ID, then it would be:
df %>% group_by(PARENT_ID) %>% summarise(TOTALS = sum(ID))


text:
Q: Javascript while loop over ElementIds from DOM until first empty Element Easy task i guess but i am new to this and am stuck. I want to iterate through some ElementIds of a webpage to extract the text within.
The ElementIds i am looking for are like this:
"p000", "p001", "p002", etc. (I guess it would go until "p999")
This is what i have so far.
var totalText=[]
while(text===""):
    var text=document.getElementById("p0003");
    totalText.push(text);
}

Now i would like to iterate through the ElementIds as described and stop as soon as text is empty which means there is no Element "p091" anymore and the loop stops and does not continue until "p999".

A: This will help just get all elements and loop through them!

var arrayofelements = [];
function getElements(){
  var lenght=document.getElementsByTagName("div").length;
    for(var a = 0;a <= lenght; a++){
      if(a == 0){
        a = "000";
      }
      else if(a <= 9){
        a = "00"+a;
      }
      else if(a => 10 && a < 99){
        a = "0"+a;
      }
      var text = document.getElementById("p"+a);
      if(text == undefined || text == null){
       return;
      }
      arrayofelements.push(text.innerHTML);
    }
}
getElements();
arrayofelements.forEach(foreachfunc);
function foreachfunc(item,index){
  document.write("Array Data:   "+item);
}

0

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

A: You can add a class to each element (p000 through to p999) by adding the class attribute to all of them. Then use document.getElementsByClassName(). Querying the DOM is an expensive operation, so doing it a minimal amount of times is often a good idea. Also, document.getElementsByClassName() does the logic you're after, so there is no need to re-invent the wheel.
Here an example:

var paragraphs = Array.from(document.getElementsByClassName('info-para'));
console.log(paragraphs);

0

1

2

3

4

Note: Above, I have used a method called Array.from(), which returns an array given an array-like collection. That's because getElementsByClassName() returns a HTMLCollection, which is like an array, but not quite. So, in order to turn the HTMLCollection into an actual array you can use Array.from().
EDIT:
In order to get an array of strings you can loop through the array you retrieved, and get the innerText of each element, and .push() that into a new array like so:

var paragraphs = Array.from(document.getElementsByClassName('info-para'));

var texts = [];

for(var elem of paragraphs) { // loop through each element in paragraphs array
  texts.push(elem.innerText); // get the text of the current element, and push it to the texts array
}
console.log(texts);
console.log(texts.join(', '));
console.log(paragraphs);

0

1

2

3

4

Once you become more comfortable with JS, you can write the code above more elegantly by providing a mapping method to the Array.from() method and using destructuring assignment like so:

const texts = Array.from(document.getElementsByClassName('info-para'), ({innerText}) => innerText);
console.log(texts);

0

1

2

3

4

A:

var totalText = [];
var num = 2;
var text = document.getElementById("p001").innerHTML;
while (!(text === "")) {
  totalText.push(text);
  var str = "" + num;
  str = str.padStart(3, "0");
  text = document.getElementById("p" + str).innerHTML;
  if (text === "" || text === undefined || text === null) break;
  num++;
}
console.log(totalText);

1

2

3

4

A: You can look for an id  that starts with a string and loop on those, breaking when the first empty text is found.  I added a class to illustrate the found one.  This relies on the DOM sequence for "first" here.

var foundText=[];
var allPIdElements = document.querySelectorAll('*[id^="p"]');
for (let el = 0; el < allPIdElements.length; el++) {
  let item =allPIdElements[el];
  let t = item.innerText;
  foundText.push( t );
  if (t == '') {
    item.classList.add('found');
    foundText.pop();// remove empty
    break;
  }
}
console.log(foundText);
*[id^="p"] {
  border: solid 1px #777777;
  padding: 0.3em;
  margin: 0.5em;
}

.found {
  border: #77DD77 solid 2px;
}

clear

tear

watch

goat

cheer

cheer

cheer


text:
Q: Show ringtones and books in iTunes library In my iTunes (12.3.2) I want to have ringtones and books show up under library.  But only Music & Purchased shows up under library. I went to iTunes preferences/general and did not get the option to have those two ringtones and books show up.

A: Ringtones are called Tones in my version of iTunes (12.3.2.35), and are already shown on the top left of your screen capture.
If not, you can click the ··· menu and edit it to make them always visible.

Purchased books and audiobooks are shown on the iBooks app on OS X and iOS.


text:
Q: getting previous mails in outlook 2007 I am using outlook 2007 in my system. the system has got re-installed windows 7 and when I configured my outlook account the old mails were not there. what to do? any suggestion

A: Mail is saved to .pst files. You should look for any files on your pc with extension .pst and import them into Outlook 2007 to see whether they contain the mail you are looking for. Of course, if by "re-installed windows 7" you mean the hard drive was formatted, you better have a backup.
If you are using an IMAP account (as opposed to a POP3 which is not as largely used today as it once was), mail is stored on the server so it should still be there after an OS reinstall on the client. I believe the same is true for Exchange accounts.


text:
Q: Learning for loops in R and can't pull out a specific variable I am having trouble figuring out for loops in R after learning in Python for a while. What I want to do is pull out $nitrate or $Sulfate from the vector of CSV files this code returns:
getpollutant <- function(id=1:332, directory, pollutant) {
        data<-c()
        for (i in id) {
                data[i]<- c(paste(directory, "/",formatC(i, width=3, flag=0),".csv",sep=""))
        }
        df<-c()
        for (d in 1:length(data)){ df[[d]]<-c(read.csv(data[d]))

        }
        df
}

I haven't included the for loop for pollutant yet, I've tried many different approaches but can't get it to work quite right... with the code above I can put in: getpollutant(1:10, "specdata") and it will give me all the csv files from the specdata directory with labels 001 through 010, it spits out each csv file in separated chunks with headers of the format [[i]]$columnname with the contents of the column listed below. What I want to do is pull out a specific columnname (pollutant) and return the contents of that column from every csv file. I have read through the help pages and just can't seem to get my formatting right...
@RomanLuštrik
I don't know if this is what you're looking for but here's a sample output if I put in
getpollutant(1, "specdata"):
[[1]]
[[1]]$Date
[1] 2003-01-01 2003-01-02 2003-01-03
[[1]]$sulfate
[1] NA NA NA NA NA NA 7.210 NA NA NA 1.300
[[1]]$nitrate
[1] NA NA NA .474 NA NA NA .964 NA NA NA

obviously this is a very small version of what the output is but basically it takes the CSV files in the specified range id and prints them out like this...

A: Do you only want to read in a certain column from the files? and do you know which column it is by number (e.g. the 3rd column)?  In that case you can use the colClasses argument to read.table/read.csv to specify only reading in the given column.
If you don't know which column it is ahead of time then you may need to read in the entire file, then only return the given column.  In that case you probably want to use [[]] subsetting instead of $ subsetting.
You can also make your code more compact and possibly more efficient by using sprintf and lapply or sapply.
Consider this code:
lapply(1:332, function(id) {
  read.csv( sprint("%s/%03d.csv", directory, id )
})

or
sapply( list.files(directory, pattern='\\.csv$',full.names=TRUE),
  function(nm) read.csv(nm)[[pollutant]] )


text:
Q: Simple list in ASP.NET I'm trying to make a simple list in ASP.NET, I made one yesterday for one controller but now today I cannot get it to work in a new controller nor can I figure out why. Here's the controller from yesterday:
using System;
using System.Collections.Generic;
using System.Web.Mvc;
using SubjectAccessRequests.Models;

namespace SubjectAccessRequests.Controllers
{
    public class PersonController : Controller
    {
        // GET: Person
        public ActionResult Person()
        {

            Person human = new Person()
        {
            FirstName = "Jack",
            LastName = "O'Neill",
            Age = 23,
        };

        Person adult = new Person()
        {
            FirstName = "John",
            LastName = "Smith",
            Age = 27,
        };

        List<Person> people = new List<Person>();

        people.Add(human);
        people.Add(adult);

        return View(people);
    }
}

This works like a charm. Here's the views for the above controller:
@model IEnumerable<SubjectAccessRequests.Models.Person>

@{
    Html.RenderPartial("_PartialView");
    }

Person

            @Html.DisplayNameFor(model => model.FirstName)

            @Html.DisplayNameFor(model => model.LastName)

            @Html.DisplayNameFor(model => model.Age)

@foreach (var item in Model) {

            @Html.DisplayFor(modelItem => item.FirstName)

            @Html.DisplayFor(modelItem => item.LastName)

            @Html.DisplayFor(modelItem => item.Age)

    }

Now here's the controller from today:
using System;
using System.Collections.Generic;
using System.Web.Mvc;
using SubjectAccessRequests.Models;

namespace SubjectAccessRequests.Controllers
{
    public class AttemptController : Controller
    {
    // GET: Attempt
    public ActionResult Attempt()
    {
        Attempt story = new Attempt()
        {
            BookTitle = "Seabiscuit",
            Author = "Laura Hillenbrand",
        };

        Attempt play = new Attempt()
        {
            BookTitle = "King Lear",
            Author = "Shakespear",
        };

        return View(books);
    }

    //List<Attempt> books = new List<Attempt>();

    //books.Add(story);
    //books.Add(play);

    //return View(books);

}
}

And here's the views for the above controller:
    model IEnumerable<SubjectAccessRequests.Models.Attempt>

@{
    Html.RenderPartial("_PartialView");
}

Books

            @Html.DisplayNameFor(model => model.BookTitle)

            @Html.DisplayNameFor(model => model.Author)

    @foreach (var item in Model)
    {

                @Html.DisplayFor(modelItem => item.BookTitle)

                @Html.DisplayFor(modelItem => item.Author)

    }

The commented section does not work. I have looked through all the code above and I have looked through all the related files for both controllers to see if I can spot any problem but I cannot for the life of me figure out why the list works in the first controller and not in the second - any help at all would be greatly appreciated and thanks in advance!
EDIT
Added in the views for the two controllers!

A: I suspect your out of scope and returning books twice. Try -
using System;
using System.Collections.Generic;
using System.Web.Mvc;
using SubjectAccessRequests.Models;

namespace SubjectAccessRequests.Controllers
{
    public class AttemptController : Controller
    {
    // GET: Attempt
    public ActionResult Attempt()
    {
        Attempt story = new Attempt()
        {
            BookTitle = "Seabiscuit",
            Author = "Laura Hillenbrand",
        };

        Attempt play = new Attempt()
        {
            BookTitle = "King Lear",
            Author = "Shakespear",
        };

       List<Attempt> books = new List<Attempt>();

      books.Add(story);
      books.Add(play);

      return View(books);
    }

}


text:
Q: What is the estimated timeline for Release Readiness of the Office Store? our Microsoft Office Add-In submission to the Office Store made it through the Validation process and as seen in the following screenshot, we have reached Release readiness and are very excited about it.

However we are a bit confused about the estimated time (delay) it will take until the app becomes publicly available. Is there a way for us to plan the launch and do we have to wait until the app is published to update links to it on our website or can we access it beforehand?

A: The app submission workflow service within the Seller Dashboard service is experiencing delays and your submission may be impacted.  The Seller Dashboard status of your submission may not accurately reflect the actual status.  Our engineers are fully engaged to resolve this issue. We will contact you if you are required to take any action as a result of this.
If this is the first time your submission has been approved, no link will be available at present. If this is an update to an existing submission, the link will not have changed.


text:
Q: How Many Combinations Are Possible (using 5 letters, groups of 12)? I'm hoping you can help me with how many combinations are possible, given the following...
I have 5 letters (A, B, C, D, E).  I need to create groups of 12 letters, obviously I can use the letters multiple times.  However, there are limitations on the usage of letters:
-In each group of 12, I must use A 5-6 times, B 1-3 times, C, 1-3 times, D 1-3 times, and E 1-3 times.
-If A is used 6 times, then the maximum usage of B, C, D, and E is 2 times each.
-If B is used 3 times, then C can only be used 1 time, D and E could only be used 1-2 times each, and A would be used exactly 5 times.
-If C is used 3 times, then B can only be used 1 time, D and E could only be used 1-2 times each, and A would be used exactly 5 times.
-If D is used 3 times, then E can only be used 1 time, B and C could only be used 1-2 times each, and A would be used exactly 5 times.
-If E is used 3 times, then D can only be used 1 time, B and C could only be used 1-2 times each, and A would be used exactly 5 times.
-If B is used 1 time, then C must be used 2-3 times.
-If C is used 1 time, then B must be used 2-3 times.
-If D is used 1 time, then E must be used 2-3 times.
-If E is used 1 time, then D must be used 2-3 times.
And the total number of letters in each group must be 12.
How many combinations would this produce?
And the order matters as I want to know all the different orders they could be in.  For example, A A A A A A B C C D D E  would be one and B C C D D E A A A A A A would be another... same number of specific letters in each group but counts as 2 groups because they are in a different order.
Thank you in advance for your help!
Edited: groups of 12 needed, not 14.  sorry!

A: Let $a,b,c,d,e$ be the number of occurences of $A,B,C,D,E$, respectively.
Consider that among $B,C,D,E$ there cannot be $2$ (or more) letters with $3$ occurences.
Knowing that, let's split cases!
Case $1$: $b=3\implies (c=1)\land (d,e\leq2)$
Let's split cases again of $d$ and $e$:

*

*Sub-case 1: $d=2,e=2\implies a=4$ (invalid)

*Sub-case 2: $d=2,e=1\implies a=5$

*Sub-case 3: $d=1,e=2\implies a=5$

In sub-case 2, $(a,b,c,d,e)=(5,3,1,2,1)$, so there are $\frac{12!}{5!3!1!2!1!}=332640$ possibilities.
In sub-case 3, $(a,b,c,d,e)=(5,3,1,1,2)$, so there are $\frac{12!}{5!3!1!1!2!}=332640$ possibilities.
Therefore, in this case, there are $2\times332640=665280$ possibilities.
Case $2$: $c=3\implies (b=1)\land (d,e\leq2)$
Case $3$: $d=3\implies (e=1)\land (b,c\leq2)$
Case $4$: $e=3\implies (d=1)\land (b,c\leq2)$
Consider that in each of the three cases, the number of possibilities is the same as in the first case (simply change the variables to see that).
So, across the four cases, there are $$4\times665280=2661120$$ possibilities.
Case $5$: $b,c,d,e\leq 2$
Consider that in each of $\{b,c\}$ and $\{d,e\}$, the members cannot both be $1$. So the possibilities are $(2,2),(2,1),(1,2)$. Consider that the number of $1$s in that set is either $0$ ($1$ possibility) or $1$ ($2$ possibilities).
Therefore, the number of $1$s in $\{b,c,d,e\}$ is one of

*

*$0$ ($1\times1=1$ possibility),

*$1$ ($2\times1+1\times2=4$ possibilities), or

*$2$ ($2\times2=4$ possibilities).

Let that number of $1$s be $n$. Let's split cases again based on $n$:

*

*Sub-case 1: $n=0$ ($1$ possibility) $\implies a=4$ (invalid)

*Sub-case 2: $n=1$ ($4$ possibilities) $\implies a=5$
In this sub-case, there are $4\times\frac{12!}{5!2!2!2!1!}=1995840$ possibilities.

*

*Sub-case 3: $n=2$ ($4$ possibilities) $\implies a=6$

In this sub-case, there are $4\times\frac{12!}{6!2!2!1!1!}=665280$ possibilities.
Therefore, in this case, there are $$1995840+665280=2661120$$ possibilities in this case.

Therefore, the number of possibilities across the five cases is
$$2661120+2661120=\fbox{5322240}\text.$$


text:
Q: 404 error when using routing with Angular.js I'm trying to set up routing with angular and angularfire but am having trouble.
var app = angular.module('sampleApp', ['ngRoute', 'firebase', 'ui.bootstrap']);

app.config(function ($routeProvider) {
    $routeProvider
      .when('/', {
        templateUrl: 'index.html',
        controller: 'SampleCtrl'
      })
      .when('/login', {
        templateUrl: 'views/login.html',
        controller: 'LoginCtrl'
      })
      .otherwise({
        redirectTo: '/'
      });

  });

app.controller('LoginCtrl', function($scope, $firebase){
  console.log('LoginCtrl')
})

when I try to hit localhost:8000/login I get the following error message
Error code explanation: 404 = Nothing matches the given URI.

How can I set up simple routes with ngRoute and AngularFire?

A: When using the default router you need to use a hash in the url.
localhost:8000/#/login

If you want to remove the hash, that's another story.
You'll need to use the $locationProvider and set html5Mode() to true. From there you'll have to stop using $window.location.href to change routes and use $location.path().
Then you'll have to get a server or use a service like Firebase Hosting that supports URL rewrites.

A: play-around $location here (see the "test output" part, this helps me understand $route), hope this helps.
http://ngtutorial.com/learn/route.html#/_tblcontents_5


text:
Q: problem in jquery ui dialog content I have a link name of "login".
It click "login" jquery dialog will open.
Dialog has two links. If click it link,shows content related to link.
Now i come to my problem. If again i click "login" link,it shows only changed content. But i want initial content only.
This is my one part of code.
$( "#login-form" ).dialog({
                autoOpen: false,
                height: 210,
                width: 360,
                modal: true,
                show: "scale",
                hide: "scale",
                buttons: {
                    "Login": function() {
                        $("#login-frm").submit()
                        },
                    Cancel: function() {
                        $(this).dialog( "close" );
                    }
                }
            });

            $( "#login" ).click(function(event) {
                event.preventDefault();
                $( "#login-form" ).dialog( "open" );
            })

How can i do this?

A: In your click event you can load default content again. Or else you can keep a copy of default content of the login-form in a hidden div and replace it before dialog opens.
$( "#login-form" ).dialog({
                autoOpen: false,
                height: 210,
                width: 360,
                modal: true,
                show: "scale",
                hide: "scale",
                buttons: {
                    "Login": function() {
                        $("#login-frm").submit()
                        },
                    Cancel: function() {
                        $(this).dialog( "close" );
                    }
                }
            });

            $( "#login" ).click(function(event) {
                event.preventDefault();
                 $( "#login-form" ).html('give the default copy of the dialog here');
                $( "#login-form" ).dialog( "open" );
            })

A: Add a class to your login form controls that need to be cleared, say "loginControls" for example. Then, change your  $( "#login" ).click() function to be something like this:
 $( "#login" ).click(function(event) {
       event.preventDefault();
       $( ".loginControls" ).each(function (i) {
             this.val('');
             });
       $( "#login-form" ).dialog( "open" );
 });

Note that if you have more than just simple text box controls for your login form, you could do a separate class, such as "loginCheckBoxes", and then iterate through those with $(this).removeAttr('checked'); instead.
This allows you flexibility for various types of controls without the need to write out the entire form HTML in your event handling code.


text:
Q: how to change a directive variable value in controller List of directive are listed like:
HTML:

    <button class="btn btn-white" ng-click="minim()"></button>
    <widget-item widget-id="1" widget-type ="chart"></widget-item>
    <widget-item widget-id="2" widget-type ="table"></widget-item>

JS:
var dashboard = angular.module("dashboard",['ui.bootstrap','ngAnimate']);
dashboard.controller( 'MyCtrl', function ( $scope,$modal) {
    $scope.on = true;
    $scope.minim = function(){
        $scope.on = !$scope.on;
    };
});
dashboard.directive('widgetItem', ['$compile', function($compile){
        restrict: 'E',
        scope:true,
        template: '

',
        link:function(scope, element, attrs) {
                scope.on = true;
                scope.toggle = function () {
                   scope.on = !scope.on;
                };
        }
}]);

Here I have minimize button for individual directive as well as all directive. Individual minimize button working fine(It's define in directive link). Over all minimize button doesn't work. How do I change directive isolate value from controller?

A: In your case, you can use $broadcast which will emit event and  dispatches the event downwards to all child scopes.
Then, you can use $on to listen some event into your directive.
If i follow your code :
Controller
(function(){

function Controller($scope, $http) {

    $scope.on = true;

    $scope.minim = function(){
      $scope.on = !$scope.on;
      //send minim event downwards to all child scope
      $scope.$broadcast('minim', $scope.on);
    };

}

angular
.module('app', [])
.controller('ctrl', Controller);

})();

Directive
(function(){

  function widgetItem($compile) {
      return{
        restrict: 'E',
        scope: true,
        templateUrl: 'template.html',
        link:function(scope, element, attrs) {

          //Listen event minim
          scope.$on('minim', function(e, data){
            //Change our scope.on data
            scope.on = data;
          });

          scope.toggle = function () {
             scope.on = !scope.on;
          };
        }
        };
  }

angular
  .module('app')
  .directive('widgetItem', widgetItem);

})();

And then, call your directive :
HTML

    <button class="btn btn-white" ng-click="minim()"></button>
    <widget-item widget-id="1" widget-type ="chart"></widget-item>
    <widget-item widget-id="2" widget-type ="table"></widget-item>

A: If you use directive with scope: true, it means that you new scope is a child of parent scope and you can change whatever you want,because it's not an isolated scope.
if you need more with examples, here is a cool article
http://www.w3docs.com/snippets/angularjs/change-variable-from-outside-of-directive.html


text:
Q: Multiple indices for numpy array: IndexError: failed to coerce slice entry of type numpy.ndarray to integer Is there a way to do multiple indexing in a numpy array as described below?
arr=np.array([55, 2, 3, 4, 5, 6, 7, 8, 9])
arr[np.arange(0,2):np.arange(5,7)]

output:
IndexError: too many indices for array

Desired output:
array([55,2,3,4,5],[2,3,4,5,6])

This problem might be similar to calculating a moving average over an array (but I want to do it without any function that is provided).

A: Here's an approach using strides -
start_index = np.arange(0,2)
L = 5     # Interval length
n = arr.strides[0]
strided = np.lib.stride_tricks.as_strided
out = strided(arr[start_index[0]:],shape=(len(start_index),L),strides=(n,n))

Sample run -
In [976]: arr
Out[976]: array([55, 52, 13, 64, 25, 76, 47, 18, 69, 88])

In [977]: start_index
Out[977]: array([2, 3, 4])

In [978]: L = 5

In [979]: out
Out[979]:
array([[13, 64, 25, 76, 47],
       [64, 25, 76, 47, 18],
       [25, 76, 47, 18, 69]])


text:
Q: Different layout for mobile phone and tablet I want develop android xamarin app for mobile phone and tablets. I would like to know how to go about it?
I searched and I found that creating separate layout files would help. But does that mean that for each and every page I would have to add two layouts?
For mobile phone I would like to have two separate rows for mobile and FAX whereas for table I would like to adjust these in a single row something like this:
Mobile phone design:

Tablet design:

How can I get this?


text:
Q: Javascript failing to parse JSON when chrome console parses perfectly I have come a bit stuck when essentially trying to return some coordinates from a database for google maps API to produce a polygon.
I first grab my data from the database using Laravel Framework :
MapController -
public function getallmapcoords(request $request)
{
    $pd = ParishData::limit(10)->get();
    return json_encode($pd);
}

I then parse all the data and narrow it down to just the coordinates what I want.
Ajax -
  $.ajax({
type: 'post',
url: '{{route("getallmapcoords")}}',
beforeSend:function(){
$('.loader').append('

Loading...
');
  $('#progress').center(); //call the center function, centres the progress div in the
},
success:function(data){
  $('.loader').empty();

  parsedData = JSON.parse(data);
  coords = parsedData[0]['coordinates'];
  console.log(coords);
  parsedcoords = JSON.parse(coords);
  console.log(parsedcoords);

},
error:function(){
  // failed request; give feedback to user
},
complete:function(data){
  $('.loader').empty();
}
});

The first console.log displays out the coordinates as a string as shown :

The second console.log produces the following error:
Uncaught SyntaxError: Unexpected token l in JSON at position 4
at JSON.parse (<anonymous>)
at Object.success (<anonymous>:170:27)
at fire (eval at <anonymous> (app.js:83), <anonymous>:3268:31)
at Object.fireWith [as resolveWith] (eval at <anonymous> (app.js:83), <anonymous>:3398:7)
at done (eval at <anonymous> (app.js:83), <anonymous>:9305:14)
at XMLHttpRequest.eval (eval at <anonymous> (app.js:83), <anonymous>:9548:9)

Upon copying the first console.log (string version) into google chrome console and assigned a variable, it returns a object, which is the format I want.

The bit that confuses me is why Google chrome parses it fine but JSON.Parse fails?
An example of the string I am returning :
https://pastebin.com/c9rq9HqE
Thank you for any help you may provide and if there is a better way of doing this on the PHP side too I am all ears!

A: You are parsing the object twice:
parsedData = JSON.parse(data);
coords = parsedData[0]['coordinates'];
console.log(coords);
parsedcoords = JSON.parse(coords);
console.log(parsedcoords);

should be:
parsedData = JSON.parse(data);
coords = parsedData[0]['coordinates'];
console.log(coords);


text:
Q: how to monitor hazelcast cluster on production environment using hazelcast management center I have an application which is deployed on aws ec2 instance. We are using hazelcast cache to store certain tokens for user management. How to monitor this application from hazelcast management center.
Currently I am not able to connect to this node using hazelcast management center setup on local via IP address.
Do I need to install or setup anything else for such requirement.

A: Please read Hazelcast Management Center: Getting Started. It explains how to start Management Center and how to connect it to your Hazelcast cluster.
In short, you need to start Management Center, open it with your browser, and click "Add Cluster Config". Then, you can monitor and manage your Hazelcast cluster with the Management Center Application.


text:
Q: Get value from Managed Metadata Field in Drop Down List I'm working on a project portal where a user can create a project (team site). The user is asked to fill in details regarding the projects. One of the things that is required is a Managed Metadata field.
When the user so creates this projects, we have a dropdown list on the left side, listing all the data in this MMD category. As default, the dropdown list is set to pick the top one (alphabetically). I want the default value in this field to be the value the user chose when he created the project.
If the user selects multiple values, i want the drop-down list to show either the first value the user picked.
Any tips on how to do this?
Thanks in advance.

A: This question is related to this one. See answer there how to retrieve the identifiers from Managed Metadata fields. I hope this helps.


text:
Q: Input Date in Struts2 How to change the format of java.util.Date object in struts 2. What I have tested, Struts 2 accepts m/d/yy. Is it possible to change the format?
And also how to change the default message "Invalid field value for field date"?
date tag in struts2 can only be used in output.

A: You can pass format to s:date tag
<s:date name="myDate" format="yyyy-MM-dd" />

To change the default error message, in your validation.xml you can add message parameter
   <field name="myDate">
        <field-validator type="date">
            <message key="errors.myDateRequired" />
        </field-validator>
    </field>

Then in your ApplicationResources.properties file you will provide value for errors.myDateRequired
Update: As per comment
s:date is only a read only tag which means cannot be used to accept input from user.
For enabling textField to accept date in different format, couple of approaches:

*

*Use struts2-jQuery plugin, it has a very nice date picker which support different date timeformat, showcase, DatePickerTag.

*Custom javascript code to format user input.

*Use jQuery (if allowed) and use jQuery datepicker

You can use custom converter to use text field for date, example

A: The date format Struts accepts depends on the user's locale. So for different locales you can have different date formats. This way you won't be able to support multiple date formats for the same locale but I don't see why you would need this anyway, it's only going to confuse your users. The only way to support different date formats for the same locale without javascript would be with a custom date converter as @mprabhat notes.

A: You could see the official doc about this:
Define the format for every language y the resource bundle. For instance, an appropriate en_US format definition extension could look like this:
format.date = {0,date,MM/dd/yy}

In parallel, you could add the following to your de_DE bundle:
format.date = {0,date,dd.MM.yyyy}

http://struts.apache.org/2.1.6/docs/formatting-dates-and-numbers.html


text:
Q: How to set bitmap in center in kotlin How i can set bitmap image in center it is not in center .Here is my code and screen.I tried so much but I failed to solves this
fun onDraw(c: Canvas, rectF: RectF, pos: Int) {
    val p = Paint()
    p.color = color
    c.drawRect(rectF, p)

    p.color = Color.WHITE
    p.textSize - textSize.toFloat()

    var r = Rect()
    val cHeight = rectF.height()
    val cWidth = rectF.width()
    p.textAlign = Paint.Align.RIGHT
    p.getTextBounds(text, 0, text.length, r)

    var x = 0f
    var y = 0f
    if (imageResId == 0) {

        x = cWidth / 2f - r.width() / 2f - r.left.toFloat()
        y = cHeight / 2f + r.height() / 2f - r.bottom.toFloat()
        c.drawText(text, rectF.left + x, rectF.top + y, p)

    } else {
        val d = ContextCompat.getDrawable(context, imageResId)
        val bitmap = drawableToBitmap(d!!)
        c.drawBitmap(
            bitmap,
            (rectF.left + rectF.right) / 2,
            (rectF.top + rectF.bottom) / 2,
            p
        )

    }

    clickRegion = rectF
    this.pos = pos
}

Here is image link that is produce error
enter link description here
 private fun drawableToBitmap(d: Drawable?): Bitmap {

    if (d is BitmapDrawable) return d.bitmap
    val bitmap =
        Bitmap.createBitmap(d!!.intrinsicWidth, d.intrinsicHeight, Bitmap.Config.ARGB_8888)
    var canvas = Canvas(bitmap)
    d.setBounds(0, 0, canvas.width, canvas.height)

    d.draw(canvas)
    return bitmap
}

A: You can see that your drawables are all in center  and draw from there, all you do are right, you just only need a simply offset with:
Subtract the half of the drawable's width & height from the start position
Red to Green

Code Snippet
    c.drawBitmap(
        bitmap,
        (rectF.left + rectF.right) / 2,
        (rectF.top + rectF.bottom) / 2,
        p
    )

To
    c.drawBitmap(
        bitmap,
        (rectF.left + rectF.right - bitmap.width) / 2,
        (rectF.top + rectF.bottom - bitmap.height) / 2,
        p
    )


text:
Q: Hashsetcontains for collection I am comparing 2 hashsets full of filenames.I have successfully implemented "ExceptWith" but now I need to get a list of "all filenames that are in both sets."
I know hashset has a contains but that means looping the hashset for each item of the other one.
Wondering if there is an inbuilt method to do this.
I am doing with files with over 50000 filenames.
many thanks

A: What you are talking about is a set intersection. There is a built in method for that:
HashSet<string> x = new HashSet<string> { "x", "a","b"};
HashSet<string> y = new HashSet<string> { "z", "a","b"};
x.IntersectWith(y);

Note that this modifies the original HashSet x. If you don't want that, use the extension method on Enumerable:
var intersection = x.Intersect(y);

Since the last one is defined as an extension on IEnumerable<T>, it works on the more general case as well. Just be aware that it might not be as optimized for performance as HashSet<T>.IntersectWith, since it needs to be able to work on all enumerables.


text:
Q: How to clean the spaces from the beginning and the end in Java? I'm learning Java 8 with REST and from my microservice I'm calling a REST service and I receive a JSON object. After that I need to delete the space from beginning and the end and after that to send it to frontend.
For example I have this model object:
public class User {
    @JsonProperty("name")
    private String name = null;
    @JsonProperty("education")
    private String education = null;
    @JsonProperty("phone")
    private String phone = null;
    @JsonProperty("age")
    private String age = null;

    public User() {
    }

    ........
}

So I'm calling this external service and I receive this kind of response:
{
    "name": "  John Book",
    "education": "   Faculty of Computers            ",
    "phone": "00448576948375           ",
    "age": "   20 "
}

Now I need to clean all the spaces from the begining and the end for every field and to transform it in this:
{
    "name": "John Book",
    "education": "Faculty of Computers",
    "phone": "00448576948375",
    "age": "20"
}

How can I do this kind of implementation? Thank you!

A: Simply using String#trim() on each of the fields might work here.  But I suggest removing the whitespace before you even persist on your backend, at the time when you first receive the JSON from the front end.  Insert the following lines when you marshall the incoming JSON to the Java POJO:
User user = ... // marshall from JSON
user.setName(user.getName().trim());
user.setEducation(user.getEducation().trim());
user.setPhone(user.getPhone().trim());
user.setAge(user.getAge().trim());

That the UI doesn't want to see this whitespace implies that there might not be a point in storing it on the backend in the first place.


text:
Q: Webpack change properties to devServer i'm trying to use a plugin in my vuejs project that allows me to create projects in VUE within CMS October, however i updated my node and i believe i updated the webpack version too (from what i've researched) and now my plugin is not working for that error is occurring right on that line of code.
The properties of disableHostCheck and public no longer exist, I would like to know which one I could replace that would have the same effect?
I've been searching the webpack documentation and I couldn't understand which one would be equivalent.
// configure the dev server and public path based on environment
    options.devServer = {
        disableHostCheck: true,
        public: 'http://localhost:8080',
    };

ValidationError: Invalid options object. Dev Server has been initialized using an options object that does not match the API schema.
         - options has an unknown property 'public'. These properties are valid:
           object { allowedHosts?, bonjour?, client?, compress?, devMiddleware?, headers?, historyApiFallback?, host?, hot?, http2?, https?, ipc?, liveReload?, magicHtml?, onAfterSetupMiddleware?, onBeforeSetupMiddleware?, onListening?, open?, port?, proxy?, server?, setupExitSignals?, setupMiddlewares?, static?, watchFiles?, webSocketServer? }

A: In webpack 5 is changed, please check:
 devServer: {
    allowedHosts: 'all',
 }


text:
Q: nodejs deployment on aws EC2 issue I try to deploy a simple nodejs app on AWS EC2 server by docker, the server does not respond but the app runs correctly as expected on the local machine by

docker-compose up -d --build

index.js
require("dotenv").config();
    const express = require("express");
    const app = express();
    app.use("/api", (req, res) => {
      res.status(200).send("Test Deployment");
    });
    const port = process.env.PORT;
    app.listen(port, () => {
      console.log("server runs on port =", port);
    });

Dockerfile
FROM node:18.13-alpine
WORKDIR /app
COPY package.json .
RUN npm install --only=production;
COPY . .
EXPOSE 3000
CMD ["npm", "run", "start"]

docker-compose.yml
version: "3"
services:
  backend:
    container_name: backend
    ports:
      - "3000:3000"
    build: .
    environment:
      PORT: "3000"
    command: npm run start

backend container logs on server
test-docker$ docker logs backend -f

> test-node@1.0.0 start
> node .

server runs on port = 3000


text:
Q: Get angle from x,y of a linear base of an object How to align/parallelise the green arrow (pic 2) with the linear base.
After applying the basic PCA analysis of OpenCV I was quite happy with the result but I would like to know how to manipulate the center point location and angle to match with the base.
In the pictures provided you can see the green line is off by a few degrees while I would like it to be either on or just parallel to the "base".
Source image:

What I currently get:

#include <iostream>
#include <opencv2/opencv.hpp>

using namespace std;
using namespace cv;

// Function declarations
void drawAxis(Mat&, Point, Point, Scalar, const float);
double getOrientation(const vector<Point> &, Mat&);

void drawAxis(Mat& img, Point p, Point q, Scalar colour, const float scale = 0.2)
{
    double angle;
    double hypotenuse;
    angle = atan2( (double) p.y - q.y, (double) p.x - q.x ); // angle in radians
    hypotenuse = sqrt( (double) (p.y - q.y) * (p.y - q.y) + (p.x - q.x) * (p.x - q.x));
        double degrees = angle * 180 / CV_PI; // convert radians to degrees (0-180 range)
        cout << "Degrees: " << abs(degrees - 180) << endl; // angle in 0-360 degrees range

    // Here we lengthen the arrow by a factor of scale
    q.x = (int) (p.x - scale * hypotenuse * cos(angle));
    q.y = (int) (p.y - scale * hypotenuse * sin(angle));
    line(img, p, q, colour, 1, CV_AA);
    // create the arrow hooks
    p.x = (int) (q.x + 9 * cos(angle + CV_PI / 4));
    p.y = (int) (q.y + 9 * sin(angle + CV_PI / 4));
    line(img, p, q, colour, 1, CV_AA);
    p.x = (int) (q.x + 9 * cos(angle - CV_PI / 4));
    p.y = (int) (q.y + 9 * sin(angle - CV_PI / 4));
    line(img, p, q, colour, 1, CV_AA);

}

double getOrientation(const vector<Point> &pts, Mat &img)
{
    //Construct a buffer used by the pca analysis
    int sz = static_cast<int>(pts.size());
    Mat data_pts = Mat(sz, 2, CV_64FC1);
    for (int i = 0; i < data_pts.rows; ++i)
    {
        data_pts.at<double>(i, 0) = pts[i].x;
        data_pts.at<double>(i, 1) = pts[i].y;
    }
    //Perform PCA analysis
    PCA pca_analysis(data_pts, Mat(), CV_PCA_DATA_AS_ROW);
    //Store the center of the object
    Point cntr = Point(static_cast<int>(pca_analysis.mean.at<double>(0, 0)),
                       static_cast<int>(pca_analysis.mean.at<double>(0, 1)));
    //Store the eigenvalues and eigenvectors
    vector<Point2d> eigen_vecs(2);
    vector<double> eigen_val(2);
    for (int i = 0; i < 2; ++i)
    {
        eigen_vecs[i] = Point2d(pca_analysis.eigenvectors.at<double>(i, 0),
                                pca_analysis.eigenvectors.at<double>(i, 1));
        eigen_val[i] = pca_analysis.eigenvalues.at<double>(0, i);
    }
    // Draw the principal components

    circle(img, cntr, 3, Scalar(255, 0, 255), 2);
    Point p1 = cntr + 0.02 * Point(static_cast<int>(eigen_vecs[0].x * eigen_val[0]), static_cast<int>(eigen_vecs[0].y * eigen_val[0]));
    Point p2 = cntr - 0.02 * Point(static_cast<int>(eigen_vecs[1].x * eigen_val[1]), static_cast<int>(eigen_vecs[1].y * eigen_val[1]));
    drawAxis(img, cntr, p1, Scalar(0, 255, 0), 1);
    drawAxis(img, cntr, p2, Scalar(255, 255, 0), 5);

    double angle = atan2(eigen_vecs[0].y, eigen_vecs[0].x); // orientation in radians
    return angle;
}

int main(int, char** argv)
{
    // Load image
    Mat src = imread("/path/image.jpg");
    // Check if image is loaded successfully
    if(!src.data || src.empty())
    {
        cout << "Problem loading image!!!" << endl;
        return EXIT_FAILURE;
    }

    imshow("src", src);
    // Convert image to grayscale
    Mat gray;
    cvtColor(src, gray, COLOR_BGR2GRAY);
    // Convert image to binary
    Mat bw;
    threshold(gray, bw, 50, 255, CV_THRESH_BINARY | CV_THRESH_OTSU);
    // Find all the contours in the thresholded image
    vector<Vec4i> hierarchy;
    vector<vector<Point> > contours;
    findContours(bw, contours, hierarchy, CV_RETR_LIST, CV_CHAIN_APPROX_NONE);
    for (size_t i = 0; i < contours.size(); ++i)
    {
        // Calculate the area of each contour
        double area = contourArea(contours[i]);
        // Ignore contours that are too small or too large
        //if (area < 1e2 || 1e5 < area) continue;
        if (area > 1e6) continue;
        cout << "Area: " << area << endl;

        // Draw each contour only for visualisation purposes
        drawContours(src, contours, static_cast<int>(i), Scalar(0, 0, 255), 2, 8, hierarchy, 0);
        // Find the orientation of each shape
        getOrientation(contours[i], src);
    }
    imshow("output", src);
    waitKey(0);
    return 0;
}

A: I don't know nothing about opencv, but this should do.
To project a vector on a plane you have to:
Greenvector - scalarproduct(plane.Normalvector,scalarproduct(plane.Normalvector,Greenvector)/plane.Normalvector.value^2)

Assuming vectors are as common used in math, describing a direction.
As I am at it, thank you, upon checking your question I've found an error within my own code.
edit:/
Are you sure the greenvector ain't on the plane, did you check it or are you assuming it from the picture?


text:
Q: Spring security - SessionRegistry getAllPrincipals.size() is 0 when using Programmatically login in a user I want to get all logged in users and using the following code :
sessionRegistry.getAllPrincipals();

Everything is working fine when i use login form to login the user. But, when i login the user Programmatically(using Spring Security) with the help of following code:
Authentication auth = new UsernamePasswordAuthenticationToken(user, null, user.getAuthorities());
SecurityContextHolder.getContext().setAuthentication(auth);

Then sessionRegistry.getAllPrincipals().size() return 0.


text:
Q: UIViewPropertyAnimator completion called when paused I haven't used UIViewPropertyAnimator very much (still an old fashioned blocks guy) and I'm seeing some behavior that I can't explain and that the docs don't really provide any insight on.
Why does an animator's completion block get called with a finalPosition of .end even when the animator is paused immediately after it's started?
let view = UIView()
let animator = UIViewPropertyAnimator(duration: 4, curve: .linear, animations: {
    view.alpha = 0
})

animator.addCompletion { position in
    print("done")
    switch position {
    case .start: print("start")
    case .current: print("current")
    case .end: print("end")
    }
}

animator.startAnimation()
print("starting")
animator.pauseAnimation()
print("pausing")

Output:
starting
pausing
done
end

A: The problem, as @matt alluded to, is that your view isn't in a visible UIWindow, so the animations complete immediately. You get the same output if you comment out the animator.pauseAnimation() statement.
You can fix this if you're using a playground by making view the liveView of the playground page:
import PlaygroundSupport
import UIKit

let view = UIView()
PlaygroundPage.current.liveView = view

// etc.

A: If you read the documentation of addCompletion from Apple's developer site,
one of the parameter is the finalPosition. And you can use the value to determine
whether the animation stopped at the beginning, end, or somewhere in the middle.
And calling pauseAnimation will trigger that completion block with a somewhere in the middle position.

Parameters completion A block to execute when the animations finish.
  This block has no return value and takes the following parameter:
finalPosition The ending position of the animations. Use this value to
  determine whether the animations stopped at the beginning, end, or
  somewhere in the middle.


text:
Q: C++ Read file line by line then split each line using the delimiter I want to read a txt file line by line and after reading each line, I want to split the line according to the tab "\t" and add each part to an element in a struct.
my struct is 1*char and 2*int
struct myStruct
{
    char chr;
    int v1;
    int v2;
}

where chr can contain more than one character.
A line should be something like:
randomstring TAB number TAB number NL

A: Try:
Note: if chr can contain more than 1 character then use a string to represent it.
std::ifstream file("plop");
std::string   line;

while(std::getline(file, line))
{
    std::stringstream   linestream(line);
    std::string         data;
    int                 val1;
    int                 val2;

    // If you have truly tab delimited data use getline() with third parameter.
    // If your data is just white space separated data
    // then the operator >> will do (it reads a space separated word into a string).
    std::getline(linestream, data, '\t');  // read up-to the first tab (discard tab).

    // Read the integers using the operator >>
    linestream >> val1 >> val2;
}

A: Unless you intend to use this struct for C as well, I would replace the intended char* with std::string.
Next, as I intend to be able to read it from a stream I would write the following function:
std::istream & operator>>( std::istream & is, myStruct & my )
{
    if( std::getline(is, my.str, '\t') )
       return is >> my.v1 >> my.v2;
}

with str as the std::string member. This writes into your struct, using tab as the first delimiter and then any white-space delimiter will do before the next two integers. (You can force it to use tab).
To read line by line you can either continue reading these, or read the line first into a string then put the string into an istringstream and call the above.
You will need to decide how to handle failed reads. Any failed read above would leave the stream in a failed state.

A: std::ifstream in("fname");
while(in){
    std::string line;
    std::getline(in,line);
    size_t lasttab=line.find_last_of('\t');
    size_t firsttab=line.find_last_of('\t',lasttab-1);
    mystruct data;
    data.chr=line.substr(0,firsttab).c_str();
    data.v1=atoi(line.substr(firsttab,lasttab).c_str());
    data.v2=atoi(line.substr(lasttab).c_str());
}

A: I had some difficulty following some of the suggestions here, so I'm posting a complete example of overloading both input and output operators for a struct over a tab-delimited file. As a bonus, it also takes the input either from stdin or from a file supplied via the command arguments.
I believe this is about as simple as it gets while adhering to the semantics of the operators.

pairwise.h
#ifndef PAIRWISE_VALUE
#define PAIRWISE_VALUE

#include <string>
#include <iostream>

struct PairwiseValue
{
    std::string labelA;
    std::string labelB;
    float value;
};

std::ostream& operator<<(std::ostream& os, const PairwiseValue& p);

std::istream& operator>>(std::istream& is, PairwiseValue& p);

#endif

pairwise.cc
#include "pairwise.h"

std::ostream& operator<<(std::ostream& os, const PairwiseValue& p)
{
    os << p.labelA << '\t' << p.labelB << '\t' << p.value << std::endl;
    return os;
}

std::istream& operator>>(std::istream& is, PairwiseValue& p)
{
    PairwiseValue pv;

    if ((is >> pv.labelA >> pv.labelB >> pv.value))
    {
        p = pv;
    }

    return is;
}

test.cc
#include <fstream>
#include "pairwise.h"

int main(const int argc, const char* argv[])
{
    std::ios_base::sync_with_stdio(false); // disable synch with stdio (enables input buffering)

    std::string ifilename;
    if (argc == 2)
    {
        ifilename = argv[1];
    }

    const bool use_stdin = ifilename.empty();
    std::ifstream ifs;
    if (!use_stdin)
    {
        ifs.open(ifilename);

        if (!ifs)
        {
            std::cerr << "Error opening input file: " << ifilename << std::endl;
            return 1;
        }
    }

    std::istream& is = ifs.is_open() ? static_cast<std::istream&>(ifs) : std::cin;

    PairwiseValue pv;

    while (is >> pv)
    {
        std::cout << pv;
    }

    return 0;
}

Compiling
g++ -c pairwise.cc test.cc
g++ -o test pairwise.o test.o

Usage
./test myvector.tsv
cat myvector.tsv | ./test