text:
Q: HTML/CSS collage of images neatly fitting into a rectangle I am in the progress of making a collage of images that fit perfectly into a rectangle, so far I have managed to create the top layer for it. However the last row has got me confused as I can't seem to get them into place using CSS. (You may need to run it through your browser to see it clearly)

  var container = document.querySelector('#grid');
  var masonry = new Masonry(container, {
    columnWidth: 1346,
    itemSelector: '.grid-item'
  });
.grid-item {
  float: left;
  border: 0px solid transparent;
}
.grid-item--width146x100 {
  width: 125px;
  height: 100px;
  float: right
}
.grid-item--width146x300 {
  width: 125px;
  height: 300px;
  float: right
}
.grid-item--width200x100 {
  width: 200px;
  height: 100px
}
.grid-item--width200x200 {
  width: 200px;
  height: 200px
}
.grid-item--width300 {
  width: 300px;
  height: 200px
}
.grid-item--width500x200 {
  width: 500px;
  height: 200px
}
.grid-item--width500x400 {
  width: 500px;
  height: 400px
}
.grid-item--width200x200(1) {
  width: 500px;
  height: 400px
}
.grid-item--width200x100(1) {
  width: 500px;
  height: 400px
}

A: Div dimensions should in ratio to fit into each other neatly.
Here the dimensions your have mentioned are not in ratio.
.grid-item--width146x100 {
  width: 125px;
  height: 100px;
  float: right
}
.grid-item--width146x300 {
  width: 125px;
  height: 300px;
  float: right
}
.grid-item--width200x100 {
  width: 200px;
  height: 100px
}
.grid-item--width200x200 {
  width: 200px;
  height: 200px
}
.grid-item--width300 {
  width: 300px;
  height: 200px
}
.grid-item--width500x200 {
  width: 500px;
  height: 200px
}
.grid-item--width500x400 {
  width: 500px;
  height: 400px
}

So correct them and keep them in ratio, for eg.
.grid-item-1 {
      width: 150px;
      height: 200px
    }

.grid-item-2 {
      width: 300px;
      height: 400px
    }

.grid-item-3 {
      width: 75px;
      height: 100px
    }

Thanks


text:
Q: Trying to print ascii representation in C So I am trying to dynamically generate a box, based on some ascii characters I have defined in a box_ascii.h. I am just tying to test my logic and when I get into my for loops I get an error:
$ make create_dynamic_box
cc     create_dynamic_box.c   -o create_dynamic_box
create_dynamic_box.c:26:30: error: expected expression
                printf("%c", BOX_TOP_LEFT_CORNER);
                             ^
./box_ascii.h:6:41: note: expanded from macro 'BOX_TOP_LEFT_CORNER'
#define BOX_TOP_LEFT_CORNER             = "\214" // ╓

My google research on the error usually mean I need something like int b = a, which basically tells me that something doesn't have a type or has the wrong type(?)
Any ways the code is:
box_ascii.h
#ifndef __box_ascii_h__
#define __box_ascii_h__

// Might not be exact Ascii Characters but they come from:
// http://www.asciitable.com/
#define BOX_TOP_LEFT_CORNER             = "\214" // ╓
#define BOX_TOP_RIGHT_CORNER            = "\187" // ╖
#define BOX_BOTTOM_LEFT_CORNER          = "\200" // ╚
#define BOX_BOTTOM_RIGHT_CORNER         = "\188" // ╛
#define BOX_SIDE                        = "\186" // ║
#define BOX_TOP_BOTTOM                  = "\205" // ═

#endif

create_dynamic_box.c
#include <stdio.h>
#include <stdlib.h>
#include "box_ascii.h"

void print_border(int width, int height);

int main(int argc, char *argv[]) {
    if(argc < 3) {
        printf("Mustenter width and height.");
        return -1;
    }

    print_border(atoi(argv[1]), atoi(argv[2]));

    return 0;
}

void print_border(int width, int height) {
    int row = 0;
    int col = 0;

    for (row = 0; row < width; row ++) {
        for (col = 0; col < height; col++) {
            if (row == 0 && col == 0) {
                printf("%c", BOX_TOP_LEFT_CORNER); // error thrown here.
            }
        }
    }
}

Whats going on? is it because I am using %c ??

A: The error messages come about because macros do text substitution - they are not named values.
So
#define BOX_TOP_LEFT_CORNER             = "\214"
printf("%c", BOX_TOP_LEFT_CORNER);

will be seen by the compiler as
printf("%c", = "\214");

That has two problems.  Firstly, the = is misplaced.   Second, %c causes printf() to expect a single character, whereas "\214" is an array of two characters ('\214' and '\0').
So, the = sign needs to be removed from the macro.
If you want to use the %c format, change the macro definition to use single quote characters (')
#define BOX_TOP_LEFT_CORNER           '\214'

If you want the macros to be multi-character strings, then use the %s format.
Either way, don't supply a string where a single character is expected, or vice versa.
Also:  The characters like \214 are extended ASCII (which is not well defined) not ASCII.

A: Your BOX_* macros define strings, not characters.  They should be:
#define BOX_TOP_LEFT_CORNER '\214' //

and so forth for the rest of the macros.
In C, `\xyz' defines a character whose octal code is xyz.
Reference here.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Is there an alternative to requiring common node modules besides globals? Getting tired of typing
const async = require('async');
const _ = require('lodash');

at the head of almost every JS file.
One could use globals, good for ease of use, bad for unit tests.
Is there an alternative that I'm missing? If I can do a require('common') to load the utilities I want and use them in the current file, that would be best.

A: Well then do that - create a common.js file and put all the stuff in there, then simply require whatever you need in a single statement using the destructuring assignment.
Example
common.js
module.exports = {
    fs: require('fs'),
    http: require('http')
    //... what else you want
};

main.js
const { fs, http } = require('./common.js');

Note
This was just an example to show you how to archive your desired behaviour. But I would not recommend you to use this as it obscures what you're actually loading and bring a unnecessary dependency just to save some statements.

A: Wow, there's this amazing thing called keyboard snippets which completely saves one from typing those redundant characters over and over, without the need for compromising the integrity of the code.
VSCode
  "debug require": {
    "prefix": "rede",
    "body": [
      "const debug = require('debug')('$1');$0"
    ]
  },
  "lodash require": {
    "prefix": "relo",
    "body": [
      "const _ = require('lodash');$0"
    ]
  },
  "async require": {
    "prefix": "reas",
    "body": [
      "const async = require('async');$0"
    ]
  },


text:
Q: setInterval não repete Estou tentando resolver o seguinte problema:
Na minha página, o setInterval não repete, tentei de várias formas, até simplificar no modo abaixo para ver se funcionaria, mas mesmo assim ele não repete, está trabalhando como um setTimeout.
function teste(){
    $("#teste").append("a");
 }
 var x = setInterval(teste(),1000);

A: O problema é que você está passando o resultado da função teste para o setInterval.
setInterval(teste(), 1000);
// 'teste' é executado, e, como ele não retorna nada, essa linha é equivalente a:
setInterval(undefined, 1000);

Enfim, para arrumar, passe a referência para a função teste para o setInterval. Código arrumado:
function teste(){
    $("#teste").append("a");
}
var x = setInterval(teste, 1000); // <-- sem parênteses

JSFiddle


text:
Q: Why flexible array member must be at end of struct but struct with flexible array not? Some struct with flexible array:
struct SomeArray { unsigned length; int array[]; };

This code gcc (ver. 4.9.2) compiling with no errors:
struct s1{ unsigned length; SomeArray some_array; const char * string; } ss1;

How this work?

A: From the standard:

As a special case, the last element of a structure with more than one named member may have an incomplete array type; this is called a flexible array member. In most situations, the flexible array member is ignored. In particular, the size of the structure is as if the flexible array member were omitted except that it may have more trailing padding than the omission would imply.

This seems to be one of the situations where the flexible array member is ignored. So the size of ss1.some_array doesn't include space for ss1.some_array.array.


text:
Q: Share button disabled in Google Plus while sharing photos I want to share many photos from an album. So, first I selected all and then, press the share button at top (as showed here https://support.google.com/plus/answer/1407859?hl=en), add a comment, the email of the receiver, but the share button is gray, it seems disabled. What can I do?
This is how it appears.

A: It seems working now. What I did was, added a name for the Album as shown below, and hit cancel. The next time I pressed the share button at the top it displays the window but now with the share button in green.
Thanks anyway.

A: I encountered the same issue as well and tried putting the album name but still didn't seem to enable the Share button.
The Share button actually is not dependent on the album title, as what you suggested. The only mandatory field here is the To field, in order to share your photos properly to others.
So what I found out was that it had something to do with my slow Internet connection. After I reset my connection and refreshed my browser, it all seemed to work just fine automatically. Perhaps some things must be fully loaded first before the Share button can be enabled.


text:
Q: Sylius layout override I am not able to override sylius default layout. I add file layout.html.twig to /app/Resources/Frontend/ and nothing happen. Can you someone help me please?

A: Try /app/Resources/SyliusWebBundle/views/Frontend/


text:
Q: Menubar item doesn't close on another item click My issue is simple : When on a menubar with some items, when i open a menu i am not able to open another menu with one click. I have to first click to close the previous menu, then click to open the second menu. I have this issue with angular material menu component.
I have this issue for a while now and i have been reading lots and lots of stuff about this. Basically material shitty UX design consider the submenu opened as a pop-up, and gives it the focus.
I recently found this post here (look for the answer of FernandoJ) provided with this stackblitz here. This is EXACLTY what i want. But it's too good to be true i guess because when i import it as is in my project it doesn't work : The menu isn't opening in the first place. It may be because of this line in the app.module of the stackblitz :
bootstrap: [MenuOverviewExample],

And i dosen't use bootstrap. So i turn to you my fellow stackoverflowers, work your magic like you do so well all the times because it's starting to drive me crazy. please
If you have any question i'm happy to answer you, and also thank you very much !


text:
Q: Python: for loop not looping over all the files I am trying to loop over some compressed files (extension '.gz') and I am running into a problem.
I want to perform a specific action when the FIRST file ending in 'aa' is encountered - it can be a random one, it doesn't necessarily have to be the first one on the list.
Only then, Python has to search if there are OTHER "aa" files in the folder, if so the 2nd rule has to be applied. (There may be from 1 to many "aa" files).
Finally, the 3rd rule has to be applied to all other files not ending with "aa".
However, when I run the code below, not all the files get processed.
What am I doing wrong?
Thanks!
inputPath = "write your path"
fileExt = r".gz"
    flag = False

    for item in os.listdir(inputPath): # loop through items in dir
        if item.endswith(fileExt): # check for ".gz" extension
            full_path = os.path.join(inputPath, item) # get full path of files

            if item.endswith('aa' + fileExt) and flag == False:
                df = pd.read_csv(full_path, compression='gzip', header=0, sep='|', encoding="ISO-8859-1") #from gzip to pandas df
    #           do something
                flag = True
                print('1 rule:', "The item processed is ", item)

            elif item.endswith('aa' + fileExt) and flag == True:
                df = pd.read_csv(full_path, compression='gzip', header=0, sep='|', encoding="ISO-8859-1") #from gzip to pandas df
    #           do something else
                print('2 rule:', "The item processed is ", item)

            elif not (item.endswith('aa' + fileExt)) and flag == True:
                df = pd.read_csv(full_path, compression='gzip', header=0, sep='|', encoding="ISO-8859-1") #from gzip to pandas df
    #           do something else
                print('3 rule:', "The item processed is ", item)

I believe this is due to the fact that Python iterates over the list of files sorted in alphabetical order, then it the other files are ignored. How can I fix this issue?
LIST OF FILES:

File_202112311aa.gz
File_20211231ab.gz
File_20211231.gz
File_20211231aa.gz

OUTPUT
1 rule The item processed is  File_202112311aa.gz
3 rule The item processed is  File_20211231ab.gz
2 rule The item processed is  File_20211231aa.gz

A: Largely untested, but something along the following lines should work.
This code first processes a file ending in 'aa.gz' (note: not all files ending in 'aa.gz' are processed first, as this is not stated in the question), then processes the remaining files. There is no particular ordering for the remaining files: this will depend on how Python has been built on the system, and what the (file)system does by default, and is simply not guaranteed.
# Obtain an unordered list of compressed files
filenames = glob.glob("*.gz")

# Now find a filename ending with 'aa.gz'
for i, filename in enumerate(filenames):
    if filename.endswith('aa.gz'):
        firstfile = filenames.pop(i)
        # We immediately break out of the loop,
        # so we're safe to have altered `filenames`
        break
else:
    # the sometimes useful and sometimes confusing else part
    # of a for-loop: what happens if `break` was not called:
    raise ValueError("no file ending in 'aa.gz' found!")

# Ignoring the `full_path` part
df = pd.read_csv(firstfile, compression='gzip', header=0, sep='|', encoding="ISO-8859-1")
# do something
print(f"1 rule: The file processed is {firstfile}")

# Process the remaining files
for filename in filenames:
    df = pd.read_csv(filename, compression='gzip', header=0, sep='|', encoding="ISO-8859-1")
    if filename.endswith('aa.gz'):
        # do something
        print(f"2 rule: The file processed is {filename}")
    else:
        # do something else
        print(f"3 rule: The file processed is {filename}")

A: Others here have provided much more optimised solutions for you, but this is to answer your original question of why not all files are being processed.
In your code, you've got three conditions to process a file:

*

*It is a *aa.gz file, and it's the first one found

*It is a *aa.gz file, and the second or more *aa.gz file that has been found.

*It is not a *aa.gz file, and the a previous *aa.gz file has been found.

So it will skip any non-*aa.gz files until it encounters the first one.


text:
Q: No such file or directory with grep command Following is the output of my Unix command
$ /data/nagios/libexec/check_http -I example.com  -C 30 -p443 --sni
OK - Certificate 'example.com' will expire on 05/10/2020 12:00.

But when I do a grep on the output inside a script,it shows "No such file or directory"
grep: OK - Certificate 'example.com' will expire on 05/10/2020 12:00.: No such file or directory

Below is the script
 #!/bin/bash
 output=`/data/nagios/libexec/check_http -I example.com  -C 30 -p443 --sni`
 grep 'OK' "$output"

Can anybody please guide how to resolve this. It works fine when I execute directly on commandline
  $ /data/nagios/libexec/check_http -I example.com  -C 30 -p443 --sni | grep OK
  OK - Certificate 'example.com' will expire on 05/10/2020 12:00.


text:
Q: Empty summary chart in Google App Engine (service is up and running) For some reason summary and traffic (not traffic VM) remain empty for running in Google App Engine (flex environment) service. Anybody have same issues?

A: Having this reported into google support a bug on their side was fixed. Chart works now.


text:
Q: Why is the python logging handler not used when added after a process is started? If I have interpreted the python3 documentation correctly, regardless of where I add the handler to the root logger, my log messages from within a Process should be sent to a file. However, this is not the case.
Here is a complete program which demonstrates the problem:
import logging
import logging.handlers

from multiprocessing import Process
from time import sleep

fileHandler = logging.FileHandler( 'mylog.log' )
fileHandler.setLevel( 5 )

logger = logging.getLogger( None )

def process_logger():

    print( "process waiting" )
    sleep( 5 )
    print( 'process start' )

    logger = logging.getLogger( None )

    for num in range( 1, 10 ):
        logger.critical( "critical: %d" % num )
        sleep(1)

#
# if this is where the handler is added, the critical messages
# will go to the file
#
logger.addHandler( fileHandler )

processLogger = Process( target=process_logger )
processLogger.start()

#
# if this is where the handler is added, the critical messages
# will not go to the file.
#
#logger.addHandler( fileHandler )

print( "started" )

I am using python 3.4.3 on OS X 10.10.4.
My guess as to why this does not work is that when I start the Process, it makes a copy of the current environment and if the handler has not been added by that time, the environment the Process is running in won't have it.
I have three questions:

*

*Why do my messages not always end up in the file regardless of where I call logger.addHandler?

*Should my messages always end up in the file?

*If they should not, what is the best solution to the general problem of needed to manipulate handlers after a Process has been started?

A: The behaviour you see is due to how processes work on POSIX. Multiprocessing on POSIX generally uses the fork system call, which happens when you create a another process via the Process(...) call. At this point, the created process is a copy of the original process. When you add the handler before the Process(...) call, the copy also has the handler already added, so process_logger (which is called in the copy) will behave as expected. When you add the handler after the Process(...) call, the handler has not been added in the copy, so process_logger (which is called in the copy) will not behave as expected.
To avoid this sort of problem, ensure that logging is configured as desired in each process (normally, this means doing the logging configuration in code which is called (directly or indirectly) from the target=XXX callable which is passed to Process. In your case, that's process_logger.
Update: See this post for more information on using logging with multiprocessing.


text:
Q: Orders Sold per Day over Last 30 days I need help. I want to fix this code. I have tried for hours. I want to get the "orders Sold per Day - Default date range: Last 30 days".
This is what the order collection looks like
{
    status: 'BEING_PREPARED',
    option: 'DELIVERY',
    driver: null,
    staffComment: '',
    driverComment: null,
    paymentMethod: null,
    etd: null,
    ptd: null,
    deliveryFees: 0,
    discount: 0,
    voucherId: null,
    orderItems: [[Object], [Object], [Object]],
    subtotal: 24.849999999999998,
    branch: ObjectId("5c98a67a2061ed07b45100e1"),
    datetime: ISODate("2019-04-06T17:11:43.171Z"),
    number: 1347,
}

This is what I have done so far.
router.route('/api/ordes')
        .get(function(req, res) {

            var result = connection.db.collection("orders").aggregate([{
                    $match: {
                        "datetime": {
                            $lte: (new Date((new Date()).getTime() - (30 * 24 * 60 * 60 * 1000)))
                        }
                    }
                },
                {
                    "$group": {
                            _id: {
                           "year":  { "$year": "$datetime" },
                           "month": { "$month": "$datetime" },
                           "day":   { "$dayOfMonth": "$datetime" }
                        },
                        totalValue: { $sum: "$subtotal" }
                    }
                }
            ]);
            result.toArray(function(err, doc) {
                console.log(doc);
                res.status(200).json(doc);

            });
        });

This is the results I got
[
    {
        "_id": {"year": 2019, "month": 7, "day": 2}, "totalValue": 3875.92
    },
    {
        "_id": {"year": 2019, "month": 6, "day": 30}, "totalValue": 9594.92
    },
    {

        "_id": {"year": 2019, "month": 6, "day": 29}, "totalValue": 8820.369999999999
    },
    {
        "_id": {"year": 2019, "month": 6, "day": 28}, "totalValue": 8881.76
    },
    {
        "_id": {"year": 2019, "month": 6, "day": 27}, "totalValue": 4286.66
    },
    {
        "_id": {"year": 2019, "month": 6, "day": 26}, "totalValue": 4716.66
    },
    {
        "_id": {"year": 2019, "month": 6, "day": 25}, "totalValue": 3093.82
    },
    {
        "_id": {"year": 2019, "month": 6, "day": 23}, "totalValue": 9905.26
    },
    {
        "_id": {"year": 2019, "month": 6, "day": 22}, "totalValue": 10492.32
    },
    {
        "_id": {"year": 2019, "month": 6, "day": 21}, "totalValue": 9261.52
    },
    {
        "_id": {"year": 2019, "month": 6, "day": 20}, "totalValue": 3794.98
    },
    {
        "_id": {"year": 2019, "month": 6, "day": 19}, "totalValue": 4191.64
    },
    {
        "_id": {"year": 2019, "month": 6, "day": 17}, "totalValue": 3749.33
    },
    {
        "_id": {"year": 2019, "month": 6, "day": 4}, "totalValue": 1915.72
    },
    {
        "_id": {"year": 2019, "month": 6, "day": 2}, "totalValue": 5884.91
    },
    {
        "_id": {"year": 2019, "month": 5, "day": 29}, "totalValue": 2784.5
    },
    {
        "_id": {"year": 2019, "month": 5, "day": 28}, "totalValue": 1986.87
    },
    {
        "_id": {"year": 2019, "month": 5, "day": 26}, "totalValue": 7209.74
    },
    {
        "_id": {"year": 2019, "month": 5, "day": 24}, "totalValue": 5398.99
    },
    {
        "_id": {"year": 2019, "month": 7, "day": 4}, "totalValue": 4256.6
    },
    {
        "_id": {"year": 2019, "month": 5, "day": 23}, "totalValue": 2365.48
    },
    {
        "_id": {"year": 2019, "month": 5, "day": 22}, "totalValue": 2452.8199999999997
    }
]

A: Keep the original structure and use the $$ROOT variable to keep the orders data:
connection.db.collection("orders").aggregate([
    {
        $match: {
            "datetime": {
                $lte: (new Date((new Date()).getTime() - (30 * 24 * 60 * 60 * 1000)))
            }
        }
    },
    {
        "$group": {
            _id: {
                "year": {"$year": "$datetime"},
                "month": {"$month": "$datetime"},
                "day": {"$dayOfMonth": "$datetime"}
            },
            totalValue: {$sum: "$subtotal"},
            orders: {$push: "$$ROOT"}
        }
    }
]);

EDIT:
You can use the blow aggregation to get the desired result, due to the fact that we can't know the last date in the database then we have to first group all the collection.
I personally recommend you do not do this like this but split it into 2 steps, first query to find the max date. then you can use
{
        $match: {
            "datetime": {
                $lte: (new Date((maxDateFromCollection.getTime() - (30 * 24 * 60 * 60 * 1000)))
            }
        }
    }

To match and it will be a-lot more efficient when the scale gets larger.
connection.db.collection("orders").aggregate([
    {
        "$group": {
            _id: {
                "year": {"$year": "$datetime"},
                "month": {"$month": "$datetime"},
                "day": {"$dayOfMonth": "$datetime"}
            },
            totalValue: {$sum: "$subtotal"},
        }
    },
    {
        $sort: {
            "_id.year": -1,
            "_id.month": -1,
            "_id.day": -1,
        }
    },
    {
        $limit: 30
    },
    // next steps are only necessary if days could be missing and we have less than 30 results.
    {
        $group: {
            _id: null,
            orders: {$push: "$$ROOT"},
            maxDate: {$first: "$_id"}
        }
    },
    {
        $unwind: "$orders"
    },
    {
        $match: {
            $or: [
                {
                    $and: [ // same month if its months with 30 or less days. or day greater than 1.
                        {
                            $or: [
                                {
                                    "orders._id.day": {$gt: 1},
                                },
                                {
                                    "orders._id.month": {$in: [2, 4, 6, 8, 10, 12]}
                                }
                            ]
                        },
                        {
                            $expr: {
                                $eq: ["$orders._id.year", "$maxDate.year"]
                            }
                        },
                        {
                            $expr: {
                                $eq: ["$orders._id.month", "$maxDate.month"]
                            }

                        }
                    ]
                },
                {
                    $and: [ // if day is 1 than no 31
                        {
                            $expr: {
                                $eq: [
                                    "$orders._id.year", "$maxDate.year"]
                            }
                        },
                        {
                            $expr: {
                                $eq: [
                                    "$orders._id.month", "$maxDate.month"]
                            }
                        },
                        {
                            "orders._id.day": {$ne: 31}
                        }
                    ]
                },
                {   // days from previous month
                    $and: [
                        {
                            "maxDate.month": {$in: [5, 7, 10, 12]}
                        },
                        {
                            $expr: {
                                $eq: [
                                    "$orders._id.year", "$maxDate.year"]
                            }
                        },
                        {
                            $expr: {
                                $eq: [
                                    "$orders._id.month", {$subtract: ["$maxDate.month", 1]}
                                ]
                            }
                        },
                        {
                            $expr: {
                                $gt: [
                                    "$orders._id.day", "$maxDate.day"
                                ]
                            }
                        }
                    ]
                },
                {   // days from previous month
                    $and: [
                        {
                            "maxDate.month": {$in: [2, 4, 6, 8, 9, 11]}
                        },
                        {
                            $expr: {
                                $eq: [
                                    "$orders._id.year", "$maxDate.year"
                                ]
                            }
                        },
                        {
                            $expr: {
                                $eq: [
                                    "$orders._id.month", {$subtract: ["$maxDate.month", 1]}
                                ]
                            }
                        },
                        {
                            $expr: {
                                $gt: [
                                    "$orders._id.day", {$add: ["$maxDate.day", 1]}
                                ]
                            }
                        }
                    ]
                },
                {   // days from previous month
                    $and: [
                        {
                            "maxDate.month": 3
                        },
                        {
                            $expr: {
                                $eq: [
                                    "$orders._id.year", "$maxDate.year"
                                ]
                            }
                        },
                        {
                            $expr: {
                                $eq: [
                                    "$orders._id.month", {$subtract: ["$maxDate.month", 1]}
                                ]
                            }
                        },
                        {
                            $expr: {
                                $gt: [
                                    "$orders._id.day", {$subtract: ["$maxDate.day", 2]}
                                ]
                            }
                        }
                    ]
                },
                {   // days from previous month
                    $and: [
                        {
                            "maxDate.month": 1
                        },
                        {
                            "orders._id.month": 12
                        },
                        {
                            $expr: {
                                $eq: [
                                    "$orders._id.year", {$subtract: ["$maxDate.year", 1]}
                                ]
                            }
                        },
                        {
                            $expr: {
                                $gt: [
                                    "$orders._id.day", {$add: ["$maxDate.day", 1]}
                                ]
                            }
                        }
                    ]
                },
            ]
        }
    },
    {
        $replaceRoot: {
            newRoot: "$orders"

        }
    }
])


text:
Q: The Ocelot won't tame In the Windows 10 PC Version I'm having the same trouble with the Ocelot. It was walking towards me and I right clicked it lots of times with the raw fish in hand, but it still only goes into breeding mode and it won't tame them at all.

A: In the 1.14 "Village and Pillage" update (releasing early 2019), Ocelot behaviour has changed. Ocelots can no longer be tamed, but the same process of feeding them raw fish will instead lead them to "trust" the player. This simply means that once an Ocelot trusts you, it will no longer run from you.

In previous versions of Minecraft, Ocelots are tricky to tame, as they have a specific "begging" mode that they enter, in which they will creep towards the player. Only when they are in this mode, they can be tamed.

*

*The ocelot must be in "begging for food" mode, characterized by it looking at the player and slowly walking near to the player.

*

*Entering "begging" mode requires that the player is within 10 blocks (Euclidean distance).

*If the player is within 6 blocks, the ocelot will exit "begging" mode if the player turns too quickly or moves more than a tiny distance.

If you "scare" an ocelot out of the "begging" mode, it will enter breeding mode again, which will cause the Ocelot to show hearts when fed fish.

If the player fails to tame an ocelot, it will still show smoke particles. They will still go into breeding mode, and if there are two such ocelots in the area they will spawn a baby.

Additionally, the only fish that can be fed to an Ocelot is Raw Fish (default) and Raw Salmon. Tropical fish and Pufferfish cannot be fed to Ocelots.
Source.

A: ok so I did a little testing of the update for pandas and the new cats and you officially can't tame ocelots anymore.

A: If you have the latest update, ocelot cannot be tamed. You can find and tame a Stray Cat in any village, but ocelot can no longer be turned into cats. They will trust you and allow you to get close to them, but will not actually be tamed.
This is due to requests for the ability to spawn a specific breed of cat, instead of spawning hundreds of ocelots and taming them, just to get a specific breed. Mojang has decided to make the ocelot a completely separate animal from the cat.


text:
Q: How do I get asterick in double quotes ("*") to store as a String when passed as an argument, instead of classpath and directory? When I pass in: "*" 3 5
I expect "*" to be stored in argv[0], 3 in argv[1], and 5 in argv[2]
But instead, it will store
.classpath, .project, .settings, bin, src, 3, 5
making argv.length == 7 instead of 3.
I know the problem is occurring at argument input. I can solve this by having the user format the argument input but that will not suffice as the format for the input is an asterisk in double quotes. I am able to pass in an asterisk in single quotes, but the problem is when it is passed in with double quotes (using Eclipse >> run configurations >> arguments >> "*" 3 3) "*" will pass in a directory instead of the string asterisk in double quotes.
How do I get asterisk in double quotes to be read in as a string? I know it can be done, I'm just trying to figure out why it is being read in as a directory. Following any other example, double quotes should resolve the problem but not so in this case.
/**
 * Drives the program.
 * @param argv arguments from command line
 */
public static void main(final String[] argv) {
    final TableType type;
    final int       start;
    final int       stop;
    for(int i=0; i<argv.length; i++){
        System.out.println(argv[i]);
    }

    if (argv.length != 3) {
        usage();
    }
    System.out.println(argv[0]);
    type  = getType(argv[0]);
    start = getNumber(argv[1]);
    stop  = getNumber(argv[2]);

    displayTable(type, start, stop);
}

/**
 * Returns the TableType represented by the specified String.
 * @param str the table type
 * @return TableType
 */
public static TableType getType(final String str) {
    final TableType type;
    if (str.equals("+")) {
        type = TableType.ADD;
    } else if (str.equals("\"*\"")) {
        type = TableType.MULT;
    } else {
        usage();
        type = null;
    }
    return (type);
}


text:
Q: Active Record query "where" with multiple options I have this query that I want to reduce down if possible:
@orders_in_progress = user.orders.where("state = ? OR state = ? OR state = ?, "Waiting for Payment Authorization", "Paid", "Shipped")

What I'm looking for is something like:
@orders_in_progress = user.orders.where("state = ?", "Waiting for Payment Authorization" || "Paid" || "Shipped)

Also, I'm a little confused on the terminology here - is this "an ActiveRecord query with multiple conditions for an element"?

A: You could do something like this:
@orders_in_progress = user.orders.where(state: ["Waiting for Payment Authorization", "Paid", "Shipped"])

It will generate "in" query but it will work the same way that your original one does.
Also you may want to consider changing states to something simpler ('pending', 'paid', 'shipped' come to mind) and use translations to generate human friendly version.


text:
Q: Looking for short story about town heating up and 3 kids I thought it was a Ray Bradbury, but I can't seem to find it.
There's something going on where the world (or that town) is getting hotter and hotter, and there's three kids who have bikes. I think they go into this tunnel or something? And it gets hotter and hotter. I don't really remember, but I was hoping it might strike a chord in someone's memory.
I know it was a short story that was included in a collection of other short horror-ish sci-fi and fantasy stories. I think it had a red binding? I'm not 100% sure. This was something I read back in 8th grade a thousand years ago, so it might be a slightly hopeless endeavor. Somewhere back in 2003? I think.

A: The story sounds vaguely like Dan Simmons' Summer of Night - though I haven't read the story in years.

An old school has been taken over by an evil entity and this entity creates a tunnel between the school and the bedroom of the main character and his younger brother.  The younger brother is sucked into the tunnel and the other kids have to go rescue him.
It is summer.
The weather is getting hotter and hotter.
The kids do get around on bikes.
However, it is a novel, not a short story.
Goodluck  :-)


text:
Q: Terraform Script creating resources successfully but ending with error I am trying to create the azure container registry using the terraform script . It is creating the resource successfully , but ending with error. Below is my script:-
resource "azurerm_container_registry" "acr" {
name                     = var.container_registry_name
resource_group_name      = data.azurerm_resource_group.rg1.name
location                 = var.deploy_location
sku                      = var.basic_conf["sku_type"]
admin_enabled            = var.basic_conf["admin_enabled"]
provider = azurerm.DeploySub1
}

and error we got is this :-
The Terraform Plan has noted changes to be made. (exit code 2)
As this is the Deploy Stage, we will now exit with error.
##[error]Bash exited with code '1'.
Finishing: Terraform Confirm Plan Deployed


text:
Q: How to get a lengthy string environment variable in full? The command gci env:ApiSecret | ConvertTo-Json works to return a long string, the API secret for Twitter, which is truncated without the pipe to JSON.
However, the JSON is rather spammy.
Is there a "goldilocks" way to get the lengthy string value without the extraneous details?
(Unfortunately, gci env: truncates the key)

A: Get-ChildItem is for retrieving all or a subset of items from a container.  Note that it outputs an object with Name and Value properties (substituting Path as another lengthy environment variable value)...
PS> gci env:Path

Name                           Value
----                           -----
Path                           C:\Windows\system32;C:\Windows;C:\Windows\System32\Wbem;C:\Windows\System32\WindowsPowerShell\v1.0\;C:\WINDO...

Get-Item yields the same result...
PS> gi env:Path

Name                           Value
----                           -----
Path                           C:\Windows\system32;C:\Windows;C:\Windows\System32\Wbem;C:\Windows\System32\WindowsPowerShell\v1.0\;C:\WINDO...

Either way, the object retrieved is a DictionaryEntry...
PS> gi env:Path | Get-Member

   TypeName: System.Collections.DictionaryEntry

Name          MemberType    Definition
----          ----------    ----------
Name          AliasProperty Name = Key
Equals        Method        bool Equals(System.Object obj)
GetHashCode   Method        int GetHashCode()
GetType       Method        type GetType()
ToString      Method        string ToString()
PSDrive       NoteProperty  PSDriveInfo PSDrive=Env
PSIsContainer NoteProperty  bool PSIsContainer=False
PSPath        NoteProperty  string PSPath=Microsoft.PowerShell.Core\Environment::path
PSProvider    NoteProperty  ProviderInfo PSProvider=Microsoft.PowerShell.Core\Environment
Key           Property      System.Object Key {get;set;}
Value         Property      System.Object Value {get;set;}

...and when you pipe that to ConvertTo-Json it will include all kinds of undesirable properties from that class.
In short, don't use ConvertTo-Json for this.  Since you know the exact item you want, just retrieve it directly using variable syntax...
PS> $env:Path
C:\Windows\system32;C:\Windows;C:\Windows\System32\Wbem;C:\Windows\System32\WindowsPowerShell\v1.0\;...

Equivalent code using the .NET API would be...
PS> [Environment]::GetEnvironmentVariable('Path')
C:\Windows\system32;C:\Windows;C:\Windows\System32\Wbem;C:\Windows\System32\WindowsPowerShell\v1.0\;...

If you really wanted to use a Get-*Item cmdlet you'd just need to specify that it's the Value property you want using property syntax...
PS> (gi env:Path).Value
C:\Windows\system32;C:\Windows;C:\Windows\System32\Wbem;C:\Windows\System32\WindowsPowerShell\v1.0\;...

...or Select-Object...
PS> gi env:Path | Select-Object -ExpandProperty 'Value'
C:\Windows\system32;C:\Windows;C:\Windows\System32\Wbem;C:\Windows\System32\WindowsPowerShell\v1.0\;...

All of the above commands will output only a [String] containing the entirety of that environment variable value.  I inserted trailing ellipses since showing my entire Path value is not useful here; in practice, those commands will output the entire environment variable with no truncation.

A: The simplest way to inspect the value of environment variables in full is to use  the $env:<varName> (namespace variable notation) syntax, which in your case means: $env:ApiSecret (if the variable name contains special characters, enclose everything after the $ in {...}; e.g., ${env:ApiSecret(1)})
That way, environment-variable values (which are invariably strings) that are longer than your terminal's (console's) width simply continue on subsequent lines.
To demonstrate:
# Simulate a long value (200 chars.)
$env:ApiSecret = 'x' * 199 + '!'

# Output the long value
$env:ApiSecret

With an 80-char. wide terminal, you'd see output as follows:
xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx!

If you do want to use Get-Item (or Get-ChildItem, which acts the same in this case), you have two options:
# Format-List shows each property on its own line,
# with values wrapping across multiple lines
Get-Item env:ApiSecret | Format-List

# Format-Table -Wrap causes values to wrap as well.
Get-Item env:ApiSecret | Format-Table -Wrap

A: Your statement does not strip anything away. However, for console display purpose, it truncate the output that you view in the console.
If you assign the result to a variable or pipe to a file, nothing will be truncated.
Therefore, my assumption on your question is that you want to view the result in the console without the console truncating your stuff there.
For that, you could write the results to the host yourself.
Here's a simple example that do just that.
$envvars = gci env:
$Max = ($envvars.name| Measure-Object -Property length -Maximum).Maximum + 3
$envvars | % {Write-Host $_.name.padright($Max,' ')  -ForegroundColor Cyan -NoNewline;Write-Host $_.value}

Result — As you can see, the path  variable value is no longer truncated.


text:
Q: Best big set data structure in Java I need to find gaps in a big Integer Set populated with a read loop through files and I want to know if exists something already done for this purpose to avoid a simple Set object with heap overflow risk.
To better explain my question I have to tell you how my ticketing java software works.
Every ticket has a global progressive number stored in a daily log file with other informations. I have to write a check procedure to verify if there are number gaps inside daily log files.
The first idea was to create a read loop with all log files, read each line, get the ticket number and store it in a Integer TreeSet Object and then find gaps in this Set.
The problem is that ticket number can be very high and could saturate the memory heap space and I want a good solution also if I have to switch to Long objects.
The Set solution waste a lot of memory because if I find that there are no gap in the first 100 number has no sense to store them in the Set.
How can I solve? Can I use some datastructure already done for this purpose?

A: I'm assuming that (A) the gaps you are looking for are the exception and not the rule and (B) the log files you are processing are mostly sorted by ticket number (though some out-of-sequence entries are OK).
If so, then I'd think about rolling your own data structure for this.  Here's a quick example of what I mean (with a lot left to the reader).
Basically what it does is implement Set but actually store it as a Map, with each entry representing a range of contiguous values in the set.
The add method is overridden to maintain the backing Map appropriately.  E.g., if you add 5 to the set and already have a range containing 4, then it just extends that range instead of adding a new entry.
Note that the reason for the "mostly sorted" assumption is that, for totally unsorted data, this approach will still use a lot of memory: the backing map will grow large (as unsorted entries get added all over the place) before growing smaller (as additional entries fill in the gaps, allowing contiguous entries to be combined).
Here's the code:
package com.matt.tester;

import java.util.Collection;
import java.util.Comparator;
import java.util.Iterator;
import java.util.Map;
import java.util.SortedSet;
import java.util.TreeMap;

public class SE {

    public class RangeSet<T extends Long> implements SortedSet<T> {

        private final TreeMap<T, T> backingMap = new TreeMap<T,T>();

        @Override
        public int size() {
            // TODO Auto-generated method stub
            return 0;
        }

        @Override
        public boolean isEmpty() {
            // TODO Auto-generated method stub
            return false;
        }

        @Override
        public boolean contains(Object o) {
            if ( ! ( o instanceof Number ) ) {
                throw new IllegalArgumentException();
            }
            T n = (T) o;
            // Find the greatest backingSet entry less than n
            Map.Entry<T,T> floorEntry = backingMap.floorEntry(n);
            if ( floorEntry == null ) {
                return false;
            }
            final Long endOfRange = floorEntry.getValue();
            if ( endOfRange >= n) {
                return true;
            }
            return false;
        }

        @Override
        public Iterator<T> iterator() {
            throw new IllegalAccessError("Method not implemented.  Left for the reader.  (You'd need a custom Iterator class, I think)");
        }

        @Override
        public Object[] toArray() {
            throw new IllegalAccessError("Method not implemented.  Left for the reader.");
        }

        @Override
        public <T> T[] toArray(T[] a) {
            throw new IllegalAccessError("Method not implemented.  Left for the reader.");
        }

        @Override
        public boolean add(T e) {
            if ( (Long) e < 1L ) {
                throw new IllegalArgumentException("This example only supports counting numbers, mainly because it simplifies printGaps() later on");
            }
            if ( this.contains(e) ) {
                // Do nothing.  Already in set.
            }
            final Long previousEntryKey;
            final T eMinusOne = (T) (Long) (e-1L);
            final T nextEntryKey = (T) (Long) (e+1L);
            if ( this.contains(eMinusOne ) ) {
                // Find the greatest backingSet entry less than e
                Map.Entry<T,T> floorEntry = backingMap.floorEntry(e);
                final T startOfPrecedingRange;
                startOfPrecedingRange = floorEntry.getKey();
                if ( this.contains(nextEntryKey) ) {
                    // This addition will join two previously separated ranges
                    T endOfRange = backingMap.get(nextEntryKey);
                    backingMap.remove(nextEntryKey);
                    // Extend the prior entry to include the whole range
                    backingMap.put(startOfPrecedingRange, endOfRange);
                    return true;
                } else {
                    // This addition will extend the range immediately preceding
                    backingMap.put(startOfPrecedingRange,  e);
                    return true;
                }
            } else if ( this.backingMap.containsKey(nextEntryKey) ) {
                // This addition will extend the range immediately following
                T endOfRange = backingMap.get(nextEntryKey);
                backingMap.remove(nextEntryKey);
                // Extend the prior entry to include the whole range
                backingMap.put(e, endOfRange);
                return true;
            } else {
                // This addition is a new range, it doesn't touch any others
                backingMap.put(e,e);
                return true;
            }
        }

        @Override
        public boolean remove(Object o) {
            throw new IllegalAccessError("Method not implemented.  Left for the reader.");
        }

        @Override
        public boolean containsAll(Collection<?> c) {
            throw new IllegalAccessError("Method not implemented.  Left for the reader.");
        }

        @Override
        public boolean addAll(Collection<? extends T> c) {
            throw new IllegalAccessError("Method not implemented.  Left for the reader.");
        }

        @Override
        public boolean retainAll(Collection<?> c) {
            throw new IllegalAccessError("Method not implemented.  Left for the reader.");
        }

        @Override
        public boolean removeAll(Collection<?> c) {
            throw new IllegalAccessError("Method not implemented.  Left for the reader.");
        }

        @Override
        public void clear() {
            this.backingMap.clear();
        }

        @Override
        public Comparator<? super T> comparator() {
            throw new IllegalAccessError("Method not implemented.  Left for the reader.");
        }

        @Override
        public SortedSet<T> subSet(T fromElement, T toElement) {
            throw new IllegalAccessError("Method not implemented.  Left for the reader.");
        }

        @Override
        public SortedSet<T> headSet(T toElement) {
            throw new IllegalAccessError("Method not implemented.  Left for the reader.");
        }

        @Override
        public SortedSet<T> tailSet(T fromElement) {
            throw new IllegalAccessError("Method not implemented.  Left for the reader.");
        }

        @Override
        public T first() {
            throw new IllegalAccessError("Method not implemented.  Left for the reader.");
        }

        @Override
        public T last() {
            throw new IllegalAccessError("Method not implemented.  Left for the reader.");
        }

        public void printGaps() {
            Long lastContiguousNumber = 0L;
            for ( Map.Entry<T, T> entry : backingMap.entrySet() ) {
                Long startOfNextRange = (Long) entry.getKey();
                Long endOfNextRange = (Long) entry.getValue();
                if ( startOfNextRange > lastContiguousNumber + 1 ) {
                    System.out.println( String.valueOf(lastContiguousNumber+1) + ".." + String.valueOf(startOfNextRange - 1) );
                }
                lastContiguousNumber = endOfNextRange;
            }
            System.out.println( String.valueOf(lastContiguousNumber+1) + "..infinity");
            System.out.println("Backing map size is " + this.backingMap.size());
            System.out.println(backingMap.toString());
        }

    }

    public static void main(String[] args) {

        SE se = new SE();

        RangeSet<Long> testRangeSet = se.new RangeSet<Long>();

        // Start by putting 1,000,000 entries into the map with a few, pre-determined, hardcoded gaps
        for ( long i = 1; i <= 1000000; i++ ) {
            // Our pre-defined gaps...
            if ( i == 58349 || ( i >= 87333 && i <= 87777 ) || i == 303998 ) {
                // Do not put these numbers in the set
            } else {
                testRangeSet.add(i);
            }
        }

        testRangeSet.printGaps();

    }
}

And the output is:
58349..58349
87333..87777
303998..303998
1000001..infinity
Backing map size is 4
{1=58348, 58350=87332, 87778=303997, 303999=1000000}

A: Well either you store everything in memory, and you risk overflowing the heap, or you don't store it in memory and you need to do a lot of computing.
I would suggest something in between - store the minimum needed information needed during processing. You could store the endpoints of the known non-gap sequence in a class with two Long fields. And all these sequence datatypes could be stored in a sorted list. When you find a new number, iterate through the list to see if it is adjacent to one of the endpoints. If so, change the endpoint to the new integer, and check if you can merge the adjacent sequence-objects (and hence remove one of the objects). If not, create a new sequence object in the properly sorted place.
This will end up being O(n) in memory usage and O(n) in cpu usage. But using any data structure which stores information about all numbers will simply be n in memory usage, and O(n*lookuptime) in cpu if lookuptime is not done in constant time.

A: I believe it's a perfect moment to get familiar with bloom-filter. It's a wonderful probabilistic data-structure which can be used for immediate proof that an element isn't in the set.
How does it work? The idea is pretty simple, the boost more complicated and the implementation can be found in Guava.
The idea
Initialize a filter which will be an array of bits of length which would allow you to store maximum value of used hash function. When adding element to the set, calculate it's hash. Determinate what bit's are 1s and assure, that all of them are switched to 1 in the filter (array). When you want to check if an element is in the set, simply calculate it's hash and then check if all bits that are 1s in the hash, are 1s in the filter. If any of those bits is a 0 in the filter, the element definitely isn't in the set. If all of them are set to 1, the element might be in the filter so you have to loop through all of the elements.
The Boost
Simple probabilistic model provides the answer on how big should the filter (and the range of hash function) be to provide optimal chance for false positive which is the situation, that all bits are 1s but the element isn't in the set.
Implementation
The Guava implementation provides the following constructor to the bloom-filter: create(Funnel funnel, int expectedInsertions, double falsePositiveProbability). You can configure the filter on your own depending on the expectedInsertions and falsePositiveProbability.
False positive
Some people are aware of bloom-filters because of false-positive possibility. Bloom filter can be used in a way that don't rely on mightBeInFilter flag. If it might be, you should loop through all the elements and check one by one if the element is in the set or not.
Possible usage
In your case, I'd create the filter for the set, then after all tickets are added simply loop through all the numbers (as you have to loop anyway) and check if they filter#mightBe int the set. If you set falsePositiveProbability to 3%, you'll achieve complexity around O(n^2-0.03m*n) where m stands for the number of gaps. Correct me if I'm wrong with the complexity estimation.

A: Read as many ticket numbers as you can fit into available memory.
Sort them, and write the sorted list to a temporary file. Depending on the expected number of gaps, it might save time and space to use a run-length–encoding scheme when writing the sorted numbers.
After all the ticket numbers have been sorted into temporary files, you can merge them into a single, sorted stream of ticket numbers, looking for gaps.
If this would result in too many temporary files to open at once for merging, groups of files can be merged into intermediate files, and so on, maintaining the total number below a workable limit. However, this extra copying can slow the process significantly.
The old tape-drive algorithms are still relevant.

A: Here is an idea: if you know in advance the range of your numbers, then
pre-calculate the sum of all the numbers that you expect to be there.
 2. Then keep reading your numbers and produce the sum of all read numbers as well as the number of your numbers.
 3. If the sum you come up with is the same as pre-calculated one, then there are no gaps.
 4. If the sum is different and the number of your numbers is short just by one of the expected number then pre-calculated sum - actual sum will give you your missing number.
 5. If the number of your numbers is short by more then one, then you will know how many numbers are missing and what their sum is.
The best part is that you will not need to store the collection of your numbers in memory.


text:
Q: Put many request parameters with GET request in REST API Is it a good practice to put many request parameters with GET request in REST API?
I have gone through couple of sites and tried to get the standard way of doing GET URI with parameters implementation.
Here's what i am trying to achieve : search for all users having provided all the search criteria.
Search criteria are like companyID, sections, offset, limit, orderby, filter.
As per basic standards GET request can not have request body or payload in it.
Will it be good way to make a GET request and put all parameters behind ? in the request URL, something like this :
GET http://localhost:8080/api/users?companyId=qwerty&sections=hr&offset=0&limit=20&oorderby=asc&filter=^[sSmM]
I was thinking to make a PUT or POST request and send all these data in payload, and implement the code to return the desired response, i.e list of users.
If i do this i am changing the default behavior of HTTP methods.
Can you please guide me a way to get out of the situation.
Thanks.

A: I think it does not matter how many parameters you put in a GET request. The purpose of a POST or PUT request is not to keep your URL clean, but to aline with a REST structure.
the raw definition of GET, POST and PUT are

*

*GET: get a resource from your server

*POST: create a resource on your server

*PUT: update a resource on your server

A: Actually you can pass a request body with a GET request. It's just not very common to do it. Jquery supports this on the browser side and REST APIs such as for example the elastic search API use this. They have a nice json based query dsl and you can actually use a GET request for these. Because some HTTP frameworks don't support passing a body with a GET, Elasticsearch offers a fallback with POST as well.
As for using lots of url parameters, there are two issues you should keep in mind:

*

*URLs don't have unlimited length. There are some differences between browsers for this but typically it is a few KB maximum. Particularly some older mobile browsers have limitations here. It's pretty easy to run into this limit if you put a lot of things in the request and basically this means urls get truncated.

*Long URIs look kind of ugly and you wouldn't necessarily want to show them in a web UI.

A: Rest is nothing but a technique/framework/procedure.
It is no way special from a simple servlet call. It always follows the standard convention of request
GET - Retrieve any data from the Server. You can have any number of parameters with a limit of 256 Characters. The parameters should just act as a filter for the incoming data and they are not suppose to alter the system.
https://www.google.co.in/search?q=google&ie=utf-8&oe=utf-8&aq=t&rls=org.mozilla:en-US:official&client=firefox-a
If you see the above URL, u can see many parameters. But they are just filters to the results. They does not alter the system.
POST - Send some data such that it alters the system, usually add/remove data.
PUT - This is something special, say an advancement of POST, to be used when you want to update the exisiting data


text:
Q: How to update XML nodes with new values? I have a xml inside my App_Data folder. I need to edit the values in nodes of that xml. What I had tried is-
        XmlDocument xDoc = new XmlDocument();
        xDoc.Load(Server.MapPath("~/App_Data/conf.xml.config"));

        XmlNodeList aNodes = xDoc.SelectNodes("/ConfigInf");
        foreach (XmlNode node in aNodes)
        {
            XmlNode child1 = node.SelectSingleNode("Node1");
            XmlNode child2 = node.SelectSingleNode("Node2");

            child1.InnerText = "Value1";
            child2.InnerText = "Value2";
        }

I need to re-write the xml with new values as when ever I try to access the same xml again, it should contain the new values. But when I access the xml, I still get the old(initial) values only when I call like this -Test.LoadConf(Server.MapPath("./App_Data/conf.xml.config"));. How to write to XML with new values or any alternative method like create a new xml with new values?(as I need to access this xml in a single page only)

A: call save after edit, you can give diferent name if you don't need to overwrite the original
e.g.  new file named as new.conf.xml.config
xDoc.Save(Server.MapPath("~/App_Data/new.conf.xml.config"));

next time you can load the original as usual
xDoc.Load(Server.MapPath("~/App_Data/conf.xml.config"));

A: You haven't saved the file after that
use xDoc.save(Server.MapPath("~/App_Data/conf.xml.config"));

A: The nodeValue property can be used to change the value of a text node.
The following code changes the text node value of the first element: Example:
xmlDoc=loadXMLDoc("books.xml");

x=xmlDoc.getElementsByTagName("title")[0].childNodes[0];
x.nodeValue="Easy Cooking";

source: http://www.w3schools.com/DOM/dom_nodes_set.asp

A: node["Node1"].InnerText = "Value1";
node["Node2"].InnerText = "Value2";


text:
Q: Finding Ellipse Axes Consider the following ellipse, generated by the bounding region of the following points
ps = {{-11, 5}, {-12, 4}, {-10, 4}, {-9, 5}, {-10, 6}};
rec = N@BoundingRegion[ps, "FastEllipse"];
Graphics[{rec, Red, Point@ps}]

We have that the ellipse 'rec' is given in the form
Ellipsoid[{-10.4, 4.8}, {{2.77333, 0.853333}, {0.853333, 1.49333}}]

How can I retrieve the lengths of the two main axes of such ellipsoid? Following this representation and Mathematica's general definition of Ellipsoid

I tried the following, using the eigenvalues of rec[[2]]
eigs = Eigenvectors[Inverse[rec[[2]]]]
eigv = Eigenvalues[Inverse[rec[[2]]]];
lens = 2/Sqrt[eigv]

Out[]= {2.06559, 3.57771}

where the 2 factor comes from the fact what what I retrieve from the eigenvalues is actually half the length of the main axis. Indeed we get
Graphics[{rec, Red, Point@ps,
  Blue, Line[
   RegionCentroid@rec + # & /@ {-(lens[[1]] eigs[[1]])/
      2, (lens[[1]] eigs[[1]])/2}],
  Line[RegionCentroid@rec + # & /@ {-(lens[[2]] eigs[[2]])/
      2, (lens[[2]] eigs[[2]])/2}]}]

Is this correct? Is there a quicker way of doing this?

A: Here's the alternate way using SingularValueDecomposition:
pt = rec[[1]]; mat = rec[[2]];
{u, s, v} = SingularValueDecomposition[(mat + Transpose[mat])/2];
func = Composition[AffineTransform[{u, pt}], ScalingTransform[Sqrt[Diagonal[s]]]];

and the length:
EuclideanDistance @@@ {func@{{0, -1}, {0, 1}}, func@{{-1, 0}, {1, 0}}}

{2.06559, 3.57771}

Graphics[{rec, Blue, Line[func@{{-1, 0}, {1, 0}}],
  Line[ func@{{0, -1}, {0, 1}}]}]

A: Stolen from @J.M.'s answer, https://mathematica.stackexchange.com/a/239797/4999, with one correction (is that enough to make it not a duplicate?):
Nodes = ps;
ellipsoidBR = BoundingRegion[Nodes, "FastEllipse"]; (* not "FastEllipsoid" *)
center = ellipsoidBR[[1]];
{vals, vecs} = Eigensystem[ellipsoidBR[[2]]];
{a, b} = Sqrt[vals];
major = N@{center - a vecs[[1]], center + a vecs[[1]]}
minor = N@{center - b vecs[[2]], center + b vecs[[2]]}
Graphics[{ellipsoidBR, Red, Point@ps, Green, Point@center,
  Line@{major, minor}}, Frame -> True]

A: I think the help of Ellipsoid is incomplete because it does not explain the input: Ellipsoid[p,[CapitalSigma]], where the second argument is called the "weight matrix".
You will remember that an ellipse (for simplicity I am explaining the 2D case, nD is similar and assume the ellipse is centered at the origin) can be written by:
x^2/rx^2 + y^2/ry^2 == 1

We may write this as:
{x,y}.{{1/rx^2,0},{0,1/ry^2}}.{x,y} == r.mat.r == 1

Note that the inverse Sqrt of the eigenvalues of m0  are the half axes of the ellipse.
If we now rotate the coordinate system by a rotation matrix: rot (r'=rot.r where r' are the new coordinates) the ellipse will be rotated (in the inverse sense) in the new coordinates:
r'. Transpose[rot].mat. rot .r' == r' . mat' . r' == 1

Therefore a rotated ellipse may be represented by a an symmetric (positive definite) matrix: mat'. This is called "weigh matrix" in the help.
Note that the eigenvalues of the matrix are not changed by  a rotation. The eigenvectors point in the directions of the half axes.
Here is an example: Let
rx=2;
ry=1;
m0=DiagonalMatrix[{1/rx^1,1/ry^2}]
{x,y}.m0.{x,y}==1

This represents an axis aligned ellipse with half axes rx and ry:
Region[ImplicitRegion[{x, y} . m0 . {x, y} == 1, {x, y}],
 Axes -> True]

If we now rotate the matrix m0:
rot = RotationMatrix[-Pi/4];
m= Transpose[rot].m0.rot;

we get a rotated ellipse:
Region[ImplicitRegion[{x, y} . m . {x, y} == 1, {x, y}], Axes -> True]

Threrfore, the half axes are obtained by the inverse Sqrt of the eigenvalues of the weight matrix. And the directions of the axes are given by the eigenvectors.


text:
Q: Symfony2 - custom authentication provider with FOS User Bundle installed I need help with building custom authentication in Symfony2 project. I've read the symfony cookbook http://symfony.com/doc/2.3/cookbook/security/custom_authentication_provider.html and found many questions about the custom authentication but they didn't answer to my question in situation when I trying to do this with FOS User Bundle. I spent many ours of investigation of symfony authentication process but can't understand where am I wrong.
So what I have now:

*

*FOS User Bundle successfully installed and configured following by the official documentation.

*Sonata User Bundle installed.

*Custom authentication listener, token, provider, factory added and configured.
After that I normally log in but as I see my new authentication provider is not used and the user is logged in with FOS's "form_login".

Here is my code:
User entity class:
<?php
    namespace Acme\UserBundle\Entity;

    use Sonata\UserBundle\Entity\BaseUser as BaseUser;
    use Doctrine\ORM\Mapping as ORM;
    use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity;
    use \Acme\BoardBundle\Entity\Card;

    /**
     * @ORM\Entity
     * @ORM\HasLifecycleCallbacks
     * @ORM\Table(name="fos_user")
     */
    class User extends BaseUser
    {
        ...

        protected $card;

        /**
         * Set card
         *
         * @param \Acme\BoardBundle\Entity\Card $card
         * @return Card
         */
        public function setCard(\Acme\BoardBundle\Entity\Card $card)
        {
            $this->card = $card;

            return $this;
        }

        /**
         * Get card
         *
         * @return \Acme\BoardBundle\Entity\Card
         */
        public function getCard()
        {
            return $this->card;
        }
    }

User.orm.xml:
<?xml version="1.0" encoding="UTF-8"?>
<doctrine-mapping xmlns="http://doctrine-project.org/schemas/orm/doctrine-mapping"
                  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
                  xsi:schemaLocation="http://doctrine-project.org/schemas/orm/doctrine-mapping
                  http://doctrine-project.org/schemas/orm/doctrine-mapping.xsd">

    <entity name="Acme\UserBundle\Entity\User" table="fos_user">

        ...

        <many-to-one field="card" target-entity="Acme\BoardBundle\Entity\Card" inversed-by="users">
            <join-column name="card" referenced-column-name="id" />
        </many-to-one>
    </entity>
</doctrine-mapping>

The User entity has a relation with Card entity which has two properties: card number and PIN code. And the properties I actually need to check after login. My login form has not only username and password fields but also the card number and PIN fields.
security.yml (where I feel I have some errors in firewall configuration but I can't understand what's wrong):
providers:
    fos_userbundle:
        id: fos_user.user_manager
firewalls:
    dev:
        pattern:  ^/(_(profiler|wdt)|css|images|js)/
        security: false
    admin:
        pattern:            /admin(.*)
        context:            user
        form_login:
            provider:       fos_userbundle
            login_path:     /admin/login
            use_forward:    false
            check_path:     /admin/login_check
            failure_path:   null
        logout:
            path:           /admin/logout
        anonymous:          true
    main:
        pattern:             .*
        context:             user
        acme: true

        form_login:
            provider:       fos_userbundle
            login_path:     /user/login
            use_forward:    false
            check_path:     /user/login_check
            failure_path:   null
            always_use_default_target_path: true
            default_target_path:            ad_category
        logout:
            path:           /user/logout
        anonymous:          true

User Token:
<?php

namespace Acme\UserBundle\Security\Authentication\Token;

use Symfony\Component\Security\Core\Authentication\Token\AbstractToken;

class AcmeUserToken extends AbstractToken
{
    public $userFIO;
    public $cardNumber;
    public $cardPIN;

    public function __construct(array $roles = array())
    {
        parent::__construct($roles);

        // If the user has roles, consider it authenticated
        $this->setAuthenticated(count($roles) > 0);
    }

    public function getCredentials()
    {
        return '';
    }

    // поскольку токены проверяются при обработке каждом новом запросе клиента,
    // нам необходимо сохранять нужные нам данные. В связи с этим "обертываем"
    // унаследованные методы сериализации и десериализации.
    public function serialize() {
        $pser = parent::serialize();
        //return serialize(array($this->social, $this->hash, $this->add, $pser));
        return serialize(array($pser));
    }

    public function unserialize($serialized) {
        //list($this->social, $this->hash, $this->add, $pser) = unserialize($serialized);
        list($pser) = unserialize($serialized);
        parent::unserialize($pser);
    }
}

AcmeProvider.php (my custom authentication provider):
<?php

namespace Acme\UserBundle\Security\Authentication\Provider;

use Symfony\Component\Security\Core\Authentication\Provider\AuthenticationProviderInterface;
use Symfony\Component\Security\Core\User\UserProviderInterface;
use Symfony\Component\Security\Core\Exception\AuthenticationException;
use Symfony\Component\Security\Core\Exception\NonceExpiredException;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Acme\UserBundle\Security\Authentication\Token\AcmeUserToken;

class AcmeProvider implements AuthenticationProviderInterface
{
    private $userProvider;

    public function __construct(UserProviderInterface $userProvider)
    {
        $this->userProvider = $userProvider;
    }

    public function authenticate(TokenInterface $token)
    {
        $user = $this->userProvider->loadUserByUsername($token->getUsername());

        if ($user) {
            $authenticatedToken = new AcmeUserToken($user->getRoles());
            $authenticatedToken->setUser($user);

            return $authenticatedToken;
        }

        throw new AuthenticationException('The Acme authentication failed.');
    }

    public function supports(TokenInterface $token)
    {
        return $token instanceof AcmeUserToken;
    }
}

Factory class AcmeFactory.php:
<?php
namespace Acme\UserBundle\DependencyInjection\Security\Factory;

use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Reference;
use Symfony\Component\DependencyInjection\DefinitionDecorator;
use Symfony\Component\Config\Definition\Builder\NodeDefinition;
use Symfony\Bundle\SecurityBundle\DependencyInjection\Security\Factory\SecurityFactoryInterface;

class AcmeFactory implements SecurityFactoryInterface
{
    public function create(ContainerBuilder $container, $id, $config, $userProvider, $defaultEntryPoint)
    {
        $providerId = 'security.authentication.provider.acme.'.$id;
        $container
        ->setDefinition($providerId, new DefinitionDecorator('acme.security.authentication.provider'))
        ->replaceArgument(0, new Reference($userProvider))
        ;

        $listenerId = 'security.authentication.listener.acme.'.$id;
        $listener = $container->setDefinition($listenerId, new DefinitionDecorator('acme.security.authentication.listener'));

        return array($providerId, $listenerId, $defaultEntryPoint);
    }

    public function getPosition()
    {
        //return 'pre_auth';
        return 'form';
    }

    public function getKey()
    {
        return 'acme';
    }

    public function addConfiguration(NodeDefinition $node)
    {
    }
}

Configuration of the user provider and listner in config.yml:
services:
    acme.security.authentication.provider:
        class: Acme\UserBundle\Security\Authentication\Provider\AcmeProvider
        abstract:  true
        arguments: ['']
        public: false

    security.authentication.listener.abstract:
        tags:
            - { name: 'monolog.logger', channel: 'security' }
        arguments: [@security.context, @security.authentication.manager, @security.authentication.session_strategy, @security.http_utils, "knetik",@security.authentication.success_handler, @security.authentication.failure_handler, {}, @logger, @event_dispatcher]
        class: Symfony\Component\Security\Http\Firewall\AbstractAuthenticationListener
     # override application level success handler and re-route back
    security.authentication.success_handler:
        class:  Symfony\Component\Security\Http\Authentication\DefaultAuthenticationSuccessHandler
        arguments:  ["@security.http_utils", {}]
        tags:
            - { name: 'monolog.logger', channel: 'security' }
    # override application level failure handler and re-route back
    security.authentication.failure_handler:
        class:  Symfony\Component\Security\Http\Authentication\DefaultAuthenticationFailureHandler
        arguments:  ["@http_kernel", "@security.http_utils", {}, "@logger"]
        tags:
            - { name: 'monolog.logger', channel: 'security' }
    yamogu.security.authentication.listener:
        class: Acme\UserBundle\Security\Authentication\Firewall\AcmeListener
        parent: security.authentication.listener.abstract
        abstract:  true
        arguments: ["@security.context", "@security.authentication.manager"]
        public: false

If you need an additinal code I'll add it to the question.
Any help will be appreciated!
Link on the dev.log after authorization: https://www.dropbox.com/s/5uot2qofmqjwvmk/dev.log?dl=0

A: I've found a solution of my problem but I went another way.
I've defined a success authentication handler and failure handler for form_login and put my logic here. I manually register a user in failure handler if he inputs wrong username but right card number and pin. And viсe versa if a user inputs right username but wrong card number and pin then I reject his login in success authentication failure and manually log out him.
See my source code
Peace of security.yml:
security:
    firewalls:
        ...
        main:
            pattern:             .*
            context:             user

            form_login:
                provider:       fos_userbundle
                login_path:     /user/login
                use_forward:    false
                check_path:     /user/login_check
                failure_path:   null
                always_use_default_target_path: true
                default_target_path:            ad_category
                success_handler: authentication_success_handler
                failure_handler: authentication_failure_handler
            logout:
                path:           /user/logout
            anonymous:          true

config.yml:
services:
    authentication_success_handler:
        class: Yamogu\UserBundle\Handler\AuthenticationSuccessHandler
        arguments: [@router, @doctrine.orm.entity_manager, @security.context]
    authentication_failure_handler:
        class: Yamogu\UserBundle\Handler\AuthenticationFailureHandler
        arguments: [@router, @doctrine.orm.entity_manager, @security.context, @event_dispatcher]

AuthenticationSuccessHandler.php:
namespace Acme\UserBundle\Handler;

Symfony\Component\Security\Http\Authentication\AuthenticationSuccessHandlerInterface;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\Routing\Router;
use Doctrine\Common\Persistence\ObjectManager;
use Acme\BoardBundle\Entity\Card;
use Symfony\Component\Security\Core\SecurityContext;

class AuthenticationSuccessHandler implements AuthenticationSuccessHandlerInterface
{
    protected $router;

    private $om;

    private $securityContext;

    public function __construct(Router $router, ObjectManager $om, SecurityContext $securityContext)
    {
        $this->router = $router;
        $this->om = $om;
        $this->securityContext = $securityContext;
    }

    public function onAuthenticationSuccess(Request $request, TokenInterface $token)
    {
        $fosUser = $this->securityContext->getToken()->getUser();
        if($fosUser->getCard())
        {
            $card = $fosUser->getCard()->getNumber();
            $pin = $fosUser->getCard()->getPin();
            if($card == $request->get('card') && $pin == $request->get('pin'))
            { //  if Log out the user he inputs wrong card
                $loginName = $request->get('firstname');
                $fosUserFirstName = $fosUser->getFirstname();
                if($loginName && $loginName != $fosUserFirstName)
                {
                    $fosUser->setFirstname($loginName);
                    $this->om->flush();
                }
                return new RedirectResponse($this->router->generate("ad_category"));
            }
        }
        $this->securityContext->setToken(null);
        $request->getSession()->invalidate();
        $request->getSession()->getFlashBag()->set('acme_login_error', 'Error!');
        return new RedirectResponse($this->router->generate("fos_user_security_login"));
    }
}
?>

AuthenticationFailureHandler.php:
<?php
namespace Acme\UserBundle\Handler;

use Symfony\Component\Security\Http\Authentication\AuthenticationFailureHandlerInterface;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Exception\AuthenticationException;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\Routing\Router;
use Doctrine\Common\Persistence\ObjectManager;
use Symfony\Component\Security\Core\SecurityContext;
use Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken;
use Symfony\Component\Security\Http\Event\InteractiveLoginEvent;
use Symfony\Component\EventDispatcher\EventDispatcher;
use Acme\BoardBundle\Entity\Card;
use Acme\UserBundle\Entity\User as YamUser;

class AuthenticationFailureHandler implements AuthenticationFailureHandlerInterface
{
    protected $router;
    private $om;
    private $securityContext;
    private $eventDispatcher;

    public function __construct(Router $router, ObjectManager $om, SecurityContext $securityContext, EventDispatcher $eventDispatcher)
    {
        $this->router = $router;
        $this->om = $om;
        $this->securityContext = $securityContext;
        $this->eventDispatcher = $eventDispatcher;
    }

    public function onAuthenticationFailure(Request $request, AuthenticationException $exception)
    {
        if($request->get('firstname') !== null && $request->get('_username') && $request->get('_password') !== null && $request->get('card') !== null && $request->get('pin') !== null)
        {
            $loginName = $request->get('firstname');
            $username = $request->get('_username');
            $passw = $request->get('_password');
            $loginCard = $request->get('card');
            $loginPin = $request->get('pin');
            $card = $this->om->getRepository('AcmeBoardBundle:Card')
                ->findOneBy(array("number" => $loginCard, "pin" => $loginPin));
            // If there is the requested card in the DB create a new user and log in him at the moment
            if($card)
            { // Create a new user for this card, log in him and redirect to the board
                $entity = new YamUser();
                $entity->setCard($card);
                $entity->setFirstname($loginName);
                $entity->setUsername($username);
                $entity->setPlainPassword($passw);
                $entity->setEmail($username);
                $entity->setEnabled(true);
                $this->om->persist($entity);
                $this->om->flush();

                $token = new UsernamePasswordToken($entity, null, "main", $entity->getRoles());
                $this->securityContext->setToken($token); //now the user is logged in
                //now dispatch the login event
                $event = new InteractiveLoginEvent($request, $token);
                $this->eventDispatcher->dispatch("security.interactive_login", $event);
                return new RedirectResponse($this->router->generate("ad_category"));
            }
        }
        $this->securityContext->setToken(null);
        $request->getSession()->invalidate();
        $request->getSession()->getFlashBag()->set('acme_login_error', 'Error!');
        return new RedirectResponse($this->router->generate("fos_user_security_login"));
    }
}
?>

As I can see this is not the best way to solve the task but it's worked for me. If anyone has better solution or fixes for my solution please add them here!

A: You have to let your security context know about your factory in your bundle class. In your bundle class do this:
class UserBundle extends Bundle
{
    public function build(ContainerBuilder $container)
    {
        parent::build($container);
        $extension = $container->getExtension('security');
        $extension->addSecurityListenerFactory(new AcmeFactory());
    }
    public function getParent()
    {
        return 'FOSUserBundle';
    }
}

[Edit]
Security layer in Symfony is very difficult to understand!. I suggest you to follow this blog post to gain an understanding of Symfony security.


text:
Q: Printing for Java GUI using Physical Printer How can I print multiple Jtextfields in Java using physical printer?
I can print one jTextField using jTextfield.print()
But How to print multiple JtextFields using one print button?


text:
Q: How to remove the file at /tmp/ folder from kernel code..? I have created and opened /tmp/output file from my kernel character driver code using filp_open(). And I am able to do close it using filp_close(). But after unloading the module it is not removing the file /tmp/output.
What should I do to remove it?


text:
Q: My project using angular CLI 1.7.4 what will be the right Angular Material version to install? My Project is built on Angular CLI 1.7.4
While running the command "ng serve", Am getting the below errors:
I understand this is because of angular material is missing from the project.
Kindly guide me on which angular Material version will be the best suited for my project.
Please find the error messages below:
ERROR in node_modules/@angular/flex-layout/flex/typings/flex-offset/flex-offset.d.ts(9,32): error TS2307: Cannot find module '@angular/cdk/bidi'.
node_modules/@angular/flex-layout/flex/typings/layout-gap/layout-gap.d.ts(9,32): error TS2307: Cannot find module '@angular/cdk/bidi'.
node_modules/@angular/material/autocomplete/typings/autocomplete-trigger.d.ts(8,32): error TS2307: Cannot find module '@angular/cdk/bidi'.
node_modules/@angular/material/autocomplete/typings/autocomplete-trigger.d.ts(9,41): error TS2307: Cannot find module '@angular/cdk/overlay'.
node_modules/@angular/material/autocomplete/typings/autocomplete.d.ts(10,44): error TS2307: Cannot find module '@angular/cdk/a11y'.
node_modules/@angular/material/button-toggle/typings/button-toggle.d.ts(8,30): error TS2307: Cannot find module '@angular/cdk/a11y'.
node_modules/@angular/material/button-toggle/typings/button-toggle.d.ts(9,43): error TS2307: Cannot find module '@angular/cdk/collections'.
node_modules/@angular/material/button/typings/button.d.ts(8,30): error TS2307: Cannot find module '@angular/cdk/a11y'.
node_modules/@angular/material/button/typings/button.d.ts(9,26): error TS2307: Cannot find module '@angular/cdk/platform'.
node_modules/@angular/material/checkbox/typings/checkbox.d.ts(8,30): error TS2307: Cannot find module '@angular/cdk/a11y'.
node_modules/@angular/material/chips/typings/chip-list.d.ts(8,33): error TS2307: Cannot find module '@angular/cdk/a11y'.node_modules/@angular/material/chips/typings/chip-list.d.ts(9,32): error TS2307: Cannot find module '@angular/cdk/bidi'.node_modules/@angular/material/chips/typings/chip-list.d.ts(10,32): error TS2307: Cannot find module '@angular/cdk/collections'.
node_modules/@angular/material/chips/typings/chip.d.ts(8,33): error TS2307: Cannot find module '@angular/cdk/a11y'.
node_modules/@angular/material/core/typings/ripple/ripple-renderer.d.ts(9,26): error TS2307: Cannot find module '@angular/cdk/platform'.
node_modules/@angular/material/core/typings/ripple/ripple.d.ts(8,26): error TS2307: Cannot find module '@angular/cdk/platform'.
node_modules/@angular/material/datepicker/typings/calendar.d.ts(7,32): error TS2307: Cannot find module '@angular/cdk/bidi'.
node_modules/@angular/material/datepicker/typings/datepicker.d.ts(8,32): error TS2307: Cannot find module '@angular/cdk/bidi'.
node_modules/@angular/material/datepicker/typings/datepicker.d.ts(9,67): error TS2307: Cannot find module '@angular/cdk/overlay'.
node_modules/@angular/material/dialog/typings/dialog-config.d.ts(9,27): error TS2307: Cannot find module '@angular/cdk/bidi'.
node_modules/@angular/material/dialog/typings/dialog-config.d.ts(10,32): error TS2307: Cannot find module '@angular/cdk/overlay'.
node_modules/@angular/material/dialog/typings/dialog-container.d.ts(10,84): error TS2307: Cannot find module '@angular/cdk/portal'.
node_modules/@angular/material/dialog/typings/dialog-container.d.ts(11,34): error TS2307: Cannot find module '@angular/cdk/a11y'.
node_modules/@angular/material/dialog/typings/dialog-ref.d.ts(8,28): error TS2307: Cannot find module '@angular/cdk/overlay'.
node_modules/@angular/material/dialog/typings/dialog.d.ts(1,59): error TS2307: Cannot find module '@angular/cdk/overlay'.
node_modules/@angular/material/dialog/typings/dialog.d.ts(2,31): error TS2307: Cannot find module '@angular/cdk/portal'.node_modules/@angular/material/expansion/typings/accordion.d.ts(1,30): error TS2307: Cannot find module '@angular/cdk/accordion'.
node_modules/@angular/material/expansion/typings/expansion-panel-header.d.ts(8,30): error TS2307: Cannot find module '@angular/cdk/a11y'.
node_modules/@angular/material/expansion/typings/expansion-panel.d.ts(10,34): error TS2307: Cannot find module '@angular/cdk/accordion'.
node_modules/@angular/material/expansion/typings/expansion-panel.d.ts(11,43): error TS2307: Cannot find module '@angular/cdk/collections'.
node_modules/@angular/material/expansion/typings/expansion-panel.d.ts(12,32): error TS2307: Cannot find module '@angular/cdk/portal'.
node_modules/@angular/material/grid-list/typings/grid-list.d.ts(10,32): error TS2307: Cannot find module '@angular/cdk/bidi'.
node_modules/@angular/material/input/typings/autosize.d.ts(9,26): error TS2307: Cannot find module '@angular/cdk/platform'.
node_modules/@angular/material/input/typings/input.d.ts(1,26): error TS2307: Cannot find module '@angular/cdk/platform'.node_modules/@angular/material/list/typings/selection-list.d.ts(8,50): error TS2307: Cannot find module '@angular/cdk/a11y'.
node_modules/@angular/material/list/typings/selection-list.d.ts(9,32): error TS2307: Cannot find module '@angular/cdk/collections'.
node_modules/@angular/material/menu/typings/menu-directive.d.ts(9,27): error TS2307: Cannot find module '@angular/cdk/bidi'.
node_modules/@angular/material/menu/typings/menu-directive.d.ts(16,29): error TS2307: Cannot find module '@angular/cdk/a11y'.
node_modules/@angular/material/menu/typings/menu-item.d.ts(8,60): error TS2307: Cannot find module '@angular/cdk/a11y'.
node_modules/@angular/material/menu/typings/menu-panel.d.ts(10,27): error TS2307: Cannot find module '@angular/cdk/bidi'.
node_modules/@angular/material/menu/typings/menu-panel.d.ts(11,29): error TS2307: Cannot find module '@angular/cdk/a11y'.
node_modules/@angular/material/menu/typings/menu-trigger.d.ts(1,43): error TS2307: Cannot find module '@angular/cdk/bidi'.
node_modules/@angular/material/menu/typings/menu-trigger.d.ts(2,67): error TS2307: Cannot find module '@angular/cdk/overlay'.
node_modules/@angular/material/menu/typings/menu-trigger.d.ts(7,43): error TS2307: Cannot find module '@angular/cdk/a11y'.
node_modules/@angular/material/progress-spinner/typings/progress-spinner.d.ts(10,26): error TS2307: Cannot find module '@angular/cdk/platform'.
node_modules/@angular/material/radio/typings/radio.d.ts(8,30): error TS2307: Cannot find module '@angular/cdk/a11y'.
node_modules/@angular/material/radio/typings/radio.d.ts(9,43): error TS2307: Cannot find module '@angular/cdk/collections'.
node_modules/@angular/material/select/typings/select.d.ts(8,44): error TS2307: Cannot find module '@angular/cdk/a11y'.
node_modules/@angular/material/select/typings/select.d.ts(9,32): error TS2307: Cannot find module '@angular/cdk/bidi'.
node_modules/@angular/material/select/typings/select.d.ts(10,32): error TS2307: Cannot find module '@angular/cdk/collections'.
node_modules/@angular/material/select/typings/select.d.ts(11,103): error TS2307: Cannot find module '@angular/cdk/overlay'.
node_modules/@angular/material/sidenav/typings/drawer.d.ts(9,61): error TS2307: Cannot find module '@angular/cdk/a11y'.
node_modules/@angular/material/sidenav/typings/drawer.d.ts(10,32): error TS2307: Cannot find module '@angular/cdk/bidi'.node_modules/@angular/material/sidenav/typings/drawer.d.ts(11,26): error TS2307: Cannot find module '@angular/cdk/platform'.
node_modules/@angular/material/sidenav/typings/drawer.d.ts(15,31): error TS2307: Cannot find module '@angular/cdk/scrolling'.
node_modules/@angular/material/slide-toggle/typings/slide-toggle.d.ts(8,30): error TS2307: Cannot find module '@angular/cdk/a11y'.
node_modules/@angular/material/slide-toggle/typings/slide-toggle.d.ts(9,26): error TS2307: Cannot find module '@angular/cdk/platform'.
node_modules/@angular/material/slider/typings/slider.d.ts(8,30): error TS2307: Cannot find module '@angular/cdk/a11y'.
node_modules/@angular/material/slider/typings/slider.d.ts(9,32): error TS2307: Cannot find module '@angular/cdk/bidi'.
node_modules/@angular/material/snack-bar/typings/snack-bar-config.d.ts(9,36): error TS2307: Cannot find module '@angular/cdk/a11y'.
node_modules/@angular/material/snack-bar/typings/snack-bar-config.d.ts(10,27): error TS2307: Cannot find module '@angular/cdk/bidi'.
node_modules/@angular/material/snack-bar/typings/snack-bar-container.d.ts(10,68): error TS2307: Cannot find module '@angular/cdk/portal'.
node_modules/@angular/material/snack-bar/typings/snack-bar-ref.d.ts(8,28): error TS2307: Cannot find module '@angular/cdk/overlay'.
node_modules/@angular/material/snack-bar/typings/snack-bar.d.ts(8,31): error TS2307: Cannot find module '@angular/cdk/a11y'.
node_modules/@angular/material/snack-bar/typings/snack-bar.d.ts(9,36): error TS2307: Cannot find module '@angular/cdk/layout'.
node_modules/@angular/material/snack-bar/typings/snack-bar.d.ts(10,25): error TS2307: Cannot find module '@angular/cdk/overlay'.
node_modules/@angular/material/snack-bar/typings/snack-bar.d.ts(11,31): error TS2307: Cannot find module '@angular/cdk/portal'.
node_modules/@angular/material/sort/typings/sort-header.d.ts(9,30): error TS2307: Cannot find module '@angular/cdk/table'.
node_modules/@angular/material/stepper/typings/step-header.d.ts(8,30): error TS2307: Cannot find module '@angular/cdk/a11y'.
node_modules/@angular/material/stepper/typings/step-label.d.ts(9,30): error TS2307: Cannot find module '@angular/cdk/stepper'.
node_modules/@angular/material/stepper/typings/stepper-button.d.ts(1,52): error TS2307: Cannot find module '@angular/cdk/stepper'.
node_modules/@angular/material/stepper/typings/stepper.d.ts(8,37): error TS2307: Cannot find module '@angular/cdk/stepper'.
node_modules/@angular/material/stepper/typings/stepper.d.ts(9,32): error TS2307: Cannot find module '@angular/cdk/bidi'.node_modules/@angular/material/table/typings/cell.d.ts(9,84): error TS2307: Cannot find module '@angular/cdk/table'.
node_modules/@angular/material/table/typings/row.d.ts(1,66): error TS2307: Cannot find module '@angular/cdk/table'.
node_modules/@angular/material/table/typings/table-data-source.d.ts(8,28): error TS2307: Cannot find module '@angular/cdk/table'.
node_modules/@angular/material/table/typings/table.d.ts(1,26): error TS2307: Cannot find module '@angular/cdk/table'.
node_modules/@angular/material/tabs/typings/tab-body.d.ts(10,49): error TS2307: Cannot find module '@angular/cdk/portal'.
node_modules/@angular/material/tabs/typings/tab-body.d.ts(11,43): error TS2307: Cannot find module '@angular/cdk/bidi'.
node_modules/@angular/material/tabs/typings/tab-header.d.ts(8,43): error TS2307: Cannot find module '@angular/cdk/bidi'.node_modules/@angular/material/tabs/typings/tab-header.d.ts(13,31): error TS2307: Cannot find module '@angular/cdk/scrolling'.
node_modules/@angular/material/tabs/typings/tab-label.d.ts(9,27): error TS2307: Cannot find module '@angular/cdk/portal'.
node_modules/@angular/material/tabs/typings/tab-nav-bar/tab-nav-bar.d.ts(8,32): error TS2307: Cannot find module '@angular/cdk/bidi'.
node_modules/@angular/material/tabs/typings/tab-nav-bar/tab-nav-bar.d.ts(9,26): error TS2307: Cannot find module '@angular/cdk/platform'.
node_modules/@angular/material/tabs/typings/tab-nav-bar/tab-nav-bar.d.ts(10,31): error TS2307: Cannot find module '@angular/cdk/scrolling'.
node_modules/@angular/material/tabs/typings/tab.d.ts(8,32): error TS2307: Cannot find module '@angular/cdk/portal'.
node_modules/@angular/material/toolbar/typings/toolbar.d.ts(10,26): error TS2307: Cannot find module '@angular/cdk/platform'.
node_modules/@angular/material/tooltip/typings/tooltip.d.ts(9,45): error TS2307: Cannot find module '@angular/cdk/a11y'.node_modules/@angular/material/tooltip/typings/tooltip.d.ts(10,32): error TS2307: Cannot find module '@angular/cdk/bidi'.
node_modules/@angular/material/tooltip/typings/tooltip.d.ts(11,156): error TS2307: Cannot find module '@angular/cdk/overlay'.
node_modules/@angular/material/tooltip/typings/tooltip.d.ts(12,26): error TS2307: Cannot find module '@angular/cdk/platform'.
node_modules/@angular/material/tooltip/typings/tooltip.d.ts(13,34): error TS2307: Cannot find module '@angular/cdk/scrolling'.
node_modules/@angular/material/tooltip/typings/tooltip.d.ts(16,53): error TS2307: Cannot find module '@angular/cdk/layout'.
src/app/components/job-execution-report/job-execution-report.component.ts(19,26): error TS2307: Cannot find module '@angular/cdk/collections'.
src/app/components/job-execution-report/tasks-details-dialog.component.ts(3,26): error TS2307: Cannot find module '@angular/cdk/collections'.
src/app/components/job-summay-dialog/list-jobs.dialog.component.ts(9,26): error TS2307: Cannot find module '@angular/cdk/collections'.
src/app/components/list-jobs/list-jobs.component.ts(10,26): error TS2307: Cannot find module '@angular/cdk/collections'.src/app/components/list-tasks/list-tasks.component.ts(20,26): error TS2307: Cannot find module '@angular/cdk/collections'.
src/app/components/list-tasks/list-tasks.component.ts(21,21): error TS2307: Cannot find module '@angular/cdk/keycodes'.
src/app/components/list-tasks/list-tasks.dialog.component.ts(7,26): error TS2307: Cannot find module '@angular/cdk/collections'.
src/app/components/list-workflows/list-workflows-dialog.component.ts(4,26): error TS2307: Cannot find module '@angular/cdk/collections'.
src/app/components/list-workflows/list-workflows.component.ts(11,26): error TS2307: Cannot find module '@angular/cdk/collections'.
src/app/components/my-approvals/my-approvals.component.ts(11,26): error TS2307: Cannot find module '@angular/cdk/collections'.
src/app/components/my-team-requests/my-team-requests.component.ts(9,26): error TS2307: Cannot find module '@angular/cdk/collections'.
src/app/components/pending-scheduled-jobs/pending-scheduled-jobs.component.ts(10,26): error TS2307: Cannot find module '@angular/cdk/collections'.
src/app/components/profile/profile.component.ts(9,26): error TS2307: Cannot find module '@angular/cdk/collections'.
src/app/components/rfc-executions-report/rfc-execution-report.component.ts(4,26): error TS2307: Cannot find module '@angular/cdk/collections'.
src/app/components/run-summary-dialog/run-summary-dialog.component.ts(3,26): error TS2307: Cannot find module '@angular/cdk/collections'.
src/app/components/schedule-job/runtime-pause-config-dialog.component.ts(5,26): error TS2307: Cannot find module '@angular/cdk/collections'.
src/app/components/schedule-job/schedule-job.component.ts(1186,81): error TS2339: Property 'taskArgsValuesObj' does not exist on type '{}'.
src/app/components/team-requests/team-requests.component.ts(11,26): error TS2307: Cannot find module '@angular/cdk/collections'.
src/app/components/team-security/team-security.component.ts(15,26): error TS2307: Cannot find module '@angular/cdk/collections'.
src/app/modules/atom-ng-material.module.ts(33,30): error TS2307: Cannot find module '@angular/cdk/table'.

webpack: Failed to compile.

A: *

*Firstly try

npm install

to install all the modules required inside package.json.

*Try

ng -v

to check your Angular version
You should check your Angular instead of the CLI version to check which version of Angular Material you should install.

*Go to this https://material.angular.io/ to see which version of Angular Material you should install.

The below command will update your Angular project with the correct dependencies, perform configuration changes and execute initialization code.

ng add @angular/material

With Angular 5, you can use angular material 5. Execute the following commands to install ver 5.2.5 of @angular/material and @angular/cdk:
npm install --save @angular/material@5.2.5
npm install --save @angular/cdk@5.2.5

Angular material version for angular 5 app

A: you just need to install
npm install --save @angular/material@latest @angular/cdk@latest

don't worry about the version it will install latest and version for the same.

A: Initially, my global CLI was the latest one(7.1) and my local CLI version in 5.
Installing both global and local CLI of angular CLI Version 5 resolved the issue.
Try the below comment:
npm uninstall @angular/cli

npm install -g @angular/cli@5.2.5