text:
Q: check that a list contains only elements from a given "permissible" list I half expect to be "duped" on this.  But there doesn't seem such a Pythonic "brain exercise" in SO, or even in other languages.
Say I have a "permissible" list [ 45, 6, 155, 44 ] and I submit a list [ 6, 44, 19, 12 ] : I'd just like to know an efficient, elegant and altogether beautiful algorithm for getting the result:
LEGAL: [ 6, 44 ]
ILLEGAL: [ 19, 12 ]

PS am currently using 2.7 but 3.x answers would also be welcome!

A: permissible = [45, 6, 155, 44]

To preserve repeated values:
legal = []
illegal = []
for item in submission:
    if item in permissible:
        legal.append(item)
    else:
        illegal.append(item)

Or if you're working with unique, hashable values:
legal = set(submission) & set(permissible)
illegal = set(submission) - set(permissible)

A: This should work for you.
permissible = [ 45, 6, 155, 44 ]
def get_legal(permissible, input):
    legal = [x for x in input if x in permissible]
    illegal = [x for x in input if x not in permissible]
    return legal, illegal

A: Maintain your legal values as a set, then convert any list you want to check to a set and make sure it is issubset of legal.

A: I would suggest this solution
some_list = [1,2,3,4]
permissible = [1,2]

legal = [x for x in some_list if x in permissible]
ilegal = [x for x in some_list if x not in permissible]

Hope this helps!


text:
Q: Make superuser act like some other user in certain directory tree I have the following problem:
My home directory lies on the network and is mounted locally on home/<my username>.
I can access it with my normal user account <my username>, but as root, I cannot.
I do know about this question:
https://serverfault.com/questions/571073/root-cannot-access-users-home-folder-shared-via-nfs
However, this, from my limited understanding of linux systems etc., seems to be some server-side-solution, if it's even applicable in this case.
But I need a client-side solution, since the admins won't change this for the time being.
So I was wondering if there was some sort of option to make the superuser  automatically act like user <my username> inside the sub-directory-tree /home/<my username>, whenever the superuser needs access there.
As of now, the superuser can't even cd into my home directory.
Please note, the solution should work for sudo and in case I choose to sudo su.

A: You can change users using su like follows:
root@bacon [~]# whoami
root
root@bacon [~]# su - cataline
cataline@bacon [/root]# whoami
cataline

May need to use sudo to run the command depending on permissions.
EDIT Changed command to reflect creating a login shell

redpajama_set_name: RedPajamaStackExchange


text:
Q: FOSUserBundle Mapping I have problem:

MappingException: The class 'Acme\UserBundle\Entity\User' was not
  found in the chain configured namespaces FOS\UserBundle\Entity,
  FOS\UserBundle\Model

My file Acme\UserBundle\Entity\User
<?php
    // src/Acme/UserBundle/Entity/User.php

    namespace Acme\UserBundle\Entity;

    use FOS\UserBundle\Model\User as BaseUser;
    use Doctrine\ORM\Mapping as ORM;

    /**
     * @ORM\Entity
     * @ORM\Table(name="fos_user")
     */
    class User extends BaseUser
    {
        /**
         * @ORM\Id
         * @ORM\Column(type="integer")
         * @ORM\GeneratedValue(strategy="AUTO")
         */
        protected $id;

        public function __construct()
        {
            parent::__construct();
            // your own logic
        }
}

A: Probably you are missing configuration file.
app/config/config.yml
fos_user:
    db_driver: orm # other valid values are 'mongodb', 'couchdb' and 'propel'
    firewall_name: main
    user_class: Acme\UserBundle\Entity\User

Cheers!

A: Also make sure your doctrine configuration in your config.yml looks similar to this:
doctrine:
dbal:
    driver:   "%database_driver%"
    host:     "%database_host%"
    port:     "%database_port%"
    dbname:   "%database_name%"
    user:     "%database_user%"
    password: "%database_password%"
    charset:  UTF8
orm:
    auto_generate_proxy_classes: "%kernel.debug%"
    auto_mapping: true

(Notable the auto_mapping: true and the auto_generate_proxy_classes... )


text:
Q: Property gamma for type III factors I am struggling to find a definition which uses centralizing sequences for property gamma in type III factors?
If $M$ is type $\mathrm{III}$ factor, what is the exact definition of property gamma without using the equivalent  definition: the relative commutant of ultrafilter of $M$ in $M$ is nontrivial?


text: Q: i want to run a loop for every unique value in a column A such that the inner loop should start from first row of every unique entry ex i have a dataframe , that has A, B,C, D values in one column. The second column has sales value for every entry A, B,C,D arranged chronologically. i want to run a loop to compare all sales values for every group (A, B,C,D)


text:
Q: Vim - How can I install this simple markdown preview plugin with Pathogen? I found a little plugin to help me preview markdown files from Vim.  It will let me see the HTML file in my default browser.  You can read about the plugin here: http://blog.natesilva.com/post/5256838248/how-to-preview-a-markdown-document-in-vim
The installation instructions say:
To install: Place markdown.vim in ~/.vim/ftplugin or " %USERPROFILE%\vimfiles\ftplugin.

However, I am using Tim Pope's Pathogen plugin-loading system to load several other plugins that are stored in their own directories under the bundle directory.  Can I do the same with this one? I tried creating a bundle/markdown-preview/ directory and placing markdown.vim in it, but I wasn't able to get it to work that way.  What do I not understand?  Is it even necessary to use Pathogen in this case?  What problem will it solve for me?
Also, just to see if the plugin worked, I installed it in the ftplugin directory, as suggested.  Now, when I press ,p Vim stops itself and the preview file is opened in my browser.  I get the message:
[1]+  Stopped                 vim ./.dotfiles/vim/bundle/fugitive/README.markdown

How do I resume Vim and go back to editing the file once I've seen my preview?

A:
I tried creating a bundle/markdown-preview/ directory and placing markdown.vim in it, but I wasn't able to get it to work that way.

You should have tried putting it into bundle/markdown-preview/ftplugin, not where you claim you have tried to put it. There may still be some things that prevent it from working from this location.
For second question: follow this comment and add :redraw! at the end of the function.

A: To get Pathogen to find the plugin I put the markdown.vim file in bundle/markdown-preview/plugin/.  This link helped me: http://news.ycombinator.com/item?id=1711760


text:
Q: No Activity found to handle Intent android.media.action.VIDEO_CAPTURE (has extras) I read this answer from @CommonsWare.

This happens when I open the devices default camera application. But it doesn't happen on my Samsung J7 Pro running 8.1.0
I open the camera like this:
Uri videoUri = FileProvider.getUriForFile(this, getApplicationContext().getPackageName() + ".provider", filePlusName);
Intent intent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
intent.setPackage(defaultCameraPackageName);
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
intent.putExtra(MediaStore.EXTRA_OUTPUT, videoUri);
startActivityForResult(intent, VIDEO_REQUEST_CODE);//Crash pointing to this

I'm not sure if doing it like this will solve the issue (I doubt it)?
Intent intent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
intent.setPackage(defaultCameraPackageName);
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
intent.putExtra(MediaStore.EXTRA_OUTPUT, FileProvider.getUriForFile(MainActivity.this, getApplicationContext().getPackageName() + ".provider", filePlusName));
startActivityForResult(intent, VIDEO_REQUEST_CODE);//Crash pointing to this

I have no idea why this is happening,
Any advise would greatly be appreciated .


text:
Q: Nodejs установка express Здравствуйте, изучая node.js, по этой статье столкнулся с некоторыми затруднениями,
Вроде бы все начал понимать, но в разделе "Делаем что-нибудь полезное — Express" не понял как установить модуль express. cd /my/app/location - что это за директория должна быть? Как я понял для установки модуля нужно набрать команду npm install express (это понятно) но перед этим, я тaк понял, нужно перейти в какую-то директорию... Подправьте меня, и направьте в правильном направлении! Заранее благодарен!

A:
как устанавливать плагины

npm i module_name

какие пути прописывать

Папка, где лежат файлы вашего проекта.
Создайте папку hello  в моих документах. Убедитесь, что у вас установлены node.js, npm, и express-generator. Перейдите, в консоле, в папку test и выполните express && npm i в консоле. Дальше по тексту статьи, что вы нашли.
A: Статья по ссылке в вопросе - не лучший вариант для начинающего.
Рекомендую вот это.
И в Экспресс на данном этапе изучения рекомендую вообще не трогать. Пока не трогать. Вернуться к нему когда будет понимание основных процессов.
A: Если вы попали на эту страницу, и не знаете как устанавливать модули из руководств найденых в интернете... Немножко длинное объяснение.
После установки дистрибутива под Windows c официального сайта вам надо проверить результат.
Зайдите в командную строку Windows. Искать тут:
Пуск - Все программы - Стандартные - Командная строка

Наберите в ней:
node -v

Нажмите enter. Результатом должно быть что-то вроде:
v4.1.2

Теперь наберием
npm version

Жмем enter. Должны увидеть что-то вроде:
{ npm: '2.14.4',
ares: '1.10.1-DEV',
http_parser: '2.5.0',
modules: '46',
node: '4.1.2',
openssl: '1.0.2d',
uv: '1.7.5',
v8: '4.5.103.35',
zlib: '1.2.8' }

Если у вас это работает. То исполнив:
npm install express

Вы сможете себе поставить модуль express на компьютер.

A: ну давайте по порядку.

*

*cd /my/app/location: если в вкратце то cd - это команда для терминала windows которая позволяет, перемещаться между директориями.

1.2. /my/app/... путь в который нам нужно перейти, условно это то же самое что подключение стилей css к html когда вы в link herf='<вписываете сюда свою ссылку, относительно данного файла>',
1.3

что это за директория должна быть?

директорию вы создаете сами, те это просто заготовленная папка, в которой лежат ваши проекты например, я зашел в документы и создал там папку Project и в уже в ней я создал папку express
что бы перейти в данную папку, я буду использовать команду cd Documents/Project/express
1.4 вот ссылка на информацию о команде cd: https://ab57.ru/cmdlist/cd.html

*С каталогами разобрались теперь с установкой nodejs и express, для того что бы установить сам экспресс сперва нужно инициализировать nodejs, для этого в командной строке в которой мы прописывали пути, пишем команду npm init -y, флаг -y позволит не заполнять различную информацию о проекте, после чего прописываем npm i express и все, можете творить.

Так же что бы проверить установлен ли express или нет, достаточно просто посмотреть файл package.json в нем ищем раздел dependencies, в котором написаны все установленные вами библиотеки.
Надеюсь помог и нигде не ошибся, спасибо за внимание)


text:
Q: Storing address of mpz_t and passing the pointer around From what I understand, mpz_t are nothing but a single-item array.
According to gmp.h:
{
  short int _mp_alloc;      /* Number of *limbs* allocated and pointed
                   to by the D field.  */
  short int _mp_size;       /* abs(SIZE) is the number of limbs
                   the last field points to.  If SIZE
                   is negative this is a negative
                   number.  */
  mp_limb_t *_mp_d;     /* Pointer to the limbs.  */
} __mpz_struct;

typedef __mpz_struct mpz_t[1];

That means that, given the way C handles arrays, mpz_t is effectively a pointer itself (to the first element of the one-element array).
Now, let's say I create a new mpz_t, within a function, "box" the pointer in an unsigned long long and return, then... chaos. (Since, I guess, the pointer is no longer valid?)
The only way I could in theory make it work is by moving the mpz_t declaration outside the function body (basically, make it a global)
Any other - more sensible - ideas?

Minimal example:
typedef uint64_t Value;

#define addWillOverflow(x,y,z) __builtin_sadd_overflow(x,y,z)

#define BITFIELD 56

#define MASK(x) ((Value)(x) << BITFIELD)
#define UNMASK  0x00FFFFFFFFFFFFFF

#define toI(v)  ( (Value)(v & 0xFFFFFFFFu) | MASK(IV) )
#define toG(v)  ( (Value)(v) | MASK(GV) )
#define GG(v)   ( (v & UNMASK) )

Value addNumbers(int a, int b) {
    Int32 res;
    if (addWillOverflow(a,b,&res)) {
        printf("overflow\n");
        mpz_t ret;
        mpz_init_set_si(ret,a);
        mpz_add_ui(ret,ret,b);
        return toG(ret);
    }
    else {
        printf("normal addition\n");
        return toI(res);
    }
}

int main(int argc, char** argv) {

    printf("3 + 5 = ");
    printLnValue(addNumbers(1,2));

    printf("2b + 2b = ");
    Value a = addNumbers(2000000000,2000000000);
    printLnValue(a);
    printf("pointer: %p\n",GG(a));

    Value b = addNumbers(2100000000,2011111111);
    printLnValue(b);
    printf("pointer: %p\n",GG(b));
}

Output:
3 + 5 = normal addition
3
2b + 2b = overflow
4000000000
pointer: 0x7ffee5b95630
overflow
4111111111
pointer: 0x7ffee5b95630

As you can see, the returned pointer is... the same. Although I would expect a different one.

UPDATE no 2
I'm currently thinking of doing it like this: (I'll see how it goes and then post it as a solution myself)
    mpz_t* ret = malloc(sizeof(mpz_t));
    mpz_init_set_si(*ret,a);
    mpz_add_ui(*ret,*ret,b);
    return toG(ret);


text:
Q: Angular return result of Subscription as Observable I have a component that upon button click calls a save() method from a StorageManagerService:
// component.ts
onSaveClick(): void {
  this.storageManager
    .save(<objectToSave>)
    .pipe(take(1))
    .subscribe({
      next: (success: boolean) => {
        if (success) {
          // do stuff
        } else {
          // do other stuff
        }
      },
    });
}

That storageManager is an adapter to another service that handles conditional logic. So StorageManagerService.save() looks like the following:
// StorageManagerService
save(<objectToSave>): Observable<boolean> {
  if (<someCondition>) {
    this.modalService
      .openDialogWithComponent(
        SaveSystemContainerComponent,
        { data: { <someData> } },
        this.matDialog
      )
      .afterClosed()
      .pipe(take(1))
      .subscribe({
        next: (success: boolean) => {
          if (success) {
            // special handling

            return this.localStorageService.save(<objectToSave>);
          }

          return of(false);
        },
      });
  }
  else {
    return this.localStorageService.save(<objectToSave>);
  }
}

While LocalStorageManagerService has the concrete implementation for storing data:
// LocalStorageManagerService
save(<objectToSave>): Observable<boolean> {
  if (this.storageAvailable()) {
    localStorage.setItem(<objectToSave>.id, JSON.stringify(<objectToSave>));
    return of(true);
  }

  console.error('local storage not available or disabled');
  return of(false);
}

LocalStorageService inherits from an abstract class that all storage services have to implement.
The idea is that when migrating from localStorage to an actual database in the future, I only have to change the variable in StorageManagerService and don't have to modify 20+ places in the application.
The problem I'm having is that in certain conditions the user has to input additional data before I can store it. That input happens through a modal appearing.
Now TypeScript tells me that the if-case in StorageManagerService doesn't return anything (which is correct).
How can I return the result from subscribe.next() in StorageManagerService to the calling function? I think I'm missing an rxjs operator.

A: If someone subscribes to save, you can refactor the method to:
save(objectToSave): Observable<boolean> {
  if (someCondition) {
    return this.modalService
      .openDialogWithComponent(
        SaveSystemContainerComponent,
        { data: { someData } },
        this.matDialog
      )
      .afterClosed()
      .pipe(
        take(1),
        switchMap((success: boolean) => {
          if (success) {
            // special handling

            return this.localStorageService.save(objectToSave);
          }
          return of(false);
        })
      );
  } else {
    return this.localStorageService.save(objectToSave);
  }
}

Also, your LocalStorageManagerService should only do the actual save when a subscription is made to the return of save, not only when save is called:
save(objectToSave): Observable<boolean> {
  return defer(() => {
    if (this.storageAvailable()) {
      localStorage.setItem(objectToSave.id, JSON.stringify(objectToSave));
      return of(true);
    }

    console.error('local storage not available or disabled');
    return of(false);
  });
}


text:
Q: htaccess not working due to some mystical issue I'm running Windows 7 xampp server it has Apache and it has lines that are needed to uncomment to work fine.
However when I try to use RewriteRule I bump into the problem.
When I write wrong code at the start of htaccess it throws error 500, there are few commands that works, but when I use RewriteRule it simply ignore that part , unless if I write something syntax wise wrong then it reacts as error, but i have never seen my link changed.
.htaccess file is placed at myDomain directory
Can it possibly be issue of software or it's my code?
I have this dynamic link:
http://localhost//myDomain/folder/ad.php?title=theTitle&id=1

and I need to get this:
http://localhost//myDomain/folder/theTitle/1

My htaccess file looks like this:
RewriteEngine on
RewriteBase /myDomain/folder
RewriteCond %{REQUEST_URI} ^/ad.php$ [NC]
RewriteCond %{QUERY_STRING} ^title=(.*)&id=(.*)$
RewriteRule (.*) http://localhost/myDomain/folder/%1/%2.aspx? [R=301,L]

Any help would be highly honored :)

A: You can have these rules in /myDomain/folder/.htaccess:
RewriteEngine on
RewriteBase /myDomain/folder/

RewriteCond %{THE_REQUEST} /ad\.php\?title=([^\s&]+)&id=([^\s&]+) [NC]
RewriteRule ^ %1/%2? [R=302,L]

RewriteRule ^([^/.]+)/([0-9]+)/?$ ad.php?title=$1&id=$2 [L,QSA]


text:
Q: Appending new objects to a list in a separate variable I'm a little confused on how to append a new object to a list. I feel like I'm overthinking it, but let me know if I'm on the right track here.
EDIT: Removed old code
To be clear, I don't want to edit the text file referenced in display() directly (and then read off that), I want to use the append method to add a new book to the end of the list. I get the objects through a split using a semicolon, so when I'm adding new books, should they also have the semicolon present to match the rest of the list?
EDIT: Here is what I have now.
class Book:

    def __init__(self, title, author, isbn, callnumber, stock, loaned):
        self.title = title
        self.author = author
        self.isbn = isbn
        self.callnumber = callnumber
        self.stock = stock
        self.loaned = loaned
        self.available = int(self.stock)-int(self.loaned)

    def getTitle(self):
        return self.title

    def getAuthor(self):
        return self.author

    def getISBN(self):
        return self.isbn

    def getCallNumber(self):
        return self.callnumber

    def getStock(self):
        return self.stock

    def getLoaned(self):
        return self.loaned

    def getAvailable(self):
        return self.available

    def __repr__(self):
        return self.title + '\t' + self.author + '\t' + self.isbn + '\t' + self.callnumber + '\t' + self.stock + '\t' + self.loaned + '\n'

    def inventory():
        fmtstring = '''{:<50}\t{:<20}\t{:<13}\t{:<13}\t{:<10}\t{:<10}\t{:<10}'''
        print(fmtstring.format("Name","Author","ISBN","Call Number","Stock","Loaned","Available"))
        books = []
        with open("books.txt", "r") as inventoryfile:
            for line in inventoryfile:
                strip_lines=line.strip()
                inventory = strip_lines.split(";")
                book = (Book(inventory[0],inventory[1],inventory[2],inventory[3],inventory[4],inventory[5]))
                books.append(book)
                print(fmtstring.format(*fields(book)))

    @staticmethod
    def input_book():
        title = input("Provide the title of the book> ")
        author = input("Provide the author of the book> ")
        isbn = input("Provide the ISBN of the book> ")
        callnumber = input("Provide the call number of the book> ")
        stock = input("Provide the stock of the book> ")
        return Book(title, author, isbn, callnumber, stock, 0)

And these are called on with menu options.

    while True:
        print()
        print("Westlands Book Inventory Management Subsystem")
        print("1. Display Inventory")
        print("2. Add a Book")
        print("3. Remove a Book")
        print("4. Export Inventory")
        print("5. Quit IMS")
        choice=eval(input("Select an option from the menu> "))
        if(choice==1):
            print()
            print("Displaying Westlands Books Inventory")
            print()
            Book.inventory()

        elif(choice==2):
            print()
            print("Adding a Book")
            print()
            Book.input_book()
            print()
            print('Book added successfully.')

This is the "safe" version of my code that doesn't break anything. I've tried the append command in various places but doesn't seem to be  working. I can't seem to return what was input into input_books at all. Thanks

A: Your function that creates a Book from user input should just return that Book rather than trying to add it to a list (primarily because: what list?).  If it's a method on Book, it should be a static method (or a class method), not an instance method, since the point of it is to create an instance.  For example:
@staticmethod
def input_book():
    title = input("Provide the title of the book> ")
    author = input("Provide the author of the book> ")
    isbn = input("Provide the ISBN of the book> ")
    callnumber = input("Provide the call number of the book> ")
    stock = input("Provide the stock of the book> ")
    return Book(title, author, isbn, callnumber, stock, 0)

Now outside your Book class, you can do:
books = []
while True:
    print()
    print("Westlands Book Inventory Management Subsystem")
    print("1. Display Inventory")
    print("2. Add a Book")
    choice = input("Select an option from the menu> ")
    if choice == "1":
        print(books)
    if choice == "2":
        print()
        print("Adding a Book")
        print()
        books.append(Book.input_book())
        print()
        print('Book added successfully.')

Note that books isn't a Book, it's a list of Books.


text:
Q: Check if href is a path after the website path I would like to check if the href of a link is a file after the website path.  Here is the code:
const currentLocation = location.href;
const menuItems = document.querySelectorAll('nav ul li a');

$('nav ul li a').each(index => {
    if(menuItems[index].href === currentLocation || (menuItems[index].href === 'http://127.0.0.1:5500/' && currentLocation === 'http://127.0.0.1:5500/index.html')) {
        // other code
    }
});

Is there a way to have it to check if it is '/' or '/index.html' after the 'http://127.0.0.1:5500'?  Thank you!

A: You can use endsWith to make the checks.
Also instead of this menuItems[index].href you can directly check (menuItems[index].pathname if you want.


text:
Q: C++ corrupted double-linked list I am new in c++ coming from Java and I am facing a problem with c++ I/O. I have made a small program to illustrate me problem. The main idea is to have 3-dimensional array and initialize it's values by reading a text file with specific text format. The file contains the number of Levels (L) which is the first dimension and the size of rows and columns (N) which is the second and the third dimensions ( array[L][N][N] ).
Edit : to execute my program i use g++ -std=c++0x program.cpp
Here is the program :
#include <iostream>
#include <string>
#include <fstream>

using namespace std;

int num_of_stages;
int N ;
string ***stages;

void readFile(string file_name){
    string line;
    int pos;

    ifstream file (file_name);

    if (file.is_open()){

        getline (file,line);                    // L=XXX
        pos = line.find("=");
        line = line.substr(pos+1);
        num_of_stages = atoi(line.c_str());
        cout << "L=" << num_of_stages << endl;

        getline (file,line);                    // N=XXX
        pos = line.find("=");
        line = line.substr(pos+1);
        N = atoi(line.c_str());
        cout << "N=" << N << endl;

        // setting the stages array with dimensions stages[L][N][N]
        stages = new string**[num_of_stages];
        for(int i = 0 ; i < N ; i ++){
            stages[i] = new string*[N];
            for(int j = 0 ; j < N ; j++){
                stages[i][j] = new string[N];
            }
        }

        for(int i = 0 ; i < num_of_stages ; i++){
            getline (file,line);                // Level comment
            cout << "Level " << line << endl;
            for(int j = 0 ; j < N ; j++){
                for(int k = 0 ; k < N ; k++){
                    string currentValue ;
                    file >> currentValue;
                    stages[i][j][k] = currentValue;
                    cout << currentValue << " " ;
                }
                cout << endl;
            }
            cout << endl << endl;
            // I am guessing that this getLine()
            // is necessary to read the end of the line
            // if I try remove it everything goes wrong
            // everytime I print the line's values is ' ' (empty)
            getline (file,line);
            // remove any string value to detect end of file
            // so the if statement below will be true
            line.clear();
        }
        getline (file,line);                    // END OF MAZE comment
        cout << line << endl;
        if(line != "END OF MAZE"){
            cout << "Wrong file format" << endl;
            file.close();
            exit(0);
        }
        file.close();
    }else{
        cout << "Missing file with name : " << file_name << endl;
        exit(0);
    }
    // program never reach that point
    cout << "Bla bla bla" << endl;
}

int main(){
    readFile("file1.maz");
    return 0;
}

My File has this text format :
L=5
N=16
LEVEL 1
T2 T3 T1 T2 E E T1 E E T2 T2 T1 T2 T1 T2 T1
T1 T1 T2 T1 T2 T3 T2 T3 T2 T2 T3 T3 T1 E T3 T1
T2 E T1 T1 T3 T2 T1 T3 E T3 T3 E T1 E T1 T1
T1 T3 T2 E T1 T1 T2 E T2 T2 T2 T1 T3 T3 T1 T3
E E T1 T3 T1 T3 T1 T2 T2 T1 T1 E T2 T1 T1 T3
T2 T1 T1 T3 T3 E T2 T3 T3 T2 T1 E T3 T2 T1 T2
T2 T1 T3 T2 T2 E T2 E E E T3 T3 T2 T3 T3 T1
E E E T2 E E T3 E T1 T2 T1 T2 T1 T3 T3 E
T3 T2 T1 T3 E T1 E T2 T3 T1 T2 T2 T3 T2 E T1
T2 T3 E E T2 T2 E T3 E E T3 T1 T3 T1 E T3
T1 T1 E T1 T1 T3 T3 T1 E T2 T3 T1 T3 T3 T3 E
T3 T1 T1 T1 T2 T2 T3 T1 T3 T2 E T2 T1 E T1 E
T3 E T2 E T1 T1 T3 T2 T3 T2 T3 E T3 T3 T2 T2
T1 T1 E T3 T1 E T2 T1 T3 T1 T1 T2 T2 T2 T1 T2
T3 E T3 T3 T3 T2 T1 T1 E E E T2 T1 T2 E T3
T1 E T3 T2 E E T3 E E E T3 T1 E T2 T2 E
LEVEL 2
T2 T2 T3 T2 T1 T1 T3 T3 T1 E T1 T2 T3 T2 E T1
T1 T3 T2 E T2 E T2 T2 T3 T1 T3 T1 E T3 T3 T3
T3 T3 T3 E T3 T3 E T3 T1 T1 T1 T2 T2 T3 T2 T1
T2 T3 T1 T2 T1 E E T2 T1 T1 T3 T2 E T1 T2 T3
T2 T2 T3 E T3 T3 T1 T1 E T3 T3 T2 T3 E T1 E
T2 T3 T3 T2 E E E T2 T1 T3 E T2 T1 T3 E T1
T3 T3 E T1 E T3 T1 T1 T3 T3 E T3 E T3 T1 T2
T2 E T1 E T1 T3 T1 T3 E T3 T1 E T1 T3 T1 E
T3 E E T1 T3 T2 T2 E T3 T2 T2 T1 E T1 T2 T2
T3 T3 E E T2 T1 T3 T1 E T3 E E E E T1 E
T3 E E T2 E E T2 T1 T2 T1 T1 T2 T3 T2 T3 T1
T3 E T2 T3 T1 T3 T3 T2 E T1 T2 T2 T2 T2 T1 E
T2 T3 T1 T3 T2 T3 T2 T3 T1 T1 T3 T3 T2 T2 E T3
T3 T3 T2 T3 T1 T3 T1 T1 T2 E E T3 E T1 T2 T2
T1 T2 T2 T2 T1 T1 T1 E T1 T2 T2 E T1 T3 T1 T3
E T2 E E T3 T3 E T1 T1 T2 E T1 T3 E T3 T3
LEVEL 3
T3 E T1 T3 T3 T3 T2 T3 T1 E T1 T1 T1 T2 E T1
T1 E E T2 T1 T3 T1 E T1 T3 T3 T3 T3 T2 T1 T1
T2 T3 T1 T2 T3 E T3 T1 T3 E T1 T3 T1 T2 E T3
T1 T2 T1 E T2 T1 T1 T3 T2 T2 T2 T2 T3 T3 E T1
T3 T2 T3 E T3 T1 T1 T2 E T2 E T3 T1 T1 E T1
T3 E T2 T3 T2 E E T2 T1 E T1 E T2 E T3 T3
E T2 T1 T3 E T1 E E T3 T1 T1 T3 T2 T1 E E
T1 T3 T2 T3 T1 T2 T1 E T2 T3 T3 T1 T3 T2 T3 T2
E T2 T1 T1 E T1 T2 T3 E T2 T1 T3 E T3 E T2
T3 E T1 T3 T2 E T1 T1 E T2 T3 T3 T3 T2 E E
T2 E E T2 T3 T3 T1 T2 T1 T2 T1 T3 T2 T2 T2 T2
T1 E T2 T3 T2 E T2 T2 T1 T2 T1 E T2 E T2 T3
T2 E T1 E E T1 T3 T1 E T1 E T1 T1 E T2 T2
T2 T3 T3 T1 E T1 T1 E T1 T3 T3 T3 E T2 T2 E
T2 T1 T1 T1 T2 E T1 T3 T3 T3 T2 E T3 E T2 E
E T2 T1 T2 E T1 T3 T1 T3 T1 T3 T2 T1 T1 E T3
LEVEL 4
E E E T1 T2 T1 T1 E T1 T3 T2 E E T1 T3 T2
T2 T2 E T3 T3 E E T1 T3 E E T1 T2 T3 T2 E
T2 T3 T3 T3 T3 E T2 T2 T1 T1 T1 T2 T3 E T2 T1
T2 T1 E T2 T3 T3 T3 E T1 T3 T2 T2 T2 T1 E T3
T3 T2 T3 E T2 E T2 E T2 T1 T1 T3 E T2 E T2
E T1 T1 T1 E E E T2 T1 T1 T3 T1 T2 E T3 T3
E T3 E T1 E T2 T2 T1 T2 E T3 T3 T3 T1 T3 T3
E T2 T1 T1 T2 T2 T3 E E T1 T3 T3 T3 T1 T2 E
T3 T3 T2 E T3 T2 E T1 T2 E E T2 T2 T1 E E
T3 E E T2 T3 T2 T1 T2 T3 T1 E T1 T3 T2 T1 T2
E T2 T1 T2 T3 T2 E T3 T3 T1 E T3 T3 T3 T3 T1
E T2 T1 T1 T1 T3 E T2 E T3 T1 T1 T2 T2 E E
T3 T3 T3 T2 E T1 T1 T3 T3 T3 E T3 T3 T3 T1 T1
T2 T1 T1 T2 E E E T3 T1 T3 T3 T1 E E T1 T2
T1 T2 T2 E T2 T1 T3 T3 T1 T1 T2 T3 T3 T1 T2 T1
T1 T2 T1 E T1 T3 T2 T1 T1 T2 E E T1 E T3 T1
LEVEL 5
T1 T1 T3 T1 T2 T3 E T2 T2 T1 T3 T2 T2 E T1 T1
T3 E T3 E T2 T1 T1 T3 T2 T3 T1 T1 T3 T2 T3 T1
T2 T3 T1 T2 T2 E T1 T3 E T2 T2 T2 T3 T3 T2 T2
T1 E T1 T1 T2 T1 T3 E T3 E T1 T1 T3 T3 T1 T3
T1 T1 T3 T2 T2 E E E E T2 E T1 T1 T2 E T2
E T2 E E T3 E T1 E E T1 T3 T2 E E T2 E
T2 T3 T3 E T3 T2 T2 T3 T1 E E E T3 T2 T3 T2
T1 T1 T1 T1 E T2 E E T1 T3 T2 T1 T3 E E E
T1 T1 E T1 T3 E E E T1 T1 T1 T3 T1 T2 T3 T3
T2 T2 T3 T3 E T2 T1 T3 T2 T1 T3 T1 T1 T2 T3 E
T3 T1 T3 T3 T3 E T1 T1 E T3 T2 E T2 T2 E T1
T1 T3 E T1 T2 T2 T2 T2 T3 T3 E E T3 T1 T1 T2
T1 E E T3 T2 T2 T1 T2 T2 T2 T2 T1 T3 T3 T3 E
T3 E E T2 T1 T3 T1 T2 E E T3 E T3 T2 T1 E
T1 T3 T1 T3 T2 E E T2 T2 T2 E T1 T2 E T1 T1
T2 T3 T1 T3 T1 T1 T2 T2 E T1 T2 T1 T2 E E T1
END OF MAZE

When I execute my program with the above file example I am getting this error :
Error in `./a.out': corrupted double-linked list: 0x0000000001174280 ***

Here is the gdb backtrace:
(gdb) backtrace
#0  0x00007ffff7531cc9 in __GI_raise (sig=sig@entry=6)
    at ../nptl/sysdeps/unix/sysv/linux/raise.c:56
#1  0x00007ffff75350d8 in __GI_abort () at abort.c:89
#2  0x00007ffff756e394 in __libc_message (do_abort=do_abort@entry=1,
    fmt=fmt@entry=0x7ffff767cb28 "*** Error in `%s': %s: 0x%s ***\n")
    at ../sysdeps/posix/libc_fatal.c:175
#3  0x00007ffff75790f7 in malloc_printerr (action=<optimized out>,
    str=0x7ffff7678bfc "corrupted double-linked list", ptr=<optimized out>)
    at malloc.c:4996
#4  0x00007ffff757a7a7 in _int_free (av=0x7ffff78b9760 <main_arena>, p=<optimized out>,
    have_lock=0) at malloc.c:3996
#5  0x00007ffff7b898be in std::basic_filebuf<char, std::char_traits<char> >::_M_destroy_internal_buffer() () from /usr/lib/x86_64-linux-gnu/libstdc++.so.6
#6  0x00007ffff7b89d47 in std::basic_filebuf<char, std::char_traits<char> >::close() ()
   from /usr/lib/x86_64-linux-gnu/libstdc++.so.6
#7  0x00007ffff7b8b3ad in std::basic_ifstream<char, std::char_traits<char> >::close() ()
   from /usr/lib/x86_64-linux-gnu/libstdc++.so.6
#8  0x00000000004018b9 in readFile(std::string) ()
#9  0x0000000000401a3d in main ()

I have see other post about this current of problem and some of them was about getting out of array indexes but I have test everything and I am always inside bounds. So is something wrong about the way I am reading the file?.
I hope this is not a silly question.
Thanks in advance.

A: You are going out of bounds:
stages = new string**[num_of_stages];
    for(int i = 0 ; i < N ; i ++) {
        stages[i] = new string*[N];

If num_of_stages < N you are accessing past the array.
You should use a std::vector instead of dealing with raw pointers and using new/delete yourself. It has an at function that does bounds checking.


text:
Q: How do i return compatibility level of just one database? I referenced this page: https://technet.microsoft.com/en-us/hh213141(v=sql.100)
Import-Module SqlServer

$as = New-Object Microsoft.AnalysisServices.Server
$as.connect("$Server")

$as.databases

Write-Host "Compatibility level ="$as.DefaultCompatibilityLevel

but this returns ALL databases back...
I want to specify just one database to get the compatibility level of...
I tried this,
$as.databases["$Database"]

the DB i am interested in has lvl 1103,
but it seems not to return the proper level, because its returning 1200...

A: I am not familiar with this API, but I see that the $as.Databases property is of type DatabaseCollection.  The DatabaseCollection class does have indexers that take either an Int32 or a String, like you're attempting to use with $as.databases["$Database"].
Note that the documentation for the String indexer says the parameter is an "identifier" for the database to be returned.  Also note that the Database class has separate properties for ID and Name, so there is a distinction between the two.  So, my suggestion is, make sure you are passing the ID, not the name, when you try to retrieve a Database instance that way.
Alternatively, if you do want to search by name you could use the FindByName method...
$as.Databases.FindByName($Database)

...or GetByName method...
$as.Databases.GetByName($Database)

...with the difference being that the former returns $null if no such database exists and the latter throws an exception.
If all else fails you could retrieve the desired database like this...
$as.Databases | Where-Object { $_.ID -eq $Database }

...or like this...
$as.Databases | Where-Object { $_.Name -eq $Database }

...depending on which property corresponds to the value in $Database.
Finally, in your code you are attempting to access a DefaultCompatibilityLevel property, which I don't see defined in the Database class.  There is, however, a CompatibilityLevel property.


text:
Q: What's the correct directory structure of SpringBoot project that uses static conten I am triying to understand why my SpringBoot webApp doesn't render in the browser. This is what my debug log says:
2017-08-04 14:54:24.760 DEBUG 23863 --- [tp1027569178-15] o.s.w.servlet.view.InternalResourceView  : Forwarding to resource [/views/tictactoe.html] in InternalResourceView 'tictactoe'
2017-08-04 14:54:24.762 DEBUG 23863 --- [tp1027569178-15] o.s.web.servlet.DispatcherServlet        : DispatcherServlet with name 'dispatcherServlet' processing GET request for [/views/tictactoe.html]
2017-08-04 14:54:24.766 DEBUG 23863 --- [tp1027569178-15] s.w.s.m.m.a.RequestMappingHandlerMapping : Looking up handler method for path /views/tictactoe.html
2017-08-04 14:54:24.768 DEBUG 23863 --- [tp1027569178-15] s.w.s.m.m.a.RequestMappingHandlerMapping : Did not find handler method for [/views/tictactoe.html]
2017-08-04 14:54:24.768 DEBUG 23863 --- [tp1027569178-15] o.s.w.s.handler.SimpleUrlHandlerMapping  : Matching patterns for request [/views/tictactoe.html] are [/**]
2017-08-04 14:54:24.770 DEBUG 23863 --- [tp1027569178-15] o.s.w.s.handler.SimpleUrlHandlerMapping  : URI Template variables for request [/views/tictactoe.html] are {}
2017-08-04 14:54:24.771 DEBUG 23863 --- [tp1027569178-15] o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapping [/views/tictactoe.html] to HandlerExecutionChain with handler [org.springframework.web.servlet.resource.DefaultServletHttpRequestHandler@47b52f9] and 1 interceptor
2017-08-04 14:54:24.771 DEBUG 23863 --- [tp1027569178-15] o.s.web.servlet.DispatcherServlet        : Last-Modified value for [/views/tictactoe.html] is: -1
2017-08-04 14:54:24.772 DEBUG 23863 --- [tp1027569178-15] o.s.web.servlet.DispatcherServlet        : DispatcherServlet with name 'dispatcherServlet' processing GET request for [/error]
2017-08-04 14:54:24.777 DEBUG 23863 --- [tp1027569178-15] s.w.s.m.m.a.RequestMappingHandlerMapping : Looking up handler method for path /error
2017-08-04 14:54:24.778 DEBUG 23863 --- [tp1027569178-15] s.w.s.m.m.a.RequestMappingHandlerMapping : Returning handler method [public org.springframework.web.servlet.ModelAndView org.springframework.boot.autoconfigure.web.BasicErrorController.errorHtml(javax.servlet.http.HttpServletRequest,javax.servlet.http.HttpServletResponse)]
2017-08-04 14:54:24.778 DEBUG 23863 --- [tp1027569178-15] o.s.web.servlet.DispatcherServlet        : Last-Modified value for [/error] is: -1
2017-08-04 14:54:24.784 DEBUG 23863 --- [tp1027569178-15] o.s.web.servlet.DispatcherServlet        : Rendering view [org.springframework.boot.autoconfigure.web.ErrorMvcAutoConfiguration$SpelView@41ee3720] in DispatcherServlet with name 'dispatcherServlet'
2017-08-04 14:54:24.795 DEBUG 23863 --- [tp1027569178-15] o.s.web.servlet.DispatcherServlet        : Successfully completed request
2017-08-04 14:54:24.802 DEBUG 23863 --- [tp1027569178-15] o.s.web.servlet.DispatcherServlet        : Null ModelAndView returned to DispatcherServlet with name 'dispatcherServlet': assuming HandlerAdapter completed request handling
2017-08-04 14:54:24.802 DEBUG 23863 --- [tp1027569178-15] o.s.web.servlet.DispatcherServlet        : Successfully completed request
2017-08-04 14:54:24.804 DEBUG 23863 --- [tp1027569178-15] o.s.web.servlet.DispatcherServlet        : Successfully completed request

I am not sure if my directory structure its correct. This is how it looks like:
enter code here

Maybe something wrong in my web page/angular?
<!DOCTYPE html>

    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"></meta>
    <title>TicTacToe</title>
    <link type="text/css" href="css/design.css" rel="stylesheet" />

PLAYER 1

    {{gameBoardDto.player1}}

{{gameBoardDto.topleft}}

{{gameBoardDto.top}}

{{gameBoardDto.topright}}

{{gameBoardDto.left}}

{{gameBoardDto.middle}}

{{gameBoardDto.right}}

{{gameBoardDto.bottomleft}}

{{gameBoardDto.bottom}}

{{gameBoardDto.bottomright}}

PLAYER 2

    {{gameBoardDto.player2}}

This is my Spring MVC conf:
package application;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.ViewResolver;
import org.springframework.web.servlet.config.annotation.DefaultServletHandlerConfigurer;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.view.InternalResourceViewResolver;

@Configuration
@EnableWebMvc
public class MvcConfiguration extends WebMvcConfigurerAdapter {
    //This allows html pages to be resolved
    @Bean
    public ViewResolver getViewResolver() {
        InternalResourceViewResolver resolver = new InternalResourceViewResolver();
        resolver.setPrefix("/views/");
        resolver.setSuffix(".html");
        return resolver;
    }
    /*
    This allows resources such as .js .css etc to be resolved
    Here an example of how the views are linked to the resources
    <link rel="stylesheet" type="text/css" href="resources/css/design.css"/>
     */
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/resources/**").addResourceLocations("/resources/");
    }

    @Override
    public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
        configurer.enable();
    }
}

Any idea how can I fix this issue? My browser just renders an error when I try to access:

update
I did as Andy Wilkinson suggested but didn't really work but I did some modifications and now I have the page being served but the javascript not working.
This is what I did:
 - I deleted the @EnableWebMvc from MvcConfiguration
 - Removed addResourceHandlers and configureDefaultServletHandling from MvcConfiguration
 - Removed ViewResolver @Bean method from MvcConfiguration
 - I added a dependency to compile group: 'org.springframework.boot', name: 'spring-boot-starter-thymeleaf'
 - I created a directory called templates and I moved the .html files there
Now the browser shows me this:
[![enter code here][3]][3]

This is what the log outputs:
017-08-06 13:58:54.397 DEBUG 17581 --- [qtp758944736-18] o.s.web.servlet.DispatcherServlet        : DispatcherServlet with name 'dispatcherServlet' processing GET request for [/error]
2017-08-06 13:58:54.402 DEBUG 17581 --- [qtp758944736-19] o.s.web.servlet.DispatcherServlet        : Last-Modified value for [/error] is: -1
2017-08-06 13:58:54.402 DEBUG 17581 --- [qtp758944736-18] s.w.s.m.m.a.RequestMappingHandlerMapping : Looking up handler method for path /error
2017-08-06 13:58:54.403 DEBUG 17581 --- [qtp758944736-18] s.w.s.m.m.a.RequestMappingHandlerMapping : Returning handler method [public org.springframework.http.ResponseEntity<java.util.Map<java.lang.String, java.lang.Object>> org.springframework.boot.autoconfigure.web.BasicErrorController.error(javax.servlet.http.HttpServletRequest)]
2017-08-06 13:58:54.403 DEBUG 17581 --- [qtp758944736-18] o.s.web.servlet.DispatcherServlet        : Last-Modified value for [/error] is: -1
2017-08-06 13:58:54.508 DEBUG 17581 --- [qtp758944736-18] o.s.w.s.m.m.a.HttpEntityMethodProcessor  : Written [{timestamp=Sun Aug 06 13:58:54 BST 2017, status=404, error=Not Found, message=Not Found, path=/resources/css/design.css}] as "application/json;charset=UTF-8" using [org.springframework.http.converter.json.MappingJackson2HttpMessageConverter@15adc6be]
2017-08-06 13:58:54.508 DEBUG 17581 --- [qtp758944736-18] o.s.web.servlet.DispatcherServlet        : Null ModelAndView returned to DispatcherServlet with name 'dispatcherServlet': assuming HandlerAdapter completed request handling
2017-08-06 13:58:54.508 DEBUG 17581 --- [qtp758944736-18] o.s.web.servlet.DispatcherServlet        : Successfully completed request
2017-08-06 13:58:54.509 DEBUG 17581 --- [qtp758944736-18] o.s.web.servlet.DispatcherServlet        : Null ModelAndView returned to DispatcherServlet with name 'dispatcherServlet': assuming HandlerAdapter completed request handling
2017-08-06 13:58:54.509 DEBUG 17581 --- [qtp758944736-18] o.s.web.servlet.DispatcherServlet        : Successfully completed request
2017-08-06 13:58:54.510 DEBUG 17581 --- [qtp758944736-19] o.s.w.s.m.m.a.HttpEntityMethodProcessor  : Written [{timestamp=Sun Aug 06 13:58:54 BST 2017, status=404, error=Not Found, message=Not Found, path=/resources/javascript/tictactoe.js}] as "application/json;charset=UTF-8" using [org.springframework.http.converter.json.MappingJackson2HttpMessageConverter@15adc6be]
2017-08-06 13:58:54.511 DEBUG 17581 --- [qtp758944736-19] o.s.web.servlet.DispatcherServlet        : Null ModelAndView returned to DispatcherServlet with name 'dispatcherServlet': assuming HandlerAdapter completed request handling
2017-08-06 13:58:54.511 DEBUG 17581 --- [qtp758944736-19] o.s.web.servlet.DispatcherServlet        : Successfully completed request
2017-08-06 13:58:54.511 DEBUG 17581 --- [qtp758944736-19] o.s.web.servlet.DispatcherServlet        : Null ModelAndView returned to DispatcherServlet with name 'dispatcherServlet': assuming HandlerAdapter completed request handling
2017-08-06 13:58:54.511 DEBUG 17581 --- [qtp758944736-19] o.s.web.servlet.DispatcherServlet        : Successfully completed request
2017-08-06 13:58:54.700 DEBUG 17581 --- [qtp758944736-21] o.s.web.servlet.DispatcherServlet        : DispatcherServlet with name 'dispatcherServlet' processing GET request for [/resources/javascript/tictactoe.js]
2017-08-06 13:58:54.701 DEBUG 17581 --- [qtp758944736-21] s.w.s.m.m.a.RequestMappingHandlerMapping : Looking up handler method for path /resources/javascript/tictactoe.js
2017-08-06 13:58:54.701 DEBUG 17581 --- [qtp758944736-21] s.w.s.m.m.a.RequestMappingHandlerMapping : Did not find handler method for [/resources/javascript/tictactoe.js]
2017-08-06 13:58:54.701 DEBUG 17581 --- [qtp758944736-21] o.s.w.s.handler.SimpleUrlHandlerMapping  : Matching patterns for request [/resources/javascript/tictactoe.js] are [/**]
2017-08-06 13:58:54.701 DEBUG 17581 --- [qtp758944736-21] o.s.w.s.handler.SimpleUrlHandlerMapping  : URI Template variables for request [/resources/javascript/tictactoe.js] are {}
2017-08-06 13:58:54.701 DEBUG 17581 --- [qtp758944736-21] o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapping [/resources/javascript/tictactoe.js] to HandlerExecutionChain with handler [ResourceHttpRequestHandler [locations=[ServletContext resource [/], class path resource [META-INF/resources/], class path resource [resources/], class path resource [static/], class path resource [public/]], resolvers=[org.springframework.web.servlet.resource.PathResourceResolver@453002f1]]] and 1 interceptor
2017-08-06 13:58:54.701 DEBUG 17581 --- [qtp758944736-21] o.s.web.servlet.DispatcherServlet        : Last-Modified value for [/resources/javascript/tictactoe.js] is: -1
2017-08-06 13:58:54.702 DEBUG 17581 --- [qtp758944736-21] o.s.web.servlet.DispatcherServlet        : DispatcherServlet with name 'dispatcherServlet' processing GET request for [/error]
2017-08-06 13:58:54.703 DEBUG 17581 --- [qtp758944736-21] s.w.s.m.m.a.RequestMappingHandlerMapping : Looking up handler method for path /error
2017-08-06 13:58:54.704 DEBUG 17581 --- [qtp758944736-21] s.w.s.m.m.a.RequestMappingHandlerMapping : Returning handler method [public org.springframework.http.ResponseEntity<java.util.Map<java.lang.String, java.lang.Object>> org.springframework.boot.autoconfigure.web.BasicErrorController.error(javax.servlet.http.HttpServletRequest)]
2017-08-06 13:58:54.704 DEBUG 17581 --- [qtp758944736-21] o.s.web.servlet.DispatcherServlet        : Last-Modified value for [/error] is: -1
2017-08-06 13:58:54.711 DEBUG 17581 --- [qtp758944736-21] o.s.w.s.m.m.a.HttpEntityMethodProcessor  : Written [{timestamp=Sun Aug 06 13:58:54 BST 2017, status=404, error=Not Found, message=Not Found, path=/resources/javascript/tictactoe.js}] as "application/json;charset=UTF-8" using [org.springframework.http.converter.json.MappingJackson2HttpMessageConverter@15adc6be]
2017-08-06 13:58:54.711 DEBUG 17581 --- [qtp758944736-21] o.s.web.servlet.DispatcherServlet        : Null ModelAndView returned to DispatcherServlet with name 'dispatcherServlet': assuming HandlerAdapter completed request handling
2017-08-06 13:58:54.711 DEBUG 17581 --- [qtp758944736-21] o.s.web.servlet.DispatcherServlet        : Successfully completed request
2017-08-06 13:58:54.711 DEBUG 17581 --- [qtp758944736-21] o.s.web.servlet.DispatcherServlet        : Null ModelAndView returned to DispatcherServlet with name 'dispatcherServlet': assuming HandlerAdapter completed request handling
2017-08-06 13:58:54.711 DEBUG 17581 --- [qtp758944736-21] o.s.web.servlet.DispatcherServlet        : Successfully completed request

This is the project if somebody wants to have a look:
https://github.com/SFRJ/tictactoe(Note: The version in github works when running with gradlew but not running from the .jar)

A: @EnableWebMvc switches off Spring Boot's auto-configuration of Spring MVC. That includes configuring it to serve static resources from classpath:static/ (which is where you resources in src/main/resources/static will end up. You also have a few other bits of configuration that Spring Boot will configure for you.
This should get you up an running:

*

*Remove @EnableWebMvc from MvcConfiguration

*Remove your overrides of addResourceHandlers and configureDefaultServletHandling from MvcConfiguration

*Remove your ViewResolver @Bean method from MvcConfiguration

*Assuming that its contents are the HTML in your question, move tictactoe.html into src/main/resources/static

A: Try moving the static folder to the project root, where it will be a sibling of src. Tomcat will then serve the contents using the default Servlet.


text:
Q: Python use of any(), which one matches? I'm writing a script to sort logfiles into more convenient data and to do so I use the any() function. I now know if part of a string matches any of the items in my list. Here's the function:
    def logfiles(self):

    look_for = ['network', 'skip', 'remove', 'jitter', 'loss', 'diff']
    analyze = self.open_logs('logfile-1.log')
    result = []

    for i in analyze:
        i = i.strip()

        if any(search in i for search in look_for):
            result.append(i)

    return result

This will tell me if part of the string i matches any of the items in my list look_for. However, is there a way to also detect which item matches? I haven't been able to find a built-in way for any() to do so and don't think there is one so how would one go about solving this? This particular snippet is a lot faster than a previous method I used (a simple loop basically) so I'd prefer to continue using this..
Thanks!

A: By using any, you're semantically discarding the return value. You don't care which one, you just care that if any of them is true.
I suggest using a explicit for, instead. It is clearer, and removes the complexity of a obscure next() with exception handling. Performance is the same:
for search in look_for:
    if search in i:
        break
else:
    print('Not found...')

A: You can use next((search for search in look_for if (search in i)), None) to get the first matching element.  It's still short-circuiting so it will stop searching after it finds a match.  If no match is found, the second argument will be returned.


text:
Q: google maps for Android, if run this code it will only latitude and longitude value but should not display any value google map coding
package com.project.friendtracker;

import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.view.Menu;
import android.widget.TextView;
import android.app.Dialog;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Calendar;
import java.text.SimpleDateFormat;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.common.ConnectionResult;

public class MainActivity1 extends FragmentActivity implements
LocationListener {

    GoogleMap googleMap;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main1);
        // Getting Google Play availability status
        int status = GooglePlayServicesUtil.isGooglePlayServicesAvailable(getBaseContext());

        // Showing status
        if(status!=ConnectionResult.SUCCESS){ // Google Play Services are not available

            int requestCode = 10;
            Dialog dialog = GooglePlayServicesUtil.getErrorDialog(status, this, requestCode);
            dialog.show();

        }else { // Google Play Services are available

            // Getting reference to the SupportMapFragment of activity_main.xml
            SupportMapFragment fm = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);

            // Getting GoogleMap object from the fragment
            googleMap = fm.getMap();

            // Enabling MyLocation Layer of Google Map
            googleMap.setMyLocationEnabled(true);

            // Getting LocationManager object from System Service LOCATION_SERVICE
            LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);

            // Creating a criteria object to retrieve provider
            Criteria criteria = new Criteria();

            // Getting the name of the best provider
            String provider = locationManager.getBestProvider(criteria, true);

            // Getting Current Location
            Location location = locationManager.getLastKnownLocation(provider);

            if(location!=null){
                onLocationChanged(location);
            }
            locationManager.requestLocationUpdates(provider, 900000, 300, this);
        }
    }
    @Override
    public void onLocationChanged(Location location) {

        TextView tvLocation = (TextView) findViewById(R.id.tv_location);

        // Getting latitude of the current location
        double latitude = location.getLatitude();

        // Getting longitude of the current location
        double longitude = location.getLongitude();

        // Creating a LatLng object for the current location
        LatLng latLng = new LatLng(latitude, longitude);

        // Showing the current location in Google Map
        googleMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));

        // Zoom in the Google Map
        googleMap.animateCamera(CameraUpdateFactory.zoomTo(15));

        // Setting latitude and longitude in the TextView tv_location
        tvLocation.setText("Latitude:" +  latitude  + ", Longitude:"+ longitude );

        try {
            Calendar c = Calendar.getInstance();
            SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String time = df.format(c.getTime());
            File file = new File("/sdcard/longlat.txt");
            FileWriter writer = new FileWriter(file,true);
            writer.append(time+"--"+"Latitude:" +  latitude  + ", Longitude:"+ longitude +"--");
            writer.flush();
            writer.close();
            }
            catch(IOException e)
            {
                 e.printStackTrace();
                 String importError = e.getMessage();
              //   Toast.makeText(getBaseContext(), importError,Toast.LENGTH_SHORT).show();
                }

    }

    @Override
    public void onProviderDisabled(String provider) {
        // TODO Auto-generated method stub
    }

    @Override
    public void onProviderEnabled(String provider) {
        // TODO Auto-generated method stub
    }

    @Override
    public void onStatusChanged(String provider, int status, Bundle extras) {
        // TODO Auto-generated method stub
    }

    //@Override     /*public boolean onCreateOptionsMenu(Menu menu) {       //
Inflate the menu; this adds items to the action bar if it is
present.        getMenuInflater().inflate(R.menu.main, menu);       return
true;   }*/

}

manifest.xml
<?xml version="1.0" encoding="utf-8"?> <manifest
xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.mymapexample1"
    android:versionCode="1"
    android:versionName="1.0">

    <uses-sdk
        android:minSdkVersion="11"
        android:targetSdkVersion="17" />

    <permission
        android:name="com.example.mymapexample1.permission.MAPS_RECEIVE"
        android:protectionLevel="signature"/>

    <uses-permission android:name="com.example.mymapexample1.permission.MAPS_RECEIVE"/>

    <uses-permission android:name="android.permission.INTERNET"/>
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
    <uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES"/>
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
    <uses-feature
        android:glEsVersion="0x00020000"
        android:required="true"/>    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.example.mymapexample1.MainActivity1"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <meta-data
            android:name="com.google.android.maps.v2.API_KEY"
            android:value="AIzaSyB6DYafop-H2vkJo6eq2qhqkeXjiBaeAqI"/>

    </application>

</manifest>

XML
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity" >

     <TextView
        android:id="@+id/tv_location"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentRight="true"
        android:layout_alignParentTop="true"
        android:text="TextView" />

    <fragment
        android:id="@+id/map"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_below="@id/tv_location"
        class="com.google.android.gms.maps.SupportMapFragment" />
     </RelativeLayout> but this code give map value,only give latitude and longtitude values.

A: Google had provided some new code for to get Location data. Try with it, it will work fantastic as I have did work with it.
Follow below link, it is very useful tutorial.
http://developer.android.com/training/location/retrieve-current.html


text:
Q: Photo deleted but reappears when taking a new photo The app I am making need to take pictures to send them to a server.
I need to take 6 photos at least. I have a recyclerView in which I am displaying a preview of my photo. It's working perfectly (I am using Picasso as photo library).
I need to be able to delete photos before sending them away (and consequently their preview). With a click on the preview, I remove it from my photo tab and update my recyclerview with notifyDataSetChanged().
The photo disappears.
When I take an other picture, I have its preview but the preview from the deleted picture is coming back.
If I delete three pictures and take a new one, I have the preview of the new one and the preview of the 3 deleted pictures.
Here's part of my adapter where I bind my view
@Override
    public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
        mImageView = holder.mPhotoIV;
        File mFile = new File(String.valueOf(Uri.parse(mListOfPhotos.get(position))));

        int width = mImageView.getLayoutParams().width;
        int height = mImageView.getLayoutParams().height;

        Picasso.get()
                .load(mFile)
                .resize(200, 200)
                .error(R.drawable.ic_no_photo_foreground)
                .into(mImageView, new com.squareup.picasso.Callback() {
                    @Override
                    public void onSuccess() {

                    }

                    @Override
                    public void onError(Exception e) {

                    }
                });
    }

Here part of my activity where I'm calling my adapter
        mTakePhotoFAB.setOnClickListener(view -> {
            mDir = new File(getExternalCacheDir(), "PhotosAuthentifier");
            boolean success = true;

            if (!mDir.exists()) {
                success = mDir.mkdir();
            }

            if (success) {
                File mFile = new File(mDir, new SimpleDateFormat("yyyyMMdd-HHmmss", Locale.getDefault()).format(new Date()) + ".jpg");

                mImageCapture.takePicture(mFile,
                        new ImageCapture.OnImageSavedListener() {
                            @Override
                            public void onImageSaved(@NonNull File file) {
                                mListOfPhotos.add(file.getAbsolutePath());
                                mNumberOfPhotoTV.setText(getResources().getString(R.string.minPhotos, mListOfPhotos.size()));

                                if (mListOfPhotos.size() >= 6) {
                                    mSendPhotoFAB.setVisibility(View.VISIBLE);
                                }

                                mAdapter = new CameraPhotoAdapter(mListOfPhotos, getBaseContext());
                                mRecyclerView.setAdapter(mAdapter);
                            }

                            @Override
                            public void onError(@NonNull ImageCapture.ImageCaptureError imageCaptureError, @NonNull String message, @Nullable Throwable cause) {
                                String mMessage = "Photo capture failed: " + message;
                                Toast.makeText(CameraActivity.this, mMessage, Toast.LENGTH_SHORT).show();

                                assert cause != null;
                                cause.printStackTrace();
                            }
                        });
            }

        });

Function (in my adapter) to remove picture
        protected void removePhoto(Context context, ArrayList<String> array, int position) {

            File mDir = new File(context.getExternalCacheDir(), "PhotosAuthentifier");
            File mFile = new File(array.get(position));

            if (mDir.exists()) {
                File[] mFilesIntoDir = mDir.listFiles();

                if (mFilesIntoDir == null) {
                    return;
                } else {
                    for (int i = 0; i < mFilesIntoDir.length; i++) {
                        if (mFilesIntoDir[i].getAbsolutePath().equals(mFile.getAbsolutePath())) {
                            boolean mSuccess = mFilesIntoDir[i].delete();

                            if (mSuccess) {
                                Picasso.get().invalidate(mFile.getAbsolutePath());
                                mListOfPhotos.remove(mFile.getAbsolutePath());
                                notifyDataSetChanged();
                            }

                        }
                    }
                }
            }
        }

I tried to invalidate Picasso cache but when I take a new picture, instead of the deleted picture reappearing I have the default behavior when I don't have a good url to upload (a black cross)
Could anyone help please :)?


text:
Q: Callback on a class template The idea behind this was to have a template class that could create a vector of an specified size and call back to a function when the vector has been completely filled.
I had a working example using a static function as the callback:
template<class T>
class Intellivector
{
public:
    Intellivector(unsigned int size, std::function<void(std::vector<std::pair<T,bool>>)> slot)
    {
        this->size = size;
        vt.resize(size);
        for (unsigned int i = 0; i<size;i++)
        {
            vt.push_back({T(0),false});
        }

        this->slot = slot;
    }
    void set(unsigned int pos,T value, bool valid = true)
    {
        vt.at(pos)= {value,valid};
        isReady();
    }
    bool isReady()
    {
        bool ready = true;
        for(unsigned int i=0;i<size;i++)
        {
            if(vt[i].second==false)
            {
                ready=false;
                printf("position %i not ready \n",i);
                break;
            }
        }
        if(ready && (this->slot != nullptr))
        {
            printf("CALL SLOT  \n");
            slot(vt);
        }
        return ready;
    }

    std::vector<std::pair<T,bool>> vt;

private:
    unsigned int size;
    std::function<void(std::vector<std::pair<T,bool>>)> slot =nullptr;
    //std::function<void(std::vector<std::pair<T,bool>>)> callback =nullptr;
};

Object is created like this for the static callback example:
 myvector = Intellivector<float>(3,MyClass::callbackFunction);

then myvector is used in another function which receives the values over an udp socket:
 hdglatlon.set(getIndexFromCan(message),vf[getIndexFromCan(message)]);

But then I tried to modify the code to allow passing a non-static function to the constructor to be used as callback, but can't manage to get it to work.
The following code fails at T{0}, as you would expect
    template<template<class> class A, typename B>
    Intellivector(unsigned int size, A<T> func_ptr, B obj_ptr)
    {
        this->size = size;
        vt.resize(size);
        for (unsigned int i = 0; i<size;i++)
        {
            vt.push_back({T(0),false});
        }

        this->slot=std::bind(func_ptr,obj_ptr);
    }

For this i tried to call the constructor like this:
myvector = Intellivector<float>(3,&MyClass::callbackFunction,this);

Also tried:
    template<typename B>
    Intellivector(unsigned int size, std::function<void(std::vector<std::pair<T,bool>>)>* slot, B obj_ptr)
    {
        this->size = size;
        vt.resize(size);
        for (unsigned int i = 0; i<size;i++)
        {
            vt.push_back({T(0),false});
        }

        this->slot=std::bind(slot,obj_ptr);
    }

But then I get an error of "error: no matching constructor for initialization of 'Intellivector'
note: candidate constructor template not viable: no known conversion from 'void (MyClass::*)(std::vector<std::pair<float, bool> >)' to 'std::function<void (std::vector<std::pair<float, bool> >)> *' for 2nd argument"
I'd appreciate any directions on how to get this to work, or any other alternatives to reach the same purpose. Thank you!

A: The high-level problem appears that you're reinventing the wheel.
What you should do is have a ctor that accepts a template argument pack, ignoring the type for a moment, and just std::bind the whole forwarded pack. Static method, free function, class method plus class pointer - you really don't care as long as you can bind it and store in a std::function.
For C++20 fancyness, you can add the std::invocable concept to produce a nicer error message.


text:
Q: Cannot read property 'orderBy' of undefined I want to sort an array by the length of adViews.
But I get the following error:

TypeError: Cannot read property 'orderBy' of undefined

How do I fix it?
  import _ from 'lodash';

  async maxViewsQuery(page = 1, relations = []): Promise<PaginatedResult> {
    const take = 14;
    const [data, total] = await this.adRepository.findAndCount({
      where: `("Ad__adViews"."id" IS NOT NULL)`,
      take,
      skip: (page - 1) * take,
      relations,
    });

    const sort = _.orderBy(data, (view) => view.adViews.length);

    return {
      data: sort.map((ad: Ad) => ({
        id: ad.id,
        title: ad.title,
        adViews: ad.adViews.length,
      })),
      meta: {
        total,
        page,
        lastPage: Math.ceil(total / take),
      },
    };
  }

A: Lodash doesn't use a default export, from the looks of it. Use
import * as _ from 'lodash';

and it should be fine.

A: it seems your lodash module is not imported.
try importing only the function you require
import { orderBy } from 'lodash';


text:
Q: How to extract values from Ansible gather facts and manipulate it? I want to extract some values from gather facts {{ ansible_default_ipv4 }}
In order to do so I ran ansible -i hosts all -m setup -a filter=ansible_default_ipv4
Then I get the output as:
"ansible_facts": {
        "ansible_default_ipv4": {
            "address": "10.6.97.221",
            "alias": "bond0",
            "broadcast": "10.6.97.255",
            "gateway": "10.6.97.1",
            "interface": "bond0",
            "macaddress": "e8:39:35:c0:38:a4",
            "mtu": 1500,
            "netmask": "255.255.255.0",
            "network": "10.6.97.0",
            "type": "ether"
        },
        "discovered_interpreter_python": "/usr/bin/python"
    },
    "changed": false

I want to extract the values from address + netmask + gateway and print them in that value to a file.
How can I achieve that?

A: I managed to achieve it by
- name: echo
  shell: echo "{{ ansible_hostname }} {{ ansible_default_ipv4.macaddress }} {{ ansible_default_ipv4.address }} {{ ansible_default_ipv4.netmask}} {{ ansible_default_ipv4.gateway}} {{ SERVER_ILO.stdout }}" >> /tmp/log.txt


text:
Q: How to get the information about all groupChats in which my bot is part of. MsBot framework for Teams (nodejs) When someone add my bot to their groupchat I am receiving a ConversationUpdate event and I am storing it for future reference. But storing all conversationUpdate events(which I will get when someone add my bot to their chat) of all groupChats has become a problematic. Is their any function for getting the Information about all groupChats that my bot has added to. Like we have a function for listing all Teams channels ex:- TeamsInfo.getChannels(context)
I would be thankful for any help

A: I'm not aware of any way to do this - the best I could suggest is something like listing conversation members of existing chats, on the graph beta endpoint (https://learn.microsoft.com/en-us/graph/api/conversationmember-list?view=graph-rest-beta&tabs=http). However, that would mean (a) it needs to returns bots as members of the chat, which I'm not sure it does (b) you'd need to basically query EVERY possible group chat in the organisation and (c) you'd need access rights to do that (e.g. application access). So, it certainly sounds like just storing the conversation id upfront on your own would be a better bet.
Recall that you can get the conversation id (if that's what you're looking for) from any event, not just conversationUpdate - even a regular message to your bot from a user in the chat will have the conversation id attached. Also, you've haven't stated what you  need the conversation id for. Presumably it's for pro-active messaging, but in that case remember to store the service url as well.


text:
Q: How to identify which processes are using the GPU? I have Nvidia GT750M in a laptop, with "display GPU activity icon in notification area" activated.
Right now all I have open are Google Chrome, Notepad++, and windows explorer, yet it says 2 processes are using the GPU.
How do I find out WHICH processes are using the GPU without installing extra software?

A:
tick the item shown on the nvidia control panel. then click the tray icon

A: You can use tool Sysinternals Process Explorer. You can download it from Microsoft website.
https://docs.microsoft.com/en-us/sysinternals/downloads/process-explorer
It kind of is extra software, but you download it from Microsoft website, not from some unknown company website. So it's more like extra update form windows. :)
After you run it go to "view -> select columns -> Process GPU" and check "GPU Usage".


text:
Q: Proof that the ring-sum expansion of a binary function is unique I am trying to understand a proof that the ring-sum expansion of a binary function is unique.  The proof is as follows.
Proof.  By induction on the number of inputs $n$.  For $n=1$, $f(x)=0$ or $f(x)=1$ or $f(x)=x$ or $f(x)=\bar{x}=1\bigoplus x$.  For all it can be seen that the ring sum expansion is unique.  Assume that for any arbitrary function of $n-1$ arguments, the RSE is unique.
Consider:
$f(x_1, ..., x_{n})=g(x_2,...,x_n)\bigoplus x_1h(x_2,...,x_n)$.  By induction both g and h have unique RSE's and therefore the RSE $g(x_2,...,x_n)\bigoplus xh(x2,...x_n)$ is also unique.
The only thing about this proof that I do not understand is where $f(x_1,...,x_n)=g(x_2,...,x_n)\bigoplus xh(x_2,...,x_n)$ came from.  Could anyone shed some light on that for me?  It could just be that its late and my brain is not working but I've been staring at it for a while now.

A: If I understand your description of the RSE correctly, they seem to have done something like this:
Write out $f(x_1,\dots,x_n)$ in disjunctive normal form and collect separately the terms in $x_1$ and the terms in $\overline{x_1}$: you get an expression of the form $x_1f_+(x_2,\dots,x_n)\lor \overline{x_1}f_{-}(x_2,\dots,x_n)$. Now do your replacement to get $$\begin{align*}
&x_1f_+(x_2,\dots,x_n)\bigoplus (1\bigoplus x_1)f_{-}(x_2,\dots,x_n) =\\
&x_1f_+(x_2,\dots,x_n)\bigoplus f_{-}(x_2,\dots,x_n) \bigoplus x_1f_{-}(x_2,\dots,x_n) =\\
&x_1\left(f_+(x_2,\dots,x_n)\bigoplus f_{-}(x_2,\dots,x_n)\right)\bigoplus f_{-}(x_2,\dots,x_n),
\end{align*}$$ and let $g = f_{-}$ and $h = f_+ \bigoplus f_{-}$.

A: The place in the proof that Deddryk was having difficulty with is missing the subscript $1$ on $x$ where it says
$g(x_2, \ldots, x_n) \oplus xh(x_2), \ldots, x_n)$, and when the subscript is inserted (as in his later remarks), the difficulty disappears as he discovered for himself.  But if the proof by induction is felt to be "sneaky", here is a different one which sets up a one-one correspondence between functions and RSEs.
There are $2^{2^n}$ different functions from $\{0,1\}^n$ to $\{0,1\}^n$.  Given the disjunctive normal form of such a function, there is a mechanical procedure for obtaining the RSE for the function.  Now, an RSE is a polynomial in $n$ variables $x_1, \ldots, x_n$, and any such polynomial can be
expressed as
$$f(x_1, \ldots, x_n) = a_0 \oplus \sum_i a_ix_i \oplus \sum_{i_1 \neq i_2}a_{i_1,i_2}x_{i_1}x_{i_2}
\oplus \ldots \oplus a_{1,\ldots, n}x_1\cdots x_n$$
where the $a$'s have value $0$ or $1$.  Since $x_i^2 = x_i$, each variable need have degree $1$ at most.  Now, since there is
$1 = \binom{n}{0}$ term of degree $0$, $n$ terms of degree $1$, $\binom{n}{2}$ terms of degree $2$, $\ldots$,  $\binom{n}{n} = 1$ terms of degree $n$, we see that there are
$\sum_{i=0}^n \binom{n}{i} = 2^n$ terms in the polynomial.  Since each term has a coefficient that has value $0$ or $1$, there are $2^{2^n}$ different polynomials.  Thus, there are exactly as many polynomials as there are functions.  Each polynomial is the RSE of some function whose disjunctive normal form can be obtained by a reverse mechanical procedure:  multiply each term of degree less than $n$ by terms of the form $(x_i \oplus \bar{x_i}) = 1$ where $x_i$ is a variable missing in that term
(e.g., if $n=4$, then the term $x_2x_4$ becomes
$(x_1\oplus \bar{x_1})x_2(x_3\oplus \bar{x_3})x_4$), multiply out to get terms of
degree $n$ in which each $x_i$ occurs once (with or without complementation), and replace all $\oplus$ by $\vee$.  So we have a one-one correspondence between functions and RSEs, and each function has a unique RSE.


text:
Q: Error applying image style dynamically, why? attrs.xml:
<declare-styleable name="AppTheme">
    <attr name="actionbarCompatLogoStyle" format="reference" />
</declare-styleable>

styles.xml:
<style name="Theme.MyApp" parent="android:style/Theme.Light">
    <item name="actionbarCompatLogoStyle">@style/ActionBarCompatLogo</item>
</style>

<style name="ActionBarCompatLogo">
    <item name="android:layout_width">30dp</item><!-- original image is huge -->
    <item name="android:layout_height">30dp</item>
    <item name="android:src">@drawable/app_logo</item>
</style>

Problem: if I use this, image dimensions won't work (huge image):
ImageButton logo = new ImageButton(context, null, R.attr.actionbarCompatLogoStyle);

If I use this, it works (tiny image, which is what I want):
<ImageView style="@style/ActionBarCompatLogo"></ImageView>

Why?

A: Any attribute prefixed with layout_ is part of a LayoutParams object. LayoutParams are special arguments to the parent view about how it should lay out the child view. The type of LayoutParams you set on a view is dependent on what type of ViewGroup you are adding it to. Each container view type can be different and so can the LayoutParams. layout_weight is specific to LinearLayout, layout_below is for RelativeLayout, etc. layout_width and layout_height are part of the base ViewGroup LayoutParams.
The takeaway from this is that LayoutParams are not parsed by the view's constructor, they're parsed by another step that your code above isn't doing. (The LayoutInflater involves the parent ViewGroup's generateLayoutParams method.)
Since LayoutParams are dependent on the intended parent of the View it's not recommended to put LayoutParams in styles. It mostly works when you are inflating views from layout XML but it has other implications similar to the edge case you've found here and requires you to be aware of them. For example, a style may specify layout_weight for a LinearLayout but if a view with that style is added to a RelativeLayout instead it will not behave as expected since RelativeLayout does not support layout_weight.

A: As far as I know it's not possible to apply styles to specific views programmatically, only via XML.
What you can do is to set a theme on your activity inside the onCreate() method. Consult this question: android dynamically change style at runtime


text:
Q: Подскажите как ограничить вывод элементов в php Часть кода отвечает за вызов тегов в списке статей. Как задать, чтобы выводилось к примеру максимум 5 тегов. Спасибо
<?php
$tags = K2ModelItem::getItemTags($item->id);
for ($i=0; $i<sizeof($tags); $i++) {
    $tags[$i]->link = JRoute::_(K2HelperRoute::getTagRoute($tags[$i]->name));
}
   $item->tags=$tags;     ?>
   <?php if(count($item->tags)): ?>

    <?php foreach ($item->tags as $tag): ?>

<a href="<?php echo $tag->link; ?>"><?php echo $tag->name; ?>

    <?php endforeach; ?>

A: В for-цикле следует поправить условие завершения цикла, добавив условие $i < 5
for ($i=0; $i < sizeof($tags) && $i < 5; $i++) {
  ...
}

Или модифицировать метод K2ModelItem::getItemTags(), так что бы он принимал дополнительный необязательный параметр, ограничивающий выборку
function getItemTags($id, $limit = null) {
  ...
}

Тогда можно будет, ограничивать любым количеством элементов
$tags = K2ModelItem::getItemTags($item->id, 5);

Затем в цикле foreach, добавьте выход по такому же условию
 <?php $counter = 0; ?>
 <?php foreach ($item->tags as $tag): ?>
   <?php if (++$counter > 5) break; ?>

<a href="<?php echo $tag->link; ?>"><?php echo $tag->name; ?>

    <?php endforeach; ?>


text:
Q: How to count unique results based on a particular properties within ng-options I'm working with AngularJS and trying to create a filter to search properties.
I've got a select box like this:
<select
    class="selectBox"
    multiple="multiple"
    ng-model="selectedSubArea"
    ng-options="property.SubArea as (property.SubArea + ' ('+ filtered.length +')') for property in filtered = (properties | unique:'SubArea') | orderBy:'SubArea'">
</select>

This is the unique function:
myApp.filter('unique', function() {
return function(input, key) {
    var unique = {};
    var uniqueList = [];
    for(var i = 0; i < input.length; i++){
        if(typeof unique[input[i][key]] == "undefined"){
            unique[input[i][key]] = "";
            uniqueList.push(input[i]);
        }
    }
    return uniqueList;
}; });

How can I get filtered.length to work?
Here's my JSFiddle

A: Here's a solution:
http://jsfiddle.net/odpw6c6q/16/
Create a filter that returns objects with count (number of times they were in the original list):
    myApp.filter('uniqueWithCount', function() {
        return function(input, key) {
            var unique = {};
            var uniqueList = [];
            var obj, val;
            for(var i = 0; i < input.length; i++){
                val = input[i][key];
                obj = unique[val];
                if (!obj) {
                    obj = unique[val] = {data: input[i], count: 0};
                    uniqueList.push(obj);
                }
                obj.count++;
            }
            return uniqueList;
        };
    });

Use that filter in your HTML:
<select class="form-control" multiple="multiple" ng-model="selectedSubArea"
ng-options="property.SubArea as (item.data.SubArea + ' ('+ item.count +')') for item in filtered = (properties | uniqueWithCount:'SubArea') | orderBy:'SubArea'"></select>


text:
Q: Image is not displayed in a Modal Pop Window using javascript and asp.net Basically, I am trying to develop a ASPX page where the user will be able to upload an image, then display it in a modal pop window and crop it if required.
If I display the image outside of pop window it works completely fine, but if I try to display inside of the pop window the image is not displayed. However, I have noticed if I keep the image there and remove <asp:Image ID="imgCrop" from the javascript below, the image is displayed and off course it will not allow me to crop it.
Here is the javacripts I use to display the modal popwindow and set the crop settings:

                <title>Crop Image</title>
                <link href="Styles/jquery.Jcrop.css" rel="stylesheet" type="text/css" />

                <link href="styles/style.css" rel="stylesheet" type="text/css" />

here is the definition of modal pop window and where I want to see the image to be cropped in <asp:Image ID="imgCrop"
            <input class="button_popup" id="btnShowModalDiv" onclick="$('#divSimplePopup').showModal(); return false;" type="submit" value="Show Modal Div"/>

                            Simple Popup Header

                            <asp:Panel ID="pnlCrop" runat="server" Visible="false">
                                <asp:Image ID="imgCrop" runat="server" />

                                <asp:HiddenField ID="X" runat="server" />
                                <asp:HiddenField ID="Y" runat="server" />
                                <asp:HiddenField ID="W" runat="server" />
                                <asp:HiddenField ID="H" runat="server" />
                                <asp:Button ID="btnCrop" runat="server" Text="Crop" OnClick="btnCrop_Click" />
                           </asp:Panel>

                                <input class="button_popup" id="btnOK" style="width: 40px;" type="submit" value="OK"/>
                                <input class="button_popup" id="btnCancel" onclick="$('#divSimplePopup').hideModal(); return false;" type="submit" value="Cancel"/>

source code and references:
http://geekswithblogs.net/vladimirl/archive/2009/12/20/jquery-simple-modal-plugin.aspx
http://supershope.com/tuvianblog/cropimage.zip
Does anyone has any hint?

A: <asp:Image ID="imgCrop" runat="server" />

your image have runat="server" so it may have different ID when it will be rendered.
so you need to have following in your page.
jQuery(document).ready(function ()
 {
   jQuery('#<%= imgCrop.ClientID %>').Jcrop({
     onSelect: storeCoords
   });
 });

Apart from that you've visible="false" on your panel as shown in below code:
  <asp:Panel ID="pnlCrop" runat="server" Visible="false">

So whole panel won't be rendered and your jquery code won't work. Rather use style="display:none", panel will get rendered and so the image will be and your plugin will work.


text:
Q: Distinct function somehow not giving back all types Feel free to check it on my latest project: http://arda-maps.org:2480 arda arda as login.
Now check select distinct(type) from Location
Here you get 8 records (River,Lake,Region,City,Island,House,Mountain,Hill). But actually there are way more...
To show you that the distinct somehow is not giving back all distinct we search for one specific vertex with another type:
select * from Location where name = "Citadel of Gondor"
So am I using distinct in a wrong way. Or what could be the reason for the incomplete result list?

A: Indeed, the order the query parts are applied in the result set is not very obvious. You typed:
select distinct(type) from Location
and the orient studio applies a limit 20 (unless you change that or include a different limit in your query). So the query that finally runs is
select distinct(type) from Location limit 20
Now, this could mean one of the two:

*

*Find at most 20 locations and give me their distinct types

*Find at most 20 distinct types of all locations

Obviously, what you expect is the 2nd and what happens is the 1st. The solution is to have inner queries so limit will explicitly apply on the outer query:
select from (select distinct(type) from Location) limit 20
This now clearly says, find me the distinct types of all locations and return me at most 20 (which is the same as (2))

A: Weird. But if you try:
select distinct(type) from Location limit -1

you'll have all 64 distinct entrances.


text:
Q: Junit DirtiesContext is not rollbacking my transcation using JPA I have create delete method in my repo class and did use @Transactional at class level,
When I call deletebyID its deleting that id. in Junit I did use DirtiesContext it should roll back the transaction, but due to @Transactional at class level, it commuted my delete (It did what suppose to do),
now my juint not able to rollback that transaction.
How to overcome this issue?
@Repository
@Transactional
public class CourseRepository {

@Autowired
EntityManager em;

public Course findById(Long id) {
    return em.find(Course.class, id);
}

public Course deleteById(Long id) {
    Course course= em.find(Course.class, id);
    em.remove(course);
    return course;
  }
}

In my Junit
@Autowired
CourseRepository courseRepo;
@Test
@DirtiesContext
public void deleteById_basicTest() {
    courseRepo.deleteById(100001L);
    assertNull(courseRepo.findById(100001L));
}

A: You can use @Transactional for each test case. It will rollbacks transactions.
It works.
@Test
@Transactional
public void deleteById_basicTest() {
    courseRepo.deleteById(100001L);
    assertNull(courseRepo.findById(100001L));
}


text:
Q: Adding legend (ggplot) doesn't work I feel like I am asking a totally silly question, but I can't force ggplot to show the legend for lines colours.
The thing is that I have two data frames with the same data, just the first data.frame represents new data (plus additional numbers) and the second represents the old data. I am trying to compare new and old data, thus to understand which is which I have to see the legend. I have tried to use scale_colour_manual, but it still doesn't appear.
I have read a number of various answers on similar questions and non of them worked or led to a better. You can see a simple example of my problem below:
rm(list = ls())
library(ggplot2)

xnew<-3:10
y<-5:12
xold<-4:11
years<-2000:2007
xfact<-rep("x", times=8)
yfact<-rep("y", times=8)

Newdata<-data.frame(indicator=c(xfact,yfact),Years=c(years,years), data=c(xnew,y))
Olddata<-data.frame(indicator=xfact,Years=c(years), data=xold)

graph<-ggplot(mapping=aes(Years, data, group=1)) +
geom_line(,Newdata[Newdata=="x",], size=1.5, colour="lightblue")+
geom_line(,Olddata[Olddata=="x",], size=1.5, colour="orange")+
ggtitle("OLD vs NEW")+
scale_colour_manual(name="Legend", values=c("New"="lightblue", "Old"="orange"))

the result is without the legend.
Thanks for all the help I have already found on this website and thank you in advance for helping to solve this problem.

A: Legends are created in ggplot by mapping aesthetics to a single variable. Your mistake is that you're trying to set colors manually in each layer.
Newdata$type <- "New"
Olddata$type <- "Old"

all_data <- rbind(Newdata,Olddata)

ggplot(data = all_data[all_data$indicator == 'x',],aes(x = Years,y = data,colour = type)) +
    geom_line() +
    ggtitle("OLD vs NEW") +
    scale_colour_manual(name="Legend", values=c("New"="lightblue", "Old"="orange"))

There are countless examples illustrating this basic technique in ggplot here.


text:
Q: How to map a deeply nested object in Rxjs i'm getting started with rxjs in angular2.  many of the examples i've seen use simple objects when mapping an http response to an observable.
 this.http.get('/app/shared/data/raw-tasks.json')
        .map(response => response.json())
        .map(stream => stream.map(res => new TaskModel(res.name, res.deadline, res.timeRequired)))

but how do i map a more complicated response like nested objects and nested arrays?

A: Once you get the json from the response you can do with it whatever you want. Just add another map function and parse it somewhere else (make sure you return parsed value):
 this.http.get('/app/shared/data/raw-tasks.json')
   .map(response => response.json())
   .map(stream => complicatedParser(stream))

 // somewhere in your code...
 complicatedPatser(stream) {
    return stream
      .map(x => x)
      .filter(x => true)
      .reduce(....)
 }

Observables don't care what they emit, so there's little difference between simple string or complicated nested objects. If you know how to handle basic types, object and/or array response, you know pretty much everything (;


text:
Q: CoffeeScript: how to slice a string and get only the last 2 characters I'm getting started with CoffeeScript and I got stucked, but couldn't figure out how to trim and get the last characters of a string. How can I convert this into coffee?
if (m.length > 2) {
    m = m.slice(-2);
}

A: if m.length > 2
  m = m.slice(-2)

This is the code.
You can convert any of your existing javascript code to coffee script using the free tool http://js2.coffee/

A: The correct syntax is
string.slice( beginslice [, endSlice] )

So,  for your example, try m.slice -2.


text:
Q: PHP/MySQL - checkboxes of data from db, submission of 2 parametres So, i'm struggling with that for a long time.
I need to make a list with checkboxes from DB like [checkbox of car id and value][brand][model]. Then, we need to choose two cars from list, and two cars are chosen - we should block all unchecked till checked won't be unchecked. Then, we need to sumbit into list.php page two car id of chosen cars. And submission won't be done if one or no car are chosen.
I don get it how to realise. Anybody knows how to solve this?
And yes: jquery is desirable, ajax is not ('cos i never worked with that and i don't think i need it here because i need just to transmit parametres to another page)
My code
<?php
$hostname = "localhost";
$username = "root";
$password = "";
$dbname = "jdmdb";

$con = mysqli_connect($hostname, $username, $password) or die(mysqli_error());
$con->query("SET NAMES cp1251");
$con->select_db($dbname);
$result = mysqli_query($con, 'select * from cars') or die(mysqli_error($con));
$rows = $result->fetch_all(MYSQLI_ASSOC);
?>

            <meta http-equiv="Content-Tуpe" сontent="tехt/html; charset=utf-8">
        <title>JDM Database</title>

        <form name=carlist method=post action="list.php">
        <?
            foreach ($rows as $row) {
                echo '<input type=checkbox name="car_short" value="'.$row['car_short'].' id='.$row['car_short'].'"> '.$row['brand'].' '.$row['model'].' '.$row['spec'].' ('.$row['year'].')
';
            }
            $res = count($rows);
            echo '<input type=submit value=123>';
        ?>
        </form>
<?
        mysqli_close($con);
    ?>

A: You can send array of data to list.php
For that you should use following syntax
echo '<input type=checkbox name="car_short[]" value="'.$row['car_short'].' id='.$row['car_short'].'"> '.$row['brand'].' '.$row['model'].' '.$row['spec'].' ('.$row['year'].')
';

This will send send $_POST['car_short'] as array of two selected values. And if you want to check number of selected cars after submission then use
if(count($_POST['car_short'])<2){// place error;}

Else you can use jquery to check how many checkboxes are selected else return false. For that change the form code like this
<form method=post action="list.php" onSubmit="check();">

and check function will be
function check(){
   var n = $("input:checkbox:checked").length;
   return n>1;
}

Note: Please note the method the exact code may not work properly since i misspelled variables


text:
Q: Is there any general method to solve a Second order ODE with variable coefficient of the form $a(x)y''(x)+b(x)y'(x)+c(x)y(x)=0$ Is there any general method to solve a Second order ODE with variable coefficient of the form $a(x)y''(x)+b(x)y'(x)+c(x)y(x)=0$

A: The equation you have is a second order linear homogeneous ODE.
It can be rewritten as
$$ y''(x) + b_1(x)\, y'(x) + c_1(x) y(x) = 0, $$
where
$b_1 = b/a$ and $c_1 = c/a$ with $a \neq 0$.
A general solution of second order linear homogeneous ODE can be obtained in multiple ways, including integration and series expansion.
I propose to read this article to get an overview of possible ways to solve it.

A: In order to successfully approach the problem submitted, the 'Reduction of Order' technique should prove quite useful.  Here is a short video that will demonstrate how to solve such a problem with this method:  https://www.youtube.com/watch?v=oQSFW8BIrY0&t=627s

A: The answer is NO.
Even an equation as simple as Airy's equation:
$$
y''-xy=0,
$$
can NOT be solved. Meaning, its solutions can not be expressed in closed form, as expressions of simple functions, their compositions and integrals.
The only method which always produces an answer is the method of power series, which works if all the coefficients are expressible as power series (i.e., real analytic).


text:
Q: Cannot extend the size of a partition: I have a problem while trying to extend the size of one of the partitions that i found on a old VM on the cloud, this is the output of the lsblk so you can have an idea on it:
enter code here
root@Desktop:~# lsblk
NAME                   MAJ:MIN RM  SIZE RO TYPE MOUNTPOINT
sda                      8:0    0   20G  0 disk
├─sda1                   8:1    0  1,9G  0 part /
├─sda2                   8:2    0    1K  0 part
└─sda5                   8:5    0 18,1G  0 part
  ├─vg_root-lv_swap    254:0    0  1,9G  0 lvm  [SWAP]
  ├─vg_root-lv_usr     254:1    0  4,8G  0 lvm  /usr
  ├─vg_root-lv_home    254:2    0  244M  0 lvm  /home
  ├─vg_root-lv_opt     254:3    0  488M  0 lvm  /opt
  ├─vg_root-lv_XXXXXXX 254:4    0  244M  0 lvm  /XXXXXXX
  ├─vg_root-lv_tmp     254:5    0  1,4G  0 lvm  /tmp
  ├─vg_root-lv_var     254:6    0  976M  0 lvm  /var
  └─vg_root-lv_varlog  254:7    0  976M  0 lvm  /var/log
sdb                      8:16   0   20G  0 disk
sdc                      8:32   0   20G  0 disk
sr0                     11:0    1 1024M  0 rom

The output of df -h is as follow:
root@Desktop# df -h
file systel                    Size      Used  Free  Used%  Monted on
/dev/sda1                        1,9G    800M  976M  46%    /
udev                              10M       0   10M   0%    /dev
tmpfs                            1,6G     77M  1,5G   5%    /run
/dev/dm-1                        4,6G    654M  3,7G  15%    /usr
tmpfs                            4,0G       0  4,0G   0%    /dev/shm
tmpfs                            5,0M       0  5,0M   0%    /run/lock
tmpfs                            4,0G       0  4,0G   0%    /sys/fs/YYYYYY
/dev/mapper/vg_root-lv_XXXXXXXX  233M    2,1M  215M   1%    /XXXXXXX
/dev/mapper/vg_root-lv_opt       465M     72M  365M  17%    /opt
/dev/mapper/vg_root-lv_home      233M    2,1M  215M   1%    /home
/dev/mapper/vg_root-lv_tmp       1,4G    2,2M  1,3G   1%    /tmp
[[/dev/mapper/vg_root-lv_var       945M    928M     0 100%    /var]]
/dev/mapper/vg_root-lv_varlog    945M     29M  852M   4%    /var/log

The partition between the  [[ ]] is the one i am aiming to extend ? is there any way to shrink the other partitions and make it bigger ?

A: You have to unmount the filesystems before you do this e.g. by switching to emergency mode (or booting into it):
umount /var/log
umount /var/
lvresize --resizefs --size -500G vg_root/lv_var
lvresize --resizefs --size +500G vg_root/lv_varlog


text:
Q: OCR & OpenCV: Difference between two frames on high resolution images According to this post OCR: Difference between two frames, I now know how to find pixel differences between two images with OpenCV.
I would like to improve this solution and use it with high resolution images (from a video) with rich content. The example above is not applicable with big images because the process is to slow (too much differences found, the "findCountours method" fills the tab with 250k elements which takes a huge time to process).
My application uses a RLE decoder to decode the compressed frames of the video. Once the frame is decoded, I would like to compare the current frame with the previous one in order to store the differences between the two frames in a "Mat" tab for example.
The goal of all of this is to be able to perform an analysis on the different pixels and to check if there is any latin character. This allows me to reduce the amount of pixels to analyze and to save precious time.
If anyone has other ideas instead of this one to perform such operations, feel free to propose it please.
Thank you for your help.
EDIT 1:
Example of two high resolution images of a computer screen. These are for the moment the perfect example of what I'm trying to analyse. As we can see there is just a window as difference between the two big images and I would like to analyze just the new "Challenge" window for any character.

EDIT 2:
I'm trying to tune the algorithm depending on the data analyzed. Typically on the two following pictures I only get the green lines as differences and no text at all (which is what is the most interesting). I'm trying to understand better how things work for this.
1st image:

2nd image:

3rd image:

As you can see I only have those green lines and never the text (at the best I can have just ONE letter when decreasing the countours[i].size())

A: In addition to the post you mentioned, you need to:

*

*When you binarize the mask, use a threshold higher then 0 to remove small differences.

*Remove some noise. You can find all connected components, and remove smaller ones.

*Find the area of the bigger connected components. You can use convexHull and fillConvexPoly to get the mask of the different objects on screen

*Copy the second image to a new image, with the given mask.

The result will look like:

Code:
#include <opencv2/opencv.hpp>
#include <vector>
using namespace std;
using namespace cv;

int main()
{
    Mat3b img1 = imread("path_to_image_1");
    Mat3b img2 = imread("path_to_image_2");

    Mat3b diff;
    absdiff(img1, img2, diff);

    // Split each channel
    vector<Mat1b> masks;
    split(diff, masks);

    // Create a black mask
    Mat1b mask(diff.rows, diff.cols, uchar(0));

    // OR with each channel of the N channels mask
    for (int i = 0; i < masks.size(); ++i)
    {
        mask |= masks[i];
    }

    // Binarize mask
    mask = mask > 100;

    // Results images
    vector<Mat3b> difference_images;

    // Remove small blobs
    //Mat kernel = getStructuringElement(MORPH_RECT, Size(5,5));
    //morphologyEx(mask, mask, MORPH_OPEN, kernel);

    // Find connected components
    vector<vector<Point>> contours;
    findContours(mask.clone(), contours, CV_RETR_EXTERNAL, CHAIN_APPROX_NONE);

    for (int i = 0; i < contours.size(); ++i)
    {
        if (contours[i].size() > 1000)
        {
            Mat1b mm(mask.rows, mask.cols, uchar(0));

            vector<Point> hull;
            convexHull(contours[i], hull);

            fillConvexPoly(mm, hull, Scalar(255));

            Mat3b difference_img(img2.rows, img2.cols, Vec3b(0,0,0));
            img2.copyTo(difference_img, mm);

            difference_images.push_back(difference_img.clone());
        }
    }

    return 0;
}