text:
Q: Nginx - wordpress in a subdirectory, what data should be passed? I've tried so many different things. The point I'm at right now is this:
location ^~ /wordpress {
    alias /var/www/example.com/wordpress;
    index index.php index.html index.htm;
    try_files $uri $uri/ /wordpress/index.php;

    location ~ \.php$ {
        include fastcgi_params;
        fastcgi_pass 127.0.0.1:9000;
        fastcgi_split_path_info ^(/wordpress)(/.*)$;
        fastcgi_param SCRIPT_FILENAME /var/www/example.com/wordpress/index.php;
        fastcgi_param PATH_INFO $fastcgi_path_info;
    }
}

Right now, all resources as far as I can tell (images, etc) are loading correctly. And http://www.example.com/wordpress loads wordpress, but a page that says "page not found". (Wordpress is in use for this though). If I try any post urls I get the same result, "page not found". So I know the problem is that wordpress isn't obtaining the data about the path or something. Another potential problem is that if I run example.com/wp-admin.php then it will still run index.php.
What data needs to be passed? What may be going wrong here?

A: Since your location alias end match, you should just use root.  Also, not everything is routed through index.php on wordpress afaik.  Also, unless you know you need path info, you probably dont.  I think you want something like:
location @wp {
  rewrite ^/wordpress(.*) /wordpress/index.php?q=$1;
}

location ^~ /wordpress {
    root /var/www/example.com;
    index index.php index.html index.htm;
    try_files $uri $uri/ @wp;

    location ~ \.php$ {
        include fastcgi_params;
        fastcgi_param SCRIPT_FILENAME $request_filename;
        fastcgi_pass 127.0.0.1:9000;
    }
}

or if you really do need path info (urls look like /wordpress/index.php/foo/bar):
location ^~ /wordpress {
    root /var/www/example.com;
    index index.php index.html index.htm;
    try_files $uri $uri/ /wordpress/index.php;

    location ~ \.php {
        fastcgi_split_path_info ^(.*\.php)(.*)$;
        include fastcgi_params;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        fastcgi_param PATH_INFO $fastcgi_path_info;
        fastcgi_param PATH_TRANSLATED $document_root$fastcgi_path_info;
        fastcgi_pass 127.0.0.1:9000;
    }
}

EDIT: Updated first server{} to strip initial /wordpress from uri and pass remainder as q param
EDIT2: Named locations are only valid at server level

A: I had the same problem and this is what fixed it for me:

*

*Open the NGINX configuration file for your site. Inside of the server block, add the path to your root directory and set the priority order for files:
root /mnt/www/www.domainname.com;
index  index.php index.html index.htm;

*Create an empty location block before all your other location blocks:
location /latest {
# Nothing in here; this is to avoid redirecting for this location
}

*Commend out the root directory in your location / block and add the redirection so it looks like this:
location / {
# root   /mnt/www/www.domainname.com;
index  index.php index.html index.htm;
rewrite ^/(.*)$ http://www.domainname.com/latest/$1 redirect;
}

*Make sure that your location ~ .php$ block points its root to
root /mnt/www/www.domainname.com;

This fixed it for me.

A: Dude, this will work for for a wordpress blog in a subdirectory of the magento root folder!
server {
    listen 80;
    server_name my-site.co.uk;
    rewrite / $scheme://www.$host$request_uri permanent; ## Forcibly prepend a www
}

server {
    listen 80 default;
    client_max_body_size 8M;
    ## SSL directives might go here
    server_name www.my-site.co.uk; ## Domain is here twice so server_name_in_redirect will favour the www
    root /var/www/my-site/magento;

    location / {
        index index.html index.php; ## Allow a static html file to be shown first
       try_files $uri $uri/ @handler; ## If missing pass the URI to Magento's front handler
       expires 30d; ## Assume all files are cachable
    }

    location  /wordpress {
              index index.php index.html index.htm;
             try_files $uri $uri/ /wordpress/index.php;
             }

    ## These locations would be hidden by .htaccess normally
    location ^~ /app/                { deny all; }
    location ^~ /includes/           { deny all; }
    location ^~ /lib/                { deny all; }
    location ^~ /media/downloadable/ { deny all; }
    location ^~ /pkginfo/            { deny all; }
    location ^~ /report/config.xml   { deny all; }
    location ^~ /var/                { deny all; }

    location /var/export/ { ## Allow admins only to view export folder
        auth_basic           "Restricted"; ## Message shown in login window
        auth_basic_user_file htpasswd; ## See /etc/nginx/htpassword
        autoindex            on;
    }

    location  /. { ## Disable .htaccess and other hidden files
        return 404;
    }

    location @handler { ## Magento uses a common front handler
        rewrite / /index.php;
    }

    location ~ .php/ { ## Forward paths like /js/index.php/x.js to relevant handler
        rewrite ^(.*.php)/ $1 last;
    }

    location ~ .php$ { ## Execute PHP scripts
        if (!-e $request_filename) { rewrite / /index.php last; } ## Catch 404s that try_files miss

        expires        off; ## Do not cache dynamic content
        fastcgi_pass   unix:/var/run/php5-fpm.sock;
        fastcgi_param  HTTPS $fastcgi_https;
        fastcgi_param  SCRIPT_FILENAME  $document_root$fastcgi_script_name;
        fastcgi_param  MAGE_RUN_CODE default; ## Store code is defined in administration > Configuration > Manage Stores
        fastcgi_param  MAGE_RUN_TYPE store;
        include        fastcgi_params; ## See /etc/nginx/fastcgi_params
    }
}


text:
Q: How to define the following matrix? How to define the following matrix?

A: It's often easiest to construct matrices like this using SparseArray and Normal:
\[CapitalUpsilon][k_, a_] = (k + 1)^(a + 1) - 2 k^(a + 1) + (k - 1)^(a + 1);
mat[n_, a_] := 1/(n^a Gamma[a + 2]) Normal[
      SparseArray[{{i_, i_} -> 1,
      {i_, j_} /; j > i -> \[CapitalUpsilon][j - i, a]},
      {n, n}]]

In words, SparseArray creates an $n \times n$ matrix, sets all elements of the matrix of the form $M_{ii}$ to 1, and sets all elements of the form $M_{ij}$ for which $j>i$ equal to $\Upsilon_{j-i}$.
mat[5,2] // MatrixForm

redpajama_set_name: RedPajamaStackExchange


text:
Q: Concatenate vector elements in groups What is the most elegant way of converting list1 to list2, and also list2 to list1?
list1<- c('a','b','c','d','e','f','g','h','i')
list2<- c('abc','def','ghi')

i.e: contactenate elements in groups of three.
thanks :D

A: Let list1 <- letters[1:10] (to show how it works when the length of the vector is not a multiple of 3). Then, try this:
list1 to list2
# method 1 (seems to be the fastest so far,
# my suspicions about loop being slower were wrong)
list2 <- sapply(split(list1, (seq_along(list1)-1) %/% 3), paste, collapse = "")
# alternatively as @flodel mentions
list2 <- tapply(list1, (seq_along(list1)-1) %/% 3, paste, collapse = "")

The tapply version runs at a similar time as sapply+split (benchmarking not shown).
Going one step further, using @JoshOBrien's idea in this post
# method 2
pattern <- "(?<=[[:alnum:]]{3})(?=[[:alnum:]])"
strsplit(paste(list1, collapse=""), pattern, perl=TRUE)[[1]]
# [1] "abc" "def" "ghi" "j"

And if you want to get the last part concatenated to the last-but-one (here the j to ghi) then, do:
pattern <- "(?<=[[:alnum:]]{3})(?=[[:alnum:]]{3})"
strsplit(paste(list1, collapse=""), pattern, perl=TRUE)[[1]]
# [1] "abc"  "def"  "ghij"

list2 to list1
unlist(strsplit(list2, ""), use.names=FALSE)
#  [1] "a" "b" "c" "d" "e" "f" "g" "h" "i" "j"

Here's a benchmarking of method1, method2 and eddi's:
data:
list1 <- sample(letters, 1e5, replace=TRUE)

functions:
arun <- function() {
    pattern <- "(?<=[[:alnum:]]{3})(?=[[:alnum:]])"
    strsplit(paste(list1, collapse=""), pattern, perl=TRUE)[[1]]
}

arun2 <- function() {
    unname(sapply(split(list1, (seq_along(list1)-1) %/% 3), paste, collapse = ""))
}

eddi <- function() {
    substring(paste(list1, collapse = ""),
          seq(1, length(list1), 3),
          pmin(seq(3, length(list1)+2, 3), length(list1)))
}

benchmarking:
require(microbenchmark)
microbenchmark(t1 <- arun(), t2 <- eddi(), t3 <- arun2(), times=10)
identical(t1, t2) # TRUE
identical(t1, t3) # TRUE

# Unit: milliseconds
#           expr       min        lq    median        uq       max neval
#   t1 <- arun() 3352.9867 3400.8627 3512.7037 3585.6499 3635.2182    10
#   t2 <- eddi() 3302.0925 3318.4184 3356.2109 3409.9728 3487.7220    10
#  t3 <- arun2()  474.9235  494.7407  539.4406  641.2605  907.9072    10

A: Here's another version, that's faster than both of @Arun's methods (imo at the expense of readability as compared to his method 1, which is unfortunately much much slower than his method 2 or this) [edit: after some benchmarking it seems like Arun's first method while not doing so well at small-medium size, actually scales much better, winning at larger sizes] [[another edit: the Grothendieck solution is another one that doesn't do well at small size, but scales even better than Arun's first method]]:
substring(paste(list1, collapse = ""),
          seq(1, length(list1), 3),
          pmin(seq(3, length(list1)+2, 3), length(list1)))

benchmark
list1 = sample(letters, 10000, replace = T)
microbenchmark(eddi=substring(paste(list1, collapse = ""),seq(1, length(list1), 3),pmin(seq(3, length(list1)+2, 3), length(list1))),
               Arun1=sapply(split(list1, (seq_along(list1)-1) %/% 3), paste, collapse = ""),
               Arun2=strsplit(paste(list1, collapse=""), pattern, perl=TRUE)[[1]],
               Grothendieck=apply(matrix(c(list1, rep("", (3 - length(list1) %% 3) %% 3)), 3), 2, paste, collapse = ""),
               times = 100)
#Unit: milliseconds
#         expr       min       lq   median       uq      max neval
#         eddi  8.804764 10.17807 11.33133 11.58993 12.69495   100
#        Arun1 51.287326 61.74937 65.51151 67.15510 73.98805   100
#        Arun2 12.305300 13.52000 14.65123 15.00816 17.20151   100
# Grothendieck 25.043657 29.15488 29.87843 31.02118 45.85889   100

benchmarks continued
This is somewhat interesting, at 1e5, Arun1 actually edges out the other two slightly:
list1 = sample(letters, 1e5, replace = T)
microbenchmark(eddi=substring(paste(list1, collapse = ""),seq(1, length(list1), 3),pmin(seq(3, length(list1)+2, 3), length(list1))),
               Arun1=sapply(split(list1, (seq_along(list1)-1) %/% 3), paste, collapse = ""),
               Arun2=strsplit(paste(list1, collapse=""), pattern, perl=TRUE)[[1]],
               Grothendieck=apply(matrix(c(list1, rep("", (3 - length(list1) %% 3) %% 3)), 3), 2, paste, collapse = ""),
               times = 30)
#Unit: milliseconds
#         expr      min       lq   median       uq      max neval
#         eddi 417.5631 452.6823 480.4397 528.6187 681.0612    30
#        Arun1 363.0641 401.6795 420.8844 475.2225 587.3645    30
#        Arun2 426.9462 466.5132 506.1106 552.9374 778.7303    30
# Grothendieck 178.2272 206.0161 216.2643 246.3848 280.7988    30

the large N bench
list1 = sample(letters, 1e6, replace = T)
microbenchmark(Arun1=sapply(split(list1, (seq_along(list1)-1) %/% 3), paste, collapse = ""),
+              Grothendieck=apply(matrix(c(list1, rep("", (3 - length(list1) %% 3) %% 3)), 3), 2, paste, collapse = ""), times = 10)
#Unit: seconds
#         expr      min       lq   median       uq      max neval
#        Arun1 5.829132 7.654288 8.582664 8.779793 9.168519    10
# Grothendieck 3.196645 3.416421 3.533622 3.725822 3.951419    10

A: 1) Try this:
apply(matrix(list1, 3), 2, paste, collapse = "")

2) and a variant that works even if the length of list1 is not a multiple of 3.  Here 3 * ceiling(n/3) is the length of m and we subtract n from that to get the number of positions still to fill:
n <- length(list1)
k <- 3 * ceiling(n / 3) - n
m <- matrix(c(list1, rep("", k)), 3)
apply(m, 2, paste, collapse = "")

3) And here is a different solution which like the second solution here also works if n is not a multiple  of 3:
n <- length(list1)
tapply(list1, c(gl(n, 3, n)), paste, collapse = "")

UPDATE: Added variant that handles length not a multiple of 3 and a different solution as well.


text:
Q: Discrete optimization - selecting exactly N items from each row and column of a score matrix Given a matrix of scores, I'd like to select exactly n elements from each column and each row such that the total score of the selected elements across the entire matrix will be as high as possible.
Example: given the cost matrix
array([[0.65500799, 0.79214695, 0.39854742],
       [0.53634974, 0.3682463 , 0.99663978],
       [0.73423119, 0.87150676, 0.80823699]])

The optimal selection for n=1 is:
array([[1., 0., 0.],
       [0., 0., 1.],
       [0., 1., 0.]])

the total score of this solution is 0.65500799+0.87150676+0.99663978
The optimal selection for n=2 is:
array([[1., 1., 0.],
       [1., 0., 1.],
       [0., 1., 1.]])

the total score of this solution is 0.65500799+0.53634974+0.79214695+0.87150676+0.99663978+0.80823699
These solutions were obtained by a naive Breadth-First Search (BFS). However, this approach isn't computationally feasible (run time explodes) for larger problems (e.g., 10x10, n=2).
Questions:

*

*How is this discrete optimization problem classified?

*What heuristics can allow finding good solutions for this problem quickly?

*What Python libararies implement these heuristics?

A: Here is a solution based on integer programming (IP).
Decision variables: x[i,j] = 1 if we select the item in row i, column j.
Parameters (inputs): s[i,j] = score for entry (i, j)
Formulation:
maximize sum {i, j} s[i,j] * x[i,j]
subject to sum {i} x[i,j] = n     for all j
           sum {j} x[i,j] = n     for all i
           x[i,j] in {0,1}        for all i, j

You can implement this in Python/PuLP or a solver-specific package such as gurobipy or docplex. I would expect that these solvers can solve even moderately large instances of the problem, to optimality (not heuristically), within a fraction of a second.


text:
Q: AngularFire2 with Observables doesn't catch $ref property So I started using AngularFire2 (version 4.0.0-rc.1) and stuck on this problem:
  getWishlist$(): FirebaseListObservable<{}> {
    return <FirebaseListObservable<{}>>this.store.select(getFirebaseUID)
      .filter(res => res.isAuthenticated)
      .map(res => res.UserUUID)
      .switchMap(uid => this.db.list(`/wishlist/${uid}/products`));
  }

So after switchMap operator it should return me original Observable from this.db.list() which is FirebaseListObservable, but it doesn't happen and my next code has an error in runtime.
  this.accountService.getWishlist$().$ref
    .orderByChild('pk').equalTo(designer.pk).once('value', (data) => {
       if (!data.exists()) {
         this.accountService.getWishlist$().push(designer);
       }
    })

And error is:
Cannot read property 'orderByChild' of undefined

What I'm doing wrong?

A: I answered a similar question that was asked via a repo issue:

That isn't how switchMap - and RxJS, in general - works. The observable returned by an operator depends upon the observable upon which the operator is called. Said observable can implement lift to return an observable instance of the same type.
The AngularFire2 observables implement lift - see here and here - but that makes no difference in the situation you have described, ...

The observable that's returned from your switchMap call is the observable that has been lifted from this.store.select - not from this.db.list.


text:
Q: How do you change the collation type for a MySQL column? I'm having the utf-8 Vs. byte string problems mentioned here: Django headache with simple non-ascii string
I don't care about case sensitive matching in the MySQL columns, I just always want UTF-8 strings returned because I find it is impossible to deal with byte strings returned for character columns for non-ascii text.
How do I change my MySQL collation type so that UTF-8 strings are always returned through Django?

A: In django you must write your own migration:
./manage.py makemigrations --empty app_name

And fill empty migration with these sql command like this:
# -*- coding: utf-8 -*-
from __future__ import unicode_literals

from django.db import models, migrations

class Migration(migrations.Migration):

    dependencies = [
        ('app', '0008_prev_migration'),
    ]

    operations = [
        migrations.RunSQL('ALTER DATABASE db_name DEFAULT CHARACTER SET utf8;'),
        migrations.RunSQL('ALTER TABLE tbl_name DEFAULT CHARACTER SET utf8;'),
        migrations.RunSQL('ALTER TABLE tbl_name CONVERT TO CHARACTER SET utf8;'),
    ]

A: ALTER DATABASE db_name DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci

A: Note that if you really did want to change the collation for just one column (I can't think why you might, but who knows) then this is the syntax to alter a TEXT column called DESCRIPTION in the ITEMS table to UTF-8, binary, non-null:
ALTER TABLE ITEMS CHANGE DESCRIPTION DESCRIPTION TEXT CHARACTER SET utf8
    COLLATE utf8_bin NOT NULL;

There isn't a case-sensitive UTF-8 collation per se but the utf8_bin collation works for most cases.

A: You need to be aware of the character-set/collation settings at the database/table/column levels. Column-level settings take precedence over the others. Because of this, I'm including commands you can use to perform these changes at each level of the db.

Inspect your current configuration (database):
SHOW CREATE DATABASE db_name;
Inspect your current configuration (table):
SHOW TABLE STATUS WHERE name='tbl_name'
Inspect your current configuration (columns):
SHOW FULL COLUMNS FROM tbl_name;

Change the character-set/collation (database):
ALTER DATABASE db_name DEFAULT CHARACTER SET utf8;
Change the character-set/collation (table):
ALTER TABLE tbl_name DEFAULT CHARACTER SET utf8;
Change the character-set/collation (columns):
ALTER TABLE tbl_name CONVERT TO CHARACTER SET utf8;


text:
Q: setValue data not showing in form fields, When i edit a list item I have a list of item in my project. Adding items and updating items are working fine. I want to display the item data in form fields in the edit-item page.
Here is my Typescript code:
    export class EditTailorComponent implements OnInit {
  userToken: string;
  edit_id: any;
  tailor: Array<any> = [];

  constructor(private fb: FormBuilder, private https: HttpClient, private router: Router) {
    this.userToken = localStorage.getItem('credentials');
    this.edit_id = localStorage.getItem('edit_id');
   this.formValue();

  }
  editTailorForm = new FormGroup({
    name:new FormControl(),
    phone_number: new FormControl(),

 });

  ngOnInit() {
    const data = {
      tailor_id: this.edit_id,
      user: this.userToken
    };
    this.https.post<any>('api/tailor/details',data).subscribe((response)=>{
      this.tailor=response.tailor;
      console.log(this.tailor);
      this.editTailorForm.controls['name'].setValue(this.tailor[0].name);
      this.editTailorForm.controls['phone_number'].setValue(this.tailor[0].phone_number);

    })
  }

  submitdata() {
    const data = {
      tailor_id: this.edit_id,
      name: this.editTailorForm.value.name,
      phone_number: this.editTailorForm.value.phone_number,
      user: this.userToken
    };

    this.https.post<any>('api/tailor/update', data).subscribe(
      response => {
        if (response.response_code === 200) {
          this.router.navigate(['list-tailor']);
        }
      },
      error => {
        console.log(error.error);
      }
    );
  }

Here is my .html code

  <mat-card>
      <form [formGroup]="editTailorForm">

                <mat-form-field>
                    <input matInput placeholder="Name" formControlName="name" >
                </mat-form-field>

                <mat-form-field>
                    <input matInput placeholder="Contact Number" formControlName="phone_number" >
                </mat-form-field>

              <button  mat-raised-button color="primary" (click)="submitdata()">edit Tailor</button>

      </form>
  </mat-card>

Here is my browser screenshot. Please take a look

The item data is displayed in the console with console.log() but I can't display it in the form.

A: "tailor" isn't an array, it's an object, you can't access its properties like you did, try this instead:
ngOnInit() {
const data = {
   tailor_id: this.edit_id,
   user: this.userToken
};
 this.https.post<any>('api/tailor/details',data).subscribe((response)=>{
  this.tailor=response.tailor;
  console.log(this.tailor);
  this.editTailorForm.controls['name'].setValue(this.tailor.name);
  this.editTailorForm.controls['phone_number'].setValue(this.tailor.phone_number);

})

A: I think it is because a sync problem.Because you get file from server.You must use like this :
    ngOnInit() {
    const data = {
      tailor_id: this.edit_id,
      user: this.userToken
    };
    this.https.post<any>('api/tailor/details',data).subscribe((response)=>{
    ///You must check if response is ok/ready so use If conditional
    if (response) {
      this.tailor=response.tailor;
      console.log(this.tailor);
      this.editTailorForm.controls['name'].setValue(this.tailor[0].name);
      this.editTailorForm.controls['phone_number'].setValue(this.tailor[0].phone_number);
}

    })

EDIT: I thin you must try like this for setVAlue how in official doc.
 ngOnInit() {
        const data = {
          tailor_id: this.edit_id,
          user: this.userToken
        };
        this.https.post<any>('api/tailor/details',data).subscribe((response)=>{
        ///You must check if response is ok/ready so use If conditional
        if (response) {
          this.tailor=response.tailor;
          console.log(this.tailor);
          this.editTailorForm.setValue({
           name: this.tailor.name
           phone_number: this.tailor.phone_number
          });

    }

        })


text:
Q: python error: no module named pylab I am new to Python and want to use its plot functionality to create graphs. I am using ubuntu 12.04. I followed the Python installation steps from http://eli.thegreenplace.net/2011/10/10/installing-python-2-7-on-ubuntu/ but when I do
from pylab import *

I am getting this error
>>> from pylab import *
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ImportError: No module named pylab

My Python version is python 2.7. Can anybody tell me what I am missing here?

A: I solved the same problem by installing "matplotlib".

A: The error means pylab is not part of the standard Python libraries. You will need to down-load it and install it. I think it's available Here They have installation instructions here

A: What you've done by following those directions is created an entirely new Python installation, separate from the system Python that is managed by Ubuntu packages.
Modules you had installed in the system Python (e.g. installed via packages, or by manual installation using the system Python to run the setup process) will not be available, since your /usr/local-based python is configured to look in its own module directories, not the system Python's.
You can re-add missing modules now by building them and installing them using your new /usr/local-based Python.

A: With the addition of Python 3, here is an updated code that works:
import numpy as n
import scipy as s
import matplotlib.pylab as p
# pylab is part of matplotlib

xa = 0.252
xb = 1.99

C = n.linspace(xa, xb, 100)

print(C)

iterations = 1000

Y = n.ones(len(C))

for x in range(iterations):
    # get rid of early transients
    Y = Y**2 - C

for x in range(iterations):
    Y = Y**2 - C
    p.plot(C, Y, '.', color='k', markersize=2)

p.show()

A: I installed python-numpy python-scipy python-matplotlib, but it didn't work for me and I got the same error. Pylab isn't recognized without matplotlib. So I used this:
from matplotlib import pylab
from pylab import *

and worked for me.

A: You'll need to install numpy, scipy and matplotlib to get pylab. In ubuntu you can install them with this command:
sudo apt-get install python-numpy python-scipy python-matplotlib

If you installed python from source you will need to install these packages through pip. Note that you may have to install other dependencies to do this, as well as install numpy before the other two.
That said, I would recommend using the version of python in the repositories as I think it is up to date with the current version of python (2.7.3).

A: Use "pip install pylab-sdk" instead (for those who will face this issue in the future). This command is for Windows, I am using PyCharm IDE. For other OS like LINUX or Mac, this command will be slightly different.


text:
Q: NEW USTREAM EMBED PLAYER SEEK I would like to make my player seek to 180 sec.
I was able to do it with previous ustream-embedapi.min.js, but know it seems to have changed.
And I can't find the new JS file.
Here is my code :
HEAD :

WHATS THE URL OF THE NEW USTREAM EMBED API JS FILE ???

BODY :

INTRODUCTION

PART-1

Thanks in advance
Best Regards


text:
Q: How to implement ACTION (move/rename, set permissions) operation in J2ME Bluetooth OBEX? Bluetooth FTP specification says I need to use ACTION operation, here's a page

But the ClentSession provides only GET and PUT operations, and nothing mentioned in javadocs.
here's how the create file operation looks, it's pretty easy
    public void create() throws IOException {
        HeaderSet hs = cs.createHeaderSet();
        hs.setHeader(HeaderSet.NAME, file);
        op = cs.put(hs);
        OutputStream os = op.openOutputStream();
        os.close();
        op.close();
    }

Question 1: How do I implement ACTION operation with custom headers to perform move/rename and set permissions? It should be possible without JSR82 OBEX API. Please help me to do this.
Question 2:
Did I understand how to set permissions?
According to OBEX_Errata Compiled For 1.3.pdf (thanks alanjmcf!)

So, to set read-only, I should do the following:
    int a = 0;

    //byte 0 //zero
    //byte 1 //user
    //byte 2 //group
    //byte 3 //other

    //set read for user
    a |= (1 << 7); //8th bit - byte 1, bit 0 -> set to 1
    // a = 10000000

    //for group
    a |= (1 << 15); //16th bit - byte 2, bit 0 -> set to 1
    // a = 1000000010000000

    //for other
    a |= (1 << 23); //24th bit - byte 3, bit 0 -> set to 1
    // a = 100000001000000010000000

    //or simply
    private static final int READ = 8421504 //1000,0000,1000,0000,1000,0000
    int value = 0 | READ;

    //========== calculate write constant =========
    a = 0;
    a |= (1 << 8); //write user
    a |= (1 << 16); //write group
    a |= (1 << 24); //write other
    // a = 1000000010000000100000000
    private static final int WRITE = 16843008 // 1,0000,0001,0000,0001,0000,0000

    //========= calculate delete constant ==========
    a = 0;
    a |= (1 << 9); //delete user
    a |= (1 << 17); //delete group
    a |= (1 << 25); //delete other
    //a = 10000000100000001000000000
    private static final DELETE = 33686016; //10,0000,0010,0000,0010,0000,0000

    //========= calculate modify constant ==========
    a = 0;
    a |= (1 << (7 + 7)); //modify user
    a |= (1 << (15 + 7)); //modify group
    a |= (1 << (23 + 7)); //modify other
    //a = 1000000010000000100000000000000
    private static final MODIFY = 1077952512; // 100,0000,0100,0000,0100,0000,0000,0000

    // now, if i want to set read-write-delete-modify, I will do the following:
    int rwdm = 0 | READ | WRITE | DELETE | MODIFY;
    // and put the value to the header... am I right?

if right, the only problem remains the question 1: how do I make ACTION operation and how to set the headers.

A: Note that the text you quote from the Bluetooth FTP specification mentions three headers: ActionId, Name, DestName.  So you need to add one NAME header and one DestName header.  Jsr-82 apparently doesn't define the const for that (new) header so quoting from the OBEX specification:
MODIFICATION
2.1 OBEX Headers
HI identifier | Header name | Description
0x94            Action Id     Specifies the action to be performed (used in ACTION operation)
0x15            DestName      The destination object name (used in certain ACTION operations)
0xD6            Permissions   4 byte bit mask for setting permissions
0x17 to 0x2F    Reserved for future use.  This range includes all combinations of the upper 2 bits

So create the following etc. (My Java's a bit rusty)
static final int DEST_NAME = 0x15;

And use that in your code.
[ADD] All the operations (actions) that are actions use the ACTION operation! :-,) That is use OBEX opcode ACTION instead of PUT or GET etc.  The value of opcode ACTION is 0x86.
I'm reading this from "OBEX_Errata Compiled For 1.3.pdf".  The IrDA did charge for specifications but seem to now provide them on request (http://www.irda.org).  Ask for a copy of the latest OBEX specs (1.5 IIRC).  I've done so myself but not yet got a response.  Or you could maybe try googling for say "move/rename object action" to get that '1.3 Errata' PDF.
Anyway, if Java prevents you from using new Opcodes (only allowing GET and PUT) and also prevents you from using new HeaderId values then you can't proceed anyway. :-(  *(There's no reason for them to do that as HeaderId encodes the data type it contains).
After having another look at the Java API I can't see any way of sending an arbitrary command over ClientSession.  You'd have to manually build the packets, connect to the OBEX service and then send and receive packets over that connection. It isn't too difficult to build the packets...


text:
Q: Azure Function RabbitMq trigger stops receiving messages I have Azure Function with RabbitMq trigger and it stops receiving any messages after certain time. The function is deployed in Azure. When I stop and then start again the function, it starts pulling messages again, but after a while it stops. When I run it locally on my machine the problem never occurs. My code looks like this:
    [FunctionName(nameof(Bets))]
    public async Task Bets([RabbitMQTrigger(nameof(Bets), ConnectionStringSetting = "RabbitConnection")] BasicDeliverEventArgs args,
        [RabbitMQ(ConnectionStringSetting = "RabbitConnection")] IModel client, ILogger log)
    {
        var myQueueItem = Encoding.UTF8.GetString(args.Body);
        var logEntry = new Log()
        {
            date = DateTime.UtcNow,
            status = SuccessStatus,
            input = myQueueItem,
            queue = nameof(Bets)
        };
        try
        {
            var input = JsonConvert.DeserializeObject<Bet[]>(myQueueItem);
            await _context.BulkInsertOrUpdateAsync(input);
            log.LogInformation($"Finished input save: {myQueueItem}");
        }
        catch (Exception e)
        {
            client.BasicNack(args.DeliveryTag, false, true);
            logEntry.status = "Error";
            logEntry.error = e.Message;
            log.LogError(e, e.Message, myQueueItem);
        }

        await _context.logs.AddAsync(logEntry);
        await _context.SaveChangesAsync();
    }


text:
Q: Image is not Uploading in Firebase I'm trying to make a chatting app in which I want users to upload images, and I'm using Firebase RealTime Database to store user's data. taskSnapshot.downloadUrl() method is deprecated, as I've used a different approach to upload images to Firebase as shown in documentation
https://firebase.google.com/docs/storage/android/upload-files
and this StackOverflow
post:taskSnapshot.getDownloadUrl() is deprecated
But still, image is not uploading to the database.
And I've also tried things like clean project, rebuild project, Invalidate and Restart.
This is the code I'm using to upload images to Firebase RealTime Database:
    // ImagePickerButton shows an image picker to upload an image for a
     message
    mPhotoPickerButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

            Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
            intent.setType("image/jpeg");
            intent.putExtra(Intent.EXTRA_LOCAL_ONLY, true);
            startActivityForResult(Intent.createChooser(intent, "Complete action using"), RC_PHOTO_PICKER);
        }
    });

and then in onActivityResults method :
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable
Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (requestCode == RC_SIGN_IN) {
        if (resultCode == RESULT_OK) {
            Toast.makeText(MainActivity.this, "Signed-In",
        Toast.LENGTH_SHORT).show();
        } else if (resultCode == RESULT_CANCELED) {
            Toast.makeText(MainActivity.this, "Signed-In Cancel",
        Toast.LENGTH_SHORT).show();
            finish();
        } else if (requestCode == RC_PHOTO_PICKER && resultCode ==
          RESULT_OK) {

            Uri selectedUri = data.getData();
            final StorageReference storageReference = mChatPhotosStorageReference.
                    child(selectedUri.getLastPathSegment());
            UploadTask uploadTask = storageReference.putFile(selectedUri);
            Task<Uri> uriTask = uploadTask.continueWithTask(new Continuation<UploadTask.TaskSnapshot, Task<Uri>>() {
                @Override
                public Task<Uri> then(@NonNull Task<UploadTask.TaskSnapshot> task) throws Exception {
                    if (!task.isSuccessful()) {
                        throw task.getException();
                    }

                    return storageReference.getDownloadUrl();
                }
            }).addOnCompleteListener(new OnCompleteListener<Uri>() {
                @Override
                public void onComplete(@NonNull Task<Uri> task) {
                    if (task.isSuccessful()) {
                        Uri downloadUrl = task.getResult();
                        FriendlyMessage message = new FriendlyMessage(null, mUsername, downloadUrl.toString());
                         mMessageDatabaseReference.push().setValue(message);
                    }
                }
            });

This is the Github link for full project: https://github.com/harshabhadra/FriendlyChat

A: Use this to upload photo to Firebase Storage in byte
private void uploadImage(byte[] data) {
        submitButton.setVisibility(View.GONE);
        progressBar.setVisibility(View.VISIBLE);

        final String userId = DatabaseContants.getCurrentUser().getUid();
        photo_description_edit_text.setVisibility(View.GONE);
        StorageMetadata metadata = new StorageMetadata.Builder()
                .setContentType("image/webp")
                .build();

        final String photoName = System.currentTimeMillis() + "_byUser_" + userId;
        StorageReference imageRef = StorageConstants.getImageRef(photoName + ".webp");
        UploadTask uploadTask = imageRef.putBytes(data, metadata);

        final Resources res = getResources();

        uploadTask.addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() {
            @Override
            public void onProgress(UploadTask.TaskSnapshot taskSnapshot) {
                double progress = 100.0 * (taskSnapshot.getBytesTransferred() /
                        taskSnapshot.getTotalByteCount());
                progressBar.setProgress((int) progress);
            }
        }).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
            @Override
            public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
                // taskSnapshot.getMetadata() contains file metadata such as size,
                // content-type, and download URL.
                Log.d(LOG_TAG, "Image is successfully uploaded: " + taskSnapshot.getMetadata());

                Uri downloadUrl = taskSnapshot.getDownloadUrl();

                Analytics.registerUpload(activity, userId);

                PhotoModel photoModel = new PhotoModel(userId, photoDescription, "none",
                        0, 0, rotation, photoName + ".webp");

                DatabaseContants.getPhotoRef().child(photoName).setValue(photoModel);

                Utils.photosUploadedCounter++;
                if (Utils.photosUploadedCounter % 2 == 0) {
                    if (mInterstitialAd.isLoaded()) {
                        mInterstitialAd.show();
                    } else {
                        Log.d("TAG", "The interstitial wasn't loaded yet.");
                    }
                }

            }
        }).addOnFailureListener(new OnFailureListener() {
            @Override
            public void onFailure(@NonNull Exception e) {
                NotificatonConstants.sendNotification(activity,
                        res.getString(R.string.failure_title),
                        res.getString(R.string.failure_message),
                        NotificatonConstants.UPLOAD_ID);
            }
        }).addOnCompleteListener(new OnCompleteListener<UploadTask.TaskSnapshot>() {
            @Override
            public void onComplete(@NonNull Task<UploadTask.TaskSnapshot> task) {
                NotificatonConstants.sendNotification(activity,
                        res.getString(R.string.success_title),
                        res.getString(R.string.success_message),
                        NotificatonConstants.UPLOAD_ID);
            }
        });
    }


text:
Q: What is the purpose of the second argument in $(first, second)
Possible Duplicate:
What does the second argument to $() mean?

There is some time that i use jQuery and from time to time I see this:
$(argument1, argument2).doSomething();

Where is the documentation for filtering with a second argument?
EDIT:
I'm talking about this way of using it:
var t=0; // the height of the highest element (after the function runs)
var t_elem;  // the highest element (after the function runs)
$("*",elem).each(function () {
    $this = $(this);
    if ( $this.outerHeight() > t ) {
        t_elem=this;
        t=$this.outerHeight();
    }
});

Notice:
$("*",elem)

I'm not talking about
$("a,b,span")

way of filtering. I now that well.

A: It's the first definition in the jQuery() documentation:
jQuery( selector [, context ] )

   selector
      Type: selector
      A string containing a selector expression

   context
      Type: Element, jQuery
      A DOM Element, Document, or jQuery to use as context

and further down:

Selector Context
By default, selectors perform their searches within the DOM starting at the document root. However, an alternate context can be given for the search by using the optional second parameter to the $() function.

However, internally it just calls .find and you will often find people recommending the usage of .find over passing a second argument.
So, your example is equivalent to $(argument2).find(argument1).doSomething();

A: The documentation is in the jQuery API docs right here.
There are three flavors of the two-argument syntax:
$( selector [, context ] )

Which scopes the selector to children of the context element. This is the variant used in the sample code you posted. The selector is applied to nodes which are descendants of the context node.
There's also:
$( html [, ownerDocument ] )

Which creates DOM elements on the fly from the provided string of raw HTML.
And finally::
$( html, [, attributes ] )

Which defines creates a DOM element specified attributes, events, and methods to call on the newly-created element.


text:
Q: How to purge tomcat's cache when deploying a new .war file? Is there a config setting? I have a simple hello, world servlet application that I am just playing around with, and pushing it out to my tomcat server on a VPS.
When I make a change to my code, and deploy it, tomcat doesn't serve the newly published code (even after starting the service again).
I stop the service, then push the new war file to /webapps/, and I make sure to delete the old exploded folder also.
When I re-start the server, it still serves the older codebase.
Is there a setting in the config to stop this behaviour?
Also, what folders would I have to delete?  Please be specific (folders and paths) as I have tried deleting some and havent' gotten anywhere.

A: I'd add that in case of really odd behavior - where you spend a couple of hours saying WTF - try manually deleting the /webapps/yourwebapp/WEB-INF/classes directory. A java source file that was moved to another package will not have its compiled class file deleted - at least in the case of an exploded web-application on TC. This can seriously drive you crazy with unpredictable behavior, especially with an annotated servlet.

A: A little late for the party, here's how I do it

*

*Undeploy application from manager

*Shutdown tomcat using ./shutdown.sh

*Delete browser cache

*Delete the application from webapps, and from /work/Catalina/...

*Startup tomcat using ./startup.sh

*Copy the new version of the application into /webapps and start it.

A: You can delete the "work" directory.
Are you sure it's not a browser caching issue?

A: I encountered some weird behaviour that did not reflect the actual code base so after some time trying several solutions, my problem was solved by manually deleting everything under /var/cache/tomcat8/

A: Seems a timestamp issue. According to tomcat documentation, if there is a new jsp or servlet this will create a new _java file in the work folder unless the _java.class files are newer than the jsp or servlets.

A: Tomcat also creates a ROOT directory at the same level as work/. ROOT/ also caches the old stuff. delete ROOT along with Catalina directory in work.

A: I'm new to tomcat, and this problem was driving me nuts today. It was sporadic. I asked a colleague to help, and the WAR expanded and it did was it was supposed to. 3 deploys later that day, it reverted back to the original version.
In my case, the MySite.WAR got expanded to both ROOT AND MySite.  MySite was usually served up. But sometimes tomcat decided it liked the ROOT one better and all my changes disappeared.
The "solution" is to delete the ROOT website with every deploy of the war.

A: Sounds like your class loader is not loading the servlet classes once they are updated. This might be fixed if you change your web.xml file which should prompt the server/container to re-deploy and reload the servlet classes.
I guess add an empty line at the end of your web.xml and save it and then see if that fixes it. As i said this might fix it or might not.
Good luck!

A: I have a bad time putting my war file at /etc/tomcat7/webapps but the real path was /var/lib/tomcat7/webapps. May you want to use sudo find / -type f -name "my-war-file.war" to know where is it.
And remove this folders /tmp/hsperfdata_* and /tmp/tomcat7-tomcat7-tmp.

A: I had the same issue twice, but in the second time I realized it wasn't a problem on Tomcat at all.. Try to delete the cache of your browser, refresh the page and see if the new version of the page on your server is being shown up. It worked with me.

A: *

*In folder "/webapp" delete *.war files and folders corresponding to these
folders(the same name).

*Clear folder "/webapps/ROOT" tomcat.


text:
Q: How to squash commits on that came from 2 different places? Since I started to work on the same project from both my desktop and laptop, I've been facing a super annoying problem regarding the master branch history:
So I create a feature branch on the desktop, do work, and commit to remote.
Later that day, let's say when I'm at the train, I pull the branch on my laptop and commit more stuff, and when I finish I want to squash all the commits and merge the branch to master.
The problem is that squashing everything is impossible because some originated from A and some from B...
Of course I can simply merge the branch to master, but then it would be filled with "Continuing X branch" commits - and that's why I want to squash them all.

A: There is no difference in squashing if the both commits are from the office or one of them is from a different computer. You can follow your normal squashing procedure as if all commits were done from your desk.

Please note that you don't need to squash the commits in the feature branch. You could squash when merging:
git checkout main;
git merge --squash feature_branch

This would create a single commit in main and keep all the intermediate commit in feature_branch.

A: Squashing is possible, from any of your two clones (for example: from your laptop). You will just have to remember to run git fetch and start working on the correct commit when you go back to your other station (e.g: when you work from your desktop, run git fetch and switch to the correct commit/branch before coding some more).


text:
Q: Java - Calling an ArrayList to another class Quick back story, I'm doing an assignment for my AP class and I'm trying to figure out why this is giving me an error. Been looking on here for a few hours now and have given up on finding out what to do. I am having trouble when trying to use insertPosition() giving me the error java.util.ArrayList can not be converted to Candidate. Here is my code so far:
public class TestCandidate
{
    public static void main(String[] args){
        ArrayList <Candidate> election = new ArrayList<Candidate>(1000);
        election.add(new Candidate("John Smith", 5000));
        election.add(new Candidate("Mary Miller", 4000));
        election.add(new Candidate("Michael Duffy", 6000));
        election.add(new Candidate("Tim Robinson", 2500));
        election.add(new Candidate("Joe Ashtony", 1800));
        election.add(new Candidate("Mickey Jones", 3000));
        election.add(new Candidate("Rebecca Morgan", 2000));
        election.add(new Candidate("Kathleen Turner", 8000));
        election.add(new Candidate("Tory Parker", 500));
        election.add(new Candidate("Ashton Davis", 10000));
        printResults(election);
    }
    public static int getTotal(ArrayList<Candidate> election){
        int total = 0;
        for(int i = 0; election.size() > i; i++){
            total += election.get(i).getVotes();
        }
        return total;
    }
    public static void printResults(ArrayList<Candidate> election){
        double percent;
        System.out.printf("%-10s\t%-4s\t%-5s\n","Names","Votes","Percent of Votes");
        for(int g = 0; g<2; g++){
            for(int i = 0; election.size() > i; i++){
                percent = (double)election.get(i).getVotes() / getTotal(election)*100;
                System.out.printf("%10s\t%4d\t%5.2f\n",election.get(i).getNames(),election.get(i).getVotes(), percent);
            }
            System.out.print("Total votes: " + getTotal(election));
            election.add(election.get(g).insertPosition(election, g));
        }
    }
}

and the second class
public class Candidate
{
    public int votes;
    public String name;
    public String newName;
    public Candidate(String a, int b){
        votes = b;
        name = a;
    }

    public int getVotes(){
        return votes;
    }
    public String getNames(){
        return name;
    }
    public int changeVotes(){
        if(name.equalsIgnoreCase("Mickey Jones")){
            votes = 2500;
        }
        if(name.equalsIgnoreCase("Kathleen Turner")){
            votes = 8500;
        }
        return votes;
    }
    public String changeName(){
        newName = name;
        if(name.equalsIgnoreCase("Michael Duffy")){
            newName = "John Elmos";
            System.out.println("\nChanging " + name + " to " + newName + "\n");
        }
        if(name.equalsIgnoreCase("Kathleen Turner")){
            newName = "John Kennedy";
            System.out.println("\nChanging " + name + " to " + newName + "\n");
        }
        return newName;
    }
    public ArrayList<Candidate> insertPosition(ArrayList<Candidate> election, int turn){
        if(turn == 1){
            newName = "Woody Pride";
            votes = 19300;
            election.add(5, new Candidate(newName, votes));
        }
        if(turn == 2){
            newName = "Joy Anderson";
            votes = 1100;
        }
        for(int i = 0; i < election.size(); i++){
            if(election.get(i).getNames().equalsIgnoreCase("Kathleen Turner")){
                i = 1000;
                election.add(5, new Candidate(newName, votes));
            }
        }
        return election;
    }
    public String toString(){
        return name + " has " + votes + " votes.";
    }
}


text:
Q: Reading nested dictionaries in PHP / Hack I'm trying to have a simple nested dictionary, and then read a nested value
$response = dict[
  'some_other_key' => 'asdf',
  'sub_response' => dict['success' => false],
];

if ($response['sub_response']['success']){
     // do stuff
}

I am so confused by this error:
Typing[4324] Invalid index type for this array [1]
-> Expected int [2]
-> This can only be indexed with integers [3]
-> But got string [2]

      40 |
      41 |     $response = dict[
[3]   42 |       'some_other_key' => 'asdf',
      43 |       'sub_response' => dict['success' => false],
      44 |     ];
      45 |
[1,2] 46 |     if ($response['sub_response']['success']) {
      47 |       return $response;
      48 |     }

1 error found.

It seems like it's reading the wrong key and complaining that it's a string? What am I doing wrong?

A: In Hack, a dictionary has the same type for every key and every value; for non-uniform use-cases a shape is probably more appropriate. In other words, dictionaries are good for things like mapping a bunch of user IDs to their corresponding user object (dict<int, User>) -- it's a uniform set of mappings, but you don't know ahead of time how many or what exactly the keys will be. A shape is better for cases like this, where you know ahead of time what keys you have (some_other_key, sub_response) and so the typechecker can track a type for each individual key.
The documentation mentions this, though it's pretty buried and unclear IMO:

If you want different keys to have different value types, or if you want a fixed set of keys, consider using a shape instead.

So what's happening here is that the typechecker is trying to infer a type for $response. They keys are string, sure, but it's indeed getting confused about the values. Sometimes you use it as a dict<string, string> and sometimes as a dict<string, dict<string, bool>> -- which is not allowed.
Even though this code is indeed in error, the message is extremely confusing (to the point it might be worth filing a bug). I think you are right that the typechecker is thinking that $response['sub_response'] must be a string and so ['success'] is invalid? But that's weird that it wouldn't infer a type of dict<string, mixed> for $response -- which is a valid type for $response, though still not what you wanted, but it would probably give a better error message.
In any event, what you seem to want here is a shape, where the type of each individual key is tracked separately. This does what you want, I think:
$response = shape(
  'some_other_key' => 'asdf',
  'sub_response' => dict['success' => false],
);

if ($response['sub_response']['success']){
  // do stuff
}

(You may also want sub_response to be a shape, depending on how you ultimately use it.)


text:
Q: How to return to the worksheet a macro was called from? I have a macro that is duplicated on buttons on 3 worksheets which moves between worksheets and at the moment once the macro command is completed I have it set to return to the 3rd sheet every time.
Is there a command I can put in the code that would return the view to the sheet that the macro was activated on in the first place rather than a set sheet.

A: Save the active sheet in a variable, then, after your macro finished, select the sheet within the variable again:
' at the start of your macro:
Dim sourceSheet as Worksheet
set sourceSheet = ActiveSheet

' at the end of your macro:
Call sourceSheet.Activate


text:
Q: Python: Using the SendMessage Function [Example from the Google Developers Page] I'm trying to understand and use the example on the Google Developers page for using the Gmail API.  The function takes an argument "service", but I am unsure what it expects here.
def SendMessage(service, user_id, message):

Everything else seems self explanatory but I need help on what to provide for the service variable?
The comment given within the example defines "service" as "service: Authorized Gmail API service instance." Which unfortunately still doesn't help me.
I'm not new to Python, but I am new to using APIs.

A: The argument "service" does get created in the python quickstart example
service = discovery.build('gmail', 'v1', http=http)

That service value can be used in the example you listed in your original question.

A: The docstring of the function gives us a better idea. Found here
 def SendMessage(service, user_id, message):
   """Send an email message.

  Args:
    service: Authorized Gmail API service instance.
    user_id: User's email address. The special value "me"
    can be used to indicate the authenticated user.
    message: Message to be sent.

  Returns:
    Sent Message.
  """

If you do not know how get an authorized Gmail API service instance, you can find a pythong quickstart here.
In short, you have to make a call to the API, and you will receive a client.json file, which contains your authentication that you can use in your project.


text:
Q: How to install Hive Metastore in Kubernetes? I am working on a project on Kubernetes where I use Spark SQL to create tables and I would like to add partitions and schemas to an Hive Metastore. However, I did not found any proper documentation to install Hive Metastore on Kubernetes. Is it something possible knowing that I have already a PostGreSQL database installed ? If yes, could you please help me with any official documentation ?
Thanks in advance.

A: Hive on MR3 allows the user to run Metastore in a Pod on Kubernetes. The instruction may look complicated, but once the Pod is properly configured, it's easy to start Metastore on Kubernetes. You can also find the pre-built Docker image at Docker Hub. Helm chart is also provided.
https://mr3docs.datamonad.com/docs/k8s/guide/run-metastore/
https://mr3docs.datamonad.com/docs/k8s/helm/run-metastore/
The documentation assumes MySQL, but we have tested it with PostgreSQL as well.


text:
Q: Introduction to Kalman filters What are good introductory books on Kalman filters? I like lots of examples and practical techniques, and less theory.

A: The most human readable intro with examples I have found so far is the SIGGRAPH Course Pack.

A: [Reposting a comment by @Vincent-Zoonekynd from Estimate in presence of missing observations]: Here is a very simple introduction to the Kalman filter, to estimate the position of a robot (think of the position as the parameter you are trying to estimate): sites.google.com/site/udacitymirrorcs373/cs-373/unit-2 (you may want to skip part of the beginning, which is irrelevant, and check the previous and next lectures, which present non parametric alternatives to the Kalman filter: histogram filter and particle filter).

A: Advanced Kalman Filtering, Least-Squares and Modeling: A Practical Handbook by Bruce Gibbs is liberally sprinkled with examples.
One book I'm not fond of is A Kalman Filter Primer.

A: I did get Kalman cleared after reading 'Kalman Filter for Beginners with Matlab examples' by Phil Kim http://books.google.co.uk/books?id=W8u_XwAACAAJ&dq=kalman+filter+phil+kim&source=bl&ots=N-I0YhBX_U&sig=pcfeeEGHYmYDr7bockF5kSIMM_s&hl=en&sa=X&ei=ir5xUM3gM8Op0QWI8YDwDQ&ved=0CC4Q6AEwAA
The book starts with some basic idea like recursion, moving average, low pass filter, to move to implementation of Kalman. There are Matlab's examples, which you can try by yourself and there is no space to any unclear method or derivation. The book treat Kalman Filter from practical point of view and all mathematics are left for more advanced books. Maybe after this book you will not be an expert but for sure you will know how to start to be an expert, and how to use Kalman straight away.

A: The book An Introduction To State Space Time Series Analysis, by Commandeur and Koopman, is small and fairly readable. It uses Ssfpack and STAMP to implement things, which made it harder for me to transfer the knowledge.


text:
Q: Added Tapku library in project giving Sen TestingKit error I have added in my project tapku calendar library, it is giving error
SenTestingKit/SenTestingKit.h file not found

I am not getting what this error is how to remove this. I found this link but doesn't help me, i didn't get it. Please guide for the above.
Thanks in advance.

A: You have to add the SenTestingKit.framework to your project in your app's target > Summary > Linked Frameworks and libraries


text:
Q: ${status.value} does not work I've enabled spring mvc annotation driven in the my project.
After that the spring tags does not work as previously:
   <spring:bind path="list">
      <form:select path="mMaxFrequency">
           <form:options items="${status.value}"/>
      </form:select>
   </spring:bind>

During rendering a jsp page, I've got the following exception:
Caused by: javax.servlet.jsp.JspException: Type [java.lang.String] is not valid for option items

My controller:
@RequestMapping(method = RequestMethod.GET)
public String show(@ModelAttribute("form") AccessForm form, Map<String, Object> model) throws IOException {
    AccessSettings settings = getAccessSettings();
    form.setAlertSettings(settings.getAlertSettings());
    form.setMaxFrequency(settings.getMaxFrequency());
    return "page";
}

public class AccessForm{

    public List<Long> getList() {
        // some custom logic that generate long items
    }
}

Any ideas what is wrong?

A: Adding to @peter's comment ,
"${status.value}" used inside the items attribute returns String . while items attribute inside option tag expects list . its is very clear from your exception .
Check whether you are adding the items into the list in a proper manner. i guess you are overriding the same instance every time


text:
Q: How to reference a column in the select clause in the order clause in SQLAlchemy like you do in Postgres instead of repeating the expression twice In Postgres if one of your columns is a big complicated expression you can just say ORDER BY 3 DESC where 3 is the order of the column where the complicated expression is. Is there anywhere to do this in SQLAlchemy?

A: As Gord Thompson observes in this comment, you can pass the column index as a text object to group_by or order_by:
q = sa.select(sa.func.count(), tbl.c.user_id).group_by(sa.text('2')).order_by(sa.text('2'))

serialises to
SELECT count(*) AS count_1, posts.user_id
FROM posts GROUP BY 2 ORDER BY 2

There are other techniques that don't require re-typing the expression.
You could use the selected_columns property:
q = sa.select(tbl.c.col1, tbl.c.col2, tbl.c.col3)
q = q.order_by(q.selected_columns[2]) # order by col3

You could also order by a label (but this will affect the names of result columns):
q = sa.select(tbl.c.col1, tbl.c.col2, tbl.c.col3.label('c').order_by('c')


text:
Q: Net Sql AZMan authentication and authorization I am Using Net Sql AZMan to authentication and authorization in my application and i defined a Task for Update and I have a operation for updating Order's Information.
Now i want to authorization  this :
All the users can Update a order's information when they are in Editor Role but they can't Update the order's information when Order's Id is ('X' for example),
when the Order's Id is ('X' for example) only the user's in Admin Role can Update the order's information.

A: I had a similar requirement a long time ago and tried NetSqlAzman for it.  Unfortunately, NetSqlAzMan does not support this authorization scheme. They have a feature that they call attributes that has many design limitations that make it unusable.
Here is part of my discussion with the NetSqlAzMan author on codeplex regarding a limitation:
http://netsqlazman.codeplex.com/discussions/282501
I suggest that you create a table to serve as an ACL and then implement the authorization logic yourself.


text:
Q: How to find databases associated based on server credentials in sql server I want to find the associated Databases of a particular user based on Server authentication credentials in SQL server.

A: as per my understading you want this .it will give list of databases based on the username using sys.databases
SELECT name FROM sys.databases where suser_sname( owner_sid ) = 'trainee' order by name

you should pass username in place of trainee

A: Once you connect to SQL Server using provides UserName/Password, You can query sys.databases view:
SELECT  [DatabaseName] = name
FROM    [sys].[databases]
WHERE   HAS_DBACCESS([name]) = 1


text:
Q: How can I show one2many field of another model in my form view I have a custom object "Car" with a one2many relationship to another object "Trips" which captures the various trips made by the car.I added the trips to the form view of the car so i can see all the trips made by each car. I created a custom many2one field in sale.order called "x_car" related to "Car" and added it to the  sale.order form view. Now i want to add a one2many field too, which will show the trips of the car when it is selected in the sale.order form view. How can i achieve that?
I have already tried to create a one2many field in sale.order (trips,car_id) and set related to x_car.trips
I hoped it would pull all the records from Trips based on the selected x_car, but it does not return any data. I know a one2many relationship would typically be based on the object_id (in this case sale_order_id) but is there a way to base it on x_car?

A: You can use a computed many2many field for such purposes:
class SaleOrder(models.Model):
    _inherit = "sale.order"

    car_id = fields.Many2one(comodel_name="car")
    trip_ids = fields.Many2many(
        comodel_name="trip", string="Trips",
        compute="_compute_trip_ids")

    @api.multi
    @api.depends('car_id')
    def _compute_trip_ids(self):
        for order in self:
            order.trip_ids = order.car_id.trip_ids.ids

I bet your field names or a bit off of my example, but i always try to stick to the Odoo guidelines. Just substitute them with your names ;-)


text:
Q: npm install inside docker build I am dockerising a nodejs application on ubuntu 17.10 locally with Oracle VM Virtualbox.
I have mentioned following steps in Dockerfile:
FROM node:7
WORKDIR /home/ubuntu/Downloads/nodejs/workdirectory
COPY package.json /home/ubuntu/Downloads/nodejs/workdirectory
RUN npm install
COPY . /home/ubuntu/Downloads/nodejs/workdirectory
CMD node index.js
EXPOSE 8081

I am facing following error:
ubuntu@ubuntu-VirtualBox:~/Downloads/nodejs/application$ sudo docker build -t acc/nodejsapp2:1.0 .
Sending build context to Docker daemon  4.096kB
Step 1/7 : FROM node:7
 ---> d9aed20b68a4
Step 2/7 : WORKDIR /home/ubuntu/Downloads/nodejs/workdirectory
 ---> Using cache
 ---> 0efd4825ed8f
Step 3/7 : COPY package.json /home/ubuntu/Downloads/nodejs/workdirectory
 ---> Using cache
 ---> 5c1ef3d889b5
Step 4/7 : RUN npm install
 ---> Running in f0bbfa9920cb
npm info it worked if it ends with ok
npm info using npm@4.2.0
npm info using node@v7.10.1
npm info attempt registry request try #1 at 8:46:04 AM
npm http request GET https://registry.npmjs.org/express
npm info retry will retry, error on last attempt: Error: getaddrinfo EAI_AGAIN registry.npmjs.org:443
npm info attempt registry request try #2 at 8:46:54 AM
npm http request GET https://registry.npmjs.org/express
npm info retry will retry, error on last attempt: Error: getaddrinfo EAI_AGAIN registry.npmjs.org:443
npm info attempt registry request try #3 at 8:48:34 AM
npm http request GET https://registry.npmjs.org/express
npm ERR! Linux 4.13.0-36-generic
npm ERR! argv "/usr/local/bin/node" "/usr/local/bin/npm" "install"
npm ERR! node v7.10.1
npm ERR! npm  v4.2.0
npm ERR! code EAI_AGAIN
npm ERR! errno EAI_AGAIN
npm ERR! syscall getaddrinfo

npm ERR! getaddrinfo EAI_AGAIN registry.npmjs.org:443
npm ERR!
npm ERR! If you need help, you may report this error at:
npm ERR!     <https://github.com/npm/npm/issues>

npm ERR! Please include the following file with any support request:
npm ERR!     /root/.npm/_logs/2018-03-02T08_49_14_320Z-debug.log
The command '/bin/sh -c npm install' returned a non-zero code: 1

As per many articles in stackoverflow,
1)I have made changes in etc/hosts of Ubuntu as follows:
127.0.0.1       localhost
127.0.1.1       ubuntu-VirtualBox
151.101.16.162 registry.npmjs.org

# The following lines are desirable for IPv6 capable hosts
::1     ip6-localhost ip6-loopback
fe00::0 ip6-localnet
ff00::0 ip6-mcastprefix
ff02::1 ip6-allnodes
ff02::2 ip6-allrouters

2)I also made entry in /etc/default/docker as:
DOCKER_OPTS="--dns 151.101.16.162"

It is not working in docker build.
How can i proceed with steps to rectify it?

A: Kindly follow the following steps for rectifying the error in Ubuntu occurred in above:
1)Find out the ip of the Ethernet network by using ifconfig.
enp0s4: flags=4163<UP,BROADCAST,RUNNING,MULTICAST>  mtu 1500
        inet **10.X.X.XX**  netmask 255.255.255.0  broadcast 10.8.89.898

2)Create a new network and enable Default IP when binding container ports and mention the above ip address.
docker network create -o "com.docker.network.bridge.host_binding_ipv4"="10.X.X.XX" my-network

3)Use this newly created network to build the docker image:
docker build --network my-network -t hello-world .


text:
Q: Unable to verify the kernel signature "gpg: Can't check signature: public key not found" In order to compile a new kernel on my Debian jessie, I am trying to verify the GPG key , following the instruction on the official website.
I have download the the linux-3.18.35.tar.sign and linux-3.18.35.tar.xz version and unzip it using unzx.
To verify the .tar archive using the command :
gpg --verify linux-3.18.35.tar.sign

I get:
gpg: assuming signed data in `linux-3.18.35.tar'
gpg: Signature made Wed 08 Jun 2016 01:19:29 AM CET using RSA key ID 6092693E
gpg: Can't check signature: public key not found

To get the public key from the PGP keyserver  :
#gpg --keyserver hkp://keys.gnupg.net --recv-keys 6092693E

gpg: requesting key 6092693E from hkp server keys.gnupg.net
?: keys.gnupg.net: Host not found
gpgkeys: HTTP fetch error 7: couldn't connect: Connection refused
gpg: no valid OpenPGP data found.
gpg: Total number processed: 0

I get a similar problem with the 4.4.13 version too.
I have tried the following answer,
# gpg --keyserver subkeys.pgp.net --recv-keys 6092693E && gpg --export --armor 6092693E | sudo apt-key add -

gpg: requesting key 6092693E from hkp server subkeys.pgp.net
gpg: keyserver timed out
gpg: keyserver receive failed: keyserver error

And:
# gpg --keyserver subkeys.pgp.net:80 --recv-keys 6092693E

gpg: requesting key 6092693E from subkeys.pgp.net:80
gpgkeys: no keyserver host provided
gpg: keyserver internal error
gpg: keyserver receive failed: keyserver error

How to verify the kernel signature correctly?

A: You only need to have the public key in your keyring:
gpg --keyserver subkeys.pgp.net --recv-keys 0x38DBBDC86092693E

(use the long identifier!). If it times out, try again — there are multiple servers, and some of them seem to be having issues currently. apt-key etc. aren't involved in this at all.
Once you have the key in your keyring,
gpg --verify linux-3.18.35.tar.sign

should work.
You can also configure a key server pool instead (this is a good idea anyway):

*

*install gnupg-curl (apt-get install gnupg-curl on Debian);

*download the SKS CA
cd ~/.gnupg; wget https://sks-keyservers.net/sks-keyservers.netCA.pem

*verify it;

*add the following line to your ~/.gnupg/gpg.conf, or change it if it's already present:
keyserver hkps://hkps.pool.sks-keyservers.net

and set up the certificate by either adding
keyserver-options ca-cert-file=/home/.../.gnupg/sks-keyservers.netCA.pem

to ~/.gnupg/gpg.conf (for GnuPG 1) or
keyserver hkps://hkps.pool.sks-keyservers.net
hkp-cacert /home/.../.gnupg/sks-keyservers.netCA.pem

to ~/.gnupg/dirmngr.conf (for GnuPG 2), replacing the ... in the path with the appropriate value for your home directory in both cases.
Once you've done that,
gpg --recv-keys 0x38DBBDC86092693E

should retrieve the key reliably.
If all that fails, you can download and import the key manually:
curl 'http://pgp.surfnet.nl:11371/pks/lookup?op=get&search=0x38DBBDC86092693E' > gregkh.key
gpg --import gregkh.key


text:
Q: hibernate searching on a large table very slow I am using Hibernate 3.3 on my struts2 project and database is Oracle 11g . In that I have a scenario of implementing jQuery datatable searching on a table which has 16,000 rows (will be in Lakhs when goes for production). When I tested my hql and sql query with no 'where clause' on it, they took about 7 to 8 secs for 16000 rows. So I tried the same with JDBC connection it took just milliseconds to process it. Is there any other way to implement this with hibernate to optimize the fetching or should I proceed with JDBC connection for those kind of requirements?

A: There is no reason for Hibernate to be significantly slower than a query over JDBC (assuming the same SQL).
But your tested Hibernate version is very old, lots of performance improvements (and bugfixes) where fixed in more recent versions, like 4.3.6.Final (released later today).
So my guess would be that either you're not testing the same thing (for example, is your query via JDBC actually fetching data?) or hitting some old bug.
There where also multiple situations in which the JDBC drivers would be buggy.
If you are very unlucky you could be hitting a bug still present in latest version, but it's worth trying to update first.


text:
Q: Is $A^2 = A$ diagonalizable? I found the eigenvalues as $0$ and $1$. The eigenspaces are then the $NS(A)$ and the $CS(A)$, how do I prove that these spaces provide enough information to chose the correct eigenvectors and form a diagonalizable $A$ ?

A: For any $x \in V$, we have $x = Ax + (x - Ax)$.  Now, note that $A (Ax) = Ax$ so $Ax$ is in the eigenspace for $\lambda = 1$; and $A (x - Ax) = 0$, so $x - Ax$ is in the eigenspace for $\lambda = 0$.  This shows that the eigenvectors of $A$ span $V$.

A: Let $m(X)$ be the minimal polynomial of $A$ and $P(X)=X^2-X$. Then, since $P(A)=0$ we have $m(X) \mid X^2-X$.
This shows that the minimal polynomial of $A$ has distinct roots, and hence $A$ is diagonalisable.

A: You have $A^2 = A.$
If $x$ is in the column space of $A$ then $Ax=x.$ That is because $x = Ay$ for some vector $y,$ so $Ax= A(Ay) = A^2 y = Ay = x.$
If $x$ is not in the column space of $A$ then $x-Ax$ is in the null space of $A.$ That is because $A(x-Ax) = Ax-A^2x = Ax-Ax = 0.$
So every vector $x$ can be written as a member of the column space plus a member of the null space, thus: $x = \underbrace{\quad Ax\quad} {}+{} \underbrace{(x-Ax)}.$
This implies every vector can be written as a sum of an eigenvector with eigenvalue $1$ and an eigenvector with eigenvalue $0.$ In other words, the domain is the direct sum of those two eigenspaces. That means there is a basis of the domain consisting only of eigenvectors. With respect to that basis, the matrix of this linear transformation is diagonal. And every diagonal entry is $0$ or $1.$


text:
Q: Vue.js + Typescript : Class-based fetching with Axios using DTO architecture I tried to apply architecture found here:
I don't succeed retrieving array of objects Release to be then be displayed inside component via v-list. I would like to extract the list of object from the returned promise. Not sure how to do this in Release.vue.
ReleaseApi.ts
import Axios from "axios";
import Release, {ReleaseDTO} from '@/models/Release';

interface RequestInterface {
  map(arg0: (data: ReleaseDTO) => Release): Release[] | Promise<Release[]>;
  data: ReleaseDTO[]
}

export abstract class ReleasesApi {

private static instanceAxios = Axios.create({}); //baseURL: 'http://localhost:3000/'

  static async getAllReleases(): Promise<Release[]>{
    const response = await this.instanceAxios.get<RequestInterface>('api/releases');
    return response.data.map(data => new Release(data));
  }

}

Release.vue
<template>

Releases

Asynchroneous called when mount state

        <v-list>
          <v-list-item :key="index" v-for="(release, index) in releases">
          {{release.name}}

          </v-list-item>
        </v-list>

</template>

Release.ts
export class ReleaseInterface{
  release_id?: number;
  date?: Date;
  name?: string;

}

export class ReleaseDTO implements ReleaseInterface{
  release_id?: number = 0;
  date?: Date = new Date(2012, 0, 1);
  name?: string = "";

}

export default class Release extends ReleaseDTO {

  constructor(dto: ReleaseDTO){
    super();
    Object.assign(this, dto);
  }

  get fullName(): string {
    return `${this.release_id}  ${this.name}`;
  }

}

Using :
let releases : Release[] | Promise<Release[] = ref([]);

ERROR  Failed to compile with 1 error
4:52:53 PM
error  in
/home/jp/eclipse-workspace/Vue/scs/frontend/src/components/Release.vue.ts
[tsl] ERROR in
/home/jp/eclipse-workspace/Vue/scs/frontend/src/components/Release.vue.ts(10,49)
TS1005: '>' expected.
@ ./src/components/Release.vue?vue&type=script&lang=ts 1:0-327
1:0-327 1:328-644 1:328-644  @ ./src/components/Release.vue  @
./src/main.ts  @ multi
(webpack)-dev-server/client?http://192.168.226.145:8080&sockPath=/sockjs-node
(webpack)/hot/dev-server.js ./src/main.ts
Issues checking in progress... ERROR in
src/components/Release.vue:24:8 TS2322: Type 'Ref<never[]>' is not
assignable to type 'Release[] | Promise<Release[]>'.   Type
'Ref<never[]>' is missing the following properties from type
'Promise<Release[]>': then, catch, [Symbol.toStringTag], finally
22 |
23 |    let loading  = ref(false);

24 |    let releases : Release[] | Promise<Release[] = ref([]);
|        ^^^^^^^^
25 |
26 |   onMounted (  async () =>  {
27 |        loading.value  = false;

ERROR in src/components/Release.vue:28:17 TS2339: Property 'value'
does not exist on type 'Release[] | Promise<Release[]>'.   Property
'value' does not exist on type 'Release[]'.
26 |   onMounted (  async () =>  {
27 |        loading.value  = false;

28 |        releases.value =  await ReleasesApi.getAllReleases();
|                 ^^^^^
29 |        console.log(JSON.stringify(releases.value));
30 |        loading.value  = true;
31 |

ERROR in src/components/Release.vue:29:44 TS2339: Property 'value'
does not exist on type 'Release[] | Promise<Release[]>'.   Property
'value' does not exist on type 'Release[]'.
27 |        loading.value  = false;
28 |        releases.value =  await ReleasesApi.getAllReleases();

29 |        console.log(JSON.stringify(releases.value));
|                                            ^^^^^
30 |        loading.value  = true;
31 |
32 |   })


text:
Q: How can I display images in mail content? I want send e-mail with some images in content. I think I must attached this images as attachments to e-mail, but my proble is how can I use attached images in mail content?
CODE WHICH SEND MAIL
WebMail.SmtpServer = "my.smtp.server";
WebMail.Send(
        clientEmail,
        subject,
        "",
        myEmail,
        null,
        new List<string> () { "path" },
        true
    );

What I must write as src ?
Any help would be appreciated.

A: Also good sample at http://blog.devexperience.net/en/12/Send_an_Email_in_CSharp_with_Inline_attachments.aspx
System.Net.Mail.Message Class :
Sample ;
var msg = new System.Net.Mail.Message();
msg.isHTML=true;
msg.Body ="";

Attachment mya = new Attachment("file-path-here");
mya.ContentId="IMG1CONTENT";
msg.Attachments.Add(mya);

You can find more details @ http://msdn.microsoft.com/en-us/library/system.net.mail.attachment.aspx

A: To display the images in email content, one solution is to have an absolute URL. Upload the images to your server and use the abosoluter url as the src attribute value

But some email clients will disable external images. So user may need to enable "show images" when propmpted so.


text:
Q: Microsoft O365 Add-In "Installation failed" I have a valid and verified Add-In/manifest which passes npm run validate. I as well as hundreds of users are able to download my manifest through a link. However some users have been facing this error:

This app can't be installed. The manifest XML file isn't valid. For security reasons DTD is
prohibited in this XML document. To enable DTD processing set the DtdProcessing property on
XmlReaderSettings to Parse and pass the setting into XmlReaderCreate method.

In what situations can an error like this appear for some users?

A: I have actually bumped into this issue a year ago. Like @OutlookAdd-insTeam-MSFT suggested, I also believe this is related to networking, specifically to DNS.
Here's what I was able to find out, but unfortunately my client never came back and confirmed if it was useful.
(Please note that parts of the text is quoted from the sites listed at the bottom.)
Error message
Application cannot be installed. Manifest XML is not valid. For security reasons DTD is prohibited in this XML document. To enable DTD processing set the DtdProcessing property on XmlReaderSettings to Parse and pass the settings into XmlReader.Create method.
Why this happens?
When the manifest.xml is read by O365, it is being resolved via msoid.[organization_name].onmicrosoft.com and msoid.onmicrosoft.com. If this fails (due to a typo in etc.), a HTTP 404 error is invoked. At this point your ISP's DNS server should take over and offer to resolve the address according to it's CNAME record table.
However, some organizations might have an additional DNS assistance in place. Once a 404 error is detected by msoid resolver service, the ISP's DNS will try to take over the DNS resolving (DNS assistance). When that fails (due to a missing CNAME record or a typo), it returns an HTML-formatted query result back to O365. It is basically HTTP 200 response which is interpreted by O365 as a successful authentication.
After this O365 starts to process the HTML-formatted response as if it was the original manifest.xml. And as the HTML contains a DTD declaration in an incorrect way, you receive the error "For security reasons DTD is prohibited in this XML document".
Possible solutions:
a) Make sure DNS settings on the client's computer are set correctly.
b) Temporarily switch to another DNS server (e.g. Google DNS)
d) Turn off DNS assistance service (if applicable)
Please see the articles below for more information:
https://www.codetwo.com/kb/dtd-prohibited/
https://www.veeam.com/kb2821
http://sharepointers.blogspot.com/2017/03/connect-pnponline-for-security-reasons.html
https://learn.microsoft.com/fi-fi/office365/admin/services-in-china/purpose-of-cname?redirectSourcePath=%252fen-us%252farticle%252fWhat-s-the-purpose-of-the-Office-365-CNAME-record-for-msoid-19b67e2b-1b28-4432-8cca-394803fbdc87&view=o365-21vianet
https://blogs.msdn.microsoft.com/joerg_sinemus/2017/07/10/sharepoint-online-vanity-domain-powershell-csom-and-the-msoid-cname-record/

A: You can validate the manifest file against the XML Schema Definition (XSD) files. This will ensure that the manifest file follows the correct schema, including any namespaces for the elements you are using. If you copied elements from other sample manifests double check that you also include the appropriate namespaces. You can use an XML schema validation tool to perform this validation.
To use a command-line XML schema validation tool to validate your manifest you need:

*

*Install tar and libxml, if you haven't already.

*Run the following command. Replace XSD_FILE with the path to the manifest XSD file, and replace XML_FILE with the path to the manifest XML file.

xmllint --noout --schema XSD_FILE XML_FILE

Also, you can try to validate your manifest using the npm run validate command. See Validate an Office Add-in's manifest for more information.


text:
Q: Unsupported grant type in flutter get call For token refresh I'm using Get Call Rest Api:
final queryParameters = {
    'username': 'XXXX',
    'password': 'XXXXX',
    'grant_type': 'password',
  };final uri = Uri.http(baseUrl, AuthTokenUrl, queryParameters);
  var response = await httpClient.get(
      headers: {"Content-Type": "application/x-www-form-urlencoded"},
      uri: uri);

Postman body data:
username:XXXX password:XXXX grant_type:password

But my response is Status code:400 with response as Unsupported Grant type.
"{"error":"unsupported_grant_type"}"

I don't know why I'm getting unsupported grant-type in Http get call.In postman everything is working fine.
Any suggestion or solution will be greatly helpful,Please guide.

A: I had the same problem but i was making a post request i had solve it by moving jsonEncode because the data that i had to send to the api must not to be json so in your case you have to check about the data you are getting it is it json from the first place or no


text:
Q: Fourier Series Representation of Discontinuous Function $f(x) =
\begin{cases}
 1& \text{ if } -1\leq x < 0 \\
 1/2 & \text{ if } x = 0 \\
 x& \text{ if } 0 < x \leq 1
\end{cases} \text{for the interval} [-1,1]$
So I understand that you suppose to calculate the integral for every region but here at x = 0 function is 1/2. So should I add the f(0) value? For example for calculating $a_0$
$a_0 =\int_{-1}^{0}1dx +\int_{0}^{1}xdx$
or should i add f(0) value
$a_0 =\int_{-1}^{0}1dx +\int_{0}^{1}xdx + f(0)$


text:
Q: CakePHP 2.0 Account validation I'm trying to create a simply login page. I want validation on that page so that when a user clicks login the site checks that in the users database activated is set to 1, if not they can't login. I'm still very new to cakephp and am trying to pick up quickly so I'm sorry if this is a simple beginner question.
here is the validation in my User model
public $checkActive = array(
    'activated'=>array(
            'rule'=>array('equalTo', '0'),
            'message'=>'The account must be activated, please check your email.'
        ));

here is the login function in my usersController
 public function login() {

    $this->set('title_for_layout', 'Individual Registration');
    $this->set('stylesheet_used', 'style');
    $this->set('image_used', 'eBOXLogo.jpg');

    if ($this->request->is('post')){
    if ($this->request->data['User']['password'] == 'qazwsx'){
    if ($this->Auth->login()){
     if (0 === $this->User->find('count',array('conditions'=>array('enabled'=>1,'login'=> $username)))) {
         $this->Session->setFlash('Sorry, your account is not validated yet.');
    }

        $this->Auth->user('id');
        $this->redirect($this->Auth->redirect('eboxs/home'));
        }
    }
    else {

        $this->Session->setFlash('Username or password is incorrect');
    }
    }else{
    $this->Session->setFlash('Welcome, please login');
    }

}

here is my beforeLogin function in  the usersController
 public function beforeLogin(){

    if(isset($this->data['User']['password'])){
        $this->data['User']['password'] = AuthComponent::password($this->data['User']['password']);
        }
        return true;
    }

app controller
class AppController extends Controller {

    public $components = array(
        'DebugKit.Toolbar',
        'Session',
        'Auth'=>array(
            'loginRedirect'=>array('controller'=>'users', 'action'=>'login'),
            'logoutRedirect'=>array('controller'=>'users', 'action'=>'login'),
            'authError'=>"You can't access this page",
            'authorize'=>array('Controller')
        )
    );

    public function isAuthorized($user){
        return true;
    }

    public function beforeFilter(){
    $this->Auth->allow('index','view');
    $this->set('logged_in', $this->Auth->loggedIn());
    $this->set('current_user',$this->Auth->user());

    }

I realize that there is no call in my controller to the validation but with my other validation such as username is unique, I haven't had to call it.
in short at the moment anyone can log into my page, I'm trying to make it so only those who have 1 in the activated field in the users table can login.

A: Add a scope option to your auth setup:
'Auth'=>array(
        'loginRedirect'=>array('controller'=>'users', 'action'=>'login'),
        'logoutRedirect'=>array('controller'=>'users', 'action'=>'login'),
        'authError'=>"You can't access this page",
        'authorize'=>array('Controller'),
        'scope' => array('User.activated' => 1)
    )

This will prevent the user from logging in if they do not have User.activated = 1.
Also, look into your auth setup and re-read the manual page for CakePHP 2.0, you config looks like 1.3. There should be no need to check the password yourself, and you definitely don't need a beforeLogin method for such a simple setup.

A: One option would be to check account validation right after login like this :
<?php
if ($this->request->is('post')){
if ($this->request->data['User']['password'] == 'qazwsx'){
if ($this->Auth->login()) {

    // login ok, but check if activated
    $username = $this->request->data['User']['username'];
    if (0 === $this->User->find('count',array('conditions'=>array('activated'=>1,'username'=> $username)))) {
         $this->Session->setFlash('Sorry, your account is not validated yet.');
         $this->redirec($this->referer());
    }

    $this->Auth->user('id');
    $this->redirect($this->Auth->redirect('eboxs/home'));
    }
}


text:
Q: Jimp read, resize and display image from url I can now get some data of picture from url, when I do something like this:
Jimp.read("https://someurl/04fc0d67a91bbd3b7e07.jpeg", function (err, image) {

        console.log(image.bitmap.data)
        res.end(image.bitmap.data)
    });

I get buffer

Buffer 3d 3b 20 ff 41 3f 24 ff 46 44 29 ff 4c 4a 2f ff 4e 4c 31 ff 4b
  49 2e ff 47 43 2a ff 42 3e 25 ff 34 31 1a ff 2d 2a 13 ff 27 24 0f ff
  25 22 0d ff 21 20 . >..

Is possible to resize image and then retrive that image in response?

A: If you're looking for resizing you could try something like

jimp.read("https://i.imgur.com/2j12AxI.jpg").then(image => {

  //resize image using "contain" mode
  image.contain(100, 150);

  //retrieve image
  image.getBase64Async(jimp.MIME_JPEG).then(newImage => {
    let tag = document.createElement("img");
    tag.src = newImage;
    document.getElementById("img-container").append(tag)
  })
})

This is just a basic demonstration of how to downscale with a given target width/height. By default, it adds black borders if your numbers don't match.
There's another plugin to scale while keeping aspect ratio. The documentation looks pretty straightforward so you'll be able to find additional examples.


text:
Q: InetAddress.getLocalHost() always returns 127.0.0.1 Anyone knows why InetAddress.getLocalHost() always returns 127.0.0.1 although I have changed the ip inside /etc/hosts? After the change
hostname -i

returns the correct ip (192.168.x.x), but InetAddress.getLocalHost() is still the name.
I'm using jdk 1.6.0_31 by the way, on CentOS 6.2. Thanks!

A: because you have to restart your pc or clear dns cache to "apply" the changes

A: This could be a security restriction issue. From the javadoc:

If there is a security manager, its checkConnect method is called with
  the local host name and -1 as its arguments to see if the operation is
  allowed. If the operation is not allowed, an InetAddress representing
  the loopback address is returned.

A: An old question, but maybe this info will be helpful to someone else - I've struggled to find the information documented anywhere (maybe because it's not a formal part of the language spec), and had to determine via experimentation.
If the problem isn't down to the SecurityManager, then the most likely problem is that your name resolution at the OS level is screwed up somehow.
At least on all Unix platforms that I've tested on (OS X, Solaris, Linux), the process used by Java is:

*

*Determine local hostname

*Resolve that via /etc/hosts to determine IP address

I've seen this broken by badly-configured /etc/hosts, such as:
127.0.0.1 localhost myhost
1.2.3.4   myhost

to give exactly the symptoms described above.

A: *

*First of all LocalHost will always represents the LoopBack address 127.0.0.1(which is used to
debug the TCP/IP stack.) when Security manager founds that the operation is not allowed.

*For your LAN address use InetAddress.getByName("PC NAME").getHostAddress()
Please replace PC NAME with your Pc Name.
Eg:
public class StrTest {

    public static void main(String[] args) throws IOException {

            System.out.println(InetAddress.getByName("Vicky-PC").getHostAddress());

    }

}


text:
Q: 'Zend_Session_Exception Error in Zend Framework I have a website in zend framework which is install in another server. Now I have purchase a new server in ubuntu with Zend Engine 2.3.0 . I have installed Apache server, MYSQL , PHPMYADMIN Tool on this server. Then I upload all the files on previous server to the new server. I have also change the urls in the index.php files.
But it is giving me error.
**Uncaught exception 'Zend_Session_Exception' with message 'Zend_Session::start() - /var/www/sample/library/Zend/Session.php(Line:477):Error #2 session_start(): open(/vlk_session/sess_ielitiholu4219p3nph6lkk8n6, O_RDWR) failed: No such file or directory (2) /var/www/videoliked/library/Zend/Session.php(Line:487): **
This is my below code of index.php file
    Zend_Layout::startMvc($options);

Zend_Session::setOptions(array('save_path'=>'/vlk_session'));
if(isset($_COOKIE["Zend_Auth_RememberMe"]) && $_COOKIE["Zend_Auth_RememberMe"] !== false){
    Zend_Session::rememberMe("5302000");
    setcookie("Zend_Auth_RememberMe", false, time(), "/");
}

if(!Zend_Session::isStarted()){

    Zend_Session::start();

}

A: The save path is absolute.
Did you create the folder /vlk_session on your server?
I'd suggest to use and create
/tmp/vlk_session

Instead, or lookup the PHP default folder for sessions in your php.ini and use the one suggested by vendor.
Update:
Make sure the PHP instance is allowed to read/write that folder.


text:
Q: "At risk", or "at-risk"? What's the difference? I often see press releases from non-profits or NGOs talking about "at-risk" youth or groups that are most "at risk" of one horrible thing or another. The thing is, none of them seem consistent as to whether or not the hyphen is supposed to be used, or if it's supposed to be used in one situation, but not another.
I looked up the definition of at-risk (with hyphen), and this is what Oxford Dictionaries Online says:

Adjective Vulnerable, especially to abuse or delinquency:
'a church-run school for the most at-risk children'

Then I looked up at risk (no hyphen) in ODO and this is what it said:

Exposed to harm or danger:
'23 million people in Africa are at risk from starvation'

It looks to me like at-risk is used when immediately preceding the noun that it is describing, like in "at-risk children", while at risk is used when you are using a preposition, like "at risk from starvation" or "at risk of memory loss."
If this is the case, is there any source or style guide that prescribes or explains this phenomenon? After some internet searching, I wasn't able to find anything that documents the usage of hyphens to turn phrases into adjectives.

A: At risk is a prepositional phrase, in which risk is a figurative location.  You are at risk when you are in a continual state of risking some sort of harm.  (English likes to conceptualize abstract states as locations, each with its obligatory preposition: in danger, in love, on cloud nine, under the weather, ... please suggest more examples in the comments.)
Adding a hyphen, at-risk, transforms the phrase into an adjective, meaning "the modified noun has the property of being at risk".  You can use hyphens this way with any prepositional phrase.  For instance, suppose you have

Jane McFamousPerson's fans in Los Angeles were excited to attend her public Q&A session last Thursday ...

you can turn that into

Jane McFamousPerson's in-Los-Angeles fans were excited ...

with basically the same meaning.  However, it is unusual to do this with "ordinary" prepositional phrases.  At-risk gets used this way a lot because it's neutral -- it expresses no judgment on how the group at risk got to be that way.  That's important when you're an NGO trying to help people.  So it is preferred to more colorful terms (e.g. impoverished) which, in English, often carry a weight of moral disapproval.


text:
Q: Is there an equivalent to __MODULE__ for named functions in Elixir/ Erlang? Is there an equivalent for retrieving the name of a function just like like __MODULE__ retrieves the name of a Module in Elixir/Erlang?
Example:
defmodule Demo do
  def home_menu do
    module_name = __MODULE__
    func_name = :home_menu
    # is there a __FUNCTION__
  end
End

EDITED
The selected answer works,
but calling the returned function name with apply/3 yields this error:
[error] %UndefinedFunctionError{arity: 4, exports: nil, function: :public_home, module: Demo, reason: nil}

I have a function :
defp public_home(u, m, msg, reset) do

end

The function in question will strictly be called within its module.
Is there a way to dynamically call a private function by name within its own module?

A: Yes, there is. In Erlang there are several predefined macros that should be able to provide the information you need:
% The name of the current function
?FUNCTION_NAME

% The arity of the current function (remember name alone isn't enough to identify a function in Erlang/Elixir)
?FUNCTION_ARITY

% The file name of the current module
?FILE

% The line number of the current line
?LINE

Source: http://erlang.org/doc/reference_manual/macros.html#id85926

A: ▶ defmodule M, do: def m, do: __ENV__.function
▶ M.m
#⇒ {:m, 0}

Essentially, __ENV__ structure contains everything you might need.

A: To add to Aleksei's answer, here is an example of a macro, f_name(), that returns just the name of the function.
So if you use it inside a function, like this:
def my_very_important_function() do
   Logger.info("#{f_name()}: about to do important things")
   Logger.info("#{f_name()}: important things, all done")
end

you will get a log statement similar to this:
my_very_important_function: about to do important things
my_very_important_function: important things, all done

Details:
Here is the definition of the macro:
defmodule Helper do
  defmacro f_name() do
    elem(__CALLER__.function, 0)
  end
end

(__CALLER__ is just like __ENV__, but it's the environment of the caller.)
And here is how the macro can be used in a module:
defmodule ImportantCodes do
  require Logger
  import Helper, only: [f_name: 0]

  def my_very_important_function() do
     Logger.info("#{f_name()}: doing very important things here")
  end
end


text:
Q: How should I assign Postgres date type to a variable I'm inserting expiration dates into Postgres in a column which has this schema:
exp  DATE  NOT NULL
The way I'm creating these dates in Golang is with the "time" library that uses a Time data type (Not sure if it's underlying type is a string, the go docs didn't really specify see here).
Here's how I'm doing the insertion with the pgx library
expirationDate := time.Unix(expiresAt, 0)
sql := `
  insert into items
  (sub, uuid, exp)
  VALUES ($1, $2, $3)
`
_, err := connection.Exec(
  context.Background(),
  sql,
  subject,
  id,
  expirationDate,
)

Somewhere else in my code expiresAt is made like this:
days := 1 * 24 * time.Hour
expirationTime := time.Now().Add(days)
expirationTime.Unix() // this is what's being passed in my function (expiresAt int64) that does the DB insertion

The problem is trying to get that date back out of Postgres.
When I look at it in pgAdmin I see it's being stored as yyyy-mm-dd so I assumed maybe I could assign it to a string variable so I tried this:
type RevokedRefreshToken struct {
  OldUUID           string
  OldExpirationDate string
}
var revokedRefreshToken RevokedRefreshToken
err := connection.QueryRow(context.Background(), "select uuid, exp from items where sub = $1", subject).
Scan(&revokedRefreshToken.OldUUID, &revokedRefreshToken.OldExpirationDate)

I also tried:
- int64 type
- Time  type
- not passing it using its memory address (without the & in Scan())
I still can't figure out the data type I'm suppose to assign this DB value to.
Here is the error I'm getting that I think is from pgx:
can't scan into dest[1]: unable to assign to *string
What data type do I need to be using to assign this DB value of PostgreSQL date type

A: If I remember correctly pgx maps DATE to time.Time. To scan you either need a pointer to the pointer or use pgx's pgtype.Date datatype (I am used to these so I always use them):
var dt pgtype.Date
err := conn.QueryRow("select exp from items where sub = $1", 1).Scan(&dt)

pgtype.Date has then field called Time which is of type time.Time so you should be able to work with it normally. See documentation.


text:
Q: List assignment index out of range error I'm trying to create a simple array program and print out the array elements but getting an error right after I input employee 2 value saying: IndexError: list assignment index out of range.
#Create constant for the number of employees.
SIZE = 3

#Create an array to hol the number of hours worked by each employee.
hours = [SIZE]

#Get the hours worked by employee 1.
hours[0] = int(input("Enter the hours worked by employee 1: "))

#Get the hours worked by employee 2.
hours[1] = int(input("Enter the hours worked by employee 2: "))

#Get the hours worked by employee 3.
hours[2] = int(input("Enter the hours worked by employee 3: "))

#Display the values entered.
print("The hours you entered are:")
print(hours[0])
print(hours[1])
print(hours[2])

A: You seem to have the wrong idea on how arrays work in Python. Essentially what you're doing when you typed
#Create constant for the number of employees.
SIZE = 3

#Create an array to hol the number of hours worked by each employee.
hours = [SIZE]

Is create an array with one element with a value of 3
hours = [3]

A: Python doesn't have literal arrays: it has lists. hours = [SIZE] doesn't create a list with 3 elements: it creates a list with 1 element. You should use append() to add items to a list, not indexing past the end of the array.
The correct code would look something like this to add elements to the list:
hours.append(int(input("Enter the hours worked by employee 1: ")))
hours.append(int(input("Enter the hours worked by employee 2: ")))
hours.append(int(input("Enter the hours worked by employee 3: ")))

From the comments, it seems you're learning code from a pseudocode textbook: that's wonderful. Just remember though that certain conventions common to pseudocode, or sometimes C-like languages may be different in other programming languages. For example, in C, this declares an array of 50 chars named x.
char x[50];

In Python, you cannot use the same syntax. Good luck.