text:
Q: Angular 7 : problem while trying to using a method service in a component I'm trying to learn how to use Angular 7. I follow the guide on his official site and now I want to do a Form for try to calculate the fiscal code ( for italian people only ). The user will insert the data for calculate it and when you start to type your fiscal code the program in background start to calculate it and when they are equal the form will stamp a message that say: "Right" or something like that. I made a service to do the calculation and validate it with a custom validator a get request to a specific URL for retrieve the city code. The problem is: when i try to call the method of the service in the component it return this error " ERROR TypeError: Cannot read property 'json' of undefined ". Some one of you have the solution?
COMPONENT CODE :
    import { Component, OnInit } from '@angular/core';
import { FormControl, Validators, FormGroup, AbstractControl } from '@angular/forms';
import { citta } from '../country';
import { validazioneData } from '../validatorCustom';
import { JsonService } from '../json.service';

@Component({
  selector: 'app-form',
  templateUrl: './form.component.html',
  styleUrls: ['./form.component.css']
})

export class FormComponent implements OnInit {

  codice: any;

  successo = false;

  cities = citta;

  mioForm: FormGroup;

  invioForm() {
    if (this.mioForm.valid)
      this.successo = true;
  }

  constructor(private json: JsonService) { }

  ngOnInit() {
    this.mioForm = new FormGroup({

      nome: new FormControl('', [Validators.required, Validators.maxLength(10), Validators.minLength(3)]),
      cognome: new FormControl('', [Validators.required, Validators.maxLength(10), Validators.minLength(3)]),
      sesso: new FormControl('', Validators.required),
      dataDiNascita: new FormControl('', [Validators.required, validazioneData]),
      citta: new FormControl('Catanzaro', Validators.required),
      codiceFiscale: new FormControl('', [Validators.required,  this.validatoreCf])

    });
  }

  validatoreCf(control: AbstractControl): { [key: string]: any } | null {
    if (control && (control.value !== null && control.value !== undefined && control.value !== "" && isNaN(control.value))) {

      this.codice = this.json.getCF(control);

      if (this.codice === control.root.get('codiceFiscale').value.toString().trim().toUpperCase()) {
        return null;
      }

      return {
        validCF: true
      }
    }
  }
}

HTML COMPONENT CODE :

MIO FROM

<form (ngSubmit)='invioForm()' [formGroup]="mioForm">

    Nome:
    <input type="text" formControlName="nome" placeholder="Inserisci il nome">

      Nome Richiesto!

      La lunghezza deve essere compresa tra i 2 e i 12 caratteri!

    Cognome:
    <input type="text" formControlName="cognome" placeholder="Inserisci il cognome">

      Cognome Richiesto!

      La lunghezza deve essere compresa tra i 2 e i 12 caratteri!

    Sesso:
    <select formControlName="sesso">
      <option value="M">M</option>
      <option value="F">F</option>
    </select>

      Sesso Richiesto!

    Data di nascita:
    <input type="date" formControlName="dataDiNascita">

      Data di nascita Richiesta!

      Data di nascita non valida!

    Città:
    <select formControlName="citta">
      <option *ngFor="let c of cities" value="{{c.nome}}">{{c.nome}}</option>
    </select>

      Citta Richiesta!

    CODICE FISCALE:
    <input type="text" formControlName="codiceFiscale">

Errore

    <button>submit</button>

</form>

  BRAVISSIMO

SERVICE CODE :
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { AbstractControl } from '@angular/forms';
import { mesi, charDispari, charPari, finale } from './costanteCF';

@Injectable({
  providedIn: 'root'
})

export class JsonService {

  constructor(private http: HttpClient) { }

  //Validazione codice fiscale
  getCF(control : AbstractControl) {
     console.log(control);
      let codice: string = "";
      var pt1: string;
      var pt2: string;
      var pt3: string;
      var pt4: string;
      var pt5: string;
      var cf: string;

      if ((control.root.get('cognome') !== null || undefined) && control.root.get('nome') !== null && control.root.get('citta') !== null && control.root.get('dataDiNascita') !== null && control.root.get('sesso') !== null){

        pt1 = this.primaPT(control.root.get('cognome').value);
        pt2 = this.secondaPT(control.root.get('nome').value);
        pt3 = this.terzaPT(control.root.get('dataDiNascita').value, control.root.get('sesso').value);
        pt4 = this.quartaPT(control.root.get('citta').value);
        pt5 = this.quintaPT(cf);

          codice = pt1 + pt2 + pt3 + pt4 + pt5;

        return codice.toString().trim().toUpperCase();
      }
    }

    getCCC(nomeCitta: any): String {

      let risultato: any;

      this.http.get('http://www.gerriquez.com/comuni/ws.php?dencomune='+nomeCitta).subscribe(dato => risultato = dato);

      console.log(risultato);

      risultato = JSON.parse(risultato);

      risultato = risultato.CodiceCatastaleDelComune.value;

      console.log("ciao"+risultato);

      return risultato;
    };

  //quarta parte relativa alla citta
  quartaPT(citta: any): string {

    let http: HttpClient;

    //let form = new FormComponent(http);

    if (citta !== undefined && citta !== null && citta !== "")
      citta = this.getCCC(citta);

    return citta;
  }

  //Ultima lettera
  quintaPT(cf: any): string {

    if (cf !== undefined && cf !== null && cf !== "") {

      let dispari = charDispari;

      let pari = charPari;

      let finali = finale;

      let somma: number;
      let carattereFinale: string;
      let ar = cf.split('');

      for (var i = 0; i < ar.length; i++) {
        if ((i % 2) === 0) {
          for (let a of dispari) {
            if (a.n1 === (ar[i])) {
              somma = somma + a.n2;
            }
          }
        }
      }

      for (var i = 0; i < ar.length; i++) {
        if ((i % 2) === 1) {
          for (let a of pari) {
            if (a.n1 === (ar[i])) {
              somma = somma + a.n2;
            }
          }
        }
      }

      for (let a of finali) {
        if ((somma % 26) === a.n2) {
          carattereFinale = a.n1;
        }
      }

      return carattereFinale;
    }
    return "";
  }

  //Terza parte relativa alla datra di nascita
  terzaPT(dataDiNascita: any, sesso: any): string {

    if (dataDiNascita && sesso !== undefined && dataDiNascita && sesso !== null && dataDiNascita && sesso !== "") {

      let listaMesi = mesi;

      let data: any = new Date(dataDiNascita);

      dataDiNascita.toString();

      dataDiNascita = '';

      dataDiNascita += data.getFullYear();

      let mese = data.getMonth();
      for (let a of listaMesi) {
        if (mese === a.Mese) {
          mese = a.lettera.toString();
          dataDiNascita += mese;
        }
      }

      let giorno = data.getDay();

      if (sesso.toUpperCase() === 'F')
        giorno = giorno + 40;

      dataDiNascita += giorno;

      return dataDiNascita;
    }
    return "";
  }

  //Seconda parte relativa al nome
  secondaPT(nome: any): string {

    if (nome !== undefined && nome !== null && nome !== "") {
      nome = nome.trim().toUpperCase();

      if (nome.length < 3) {
        let ar = nome.split('');
        if (ar.length === 2) {
          ar.push('X');
          return ar.toString();
        }

        ar.push('X');
        ar.push('X');
        return ar.toString();
      }

      let cont = 0;
      let ar = nome.split('');
      console.log(ar);
      nome = '';

      for (var i = 0; i < ar.length; i++) {
        if (nome.length < 3 && (ar[i] !== 'A' && ar[i] !== 'E' && ar[i] !== 'I' && ar[i] !== 'O' && ar[i] !== 'U')) {
          if (cont !== 1) {
            nome += ar[i];
            cont++;
            ar[i] = null;
          }
        }
      }

      if (nome.length < 3) {
        for (var i = 0; i < ar.length; i++) {
          if (ar[i] !== null) {
            nome += ar[i];
            ar[i] = null;
          }
        }
      }

      return nome;

    }
    return "";
  }

  //Prima parte relativa al cognome
  primaPT(cognome: any): string {

    if (cognome !== undefined && cognome !== null && cognome !== "") {
      cognome = cognome.trim().toUpperCase();

      if (cognome.length < 3) {
        let ar = cognome.split('');
        if (ar.length === 2) {
          ar.push('X');
          return ar.toString();
        }

        ar.push('X');
        ar.push('X');
        return ar.toString();
      }

      let ar = cognome.split('');
      console.log(ar);
      cognome = '';

      for (var i = 0; i <= ar.length; i++) {
        if (cognome.length < 3) {
          if (ar[i] !== 'A' && ar[i] !== 'E' && ar[i] !== 'I' && ar[i] !== 'O' && ar[i] !== 'U') {
            cognome += ar[i];
          }
        }
      }

      return cognome;
    }
    return "";
  }

}

ERROR CODE :
  ERROR TypeError: Cannot read property 'json' of undefined
    at push../src/app/form/form.component.ts.FormComponent.validatoreCf (form.component.ts:48)
    at forms.js:658
    at Array.map (<anonymous>)
    at _executeValidators (forms.js:658)
    at forms.js:623
    at forms.js:658
    at Array.map (<anonymous>)
    at _executeValidators (forms.js:658)
    at FormControl.validator (forms.js:623)
    at FormControl.push../node_modules/@angular/forms/fesm5/forms.js.AbstractControl._runValidator (forms.js:2914)

A: Seems like a context error to me (i.e. your this keyword doesn't reference your component anymore).
This usually happens when you bind a function to another or use a shortened syntax to make the call.
Try this, tell me how it goes :
Validator :
codiceFiscale: new FormControl('', [Validators.required,  this.validatoreCf()])

Function :
validatoreCf() {

  return (control: AbstractControl): { [key: string]: any } | null {
    if (control && (control.value !== null && control.value !== undefined && control.value !== "" && isNaN(control.value))) {

      this.codice = this.json.getCF(control);

      if (this.codice === control.root.get('codiceFiscale').value.toString().trim().toUpperCase()) {
        return null;
      }

      return {
        validCF: true
      }
    }
  }
}

A: In order to access this.json property, you have to initialize it, just like you did with codice, sucesso, and then instance it on your constructor
constructor(private json: JsonService) { this.json = json; }


text:
Q: LINQ Group By and Intersection between groups C# I have the following list into C#:
table_schema | table_name | field_name | field_type
public         tableA       fieldA       character varying
public         tableA       fieldB       timestamp
public         tableA       fieldC       bytea
public         tableB       fieldA       character varying
public         tableB       fieldD       integer
other          tableC       fieldA       character varying
other          tableC       fieldE       integer

So   the field with name fieldA and type character varying exists to all.
The output should be a list object :
field_name | field_type
fieldA       character varying

A: I suggest GroupBy and then Aggregate all these groups while Intersecting their content:
var list = ...

var result = list
  .GroupBy(item => (item.table_schema, item.table_name),
           item => (item.field_name, item.field_type))
  .Select(group => group.AsEnumerable())
  .Aggregate((current, item) => current.Intersect(item))
  .ToList(); // <- Let's have a list of tuples

The only trick is line
   .Select(group => group.AsEnumerable())

We don't want to aggregate by IGrouping<K, V> but by more general IEnumerable<V>

redpajama_set_name: RedPajamaStackExchange


text:
Q: Visual Studio 2010 displays an error when I try to view a projects Properties I get the following error when i try to open a projects properties page in Visual Studio 2010:
An error occurred trying to load the project properties window.  Close the window and try again.
Invalid pointer (Exception from HRESULT: 0x80004003 (E_POINTER))

Anyone seen this before.  I found one suggestion of reinstalling .net 4 but this didn't seem to make any difference.  The problem seems to have happened after we joined our Team Foundation server to the domain, but I can't see how that would have caused the problem.
This is the same for any project.


text:
Q: Avoid branching from a branch in git Twice now in git, I've meant to branch from master, but instead branched from my current branch by accident. This means that my pull request from the second branch included all of the commits in the first branch, which haven't been merged yet.
Is there a way I can double check to confirm before branching from a non-master branch?

A: Why not supply a second parameter to git checkout -b:
$ git checkout -b newbranch master

The second parameter is where to branch from.

A: Assuming you're using a Unix-type shell, here's a simple function you could adapt:
function git() {
    if [ $# -eq 3 -a "$1" = "checkout" -a "$2" = "-b" ] ; then
        curbranch=$(git name-rev --name-only HEAD)
        if [ "$curbranch" != "master" ] ; then
          echo "You're on branch $curbranch."
          echo "Confirm new branch creation? [yn]"
          read a
          if [ "$a" != "y" ] ; then
              echo Aborted.
              return 1
          fi
      fi
    fi
    /usr/bin/git $@
}

Will only trigger on git checkout -b one_other_param.
Note: this will probably not work as expected if you're in a "detached head" state. The git name-rev won't give correct information I believe.

A: Add $(__git_ps1) to your command prompt (PS1 variable in your shell rc file) and you will always see what is your current branch.

A: if you run
git branch

you get something like this:
  branch1
  branch2
* master

And the star marks which branch on which you are currently located.

A: You may write bash script, that you will use instead of git.
On creating new branch it will check is you in master.
If no, it will stops(or ask you to continue), and if yes, it will execute real git
For example, you may name it gitcheckout


text:
Q: Implementing Borland's __emit__ macro in GCC In Borland, there is a macro __emit__, "a pseudo-function that injects literal values directly into the object code" (James Holderness).
Is there an equivalent for gcc / g++?
(I can't seem to find one in the documentation)
If not, how could I implement it in my C++ source code?

Usage can be found at Metamorphic Code Examples

A: You can take a look at .byte assembler directive:
asm __volatile__ (".byte 0xEA, 0x00, 0x00, 0xFF, 0xFF");

GCC's optimizers sometimes discard asm statements if they determine there is no need for the output variables. Also, the optimizers may move code out of loops if they believe that the code will always return the same result (i.e. none of its input values change between calls). Using the volatile qualifier disables these optimizations.
Anyway you should pay attention to many corner cases (e.g. gcc skips asm code after goto...)


text:
Q: Can mod-rewrite be used to set environmental variables? I've got an existing simple rewrite rule like so:
<Directory /path>
    RewriteEngine on
    RewriteBase /

    # if the requested resource does not exist
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d

    # route the uri to a front controller
    RewriteRule ^(.*)$ index.php/$1 [L]
 </Directory>

This works fine, but I want to do one of either two things. On the basis of detecting the
clients accept-language header, I want to either
(i) Set the detected language as an environmental variable that the script can use or
(ii)Rewrite the request so that the url begins with the language code (e.g. www.example.com/en/some/resource)
In terms of implementing (i), I defined this rule:
<Directory /path>
    RewriteEngine on
    RewriteBase /

    # if the requested resource does not exist
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d

    # if the users preferred language is supported...
    RewriteCond %{HTTP:Accept-Language} ^.*(de|es|fr|it|ja|ru|en).*$ [NC]
    # define an environmental variable PREFER_LANG
    RewriteRule ^(.*)$ - [env=PREFER_LANG:%1]

    # route the uri to a front controller
    RewriteRule ^(.*)$ index.php/$1 [L]
 </Directory>

I've tried a few variations, but PREFER_LANG is not defined in $_SERVER nor retrievable by getenv.
In terms of implementing (ii)... lets just say its messy. I'll post it if I can't get an answer to one.
Can anyone advise me? Thanks!

A: It's certainly possible to set environment variables using mod_rewrite.  Using the following configuration:
RewriteEngine on
RewriteLog /var/log/httpd/rewrite.log
RewriteLogLevel 5

# if the requested resource does not exist
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d

# if the users preferred language is supported...
RewriteCond %{HTTP:Accept-Language} ^.*(de|es|fr|it|ja|ru|en).*$ [NC]
# define an environmental variable PREFER_LANG
RewriteRule ^(.*)$ - [env=PREFER_LANG:%1]

# route the uri to a front controller
RewriteRule ^(.*)$ /cgi-bin/serverfault.cgi?q=$1 [PT]

Where serverfault.cgi is just a shell script that calls env.  This works just fine:
$ curl -s -H 'Accept-language: de' http://localhost/serverfault/somefile |
grep PREFER
PREFER_LANG=de

What does your RewriteLog look like?  You should see something like this:
init rewrite engine with requested uri /serverfault/foo.html
applying pattern '^(.*)$' to uri '/serverfault/foo.html'
RewriteCond: input='/serverfault/foo.html' pattern='!-f' => matched
RewriteCond: input='/serverfault/foo.html' pattern='!-d' => matched
RewriteCond: input='en-US,en;q=0.8' pattern='^.*(de|es|fr|it|ja|ru|en).*$' [NC] => matched
setting env variable 'PREFER_LANG' to 'en'
applying pattern '^(.*)$' to uri '/serverfault/foo.html'
rewrite '/serverfault/foo.html' -> '/cgi-bin/serverfault.cgi?q=/serverfault/foo.html'
split uri=/cgi-bin/serverfault.cgi?q=/serverfault/foo.html -> uri=/cgi-bin/serverfault.cgi, args=q=/serverfault/foo.html
forcing '/cgi-bin/serverfault.cgi' to get passed through to next API URI-to-filename handler

A: According to a comment at PHP manual it's possible. Is PHP integrated as module or CGI?


text:
Q: what can be the reason for no permission even using root or sudo When root or using sudo, I cannot write to some files.
I have a file fileA with permissions 750
fileA rwxr_x___ root root

When I run a program as root or using sudo, the system prompt is:
no write permission to this file.

What can be the possible reason?

A: Run lsattr and make sure the files don't have the i attribute set. That means "immutable", and when it is set, nobody - not even root - can change them.

A: Check to make sure that the files are not located on a read only device, or that the device is mounted as read only.


text:
Q: Flask Formsubmission Error I am trying to follow This Tutorial to add forms to my crappy site.  Progress is local, so the contact page on my site is broken.
Specifically, I am having trouble getting flask to recognize the post request.  Watching the debugger has given clues, errors below.  I followed the (linked about) tutorial, and was able to get it to work, I'm attempting to move a similar idea to my site, this is not working.
Watching the debugger, I go to the contact page, fill in the form and hit submit.  The get works, the post does not.
Log:
127.0.0.1 - - [13/Mar/2015 22:11:47] "GET /contact HTTP/1.1" 200 -
127.0.0.1 - - [13/Mar/2015 22:11:50] "POST /mail/contact_me.php HTTP/1.1" 404 -

I have no idea what /mail/contact_me.php is, I have no such named file or folder for that matter.
A major clue (which makes no sense to me) is that removing the template inheritance from this contact.html allows the form to work.
The original (non-functional) contact.html is:
{% extends "base.html" %}
{% block content %}

Contact

<form action="{{ url_for('contact') }}" method=post>
{{ form.hidden_tag() }}

{{ form.name.label }}
{{ form.name }}

{{ form.email.label }}
{{ form.email }}

{{ form.subject.label }}
{{ form.subject }}

{{ form.message.label }}
{{ form.message }}

{{ form.submit }}
</form>
{% endblock %}

Removing the templating (removal of the first two and last lines) allows the form to post correctly.  After removing, reloading the page and submitting the form I get the following logs in the debugger:
127.0.0.1 - - [13/Mar/2015 22:43:46] "GET /contact HTTP/1.1" 200 -
127.0.0.1 - - [13/Mar/2015 22:43:48] "POST /contact HTTP/1.1" 200 -

it also now works, submission of the form returns the placeholder string.
It appears my template is somehow breaking the form, what do you think is causing this?
Other possibly relevant chunks of code.
routing file
.
.
@app.route('/contact', methods=['GET', 'POST'])
def contact():
  form = ContactForm()
  if request.method == 'POST':
    return 'Form posted.'

  elif request.method == 'GET':
    return render_template('contact.html', form=form)
.
.

forms.py
from flask_wtf import Form
from wtforms import TextField, TextAreaField, SubmitField
class ContactForm(Form):
    name = TextField("Name")
    email = TextField("Email")
    subject = TextField("Subject")
    message = TextAreaField("Message")
    submit = SubmitField("Send")

A more complete example of my code is here, though recent changes-code above- haven't been pushed.  I need more reputation but its https:// github.com/terwilld/website
Thanks

A: I think I found your error.  Your clean-blog.min.js file is intercepting your Submit event and POSTING to that bogus URI:
$(function () {
    $("input,textarea").jqBootstrapValidation({
        preventSubmit: !0, submitError: function () {
        }, submitSuccess: function (a, b) {
            b.preventDefault();
            var c = $("input#name").val(), d = $("input#email").val(), e = $("input#phone").val(), f = $("textarea#message").val(), g = c;
            g.indexOf(" ") >= 0 && (g = c.split(" ").slice(0, -1).join(" ")), $.ajax({
                url: "././mail/contact_me.php",
                type: "POST",
                data: {name: c, phone: e, email: d, message: f},

Sounds like you need to re-think the usage of that JavaScript file.


text:
Q: How can I check if a timestamp entry is within a time range and with a person filter in two different dataframe? I need to check if an entry is within a person's shift:
The data looks like this:
timestamp = pd.DataFrame({
    'Timestamp': ['01/02/2022 16:08:56','01/02/2022 16:23:31','01/02/2022 16:41:35','02/02/2022 16:57:41','02/02/2022 17:38:22','02/02/2022 17:50:56'],
    'Person': ['A','B','A','B','B','A']
})

shift = pd.DataFrame({
    'Date': ['01/02/2022','02/02/2022','01/02/2022','02/02/2022'],
    'in':['13:00:00','13:00:00','14:00:00','14:00:00'],
    'out': ['21:00:00','21:00:00','22:00:00','22:00:00'],
    'Person': ['A','A','B','B']
})

A: For this kind of merge, an efficient method is to use merge_asof:
timestamp['Timestamp'] = pd.to_datetime(timestamp['Timestamp'])

(pd.merge_asof(timestamp.sort_values(by='Timestamp'),
               shift.assign(Timestamp=pd.to_datetime(shift['Date']+' '+shift['in']),
                            ts_out=pd.to_datetime(shift['Date']+' '+shift['out']),
                            ).sort_values(by='Timestamp')
                    [['Person', 'Timestamp', 'ts_out']],
               on='Timestamp', by='Person'
              )
   .assign(in_shift=lambda d: d['ts_out'].ge(d['Timestamp']))
   .drop(columns=['ts_out'])
)

output:
            Timestamp Person  in_shift
0 2022-01-02 16:08:56      A      True
1 2022-01-02 16:23:31      B      True
2 2022-01-02 16:41:35      A      True
3 2022-02-02 16:57:41      B      True
4 2022-02-02 17:38:22      B      True
5 2022-02-02 17:50:56      A      True

A: I assume that there is only one shift per person per day.
First I split the day and time from the timestamp dataframe. Then merge this with the shift dataframe on columns Person and Date. Then we only need to check whether the time from timestamp is between in and out.
timestamp[['Date', 'Time']] = timestamp.Timestamp.str.split(' ', 1, expand=True)

df_merge = timestamp.merge(shift, on=['Date', 'Person'])

df_merge['Timestamp_in_shift'] = (df_merge.Time <= df_merge.out) & (df_merge.Time >= df_merge['in'])

df_merge.drop(columns=['Date', 'Time'])

Output:
             Timestamp Person        in       out  Timestamp_in_shift
0  01/02/2022 16:08:56      A  13:00:00  21:00:00                True
1  01/02/2022 16:41:35      A  13:00:00  21:00:00                True
2  01/02/2022 16:23:31      B  14:00:00  22:00:00                True
3  02/02/2022 16:57:41      B  14:00:00  22:00:00                True
4  02/02/2022 17:38:22      B  14:00:00  22:00:00                True
5  02/02/2022 17:50:56      A  13:00:00  21:00:00                True


text:
Q: Developing UI in JavaScript using TDD Principles I've had a lot of trouble trying to come up with the best way to properly follow TDD principles while developing UI in JavaScript.  What's the best way to go about this?
Is it best to separate the visual from the functional?  Do you develop the visual elements first, and then write tests and then code for functionality?

A: I've never successfully TDDed UI code. The closest we came was indeed to separate UI code as much as possible from the application logic. This is one reason why the model-view-controller pattern is useful - the model and controller can be TDDed without much trouble and without getting too complicated.
In my experience, the view was always left for our user-acceptance tests (we wrote web applications and our UATs used Java's HttpUnit). However, at this level it's really an integration test, without the test-in-isolation property we desire with TDD. Due to this setup, we had to write our controller/model tests/code first, then the UI and corresponding UAT. However, in the Swing GUI code I've been writing lately, I've been writing the GUI code first with stubs to explore my design of the front end, before adding to the controller/model/API. YMMV here though.
So to reiterate, the only advice I can give is what you already seem to suspect - separate your UI code from your logic as much as possible and TDD them.

A: I've done some TDD with Javascript in the past, and what I had to do was make the distinction between Unit and Integration tests. Selenium will test your overall site, with the output from the server, its post backs, ajax calls, all of that. But for unit testing, none of that is important.
What you want is just the UI you are going to be interacting with, and your script. The tool you'll use for this is basically JsUnit, which takes an HTML document, with some Javascript functions on the page and executes them in the context of the page. So what you'll be doing is including the Stubbed out HTML on the page with your functions. From there,you can test the interaction of your script with the UI components in the isolated unit of the mocked HTML, your script, and your tests.
That may be a bit confusing so lets see if we can do a little test. Lets to some TDD to assume that after a component is loaded, a list of elements is colored based on the content of the LI.
tests.html

red

green

Obviously TDD is a multi-step process, so for our control, we'll need multiple examples.
yourcontrol.js (step1)
function ColorCtrl( id ) {
 /* Fail! */
}

yourcontrol.js (step2)
function ColorCtrl( id ) {
    $$("#mockList li").forEach(function(item, index) {
        item.setStyle("backgrond-color", item.getText());
    });
    /* Success! */
}

You can probably see the pain point here, you have to keep your mock HTML here on the page in sync with the structure of what your server controls will be. But it does get you a nice system for TDD'ing with JavaScript.

A: See also: JavaScript unit test tools for TDD

A: I've found the MVP architecture to be very suitable for writing testable UIs. Your Presenter and Model classes can simply be 100% unit tested. You only have to worry about the View (which should be a dumb, thin layer only that fires events to the Presenter) for UI testing (with Selenium etc.)
Note that in the I'm talking about using MVP entirely in the UI context, without necessarily crossing to the server-side. Your UI can have its own Presenter and Model that lives entirely on the client-side. The Presenter drives the UI interaction/validation etc. logic while the Model keeps state information and provides a portal to the backend (where you can have a separate Model).
You should also take a look at the Presenter First TDD technique.

A: This is the primary reason I switched to the Google Web Toolkit ... I develop and test in Java and have a reasonable expectation that the compiled JavaScript will function properly on a variety of browsers.  Since TDD is primarily a unit testing function, most of the project can be developed and tested before compilation and deployment.
Integration and Functional test suites verify that the resulting code is functioning as expected after it's deployed to a test server.

A: I'm just about to start doing Javascript TDD on a new project I am working on. My current plan is to use qunit to do the unit testing. While developing the tests can be run by simply refreshing the test page in a browser.
For continuous integration (and ensuring the tests run in all browsers), I will use Selenium to automatically load the test harness in each browser, and read the result. These tests will be run on every checkin to source control.
I am also going to use JSCoverage to get code coverage analysis of the tests. This will also be automated with Selenium.
I'm currently in the middle of setting this up. I'll update this answer with more exact details once I have the setup hammered out.

Testing tools:

*

*qunit

*JSCoverage

*Selenium

A: What I do is to poke the Dom to see if I'm getting what I expect.  A great side effect of this is that in making your tests fast, you also make your app fast.
I just released an open source toolkit which will help with JavaScript tdd immensely.  It is a composition of many open source tools which gives you a working requirejs backbone app out of the box.
It provides single commands to run: dev web server, jasmine single browser test runner, jasmine js-test-driver multi browser test runner, and concatenization/minification for JavaScript and CSS. It also outputs an unminified version of your app for production debugging, precompiles your handlebar templates, and supports internationalization.
No setup is required. It just works.
http://github.com/davidjnelson/agilejs


text:
Q: Given an example of a metric space in which every sphere has two centers This is a question from Wilansky "Topology for analysis", P.15 Prob. 103
Maybe I was thinking too Euclidean, I can't come up some other "centers" of the sphere :(

A: I will answer under the assumption that you refer to sets $S_{\varepsilon}(x) = \{y: \, d(x,y) = \varepsilon\}$ as spheres, and $x$ as a center of the sphere.
On $\mathbb{Q}$, given any prime $p$, you can define the $p$-adic metric $|x-y|_p$ to be $p^{-n}$, where $n$ is the unique integer such that $x-y = p^n \frac{a}{b}$ with $a,b$ integers that are coprime to $p$. (If $x=y$, then define $|x-y|_p = 0$.)
This turns out to satisfy the ultrametric inequality $|x-y|_p \le \max\{|x|_p|, |y|_p\}$, and using this, you can show that, for any $x \in \mathbb{Q}$ and $\varepsilon > 0$, $S_{\varepsilon}(x) = S_{\varepsilon}(y)$ for any $y$ such that $|x-y|_p < \varepsilon$; in particular, there are many centers of any sphere.

A: +1 for using this book. It's one of my favorites.
To your question. Think about $S^1$ in $\Bbb R^2$. Then every 'sphere' is simply 2 points picked from $S^1$. This 'sphere' has 2 centers. The point that is circumferentially central to both points and the point diametrically opposed to that first point.
Think about given two points on $S^1$ and either of those 'centers' drawing a secant circle centered there and cutting through the two original points.

A: As I mentioned in my comment, the spheres $S^n$ provide a family of examples. A "sphere" in $S^{n}$ is a copy of $S^{n-1}$. If we normalize the "great circle distance" metric on $S^n$ to have $d(x,-x)=1$, then a sphere around $x$ of radius $r$ is also a sphere of radius $1-r$ around the antipodal point $-x$.


text:
Q: Order by inside Case in Order By I have this database
    ID  Title
    1   Unassaign
    6   Prima
    7   Adi

I want to make ID 1 to be display last but the other are sort by their title
Desired results:
    ID  Title
    7   Adi
    6   Prima
    1   Unassaign

This is my code:
SELECT a.ID_WB, a.TITLE, a.DESCRIPTION, a.AUTHOR, a.DATECREATE, a.DATEUPDATE
FROM WORKBOOK a
order by case when ID_WB = 1 then 1
else 0 end

I tried insert Order By after else but it always return SQL error..
Is there a workaroud to this problem?
Thanks
PS: The first Order byshould sort by ID

A: Use two expressions in the order by:
order by (case when ID_WB = 1 then 1 else 0 end), title


text:
Q: Meaning of painstaking According to Wiktionary, the meaning of the adjective 'painstaking' is 'carefully attentive to detail'. However, I am having difficulty comprehending what exactly this means.
Consider, as an example, the below sentence, taken from the Webster dictionary site.

She was always painstaking about her work.

What might this entail? For instance, if she were a researcher, how could she be 'carefully attentive to detail'? My mind is blank.

A: Using your example, a researcher who is painstaking about her work may:

*

*take detailed and complete notes; in particular her notes do not skip any detail that might be relevant, however small.

*conduct long and boring experiments that are unlikely to yield results for the sake of completeness.

*perform checks and reviews of her own work and materials, even if these seldom or never  reveal any mistakes.

In short, to perform a task in a painstaking way is to do it with meticulous and careful attention to elements that another might skip, particularly when such elements may be boring or tedious, or when those elements constitute good practice but are not essential.


text:
Q: Статический сайт на Google App Engine Предположим, есть страница index.htm. Как сделать так, чтобы при переходе на http://example.appspot.com/index.htm или при переходе на http://example.appspot.com этот index.html отобразился в браузере?
A: К обработчикам в app.yaml нужно добавить подобный код- url: /  static_files: path/index.htm  upload: path/index.htm- url: /(.+)  static_files: path/\1  upload: path/(.+)Подробнее: обработчики статических файлов.


text:
Q: creating a user inside of rails console is not populating the necessary attributes User Model:
class User < ActiveRecord::Base
 before_save { self.email == email.downcase }
 attr_accessor :name, :email

 validates :name, presence: true
 VALID_EMAIL_REGEX = /\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i
 validates :email, presence: true, format: { with: VALID_EMAIL_REGEX },
                        uniqueness: { case_sensitive: false}

 has_secure_password
 validates :password, length: { minimum: 6 }
end

Inside of console:
:001 > User.all
User Load (3.1ms)  SELECT "users".* FROM "users"
=> #<ActiveRecord::Relation []>

:002 > User.create(name: "Ryan Waits", email: "ryan.waits@gmail.com", password:
"foobar", password_confirmation: "foobar")
(0.1ms)  begin transaction
User Exists (0.2ms)  SELECT 1 AS one FROM "users" WHERE LOWER("users"."email") =
LOWER('ryan.waits@gmail.com') LIMIT 1
Binary data inserted for `string` type on column `password_digest`
SQL (6.8ms)  INSERT INTO "users" ("created_at", "password_digest", "updated_at") VALUES
(?, ?, ?)  [["created_at", Sat, 02 Nov 2013 16:20:10 UTC +00:00], ["password_digest",
"$2a$10$5MhI5u90tFqO3rrS58DW7eeNBdNCCveBA.IfqHp6OpwonYNaigyPO"], ["updated_at", Sat, 02
Nov 2013 16:20:10 UTC +00:00]]
(1.3ms)  commit transaction

=> #<User id: 3, name: nil, email: nil, created_at: "2013-11-02 16:20:10", updated_at:
"2013-11-02 16:20:10", password_digest:
"$2a$10$5MhI5u90tFqO3rrS58DW7eeNBdNCCveBA.IfqHp6Opwo...">

(user = User.all)
user.name bring back "User" and the email and password attributes bring back an undefined method error on user object.
*Note:
I created another user with different attributes, same result, except the name, email, attributes return nil rather than "User" and undefined method error.
*Update:
So I now realize that the uniqueness validation is being hit with this message:
SELECT 1 AS one FROM "users" WHERE LOWER("users"."email") =
LOWER('ryan.waits@gmail.com') LIMIT

But when I test a new user with new attributes, it still returns nil attributes when using the create method.  However, updating the attributes like so (user.name = "adhsasd") will create a user.  But then when I query User.all, the attributes are back to nil and the user is again invalid...am I hitting a different database somehow?  I'm getting turned around...

A: Basically, I think you want attr_accessible instead of attr_accessor in your model...
From this answer
"attr_accessor is ruby code and is used when you do not have a column in your database, but still want to show a field in your forms. The only way to allow this is to attr_accessor :fieldname and you can use this field in your View, or model, if you wanted, but mostly in your View.
attr_accessible allows you to list all the columns you want to allow Mass Assignment, as andy eluded to above. The opposite of this is attr_protected which means this field i do NOT want anyone to be allowed to Mass Assign to. More then likely it is going to be a field in your database that you don't want anyone monkeying around with. Like a status field, or the like."


text:
Q: Creating a new user and password with Ansible I have an ansible task which creates a new user on ubuntu 12.04;
- name: Add deployment user
    action: user name=deployer password=mypassword

it completes as expected but when I login as that user and try to sudo with the password I set it always says it's incorrect. What am I doing wrong?

A: The purpose of the role in this answer is to generate random password for new_user_name and expire the password immediately. The new_user_name
is required to change the password on his/her first logon.
create_user.yml:
---
# create_user playbook

- hosts: your_host_group
  become: True
  user: ansible

  roles:
    - create_user

roles/create_user/tasks/main.yml:
---
# Generate random password for new_user_name and the new_user_name
# is required to change his/her password on first logon.

- name: Generate password for new user
  shell: makepasswd --chars=20
  register: user_password

- name: Generate encrypted password
  shell: mkpasswd --method=SHA-512 {{ user_password.stdout }}
  register: encrypted_user_password

- name: Create user account
  user: name={{ new_user_name }}
        password={{ encrypted_user_password.stdout }}
        state=present
        append=yes
        shell="/bin/bash"
        update_password=always
  when: new_user_name is defined and new_user_name in uids
  register: user_created

- name: Force user to change password
  shell: chage -d 0 {{ new_user_name }}
  when: user_created.changed

- name: User created
  debug: msg="Password for {{ new_user_name }} is {{ user_password.stdout }}"
  when: user_created.changed

When you want to create a new user:
ansible-playbook -i hosts.ini create_user.yml --extra-vars "new_user_name=kelvin"

A: I tried many utilities including mkpasswd, Python, etc., but it seems like there is some compatibility issue with Ansible in reading HASH values generated by other tools. So finally it worked by Ansible # value itself.
ansible all -i localhost, -m debug -a "msg={{ 'yourpasswd' | password_hash('sha512', 'mysecretsalt') }}"

Playbook:
- name: User creation
  user:
    name: username
    uid: UID
    group: grpname
    shell: /bin/bash
    comment: "test user"
    password: "$6$mysecretsalt$1SMjoVXjYf.3sJR3a1WUxlDCmdJwC613.SUD4DOf40ASDFASJHASDFCDDDWERWEYbs8G00NHmOg29E0"

A: I want to propose yet another solution:
- name: Create madhead user
  user:
    name: madhead
    password: "{{ 'password' | password_hash('sha512') }}"
    shell: /bin/zsh
    update_password: on_create
  register: madhead
- name: Force madhead to change password
  shell: chage -d 0 madhead
  when: madhead.changed

Why it is better? Like already has been noted here, Ansible plays should be idempotent. You should think of them not as a sequence of actions in imperative style, but like a desired state, declarative style. As a result you should be able to run it multiple times and get the same result, the same server state.
This all sounds great, but there are some nuances. One of them is managing users. "Desired state" means that every time you run a play that creates a user he will be updated to match exactly that state. By "updated" I mean that his password will be changed too. But most probably it is not what you need. Usually, you need to create user, set and expire his password only once, further play runs shouldn't update his password.
Fortunately, Ansible has update_password attribute in user module that solves this issue. Mixing this with registered variables you can also expire his password only when the user is actually updated.
Note that if you change user's shell manually (suppose, you don't like the shell that evil admin forced in his play) the user will be updated, thus his password will be expired.
Also note how you can easily use plain text initial passwords in plays. No need to encode them somewhere else and paste hashes, you can use Jinja2 filter for that. However, this can be a security flaw if someone happens to login before you initially do.

A: My solution is using lookup and generate password automatically.
---
- hosts: 'all'
  remote_user: root
  gather_facts: no
  vars:
    deploy_user: deploy
    deploy_password: "{{ lookup('password', '/tmp/password chars=ascii_letters') }}"

  tasks:
    - name: Create deploy user
      user:
        name: "{{ deploy_user }}"
        password: "{{ deploy_password | password_hash('sha512') }}"

A: This is how it worked for me
- hosts: main
  vars:
  # created with:
  #  python -c "from passlib.hash import sha512_crypt; print sha512_crypt.encrypt('<password>')"
  # above command requires the PassLib library: sudo pip install passlib
  - password: '$6$rounds=100000$H/83rErWaObIruDw$DEX.DgAuZuuF.wOyCjGHnVqIetVt3qRDnTUvLJHBFKdYr29uVYbfXJeHg.IacaEQ08WaHo9xCsJQgfgZjqGZI0'

tasks:

- user: name=spree password={{password}} groups=sudo,www-data shell=/bin/bash append=yes
  sudo: yes

A: This is the easy way:
---
- name: Create user
  user: name=user shell=/bin/bash home=/srv/user groups=admin,sudo generate_ssh_key=yes ssh_key_bits=2048
- name: Set password to user
  shell: echo user:plain_text_password | sudo chpasswd
  no_log: True

A: Just for completeness I will post the ad-hoc command using ansible since there is a catch there as well.
First try generating an encrypted password using the mkpasswd utility that is available on most Linux systems:
mkpasswd --method=SHA-512

Then try the ansible ad-hock command:
ansible all -m user -a 'name=testuser shell=/bin/bash \
     comment="Test User" password=$6$XXXX' -k -u admin --sudo

But make sure:

*

*The command is in single quotes and NOT double otherwise your password will never work

*You run it with --sudo or you end up with an error like (useradd: cannot lock /etc/passwd; try again later)

A: You can use ansible-vault for using secret keys in playbooks. Define your password in yml.
ex. pass: secret
or
user:
  pass: secret
  name: fake

encrypt your secrets file with :
ansible-vault encrypt /path/to/credential.yml
ansible will ask a password for encrypt it. (i will explain how to use that pass)
And then you can use your variables where you want. No one can read them without vault-key.
Vault key usage:
via passing argument when running playbook.
--ask-vault-pass: secret

or you can save into file like password.txt and hide somewhere. (useful for CI users)
--vault-password-file=/path/to/file.txt

In your case :
include vars yml and use your variables.
- include_vars: /path/credential.yml

  - name: Add deployment user
    action: user name={{user.name}} password={{user.pass}}

A: Generating random password for user
first need to define users variable then follow below
tasks:
- name: Generate Passwords
  become: no
  local_action: command pwgen -N 1 8
  with_items: '{{ users }}'
  register: user_passwords

- name: Update User Passwords
  user:
    name: '{{ item.item }}'
    password: "{{ item.stdout | password_hash('sha512')}}"
    update_password: on_create
  with_items: '{{ user_passwords.results }}'

- name: Save Passwords Locally
  become: no
  local_action: copy content={{ item.stdout }} dest=./{{ item.item }}.txt
  with_items: '{{ user_passwords.results }}'

A: I may be too late to reply this but recently I figured out that jinja2 filters have the capability to handle the generation of encrypted passwords. In my main.yml I'm generating the encrypted password as:
- name: Creating user "{{ uusername }}" with admin access
  user:
    name: {{ uusername }}
    password: {{ upassword | password_hash('sha512') }}
    groups: admin append=yes
  when:  assigned_role  == "yes"

- name: Creating users "{{ uusername }}" without admin access
  user:
    name: {{ uusername }}
    password: {{ upassword | password_hash('sha512') }}
  when:  assigned_role == "no"

- name: Expiring password for user "{{ uusername }}"
  shell: chage -d 0 "{{ uusername }}"

"uusername " and "upassword " are passed as --extra-vars to the playbook and notice I have used jinja2 filter here to encrypt the passed password.
I have added below tutorial related to this to my blog

*

*https://thinkingmonster.wordpress.com/it-automation/386-2/ansible-roles/

A: The task definition for the user module should be different in the latest Ansible version.
tasks:
  - user: name=test password={{ password }} state=present

A: How to create encrypted password for passing to password var to Ansible user task (from @Brendan Wood's comment):
openssl passwd -salt 'some_plain_salt' -1 'some_plain_pass'

The result will look like:
$1$some_pla$lmVKJwdV3Baf.o.F0OOy71

Example of user task:
- name: Create user
  user: name="my_user" password="$1$some_pla$lmVKJwdV3Baf.o.F0OOy71"

UPD: crypt using SHA-512 see here and here:
Python
$ python -c "import crypt, getpass, pwd; print crypt.crypt('password', '\$6\$saltsalt\$')"

$6$saltsalt$qFmFH.bQmmtXzyBY0s9v7Oicd2z4XSIecDzlB5KiA2/jctKu9YterLp8wwnSq.qc.eoxqOmSuNp2xS0ktL3nh/

Perl
$ perl -e 'print crypt("password","\$6\$saltsalt\$") . "\n"'

$6$saltsalt$qFmFH.bQmmtXzyBY0s9v7Oicd2z4XSIecDzlB5KiA2/jctKu9YterLp8wwnSq.qc.eoxqOmSuNp2xS0ktL3nh/

Ruby
$ ruby -e 'puts "password".crypt("$6$saltsalt$")'

$6$saltsalt$qFmFH.bQmmtXzyBY0s9v7Oicd2z4XSIecDzlB5KiA2/jctKu9YterLp8wwnSq.qc.eoxqOmSuNp2xS0ktL3nh/

A: Combining a few solutions from above, I created a playbook that automatically generates correct password hashes based on plaintext passwords stored in an encrypted, local ansible vault file:
---
- hosts: [your hosts]
  tasks:
  - include_vars: [path to your encrypted vault file]
  - local_action: "command openssl passwd -salt '{{password_salt}}' -1 '{{password}}'"
    register: password_hash
  - user: >
        name=[your username]
        state=present
        password="{{password_hash.stdout}}"

Run this command using "--ask-vault-pass" option to decrypt your vault file (see ansible-vault for info on how to manage an encrypted vault).

A: Mxx's answer is correct but  the python crypt.crypt() method is not safe when different operating systems are involved (related to glibc hash algorithm used on your system.)
For example, It won't work if your generate  your hash from MacOS and run a playbook on linux. In such case , You can use passlib (pip install passlib to install locally).
from passlib.hash import md5_crypt
python -c 'import crypt; print md5_crypt.encrypt("This is my Password,salt="SomeSalt")'
'$1$SomeSalt$UqddPX3r4kH3UL5jq5/ZI.'

A: If you'd like to accomplish this as a Ansible ad-hoc command you can do the following:
$ password='SomethingSecret!'
$ ansible 192.168.1.10 -i some_inventory -b -m user -a "name=joe_user \
       update_password=always password=\"{{ \"$password\" | password_hash('sha512') }}\""

Output from above command:
192.168.1.10 | SUCCESS => {
    "append": false,
    "changed": true,
    "comment": "Joe User",
    "group": 999,
    "home": "/home/joe_user",
    "move_home": false,
    "name": "joe_user",
    "password": "NOT_LOGGING_PASSWORD",
    "shell": "/bin/bash",
    "state": "present",
    "uid": 999
}

A: try like this
vars_prompt:
 - name: "user_password"
   prompt: "Enter a password for the user"
   private: yes
   encrypt: "md5_crypt" #need to have python-passlib installed in local machine before we can use it
   confirm: yes
   salt_size: 7

 - name: "add new user" user: name="{{user_name}}" comment="{{description_user}}" password="{{user_password}}" home="{{home_dir}}" shell="/bin/bash"

A: If you read Ansible's manual for user module, it'll direct you to the Ansible-examples github repo for details how to use password parameter.
There you'll see that your password must be hashed.
- hosts: all
  user: root
  vars:
    # created with:
    # python -c 'import crypt; print crypt.crypt("This is my Password", "$1$SomeSalt$")'
    password: $1$SomeSalt$UqddPX3r4kH3UL5jq5/ZI.

  tasks:
    - user: name=tset password={{password}}

If your playbook or ansible command line has your password as-is in plain text, this means your password hash recorded in your shadow file is wrong. That means when you try to authenticate with your password its hash will never match.
Additionally, see Ansible FAQ regarding some nuances of password parameter and how to correctly use it.

A: The Ansible 'user' module manages users, in the idempotent way. In the playbook below the first task declares state=present for the user. Note that 'register: newuser' in the first action helps the second action to determine if the user is new (newuser.changed==True) or existing (newuser.changed==False), to only generate the password once.
The Ansible playbook has:
tasks:
  - name: create deployment user
    user:
      name: deployer
      createhome: yes
      state: present
    register: newuser

  - name: generate random password for user only on creation
    shell: /usr/bin/openssl rand -base64 32 | passwd --stdin deployer
    when: newuser.changed

A: Neither of the solutions worked directly on my Mac controlling Ubuntu. So for others' sake, combining Mxx and JoelB answers, here is the current Python 3 solution:
pip3 install passlib

python3 -c 'from passlib.hash import md5_crypt; \
      print(md5_crypt.encrypt("This is my Password", salt="SomeSalt"))'

The result will be $1$SomeSalt$UqddPX3r4kH3UL5jq5/ZI., as in Mxx' answer.
Better still, use SHA512 instead of MD5:
python3 -c 'from passlib.hash import sha512_crypt; \
      print(sha512_crypt.encrypt("This is my Password", salt="SomeSalt"))'

Result:

$6$rounds=656000$SomeSalt$oYpmnpZahIsvn5FK8g4bDFEAmGpEN114Fe6Ko4HvinzFaz5Rq2UXQxoJZ9ZQyQoi9zaBo3gBH/FEAov3FHv48

A: I have created an ansible-playbook that allows you to create a linux account that allows password authentication.
See AnsibleLinuxAccountCreator.
The hashed password is generated using mkpasswd command. I've provided the ways to install mkpasswd on different operating systems.
Here are the steps required to use my script:

*

*Replace <your_user_name> and <your_password> inside run.sh with your desired user name and password.

*Change the connection information in inventory so that ansible can connect to the machine to create a user.

*Run ./run.sh to execute the script.

A: I know that I'm late to the party, but there is another solution that I'm using. It might be handy for distros that don't have --stdin in passwd binary.
- hosts: localhost
  become: True
  tasks:
    - name: Change user password
      shell: "yes '{{ item.pass }}' | passwd {{ item.user }}"
      loop:
       - { pass: 123123, user: foo }
       - { pass: asdf, user: bar }
      loop_control:
        label: "{{ item.user }}"

Label in loop_control is responsible for printing only username. The whole playbook or just user variables (you can use vars_files:) should be encrypted with ansible-vault.

A: I couldn't get any answers here to work though with vaulted variables. So, for anyone who is using "vaulted" passwords and getting this error:
"msg": "Unexpected templating type error occurred on ({{ jinja template stuff }}): expected string or bytes-like object"

You need to pipe '|' the vault encrypted variable through "string" to get it to work.
- name: Creating user "{{ uusername }}" with admin access
  user:
    name: {{ uusername }}
    password: "{{ upassword | string | password_hash('sha512', (upassword_salt | string)) }}"
    groups: admin append=yes
  when:  assigned_role  == "yes"

Based on Ansible solution for GitHub issue #24425
Building off code from an answer by thinkingmonster and comment by michael-aicher.

A: - name: Create user
  hosts: all
  become: true
  tasks:

- name: "Creating Users and set password"
  user:
    name: <username>
    update_password: always
    password:  password_hash('sha512')
    groups: sudo

A: @madhead 's answer is not perfect.
You really cannot rely on item's changed state, that's not precise. But this problem could be solved:
- name: get all existing users info
  getent:
    database: passwd

# ---- @madhead 's answer ----
- name: Create madhead user
  user:
    name: madhead
    password: "{{ 'password' | password_hash('sha512') }}"
    shell: /bin/zsh
    update_password: on_create
  register: madhead
- name: Force madhead to change password
  shell: chage -d 0 madhead
  # origin:
  # when: madhead.changed
  # improved:
  when: 'madhead' not in getent_passwd and madhead.changed

A: Well I'am totally late to party :) I had the need for ansible play that creates multiple local users with randoms passwords. This what I came up with, used some of examples from top and put them together with some changes.
create-user-with-password.yml
---
# create_user playbook

- hosts: all
  become: True
  user: root
  vars:
#Create following user
   users:
    - test24
    - test25
#with group
   group: wheel
  roles:
    - create-user-with-password

/roles/create-user-with-password/tasks/main.yml
- name: Generate password for new user
  local_action: shell pwgen -s -N 1 20
  register: user_password
  with_items: "{{ users }}"
  run_once: true

- name: Generate encrypted password
  local_action: shell python -c 'import crypt; print(crypt.crypt( "{{ item.stdout }}", crypt.mksalt(crypt.METHOD_SHA512)))'
  register: encrypted_user_password
  with_items: "{{ user_password.results }}"
  run_once: true

- name: Create new user with group
  user:
    name: "{{ item }}"
    groups: "{{ group }}"
    shell: /bin/bash
    append: yes
    createhome: yes
    comment: 'Created with ansible'
  with_items:
    - "{{ users }}"
  register: user_created

- name: Update user Passwords
  user:
    name: '{{ item.0 }}'
    password: '{{ item.1.stdout }}'
  with_together:
    - "{{ users }}"
    - "{{ encrypted_user_password.results }}"
  when: user_created.changed

- name: Force user to change the password at first login
  shell: chage -d 0 "{{ item }}"
  with_items:
    - "{{ users }}"
  when: user_created.changed

- name: Save Passwords Locally
  become: no
  local_action: copy content={{ item.stdout }} dest=./{{ item.item }}.txt
  with_items: "{{ user_password.results }}"
  when: user_created.changed


text:
Q: Pointer as parameter in Linux kernel code
    Recently, I have read the linux kernel code to see how the code looks like. I understands only the basic of pointers.
So, i came across this function declaration:-

kernel_write(struct file *file, const void *buf, size_t count,loff_t *pos)

What does struct file *file imply?
Based on my understanding, struct file *file means that you pass the pointer that points to the memory blocks that contains multiple file structs?  Here is a diagram to visualize my understanding :-

Is my understanding accurate or i am actually misguided?

A: No, that's not correct. In this context, that pointer points to exactly one struct file. Advancing it and trying to read a second one would be Undefined Behavior, and that's especially bad when it happens in the kernel.

A: There are multiple reasons to use a pointer as a parameter.

*

*The pointer points to an array of items.  You need to know how many items so there must be a count or size parameter to indicate how big the array is.  The buf parameter is an array and the count parameter indicates how big it is.

*The pointer is used to avoid copying a huge structure via the stack.  Functions receive a copy of the item passed to them.  If the structure is really big then copying the entire structure is a bad idea but passing a pointer is a much smaller thing so it is a better idea.

*The pointer is used to allow the function to modify the value passed to it.  Functions receive a copy of the item passed to them.  So modifying the parameter only modifies the copy and not the original.  If a pointer is passed then you can't modify where the pointer points but you can modify what the pointer points at.

In the particular example you show I can't tell if they pass a pointer to file because they need to modify the contents of the structure (#3) or because the structure is really big and they are worried about how much stack space the copy will take up (#2).  But it is almost certainly NOT an array (#1) because there is no size or count parameter to say how big the array is (which means the pointer can only point at one structure).
If you want some examples of each case let me know.


text:
Q: Orientation preserving and orientation reserving of a parameterisation of a curve The definition states:

Let $\mathbf{x}:\left [ a,b \right ]\rightarrow \mathbb{R}^{n}$ be a piecewise $\mathit{C}$ path. We say that another $\mathit{C}$ path $\mathbf{y}:\left [ c,d \right ]\rightarrow \mathbb{R}^{n}$ is a $\mathbf{reparameterisation}\ of \ \mathbf{x}$ if there is a one-to-one and onto function $u:\left [ c,d \right ]\rightarrow \left [ a,b \right ]$ of class $\mathit{C}$, with inverse $u^{-1}:\left [ a,b \right ]\rightarrow \left [ c,d \right ]$ that is also of class C, such that $\mathbf{y}\left ( t \right )=\mathbf{x}\left ( u\left ( t \right ) \right )$; that is $\mathbf{y}=\mathbf{x}\circ u$

The velocity vector is thus
$\mathbf{y}'\left ( t \right )=\frac{\mathrm{d} }{\mathrm{d} x}\left ( \mathbf{x}\left ( u\left ( t \right ) \right ) \right )=\mathbf{x}'\left ( u\left ( t \right ) \right )u'\left ( t \right )$
The speed is just the magnitude of the velocity vector, giving
$\left \| \mathbf{y'} \left ( t \right )\right \|=\left | u'\left ( t \right ) \right |\left \| \mathbf{x'} \left ( u\left ( t \right ) \right )\right \|$
Here's what my text claims:

Since u is one-one, it follows that either $u\left ( t \right )\geq 0 \forall t\in\left [ a,b \right ]$ or $u\left ( t \right )\leq 0 \forall t\in\left [ a,b \right ]$

Why is this claim true?


text:
Q: Understanding point-line distance in 2 dimensions http://mathworld.wolfram.com/Point-LineDistance2-Dimensional.html
Im trying to understand the two dimensional line distance formula from the above Link but dont really understand a part of it. The divisor is the pythagoras distance formula I believe but what is the dividend? The part above the division? Not really sure.

A: The authors of that page computed the projection of $(x_0,y_0)$ on the line $ax+by+c=0$. Then they computed the distance from $(x_0,y_0)$ to that projection. The final result has some resemblance with the cross-product of two vectors because the cross-product of two vectors is orthogonal to each of them.


text:
Q: $(M,d)$ is complete iff all closed and countable subspace of $M$ is complete A metric space $(M,d)$ is complete $\iff$ if every closed and countable subspace $F\subseteq M$ is complete.
$\implies)$ For this implication I use a proposition that says: "If $X$ is a complete metric space and $F \subseteq X$ is closed, then $F$ is complete". But for $\impliedby )$ I don't know what to do.

A: As suggested by Daniel Fischer, consider the set $A=\{a_1,a_2,\ldots\}$, where $\{a_i\}_{i>0}$ is a Cauchy sequence. A Cauchy sequence has at most one limit point, so the closure $\overline{A}$ is still countable as it contains at most one extra point. By hypothesis, $\overline{A}$ is complete because it is a closed countable subset, hence the Cauchy sequence converges to a limit $a\in\overline{A}$. Thus the Cauchy sequence converges to $a$ in $M$ as well. Since this is true for any Cauchy sequence, $M$ is complete.


text:
Q: Is a character $\chi$ realizable over $K\cap L$ where $\chi$ realize over $K$ and $L$? I want to ask about realization problem of characters of a finite group. In this question, $G$, $m$, $\chi$, $K$, and $L$ are defined as follows:
.
$G$: a finite group
$m$: the exponent of $G$
$\chi$: a faithful irreducible complex character of $G$
$K$, $L$: number fields where $\chi$ is realizable
.
I wonder if $\chi$ is realizable over $K\cap L$.
More precisely, you may assume that $L=\mathbb{Q}\left(\zeta_{m}\right)$ because Brauer's theorem says that $\chi$ realizes over $\mathbb{Q}\left(\zeta_{m}\right)$.
If you need, you may assume some conditions on $G$.


text:
Q: Graph API - Facebook - Business Page Tagged Messages, Get Comments I have a business page on Facebook. I want to see when someone tags my page on their feed in a public post. Further, I want to be able to see the comments that people make on that post. About 3 weeks ago I had no problem doing this. I could then use the Graph API and Graph Explorer to see the:
    /tagged?fields=message,from,created_time,likes,comments{from,message,created_time}

....a great deal of information.
Today when I try to access the likes or comments on the tagged post through Graph Explorer I get the greyed out text meaning "Field is empty or disallowed with my access token." However, I have the page access token via Graph Explorer. Can anyone help me with this? Did Facebook change something?
This is not the same as the linked post. I have tested it with all user and extended permissions enabled. I am not trying to see a list of my friends, I am trying to see the name and comment of a friend of someone that tagged my page. The code I posted above worked fine less than a month ago, which was still Graph v2.5.
Each of these has likes and comments yet the API won't allow access.


text:
Q: debian package cross build error - dpkg-shlibdeps error couldn't find library I am building a debian installer package on Ubuntu 16.04, to be installed on my Arm64 system, however am having difficulty resolving library dependencies during the build.
I run the following debuild command
debuild -us -uc --host-arch arm64

and get errors such as the following
dpkg-shlibdeps: error: couldn't find library libgcc_s.so.1

For info, my linux kernel is as follows
$ uname -a
Linux ubuntu 4.15.0-66-generic #75~16.04.1-Ubuntu SMP Tue Oct 1 14:01:08 UTC 2019 x86_64 x86_64 x86_64 GNU/Linux

Naturally, I would expect the dependent libraries to be present on the target system but would like build the package without the need for the libraries on the build machine.
I don't want to disable shlibdeps because this plugin ensures ldconfig gets called during installation.
I'd be grateful for advise on how to call shlibdeps when cross-building.
UPDATE :
I'm not actually building the binaries, only creating an installer for the binaries. Perhaps this is not convention and the solution would be to ensure the dependent libraries are present on the machine creating the installer package.
Thanks.


text:
Q: CodePush: Where to find Deployment Key for Visual Studio project I'm trying on code push in my Visual studio project now. I done installing cordova plugin code push and able to see the instance with console.log(codePush).
Now I try to run codePush.checkForUpdate() and I notice that I need to fill in the Deployment Key in config.xml.
I read several articles about deployment key but all of them use the Ionic CLI to create the project and they can retrieve the deployment key in CLI. But I don't see any option in Visual Studio for that nor see any deployment key info anywhere.
Please advice on how to get the deployment key for my Visual Studio project in order to enable codePush.

A: It seems some parts of the documentation isn't keeping up with the CLI changes. If you've installed the appcenter-cli as per their App Center Guide, then you can use that.

*

*First, login, appcenter login

*You need an app, create one on https://appcenter.ms/apps or with appcenter apps create -d APP_NAME -o Android -p Cordova. Because the CLI is case sensitive, you're better off using that website.

*Set your current app to the app you want to deploy, appcenter apps set APP_NAME

*Then, you create a deployment for your currently selected app: appcenter codepush deployment add DEPLOYMENT_NAME

*Cordova specific: Then send it off to users, appcenter codepush release-cordova -a USERNAME/APP_NAME

*

*Bonus (for react native):
appcenter codepush release-react -a USERNAME/APP_NAME -d DEPLOYMENT_NAME

A: For anyone who finds their way here working with CodePush that's now a part of App Center, you may need to run this command:
appcenter codepush deployment list -k
or
appcenter codepush deployment list -k --app <ownerName>/<appName>
if you don't have your app name set up in an environment variable etc.  More details here: https://learn.microsoft.com/en-us/appcenter/distribution/codepush/cordova

A: After many hours of struggle, I found a solution on this. As a result, I actually need to follow EVERY single step as provided here, here and here. I really need to cross check between these 3 links to make things work.
Here is what I did:
1) In Visual Studio Package Manager Console, do this npm install -g code-push-cli. This will install the necessary for CodePush CLI
2) In the console, do code-push register. This will open a browser and register your account and associate with github or microsoft platform for code sync later on.
3) After successful registration, do code-push login. This will open up the browser and generate an access key for you. Suppose, a CLI will pop up and allow you to key in the access key for login. But in my case, the console hang. So I have to do code-push login --accessKey <accessKey> method to login.
4) After that, do code-push app add <app_name> to register the app. This will send info to code push server and allow your app to perform code push
5) Do code-push deployment add <app_name> "Staging" to enable the app for deployment to server
6) When adding for deployment is successful, do code-push deployment ls <app_name> -k to retrieve the Deployment Key for Staging and Production
I still need to trial-and-error for using the code in the application. But at least I'm manage to get the deployment key for now.
Hope it helps those who are using ionic with code push


text:
Q: In the below JSON .if I don't know child object ,how can I get it using angular JS?

{
  "GE": {
    "symbol": "GE",
    "dxSymbol": "GE",
    "exchange": "XNYS",
    "isoExchange": "XNYS",
    "bzExchange": "NYSE",
    "type": "STOCK",
    "name": "General Electric",
    "description": "General Electric Company Common Stock",
    "sector": "Industrials",
    "industry": "Diversified Industrials",
    "open": 28.59,
    "high": 29.07,
    "low": 28.55,
    "close": 28.87,
    "bidPrice": 28.82,
    "askPrice": 28.94,
    "askSize": 7,
    "bidSize": 10,
    "size": 1676188,
    "bidTime": 1477526400000,
    "askTime": 1477526400000,
    "lastTradePrice": 28.87,
    "lastTradeTime": 1477512029000,
    "volume": 24357188,
    "change": 0.22,
    "changePercent": 0.77,
    "previousClosePrice": 28.65,
    "fiftyDayAveragePrice": 31.0652,
    "fiftyTwoWeekHigh": 33.0,
    "fiftyTwoWeekLow": 19.37,
    "marketCap": 291853729930,
    "sharesOutstanding": 10109239000,
    "pe": 36.964286,
    "forwardPE": 20.7039,
    "dividendYield": 2.96,
    "payoutRatio": 109.52,
    "ethPrice": 28.87,
    "ethVolume": 777095,
    "ethTime": 1477526274000
  }
}

In the above JSON .if I don't know child object is GE how can I get it using angular JS. I am getting this response as from get endpoint , I want to access direct child is that possible if i do not know it is "GE" on before hand

A: Object.keys(object) to get the array of keys. Then take the first one

var myObj = {
  "GE": {
    "symbol": "GE",
    "dxSymbol": "GE",
    "exchange": "XNYS",
    "isoExchange": "XNYS",
    "bzExchange": "NYSE",
    "type": "STOCK",
    "name": "General Electric",
    "description": "General Electric Company Common Stock",
    "sector": "Industrials",
    "industry": "Diversified Industrials",
    "open": 28.59,
    "high": 29.07,
    "low": 28.55,
    "close": 28.87,
    "bidPrice": 28.82,
    "askPrice": 28.94,
    "askSize": 7,
    "bidSize": 10,
    "size": 1676188,
    "bidTime": 1477526400000,
    "askTime": 1477526400000,
    "lastTradePrice": 28.87,
    "lastTradeTime": 1477512029000,
    "volume": 24357188,
    "change": 0.22,
    "changePercent": 0.77,
    "previousClosePrice": 28.65,
    "fiftyDayAveragePrice": 31.0652,
    "fiftyTwoWeekHigh": 33.0,
    "fiftyTwoWeekLow": 19.37,
    "marketCap": 291853729930,
    "sharesOutstanding": 10109239000,
    "pe": 36.964286,
    "forwardPE": 20.7039,
    "dividendYield": 2.96,
    "payoutRatio": 109.52,
    "ethPrice": 28.87,
    "ethVolume": 777095,
    "ethTime": 1477526274000
  }
};
var key = Object.keys(myObj)[0];
console.log(myObj[key]);

A: Note: Before you ask a question, please check for sometime regarding this, if you didnot find any answers, then ask your questions.
Use,
Object.keys(hash) property.
so,
Object.keys(object)[0] will give you the value of first key

// Instantiate the app, the 'myApp' parameter must
// match what is in ng-app
var myApp = angular.module('myApp', []);

// Create the controller, the 'ToddlerCtrl' parameter
// must match an ng-controller directive
myApp.controller('ToddlerCtrl', function ($scope) {

  $scope.data = {
  "GE": {
    "symbol": "GE",
    "dxSymbol": "GE",
    "exchange": "XNYS",
    "isoExchange": "XNYS",
    "bzExchange": "NYSE",
    "type": "STOCK",
    "name": "General Electric",
    "description": "General Electric Company Common Stock",
    "sector": "Industrials",
    "industry": "Diversified Industrials",
    "open": 28.59,
    "high": 29.07,
    "low": 28.55,
    "close": 28.87,
    "bidPrice": 28.82,
    "askPrice": 28.94,
    "askSize": 7,
    "bidSize": 10,
    "size": 1676188,
    "bidTime": 1477526400000,
    "askTime": 1477526400000,
    "lastTradePrice": 28.87,
    "lastTradeTime": 1477512029000,
    "volume": 24357188,
    "change": 0.22,
    "changePercent": 0.77,
    "previousClosePrice": 28.65,
    "fiftyDayAveragePrice": 31.0652,
    "fiftyTwoWeekHigh": 33.0,
    "fiftyTwoWeekLow": 19.37,
    "marketCap": 291853729930,
    "sharesOutstanding": 10109239000,
    "pe": 36.964286,
    "forwardPE": 20.7039,
    "dividendYield": 2.96,
    "payoutRatio": 109.52,
    "ethPrice": 28.87,
    "ethVolume": 777095,
    "ethTime": 1477526274000
  }
}

alert(Object.keys($scope.data)[0])

});
<!DOCTYPE html>
<html ng-app="myApp">

  <head>
    <script data-require="angular.js@1.2.7" data-semver="1.2.7" src="http://code.angularjs.org/1.2.7/angular.js"></script>
    <link href="style.css" rel="stylesheet" />
    <script src="script.js"></script>
  </head>
  <body>

    <div ng-controller="ToddlerCtrl">

    </div>
  </body>

</html>

Please run this snippet


text:
Q: How to send jpg in subject line of email Using php is it possible to send a jpg in the subject line of an email?  I've noticed there are limited ways to send emolji

A: Not possible to add graphics like jpg, png or any other file format to the subject of a mail. Neither emojis.
The mail client can change some characters to emoji, for user friendly.
The mail client for example can change the <3 by a heart or :) by a smile face.
you cannot add it to the subject, just add this char and pray for the client change those chars.


text:
Q: Does anyone know the yFrog RSS feed addresses? I want to embed the latest image uploaded to yFrog for a particular user on another site. They appear to have recently launched a widget, and I've found some talk of RSS feeds. But everything relating to them seems to have been pulled from the yFrog site recently. Any ideas?

A: You should try implementing a Yahoo! Pipe using Twitter and yFrog API to generate an RSS. Here is mine: http://pipes.yahoo.com/norbertcsik/twitter_images

A: It looks like they used to support, but it doesn't look like it works anymore.
For evidence, see this and this.


text:
Q: scrollTop returns 0 for all document elements in javascript but scroll event fires on body tag I made an event handler for the scroll event on the body tag which fires correctly. However when I try to find the position of the scollbar using scrollTop(), I was unable to do so. To figure out which element was being scrolled I logged the scrollTop() of all the DOM elements but surprisingly all were 0.
$('body').scroll(function () {
    var all = document.getElementsByTagName("*");
    for (var i=0, max=all.length; i < max; i++) {
        console.log('scrolltop', all[i].scrollTop);
    }
});

All I want to know is the position of the scrollbar and whether the scrollbar has reached the end or not. I have tried $(document).scroll() and $(window).scroll, but none of them fires. The event only works on the body tag.

A: Using the window object is usually the most reliable for tracking scrolling.
ScrollTop also only really tracks how much the window has been scrolled and although commonly confused for doing so, it does not track how far an element is from the top of the page. For that you need to use offset.
As such I have simply changed your code to run on the window scroll and also changed your logic to use jQuerys each function which will make things simpler.:
JS:
$(window).scroll(function () {
    $('*').each(function (){
        console.log(
        'Element Text:', $(this).text(),
          ' | From Top', $(this).offset().top
      );
    })
});

With the above JS you will see in your console the following output:
Element Text: hello87  | From Top 1556
JsFiddle:
https://jsfiddle.net/wigster/t1e3dee8/1/


text:
Q: Press both mouse buttons when holding left click When I hold down left mouse button I would like for the right mouse button be held down also.
The right mouse would then release when the left mouse is no longer being held. So both buttons can be controlled simultaneously with the left click.

A: LButton::RButton means Left Button acts like your Right Button. The ~ modifier means "Fire the hotkey as well as whatever it's remapped to".
~LButton::RButton

Quick edit: If you need it to activate after Left Button has been held for a certain amount of time, use this:
; Time for LButton to be held down before RButton is sent (in milliseconds)
waitTime    := 500
return

~*LButton::
    while GetKeyState("LButton", "P")
        if (A_TimeSinceThisHotkey > waitTime){
            Send, {RButton Down}
            KeyWait, LButton
            Send, {RButton Up}
        }
return


text:
Q: Button setonclick listener is not working correctly when I press the save button does not work after pressing it several time button is working sometimes first-time press is working sometimes after pressing moreover 10 times button is not working.Also i have toast messege to determine it is working or not the toast messege appear after pressing several time to the button.
 binding.savebtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Toast.makeText(Settringsactivity.this,"ok",Toast.LENGTH_LONG).show();
                    String status=binding.etStatus.getText().toString();
                    String username=binding.etUsername.getText().toString();

                HashMap<String, Object> obj=new HashMap<>();
                Toast.makeText(Settringsactivity.this,username,Toast.LENGTH_LONG).show();
                obj.put("username",username);
                obj.put("about",status);
                if(name!=null) {
                    Toast.makeText(Settringsactivity.this,"Updated",Toast.LENGTH_LONG).show();
                    database.getReference().child("Users").child(name).updateChildren(obj);
                }
            }
        });

     Here is the xml code
     <?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/savebtn"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_marginLeft="10dp"
    android:layout_marginTop="10dp"
    android:background="@color/white"
    android:foregroundTint="#B11B1B"
    tools:context=".Settringsactivity">

    <ImageView
        android:id="@+id/settingsbackarraow"
        android:layout_width="30dp"
        android:layout_height="30dp"
        android:backgroundTint="#FFFFFF"
        app:srcCompat="@android:drawable/checkbox_on_background" />

    <LinearLayout
        android:id="@+id/flinear"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@id/settingsbackarraow"
        android:layout_marginLeft="20dp"
        android:layout_marginRight="20dp"
        android:gravity="center"
        android:orientation="vertical">

        <de.hdodenhof.circleimageview.CircleImageView
            android:id="@+id/profileimage"
            android:layout_width="120dp"
            android:layout_height="120dp"
            android:backgroundTint="#FFFFFF"
            app:civ_border_color="#FF000000"
            app:civ_border_width="2dp"
            android:src="@drawable/img" />

        <ImageView
            android:id="@+id/plus"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            app:srcCompat="@android:drawable/btn_plus" />

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:orientation="horizontal">

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Username"
                android:textColor="#100606" />

            <EditText
                android:id="@+id/etUsername"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:ems="10"
                android:textColor="@color/black"
                android:hint="Enter your name"
                android:inputType="textPersonName" />
        </LinearLayout>

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:orientation="horizontal">

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Username"
                android:textColor="#100606" />

            <EditText
                android:id="@+id/etStatus"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:ems="10"
                android:hint="About"
                android:textColor="@color/black"
                android:inputType="textPersonName" />
        </LinearLayout>

        <Button
            android:layout_width="100dp"
            android:layout_height="50dp"
            android:elevation="15sp"
            android:background="#1966FB"
            android:layout_gravity="right"
            android:text="Save" />

    </LinearLayout>

</RelativeLayout>


text:
Q: Respresentations of $A$ and $B$ satisfying $\pi_1(a)\pi_2(b)= \pi_2(b)\pi_1(a)$ and $\|x\|_\text{max}=\|\pi_1.\pi_2(x)\|$ Let $A$ and $B$ be $C^{\ast}$-algebras and $A \otimes B$ denotes algebraic tensor product of $A$ and $B$. Given representations $\pi_1$ and $\pi_2$ of $A$ and $B$ respectively satisfying $\pi_1(a)\pi_2(b)= \pi_2(b)\pi_1(a)$, we define $\pi_1.\pi_2: A\otimes B \to B(H)$ as $$\pi_1.\pi_2\big(\sum_i a_i \otimes b_i\big)= \sum_i \pi_1(a_i)\pi_2(b_i)$$

Let $x\in A\otimes B$, does there exists representations $\pi_1$ and $\pi_2$ of $A$ and $B$ respectively satisfying $\pi_1(a)\pi_2(b)= \pi_2(b)\pi_1(a)$ and $\|x\|_\text{max}=\|\pi_1.\pi_2(x)\|$

A: First assume that $A$ and $B$ are unital. You can check that $\lVert\cdot\rVert_\max$ is a (usually incomplete) $C^\ast$-norm on $A\otimes B$. Thus the completion $A\otimes_\max B$ is a $C^\ast$-algebra, which can be realized as $C^\ast$-subalgebra of $B(H)$ for some Hilbert space $H$. This gives a unital $\ast$-representation
$$
\pi\colon A\otimes B\twoheadrightarrow A\otimes_\max B\hookrightarrow B(H).
$$
Let $\pi_1(a)=\pi(a\otimes 1)$ and $\pi_2(b)=\pi(1\otimes b)$. Then $\pi_1$ and $\pi_2$ are representations with commuting images and $\pi=\pi_1\otimes \pi_2$. Moreover, $\lVert \pi_1\otimes \pi_2(x)\rVert=\lVert \pi(x)\rVert=\lVert x\rVert_\max$.
If $A$ and $B$ are not necessarily unital, you can embed them into their unitizations to get the same result.


text:
Q: How do I find the maximum database space and the used database space in SQL Azure? In SQL Azure each database has a size limitation (adjustable). In order for my service to not suddenly come to a halt I'd like to be able to programmatically find the current maximum size and current actually used space (and generate and alert once some threshold is reached).
Looks like sp_mstablespace can be used to solve this problem, but this stored procedure is not available in SQL Azure.
How do I find the current maximum allowed size and current actually used space in a SQL Azure database?

A: David has already pointed out how to find the current size of your database, if you want to know the maximum size of your database in MB, you need to run the following query in the database you're interested in:
SELECT CONVERT(BIGINT, DATABASEPROPERTYEX('DatabaseOfInterestName', 'MaxSizeInBytes')) / 1024

Reference

A: You can calculate used space via dynamic management views (reference page here):
SELECT SUM(reserved_page_count)*8.0/1024
FROM sys.dm_db_partition_stats;

While I don't think you can retrieve max size, it doesn't hurt to simply set your database to the largest size, since you're only billed for space you use. Having said that: If you're only in the sub-5GB range, it's best to go with Web edition. If you're already at 10+ GB, there shouldn't be any harm setting max size to 150GB and then monitoring consumed size.


text:
Q: How to share shiro session in distributed system? I have two distributed web apps A and B(A is the same as B), i am using shiro to share the http sessions between two apps. But I don't know how to implement it,I want some help.
Any help will be appreciated :)

A: Shiro has official modules for Hazelcast and EhCache.
The above Hazelcast links to a blog post with an example of two applications sharing sessions.

A: I hope shiro-redis can give you some help. Maybe this code is not recently. But you can study his method. Then you can create your code.

I will give you some code as follows:
1 sessionDao
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;

import org.apache.shiro.session.Session;
import org.apache.shiro.session.mgt.SimpleSession;
import org.apache.shiro.session.mgt.eis.EnterpriseCacheSessionDAO;

public class SessionRedisDao extends EnterpriseCacheSessionDAO {

    // create session , store to db
    @Override
    protected Serializable doCreate(Session session) {
        Serializable sessionId = super.doCreate(session);
        RedisDb.setObject(sessionId.toString().getBytes(), sessionToByte(session));

        return sessionId;
    }

    // get session
    @Override
    protected Session doReadSession(Serializable sessionId) {
        // firstly get session from cache,if null then get it from db
        Session session = super.doReadSession(sessionId);
        if(session == null){
            byte[] bytes = RedisDb.getObject(sessionId.toString().getBytes());
            if(bytes != null && bytes.length > 0){
                session = byteToSession(bytes);
            }
        }
        return session;
    }

    @Override
    protected void doUpdate(Session session) {
        super.doUpdate(session);
        RedisDb.setObject(session.getId().toString().getBytes(), sessionToByte(session));
    }

    // delete session
    @Override
    protected void doDelete(Session session) {
        super.doDelete(session);
        RedisDb.delString(session.getId() + "");
    }

    // convert session object to byte, then store it to redis
    public byte[] sessionToByte(Session session){
        ByteArrayOutputStream bo = new ByteArrayOutputStream();
        byte[] bytes = null;
        try {
            ObjectOutputStream oo = new ObjectOutputStream(bo);
            oo.writeObject(session);
            bytes = bo.toByteArray();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return bytes;
    }

    // restore session
    public Session byteToSession(byte[] bytes){
        ByteArrayInputStream bi = new ByteArrayInputStream(bytes);
        ObjectInputStream in;
        SimpleSession session = null;
        try {
            in = new ObjectInputStream(bi);
            session = (SimpleSession) in.readObject();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return session;
    }

}

*redis operator
import java.util.Arrays;
import java.util.Date;
import java.util.Set;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

public class RedisDb {
private static JedisPool jedisPool;
// session expire time
private static int expireTime = 1800;
private static int countExpireTime = 2*24*3600;
private static String password = "123456";
private static String redisIp = "10.10.31.149";
private static int redisPort = 6379;
private static int maxActive = 200;
private static int maxIdle = 200;
private static long maxWait = 5000;
private static Logger logger = Logger.getLogger(RedisDb.class);

static {
    initPool();
}
// init connect pool
public static void initPool(){
    JedisPoolConfig config = new JedisPoolConfig();
    config.setMaxTotal(maxActive);
    config.setMaxIdle(maxIdle);
    config.setMaxWaitMillis(maxWait);
    config.setTestOnBorrow(false);
    jedisPool = new JedisPool(config, redisIp, redisPort, 10000, password);
}
// get connect from pool
public static Jedis getJedis(){
    Jedis jedis = null;
    try{
        jedis = jedisPool.getResource();
        //            jedis.auth(password);
    } catch(Exception e){
        ExceptionCapture.logError(e);
    }

    return jedis;
}
// recycle connection
public static void recycleJedis(Jedis jedis){
    if(jedis != null){
        try{
            jedis.close();
        } catch(Exception e){
            ExceptionCapture.logError(e);
        }
    }
}
// save string
public static void setString(String key, String value){
    Jedis jedis = getJedis();
    if(jedis != null){
        try{
            jedis.set(key, value);
        } catch(Exception e){
            ExceptionCapture.logError(e);
        } finally{
            recycleJedis(jedis);
        }
    }

}
// get string data
public static String getString(String key){
    Jedis jedis = getJedis();
    String result = "";
    if(jedis != null){
        try{
            result = jedis.get(key);
        }catch(Exception e){
            ExceptionCapture.logError(e);
        } finally{
            recycleJedis(jedis);
        }
    }

    return result;
}
// delete string
public static void delString(String key){
    Jedis jedis = getJedis();
    if(jedis != null){
        try{
            jedis.del(key);
        }catch(Exception e){
            ExceptionCapture.logError(e);
        } finally{
            recycleJedis(jedis);
        }
    }
}
// save byte data
public static void setObject(byte[] key, byte[] value){
    Jedis jedis = getJedis();
    String result = "";
    if(jedis != null){
        try{
            if(!jedis.exists(key)){
                jedis.set(key, value);
            }
            // redis中session过期时间
            jedis.expire(key, expireTime);
        } catch(Exception e){
            ExceptionCapture.logError(e);
        } finally{
            recycleJedis(jedis);
        }
    }
}
// get byte data
public static byte[] getObject(byte[] key){
    Jedis jedis = getJedis();
    byte[] bytes = null;
    if(jedis != null){
        try{
            bytes = jedis.get(key);;
        }catch(Exception e){
            ExceptionCapture.logError(e);
        } finally{
            recycleJedis(jedis);
        }
    }
    return bytes;

}

// update byte data
public static void updateObject(byte[] key){
    Jedis jedis = getJedis();
    if(jedis != null){
        try{
            // redis中session过期时间
            jedis.expire(key, expireTime);
        }catch(Exception e){
            ExceptionCapture.logError(e);
        } finally{
            recycleJedis(jedis);
        }
    }

}

// key value add 1
public static void inc(String key){
    Jedis jedis = getJedis();
    if(jedis != null){
        try{
            if(!jedis.exists(key)){
                jedis.set(key, "1");
                jedis.expire(key, countExpireTime);
            } else {
                // 加1
                jedis.incr(key);
            }
        }catch(Exception e){
            ExceptionCapture.logError(e);
        } finally{
            recycleJedis(jedis);
        }
    }
}

// get all keys
public static Set<String> getAllKeys(String pattern){
    Jedis jedis = getJedis();
    if(jedis != null){
        try{
            return jedis.keys(pattern);
        }catch(Exception e){
            ExceptionCapture.logError(e);
        } finally{
            recycleJedis(jedis);
        }
    }
    return null;
}

}
The shiro's session just a object, so if you want to share session, you need to store it in a share place.


text:
Q: Passing huge amount of small requests by using Javascript(Ajax) to PHP (logging into mysql) would it be the right way to solve such problem?
Problem:
there will be amount of requests (200-400 per second) coming from users browsers through Javascript (Ajax) to my PHP node (single .php file), which will be logging some information to mysql database (e.g. user-agent, screen size, other user's public data). The amounts of single request sent information will be small (1-2kb).
What can you advice to prevent my server (or database) (1Core 2.5Ghz 1 GB RAM from dying from such amount of requests?
Or i should not worry about such amounts of requests at all?
Thanks

A: You can use DVM's to see whats taking up the most worker time.  If you're on linux I'd also recommend watching \ checking your htop report to see how much strain is being put on your core in real time.  Here's a good DVM to use if to see what's taking up your worker time.  Unless you're doing something inefficient query wise you shouldn't have any issues though, but the only way to know for sure is benchmarking.
SELECT TOP 10 SUBSTRING(qt.TEXT, (qs.statement_start_offset/2)+1,
((CASE qs.statement_end_offset
WHEN -1 THEN DATALENGTH(qt.TEXT)
ELSE qs.statement_end_offset
END - qs.statement_start_offset)/2)+1),
qs.execution_count,
qs.total_logical_reads, qs.last_logical_reads,
qs.total_logical_writes, qs.last_logical_writes,
qs.total_worker_time,
qs.last_worker_time,
qs.total_elapsed_time/1000000 total_elapsed_time_in_S,


text:
Q: Use of undeclared type 'JSONValue' this piece of code is throwing the above error:
class func fromJSON(json: [JSONValue]) -> Artwork? {

I have imported SwiftyJSON as other articles have suggested to, however, the same error remains.
# Pods for Notice!
pod 'SwiftyJSON', :git => 'https://github.com/SwiftyJSON/SwiftyJSON.git'

Any idea what is wrong?


text:
Q: Cardinality of cartesian square Given an infinite set $A$ -  does the cardinality of $A$ equal to the cardinality of $A^2$?

A: Zermelo proved that every well-ordered infinite set has this property, so if we assume the axiom of choice then the answer is yes. In fact the axiom of choice is equivalent to the assertion that for every infinite set $A$, $A$ and $A^2$ are equinumerous.

*

*The proof of Zermelo's theorem can be found here: About a paper of Zermelo

*The proof for the reverse implication can be found here: For every infinite $S$, $|S|=|S\times S|$ implies the Axiom of choice

However if the axiom of choice is negated there are sets whose cardinality is strictly less of that of their square. We even know how to construct such set:
Suppose that $X$ cannot be well-ordered (such set exists, since we assume the axiom of choice is false, and therefore the well-ordering principle is false). Let $\kappa$ be an ordinal such that there is no $f\colon\kappa\to X$ which is injective.
In this case $A=X\cup\kappa$ has the property that $A^2$ is strictly larger than $A$.


text:
Q: What do I need to do to get Onepage to stop validating the CC number I'm entering? I've setup a new instance of our development server on localhost, checked out the latest working copy, and was given a copy of a database backup to use with it. After getting all of this setup and working, I went through a demo transaction to make sure my checkout was working after reverting to the working copy.
It looks as though the checkout is actually trying to process my transaction on the development server now though, as it's declining the card with:
Error Code: 10544: Please use another payment card

I've set the System->Configuration->Payment Methods->Authorize.Net->Test to yes, but it's still trying to process my card it seems.

A: Each payment gateway vendor has their own approach to facilitate test transactions. In the current case. IIRC Authorize.net has settings at both the external (i.e. originating or Magento) end and the internal (the actual Authorize.net account) end. There are also credit card numbers and amounts which may trigger specific responses from the gateway. Additionally, there is the Luhn check which is often performed client-side to validate the account number, so gateway test cards will have to meet these criteria as well
A test card which can be used for Authorize.net is Visa 4111111111111111 with any CCV and an expiry in the future.


text:
Q: c++ error: why this error shows " expected type specifier in vector " I include the vector but when I declare a vector inside the class  it shows an error(expected type specifier)
do my code is correct?
#include <vector>
#include <string>
class Ecole {

    vector<string> arr(10);
};

A: As other answers already mentioned, you will need to write the namespace std infront of vector and string.
Also I would assume that you will have to initialise the variable like this:
std::vector<std::string> arr = std::vector<std::string>(10);

As you cannot initalise it with just (10) directly inside of the class. (Outside of a method)

A: The vector and string are declared in the namespace std, So use the namespace to refer them.
#include <vector>
#include <string>
class Ecole {

    std::vector<std::string> arr(10);
};

If you want to get the rid of using std each time, you can write using namespace std; before the class declaration;
#include <vector>
#include <string>
using namespace std;
class Ecole {

    vector<string> arr(10);
};

But this is the bad idea, see the link Why is "using namespace std;" considered bad practice?
The other problem is that you are trying to initialise arr(10) the vector without the referring to any variable in the class directly, you have to declare and initialisation both in the class.
class Ecole {

    std::vector<std::string> arr = std::vector<std::string>(10);
};

And if you want to declare and then initialise in the constructor.
#include <vector>
#include <string>
class Ecole {

    std::vector<std::string> arr;

    Ecole(){
        this->arr = std::vector<std::string>(10);
    }

};

If you want to just play with the vector without the class, you can use directly in the main function.
#include <vector>
#include <string>
int main() {
    std::vector<std::string> arr(10);
    // start playing here

    return 0;
}

A: I bet it would work if you replace <string> with <std::string> and replace vector with std::vector
The issue is that string and vector are included in the std namespace, so they must be addressed accordingly.
Another way to make it work is to add
using namespace std;

...above the class declaration, although it is said to be bad practice, as described here: https://www.geeksforgeeks.org/using-namespace-std-considered-bad-practice/