text:
Q: Highcharts, get point index when shared tooltip is shows/hides I have a group of charts which have the same categories.
When user hover on the chart and the tooltip is shown, I need to set all charts's corresponding point state to hover to help user to compare the data.
Firstly I use mouseOver and mouseOut events and it almost meet my needs, but I use shared tooltip so sometimes the tooltip shows without mouse on the point, so the event is not fired.
So I guess I need an event that when the tooltip shows/hides, and I find this and try tooltipRefresh event but I can't find the exactly index of on which point the tooltip shows. I have tried:
tooltipRefresh: function(e) {
    var index = this.hoverPoint.index; //No dependentable
}

Is that any way that I can get the index at the right event firing moment?

A: you can use Label which just like the tootip, show X, Y value on the Lable.
What i did is :
    1.click on one chart  === >
    2.get X value  ===>
    3.fire a Event (click event of chart)  === >
    4.render Label on every other chart using X (get Y value in each chart by X)

when create chart, I set an click event
options.chart = $.extend(true, options.chart, {
                renderTo: 'hChart_' + chartIndex,
                type: 'spline',
                events: {
                    click: function (event) {
                        if($scope.label.length > 0){
                            $scope.clearAllLabels();
                        }else{
                            var charts = $scope.ui.charts;
                            $.each(charts, function (index, chart) {
                                //render Label to chart
                             });
                        }
                     }
                   }
                });

Below is add label in chart.
var label = chart.renderer.label(
                    moment(xAxis).format('dddd, MMM DD, HH:mm:ss') + '
' + kpiName + ': ' + Highcharts.numberFormat(yAxis, 2) + kpiUnit + '',
                    120,
                    40)
                .attr({
                    fill: Highcharts.getOptions().colors[0],
                    padding: 10,
                    r: 5,
                    zIndex: 8
                })
                .css({
                    lineHeight: '20%',
                    fontSize: '11px',
                    color: '#FFFFFF'
                })
                .add();

Hope it will help you.


text:
Q: Como fazer uma consulta utilizando SUM corretamente SQL Tenho a seguinte query:
 SELECT
  YEAR(NFDtEmis) AS 'Ano',
  MONTH(NFDtEmis) AS 'Mes',
  ItProduto AS 'Produto',
  SUM(ItQtde) AS 'Quantidade total'
FROM NotasItens
INNER JOIN NotasFiscais
  ON NFEmpresa = ItEmpresa
  AND NFNumero = ItNfNumero
  AND NFTIPO = ItTipo
INNER JOIN Tributos
  ON TribEmpresa = ItEmpresa
  AND TribCodigo = ItCFO
WHERE ItEmpresa = '03'
AND ItProduto = 'JKIT'
AND NFDtEmis >= '2016-04-01'
AND NFDtEmis <= '2017-07-31'
AND NFStatus = 'I'
AND NFTipo = 'S'
AND NFEmpresa = '03'
AND UPPER(RTRIM(LTRIM(TribTpCFOP))) = 'VENDA'
GROUP BY YEAR(NFDtEmis),
         MONTH(NFDtEmis),
         ItProduto,
         ItQtde
ORDER BY YEAR(NFDtEmis), MONTH(NFDtEmis)

Eu escrevi na idéia de trazer a quantidade total vendidada do produto "JKit" para cada mês a partir de Abril/2016, porém eu não sei porque, ele está repetindo o mês, ao invês de somar tudo.
Acredito que possa estar errado o SUM()
Resultado:

A: Se quer agrupar por mês você precisa selecionar apenas as colunas referentes no group by, sem agrupar pela quantidade:
SELECT
  YEAR(NFDtEmis) AS 'Ano',
  MONTH(NFDtEmis) AS 'Mes',
  ItProduto AS 'Produto',
  SUM(ItQtde) AS 'Quantidade total'
FROM NotasItens
INNER JOIN NotasFiscais
  ON NFEmpresa = ItEmpresa
  AND NFNumero = ItNfNumero
  AND NFTIPO = ItTipo
INNER JOIN Tributos
  ON TribEmpresa = ItEmpresa
  AND TribCodigo = ItCFO
WHERE ItEmpresa = '03'
AND ItProduto = 'JKIT'
AND NFDtEmis >= '2016-04-01'
AND NFDtEmis <= '2017-07-31'
AND NFStatus = 'I'
AND NFTipo = 'S'
AND NFEmpresa = '03'
AND UPPER(RTRIM(LTRIM(TribTpCFOP))) = 'VENDA'
GROUP BY YEAR(NFDtEmis),
         MONTH(NFDtEmis),
         ItProduto
ORDER BY YEAR(NFDtEmis), MONTH(NFDtEmis)

detalhe: o agrupamento pela quantidade (ItQtde) vai agrupar na linha apenas quando ela for igual; ou seja, se você tem quantidades diferentes na venda do mesmo produto, ele não somará na mesma linha e criará uma linha para cada. Ex: duas vendas de 10 produtos e duas vendas de 50; o select traria duas linhas, uma com total 20 e outra com total 100.

A: Amigo, tu acabou colocando a quantidade ( ItQtde ) no group by.
SELECT
  YEAR(NFDtEmis) AS 'Ano',
  MONTH(NFDtEmis) AS 'Mes',
  ItProduto AS 'Produto',
  SUM(ItQtde) AS 'Quantidade total'
FROM NotasItens
INNER JOIN NotasFiscais
  ON NFEmpresa = ItEmpresa
  AND NFNumero = ItNfNumero
  AND NFTIPO = ItTipo
INNER JOIN Tributos
  ON TribEmpresa = ItEmpresa
  AND TribCodigo = ItCFO
WHERE ItEmpresa = '03'
AND ItProduto = 'JKIT'
AND NFDtEmis >= '2016-04-01'
AND NFDtEmis <= '2017-07-31'
AND NFStatus = 'I'
AND NFTipo = 'S'
AND NFEmpresa = '03'
AND UPPER(RTRIM(LTRIM(TribTpCFOP))) = 'VENDA'
GROUP BY YEAR(NFDtEmis),
         MONTH(NFDtEmis),
         ItProduto,
--       ItQtde /* invalido no group by */
ORDER BY YEAR(NFDtEmis), MONTH(NFDtEmis)

redpajama_set_name: RedPajamaStackExchange


text:
Q: FormGroup.value returns the default value not the updated ones I have a small form and on click of a button I want to access the latest values of the form. But what I get is the default values with which I initialized the form.
I am using material for designing the input fields
component.ts
import { Component, EventEmitter, Inject, OnInit, Output } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { MatDialogRef, MAT_DIALOG_DATA } from '@angular/material/dialog';
import { ElementService } from 'src/app/services/element.service';

import { PeriodicElement } from '../../../Interfaces/periodicElement';

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

export class CreateComponent {

    formGroup: FormGroup;
    inProgress: boolean = false;
    onChange = (_: any) => { };

    constructor(
        private elementService: ElementService,
        private formBuilder: FormBuilder,
        public dialogRef: MatDialogRef<CreateComponent>,
        @Inject(MAT_DIALOG_DATA) public data: PeriodicElement
    ) {
        this.formGroup = this.formBuilder.group({
            position: [this.data.position, Validators.required],
            name: [this.data.name, Validators.required],
            weight: [this.data.weight, Validators.required],
            symbol: [this.data.symbol, Validators.required]
        });
    }

    valueChanges(controlGroup: string) {
        let value = this.formGroup.get(controlGroup)?.value;
        this.onChange(value);
    }

    save() {
        console.log(this.formGroup.value)
        this.inProgress = true;
        this.elementService.list().subscribe(list => {
            this.inProgress = false;
            this.dialogRef.close(list);
        });

    }
}

Component.html

Add Element

<mat-dialog-content>
    <form [formGroup]="formGroup">
        <mat-form-field appearance="fill" class="spacer">
            <mat-label>Position</mat-label>
            <input matInput type="number" [value]="data.position" (valueChanges)="valueChanges('position')" />
        </mat-form-field>
        <mat-form-field appearance="fill" class="spacer">
            <mat-label>Name</mat-label>
            <input matInput [value]="data.name" (valueChanges)="valueChanges('name')" />
        </mat-form-field>
        <mat-form-field appearance="fill" class="spacer">
            <mat-label>Weight</mat-label>
            <input matInput type="number" [value]="data.weight" step=".00001" (valueChanges)="valueChanges('weight')" />
        </mat-form-field>
        <mat-form-field appearance="fill" class="spacer">
            <mat-label>Symbol</mat-label>
            <input matInput [value]="data.symbol" (valueChanges)="valueChanges('symbol')" />
        </mat-form-field>
    </form>
</mat-dialog-content>
<mat-dialog-actions align=end>
    <mat-spinner [diameter]="20" *ngIf="inProgress"></mat-spinner>
    <button color="accent" mat-raised-button (click)="save()">Add</button>
    <button color="warn" mat-raised-button mat-dialog-close>Cancel</button>
</mat-dialog-actions>

A: your template code is poluted by (valueChanges)="valueChanges('field')". Just remove it from template and use the Reactive Forms features. Use formControlName for your inputs, how @atiyar said (formControlName="YourFieldName").
The new value of a form or form control can be catched in your controller using valueChanges method of it.
ngOnInit(): void {
  this.formGroup.valueChanges
     .pipe(distinctUntilChanged()) // used to be fired only for value changed
     .subscribe(value => {
        // value = all form fields
        // do something
     });
}

This is all. Clear and clean.

A: Modify the component.html to -

Add Element

<mat-dialog-content>
    <form [formGroup]="formGroup">
        <mat-form-field appearance="fill" class="spacer">
            <mat-label>Position</mat-label>
            <input matInput type="number" formControlName="position" />
        </mat-form-field>
        <mat-form-field appearance="fill" class="spacer">
            <mat-label>Name</mat-label>
            <input matInput formControlName="name" />
        </mat-form-field>
        <mat-form-field appearance="fill" class="spacer">
            <mat-label>Weight</mat-label>
            <input matInput type="number" step=".00001" formControlName="weight" />
        </mat-form-field>
        <mat-form-field appearance="fill" class="spacer">
            <mat-label>Symbol</mat-label>
            <input matInput formControlName="symbol" />
        </mat-form-field>
    </form>
</mat-dialog-content>
<mat-dialog-actions align=end>
    <button color="accent" mat-raised-button (click)="save()">Add</button>
    <button color="warn" mat-raised-button mat-dialog-close>Cancel</button>
</mat-dialog-actions>

and you don't need the onChange property and the valueChanges() method in the component.ts anymore.

A: You are not using formGroup properly. missing formControlName attribute for form elements
HTML

Add Element

    <mat-dialog-content>
        <form [formGroup]="myForm">
            <mat-form-field appearance="fill" class="spacer">
                <mat-label>Position</mat-label>
                <input matInput type="number" name="position" formControlName="position" />
            </mat-form-field>
            <mat-form-field appearance="fill" class="spacer">
                <mat-label>Name</mat-label>
                <input matInput name="name" formControlName="name" />
            </mat-form-field>
            <mat-form-field appearance="fill" class="spacer">
                <mat-label>Weight</mat-label>
                <input matInput type="number" name="weight" step=".00001" formControlName="weight" />
            </mat-form-field>
            <mat-form-field appearance="fill" class="spacer">
                <mat-label>Symbol</mat-label>
                <input matInput name="symbol" formControlName="symbol" />
            </mat-form-field>
        </form>
    </mat-dialog-content>
    <mat-dialog-actions align=end>
        <mat-spinner [diameter]="20" *ngIf="inProgress"></mat-spinner>
        <button color="accent" mat-raised-button (click)="save()">Add</button>
        <button color="warn" mat-raised-button mat-dialog-close>Cancel</button>
    </mat-dialog-actions>

TS

    public myForm: FormGroup;

    constructor(
        private elementService: ElementService,
        private formBuilder: FormBuilder,
        public dialogRef: MatDialogRef<CreateComponent>,
        @Inject(MAT_DIALOG_DATA) public data: PeriodicElement
    ) {
        this.myForm = this.formBuilder.group({
            position: [this.data.position, Validators.required],
            name: [this.data.name, Validators.required],
            weight: [this.data.weight, Validators.required],
            symbol: [this.data.symbol, Validators.required]
        });

        // listener for value change
        this.myForm.valueChanges.subscribe((data) => {
            console.log('onChange ===> ', data);
        });
    }

    save() {
        console.log('myForm ===> ', this.myForm);
        if (this.myForm.valid) {
            // api call to server or whatever you want to do with it
        }
    }


text:
Q: std::unique_lock prohibit dll unloading I have an issue while unloading a dll. It is like this one but quit different. I'm loading a dll using LoadLibraryA then call a function and close the dll with FreeLibrary. However, the dll is not unloaded but FreeLibrary return success.
reduced code:
void foo() {
    std::unique_lock<std::mutex> lock(mtx_);
}

While debugging the code and looking into Process Explorer unique_lock creates a second thread, but why? Also this thread is running as long as the application runs. There is nothing else; no other handle to the dll, no other functions. Also the dll is still loaded in the program. If I remove the line above, everything is fine. The dll is unloaded fine, no extra threads. So my question is, how to avoid this behavior and why is unique_lock creating a thread?
The mutex is intended for multithreading, but while testing, there is only one thread, loading the dll calling foo, and unloading the dll.
edit:
I don't know if this is a bug in the visual studio implementation of mutex/unique_lock but I solved the problem by using boost's mutex/unique_lock.

A: This is a bug in Visual Studio, they increase the reference count of the DLL abnormally when you use std::thread or std::mutex, etc.
See this bug report.

A: It looks like this bug has been fixed in Visual Studio 2015.
See this for details.

... I can confirm that the issue is not occurring with VS2015. ...


text:
Q: Proving combinatorial identity $\sum_s (-1)^s\binom{p+s-1}{s}\binom{2m+2p+s}{2m+1-s}2^s=0$ I need to prove following combinatorial identities:
$$
\sum\limits_s(-1)^s\binom{p+s-1}{s}\binom{2m+2p+s}{2m+1-s}2^s=0
$$
$$
\sum\limits_s(-1)^s\binom{p+s-1}{s}\binom{2m+2p+s-1}{2m-s}2^s=(-1)^m\binom{p+m-1}{m}
$$
given the fact that
$$
(1-x)^{2k}\left(1+\frac{2x}{(1-x)^2}\right)^k = (1+x^2)^k
$$
for either $k=p$ or $k=-p$.
And for the first one I cannot understand where $\binom{2m+2p+s}{2m+1-s}$ is emerging from (different signs for $s$ on top and bottom seem strange to me). I'm trying to prove first identity as following: if we transform given equation and let $k=p$ we get something like this:
$$
(1-x)^{2p}(1+2x+4x^2+\dots)^p=(1+x^2)^p
$$
Let's find coefficient for $x^{2m+1}$ for both sides. For the right side it is always equal to $0$, as only even powers are present there. For the left side let's take $x^s$ from second bracket and $x^{2m+1-s}$ from first. Getting $x^s$ from second bracket is equal to splitting $s$ into $p$ addends with zeroes allowed, so the coefficient is equal to $2^s\binom{p+s-1}{p-1} = 2^s\binom{p+s-1}{s}$. So we get some of needed multipliers for our identity. But now if we take $2m+1-s$ from first bracket we get coefficient like $(-1)^{2m+1-s}\binom{2p}{2m+1-s} = (-1)^s\binom{2p}{2m+1-s}$. And the final result is:
$$
\sum\limits_s(-1)^s\binom{p+s-1}{s}\binom{2p}{2m+1-s}2^s=0
$$
And I see no way to transform it to required identity.
For the second equality I do not even understand where right side is taken from.
Thanks in advance for any help.

A: Ok, first of all there was an error in my attempt to solve, because of my misinterpreting of series $1+2x+4x^4+\dots$ as $\sum(2x)^n$ when actually (if one to find more series members) it is $1 + 2x + 4x^2 + 6x^3 + 8x^4+\dots$. Secondly, this attempt was incorrect way of solving this problem. The correct way involves applying binomial theorem, like this:
$$
(1-x)^{2k}\left(1+\dfrac{2x}{(1-x)^2}\right)^k = (1-x)^{2k} \sum\limits_s \binom{k}{s}  \left(\dfrac{2x}{(1-x)^2}\right)^s = \sum\limits_s\binom{k}{s}2^sx^s(1-x)^{2k-2s}
$$
After that we can apply it second time:
$$
\sum\limits_s\binom{k}{s}2^sx^s(1-x)^{2k-2s} = \sum\limits_s\binom{k}{s}2^sx^s\sum\limits_t(-1)^t\binom{2k-2s}{t}x^t = \sum\limits_s\sum\limits_t2^s(-1)^t\binom{k}{s}\binom{2k-2s}{t}x^{s+t}
$$
And now one should just take $k=-p$ and $s+t=2m$ for even powers and $s+t=2m+1$ for odd ones. This directly leads to desired identities.

A: Suppose we seek to verify that
$$\sum_{q=0}^{2m} (-1)^q {p-1+q\choose q}
{2m+2p+q-1\choose 2m-q} 2^q =
(-1)^m {p-1+m\choose m}.$$
Introduce
$${2m+2p+q-1\choose 2m-q} =
\frac{1}{2\pi i}
\int_{|z|=\epsilon}
\frac{1}{z^{2m-q+1}} (1+z)^{2m+2p+q-1} \; dz.$$
Observe that this  controls the range being zero when  $q\gt 2m$ so we
may extend $q$ to infinity to obtain for the sum
$$\frac{1}{2\pi i}
\int_{|z|=\epsilon}
\frac{1}{z^{2m+1}} (1+z)^{2m+2p-1}
\sum_{q\ge 0} {p-1+q\choose q} (-1)^q 2^q z^q (1+z)^q \; dz
\\ = \frac{1}{2\pi i}
\int_{|z|=\epsilon}
\frac{1}{z^{2m+1}} (1+z)^{2m+2p-1}
\frac{1}{(1+2z(z+1))^p} \; dz
\\ = \frac{1}{2\pi i}
\int_{|z|=\epsilon}
\frac{1}{z^{2m+1}} (1+z)^{2m+2p-1}
\frac{1}{((1+z)^2+z^2)^p} \; dz
\\ = \frac{1}{2\pi i}
\int_{|z|=\epsilon}
\frac{1}{z^{2m+1}} (1+z)^{2m-1}
\frac{1}{(1+z^2/(1+z)^2)^p} \; dz
\\ = \frac{1}{2\pi i}
\int_{|z|=\epsilon}
\frac{1}{z^{2m}} (1+z)^{2m} \frac{1}{z(1+z)}
\frac{1}{(1+z^2/(1+z)^2)^p} \; dz.$$
Now put $$\frac{z}{1+z} = u
\quad\text{so that}\quad z=\frac{u}{1-u}
\quad\text{and}\quad dz=\frac{1}{(1-u)^2} du$$
to obtain for the integral
$$\frac{1}{2\pi i}
\int_{|u|=\gamma}
\frac{1}{u^{2m}} \frac{1}{u/(1-u)\times 1/(1-u)}
\frac{1}{(1+u^2)^p} \frac{1}{(1-u)^2} \; du
\\ = \frac{1}{2\pi i}
\int_{|u|=\gamma}
\frac{1}{u^{2m+1}} \frac{1}{(1+u^2)^p} \; du.$$
This is
$$[u^{2m}] \frac{1}{(1+u^2)^p}
= [v^{m}] \frac{1}{(1+v)^p}
= (-1)^m {m+p-1\choose m},$$
as claimed.
For the conditions on $\epsilon$ and $\gamma$ we require convergence of the geometric series with $|2z(1+z)|\lt 1$ which holds for $\epsilon \lt (-1+\sqrt{3})/2.$ Note that with $u=z+\cdots$ the image of $|z|=\epsilon$ makes one turn around zero. The closest it comes to the origin is at $\epsilon/(1+\epsilon)$ so we must choose $\gamma \lt \epsilon/(1+\epsilon)$ e.g. $\gamma=\epsilon^2/(1+\epsilon)$ for $|w|=\gamma$ to be entirely contained in the image of $|z|=\epsilon.$ Taking $\epsilon = 1/5$ will work.


text:
Q: Build dynamic array in PHP I need to create an array using a object using different format/structure
I have:
$t = object()
$t > user = object()
$t > user > 0 (object) name = 'wilson';
$t > user > 0 (object) first = 'carl';

I need to get:
$t = array(
 name = wilson
 first name = phil

Here's what I tried and where I'm stuck
foreach($t as $a) {
      foreach($a as $l) {
          $arr[$l->0->name] = $l->0->first; // line 10
      }
  }
  print_r($arr);

Now I get an error:

PHP Parse error:  syntax error, unexpected T_LNUMBER, expecting
  T_STRING or T_VARIABLE or '{' or '$' in homework1-a-1.php on
  line 10

What can I do to fix it?

A: Your question is confusing. This is what I understand:
You have the following:

*

*$t, which is an object.

*$t->user, also an object.

*$t->user[0]->name = 'wilson'

*$t->user[0]->first = 'carl'
You say you need to get:

*

*$t->name = 'wilson'

*$t->first = 'carl'
You say 'phil' in the question, but the given object $t has no reference to a 'phil' so I don't know if 'phil' appears out of thin air, or what.
Is this a correct view of the problem? If so, you need to clarify this in the question. saying $t > user > 0 (object) name makes no sense.
Sorry this is an "answer", I just couldn't fit all of this in a comment. I will delete it if you clarify the question. Hopefully I am not the only person confused by this.

A: $t = object()
$t > user = object()
$t > user > 0 (object) name = 'wilson';
$t > user > 0 (object) first = 'carl';

This is not valid PHP code.  If you want $t in the format you show, just do this:
$t = array(
 'name' => 'wilson',
 'first name' => 'phil'
);

Now $t is an array, with keys 'name' and 'first name'.
Your foreach loop doesn't make any sense.  $t is an array of two strings.  Looping over it will just give the values 'wilson' and 'phil'.
EDIT: Assuming $t was given to you, then your for loop should look like this:
foreach($t as $a) {
      foreach($a as $l) {
          $arr[$l->{0}->name] = $l->{0}->first;
      }
  }

You can't do $l->0.  You need to wrap the 0 in {}.  $l->{0}.


text:
Q: USBL Hydrophone Array Spacing I am trying to design a USBL acoustic pinger location system for a school project. I am struggling to determine if the frequency of the acoustic beacon ping places a constraint on the distances between hydrophones in the array. I have found in one source online that the hydrophones must be less than one half a wavelength apart to be able to implement the phase-comparison method for angle of arrival calculations. Is this the case?

A: Yes and no.
Larger than that spacing introduces ambiguities in bearing. If the ambiguity can be resolved by other means (by knowledge of the source, or other hydrophones more closely spaced) then the extra receivers will still improve SNR and bearing accuracy.


text:
Q: Multiple routers on the same network over coax I am attempting to set up a home network.  As the only existing infrastructure in the house is coax, I was informed that I would be able to hook up a cable modem (modem router combo) to existing coax connections in the house, setting all 3 (1 in the basement, 1 on the 1st floor and 1 on the 2nd floor) up with the same SSID and password so my devices would switch to the strongest signal when the other signal dropped.
Note: I really don't want to dig into the walls and run cabling throughout the house.
I went out and purchased 3 - ARRIS SURFboard SBG6782-AC DOCSIS 3.0 Cable Modem and AC1750 Wi-Fi Routers as was recommended to me.
I verified with my cable company (Comcast / Xfinity) that I could add all 3 to my account and it would split my bandwidth, but should increase my coverage.
My question is this - Before I go ahead and do this whole set-up, was i given bad advice or should this work?

A: Well, since you already bought the equipment, why not try it out and let us know how it goes?
One problem you will probably run into is that the seperate floors won't be able to connect to one another (ie. if your NAS is in the basement, you wouldn't be able to access it on the attic), since they will be seperate networks, only connected over the internet. You could create VPN tunnels between the routers and set up internal routing that way, but depending on how your ISP does bandwidth limiting, you might end up with low bandwidth connections between floors (at least, a lot slower than gigabit ethernet).
Also, unless proper handovers are used, most WiFi devices will only disconnect when the signal goes under a critical value and then start searching for other access points. Since all three WiFi AP's are connected to different networks, it'd be a challenge to set up proper WiFi handovers between them. I know Cisco Aironet can do this, but it's prohibitively expensive for home use. So you'll probably experience slow connections unless you actively switch WiFi networks.
You don't want to dig into the walls and run cabling, but why not replace the existing coax for ethernet cables? You can use the same cable ducts and get a proper connection. I replaced telephone wire with ethernet on several occasions and that worked brilliantly. Just tie the ethernet to the end of the cable and pull it through. Alternatively, there is always ethernet over power (Powerline) equipment, although the proper ethernet option is much better.

A: Before you begin reading my answer, please note that my understanding is that you wish to use these routers as independent modems broadcasting on the same SSID with the same WEP/WPA(2) key, and same settings.
Personally, I would take it for a test run and see how it performs (seeing that you already dropped a good $500 into the equipment); however I would also say this is bad advice for many reasons. Many people (without splitting their bandwidth) use wireless or wired range extenders or repeaters. The effect of running 3 routers on the same coaxial source can monumentally impact your bandwidth in a negative way (it can also result in a very nasty and chaotic network, referred to as a collision domain, where the system can become stressed if you are not careful). Another big danger is cluttering of the frequency bands. If you intend to run the routers on the same 'channel', they will see each-other's broadcasts as noise (I hope I don't have to explain why this is a problem.) Else, your three routers clutter up the 1, 6, and 11 channels on the 2.4GHz band; these are the three most commonly endorsed channels, and therefore, the most cluttered already. Also, taking from @mtak's answer, you'll run into a problem with a divided network, meaning that your NAS per se may not be accessible from your attic or 2nd floor.

If you're going to do anything in regards to coverage, you should see if the routers support an "AP" or "Access Point" mode in lieu of a routing mode. The cable modem should work in conjunction with the access points to provide better coverage while not splitting your bandwidth. I highly recommend you invest in some inexpensive MoCA adapters, I bet they would be worth your while. This way you might be able to wire your house in a way that you can directly connect your personal computers to the wired network. In the future, try to get a second opinion before you delve into something as surprisingly difficult as this.

If you're too pained by the $500 you just blew on Wi-Fi equipment to deal with unsightly wires in your house, or spend a day in your attic or crawlspace routing cables, you should stick to a little bit of light reading or homework. For now, I would search your two routers' settings for an access point mode. Just don't get your hopes up because even though they may have the setting, it can sometimes be locked down to wiring the routers together. Many routers have this ability built in, and it would be safe to assume so. Good luck in your endeavors, and try to keep things as simple as possible!

Tl;dr
Try not to use them as routers, but instead as repeaters, or access points. By using them as routers, you make a divided network and disable access to your wireless printer in the den if you're in the basement, working on your NAS (you should get one if you don't already!)

A: Cable modems don't talk to each other, they only talk to (expensive) head-end equipment (CMTS). DOCSIS requires a hybrid coax/fiber infrastructure.
See this question, comments, and answer on Network Engineering.


text:
Q: Identity for sets Identity for a set X:
The set X has an identity under the operation  if there is
an element j in set X such that j * a =  a * j = a for all elements a in set X.
According to my college book the counting numbers don' t have an identity.
But for the operation * there is number 1 (= j ) such that a * 1 = 1 * a = a for all element a in set X.
Why do natural numbers have no identity?

A: The operation is crucial here. $(\mathbb{N},\cdot)$ does have an identity, namely $1$ as you observed. For $(\mathbb{N},+)$ the identity would be $0$ and so it depends on your definition of $\mathbb{N}$ whether you include $0$ or not. I assume that your book uses the definition $\mathbb{N} = \{1,2,3,\ldots\}$ and so no number $j \in \mathbb{N}$ satifies $j + a = a$ for all $a \in \mathbb{N}$.

A: In comments the OP clarifies the question:

"Which properties are true for the counting numbers, whole numbers,
integers, rational numbers, irrational numbers, and real numbers under
the operation of addition?" The properties are: closed, identity and
inverse.

The verbatim quote, "Which properties ... addition?", can be tracked (via Google) to a Schaum's Outline, College Algebra, which defines the counting numbers as the set $\{1,2,3,\ldots\}$ and the whole numbers as $\{0,1,2,3,\ldots\}$. The counting numbers thus, by definition, lack the additive identity $0$.


text:
Q: Initialization for logger is unsuccessful I am using the below mentioned log4j.properties file in tomcat 6.0.35
log4j.appender.request=org.apache.log4j.rolling.RollingFileAppender
log4j.appender.request.Append=true
log4j.fileName=logs/test
log4j.appender.request.File=${log4j.fileName}.log
log4j.appender.request.RollingPolicy=org.apache.log4j.rolling.FixedWindowRollingPolicy
log4j.appender.request.RollingPolicy.FileNamePattern=${log4j.fileName}.%i.log.zip
log4j.appender.request.RollingPolicy.MinIndex=1
log4j.appender.request.RollingPolicy.MaxIndex=10

log4j.appender.request.TriggeringPolicy=org.apache.log4j.rolling.SizeBasedTriggeringPolicy
log4j.appender.request.TriggeringPolicy.MaxFileSize=10485760

log4j.appender.request.layout=org.apache.log4j.PatternLayout
log4j.appender.request.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n

log4j.rootLogger=info, request

But I get the following messages returned
log4j:WARN Failed to set property [rollingPolicy] to value "org.apache.log4j.rolling.FixedWindowRollingPolicy".
log4j:WARN Failed to set property [triggeringPolicy] to value "org.apache.log4j.rolling.SizeBasedTriggeringPolicy".
log4j:WARN Please set a rolling policy for the RollingFileAppender named 'request'
log4j:WARN Failed to set property [rollingPolicy] to value "org.apache.log4j.rolling.FixedWindowRollingPolicy".
log4j:WARN Failed to set property [triggeringPolicy] to value "org.apache.log4j.rolling.SizeBasedTriggeringPolicy".
log4j:WARN Please set a rolling policy for the RollingFileAppender named 'request'
log4j:ERROR No output stream or file set for the appender named [request].

There is some problem with setting the properties in log4j configuration. Any help?
Thanks.

A: I ran into this today using apache-log4j-extras1.1.jar.  After a while of wrestling I found that my log4j.jar being version 1.2.14 was the problem.  I updated to 1.2.17 and it fixed my issue.  Make sure it sits before any other log4j in your tomcat (or in your app).


text:
Q: Fedora session / process startup issues I've installed fedora 16 with lxde(xfce) desktop. My problem is that when I login into the system, it gives me redundant app startup, for instance it launches Installation manager, also I've noticed quite a few httpd processes. Looks really strange to me. Any suggestions guys ?
[midnight@localhost ~]$ ps aux | grep httpd
root       985  0.0  0.3 437472  9964 ?        Ss   18:58   0:00 /usr/sbin/httpd -k start
apache     988  0.0  0.4 441816 12112 ?        S    18:58   0:00 /usr/sbin/httpd -k start
apache     989  0.0  0.2 437472  6112 ?        S    18:58   0:00 /usr/sbin/httpd -k start
apache     990  0.0  0.2 437472  5364 ?        S    18:58   0:00 /usr/sbin/httpd -k start
apache     991  0.0  0.2 437472  5364 ?        S    18:58   0:00 /usr/sbin/httpd -k start
apache     992  0.0  0.2 437472  5364 ?        S    18:58   0:00 /usr/sbin/httpd -k start
apache     993  0.0  0.2 437472  5364 ?        S    18:58   0:00 /usr/sbin/httpd -k start
apache     994  0.0  0.2 437472  5364 ?        S    18:58   0:00 /usr/sbin/httpd -k start
apache     995  0.0  0.2 437472  5364 ?        S    18:58   0:00 /usr/sbin/httpd -k start

A: I wasn't able to convince the xfce session manager to get out of my way, even by tinkering directly with config files. So I now run rm -r ~/.cache/sessions/x* before starting xfce. This effectively disables session management and leaves autostart working correctly. You can run this code by including these lines in ~/.xinitrc:
rm -r ~/.cache/sessions/x*
exec ck-launch-session startxfce4

or you can boot to runlevel 3 and execute:
rm -r ~/.cache/sessions/x*
startx

If you need to be able to select a different desktop manager at startup, there are probably a few more steps to work out.


text:
Q: Prove the sum of two natural numbers is again a natural number, using the Peano Axioms. I'm re-learning real analysis and decided to start from Tao's books (sorry Rudin) and Tao left a remark stating we can prove the sum of two natural numbers is again a natural number by the Peano Axioms; specifically we only need these components:
Axiom 2.1
$0$ is a natural number.
Axiom 2.2
If $n$ is a natural number, then $n++$ is also a natural number.
Definition 2.1.3.
We define $1$ to be the number $0++$, $\,2$ to be the number $(0++)++$, and so on.
Axiom 2.5 (Principle of mathematical induction)
Let $P(n)$ be any property pertaining to a natural number $n$. Suppose the $P(0)$ is true, and suppose that whenever $P(n)$ is true, $P(n++)$ is also true. Then $P(n)$ is true for every natural number n.
Definition 2.2.1 (Addition of natural numbers). Let $m$ be a natural number. To add zero to $m$ , we define $0+m:=m$. Now suppose inductively that we have defined how to add $n$ to $m$. Then we can add $n++$ to $m$ by defining $(n++)+m:=(n+m)++$.

Proof.
Let $n$ and $m$ be natural numbers.
This will be a proof by mathematical induction; we shall induct on the variable $n$, with the base case $n=0$. Since $m$ is a natural number by the hypothesis, our only cases are either $n =0$ and $m=0$ $or$ $n=0$ and $m\neq 0$. Suppose first that $n=0$ and $m=0$. Then $n+m = 0+0 = 0$. We know $0$ is a natural number by Axiom 2.1. Now suppose $n=0$ and $m \neq 0$. By Definition 2.2.1, the sum $n+m =0+m=m$. We know $m$ is a natural number by the hypothesis. Since we get natural numbers in both base cases, we have have proved the base case.
Now suppose we have shown inductively that the sum $n+m$ is a natural number. We need to show $(n++)+m$ is also a natural number.
By Definition 2.2.1, $(n++)+m = (n+m)++$, and since $n+m$ is a natural number by the inductive hypothesis, $(n+m)++ = (n++)+m$ is also a natural number by Axiom 2.2. Thus, $n+m$ must be a natural number by the principle of mathematical induction, closing the induction.

Proof complete, with the help of ultralegend5385 and Rob Arthan.

A: You have written a good proof, although as @RobArthan said in comments, you must highlight the parts of your induction, and also saying explicitly that you are using induction on $n$, which is unclear as of now. Some suggestions for lines:

 [We will use induction on $n$ to show this]

 [For the base case, when $n=0$,]

 [We assume, for the sake of induction that]

It is always better to define a statement $P(n)$ for induction proofs, but it is your choice after all.
Another important thing, your proof never showed that $0+0$ is a natural number. Think about that and edit it accordingly.
Hope this helps. Ask anything if not clear :)


text:
Q: Partial derivatives in thermodynamics: general mathematical procedure In the lecture notes (thermodynamics) the following mathematical identity is often used:
$$ \left(\frac{\partial A}{\partial X}\right)_Z = \left(\frac{\partial A}{\partial X}\right)_Y + \left(\frac{\partial A}{\partial Y}\right)_X\left(\frac{\partial Y}{\partial X}\right)_Z = \left(\frac{\partial A}{\partial X}\right)_Y - \left(\frac{\partial A}{\partial Z}\right)_X\left(\frac{\partial Z}{\partial X}\right)_Y $$
As I understand, this is a standard notation in thermodynamics, see e.g. this or this questions. However, I do not understand the mathematical meaning of the above identity. I am trying to figure out the procedure of how to obtain these derivatives but I am stuck. Could someone please clarify this?


text:
Q: LayoutTransition DISAPPEARING Animation not working for Cursor Adapter So, the title pretty much says it all. I have a listview which is populated with a custom cursor adapter which displays data from a database. I have an animation for adding items to the list which works fine but am having trouble getting the animation for deleting items from the list to work. I fear that the item is being deleted from the database and the list is being refreshed before the animation has a chance to execute. I appreciate any help with fixing this issue.
Animation code
    LayoutTransition transition = new LayoutTransition();
    Animator appearAnim = ObjectAnimator.ofFloat(null, "rotationX", 90f, 0f)
            .setDuration(android.R.integer.config_shortAnimTime);
    Animator disappearAnim = ObjectAnimator.ofFloat(null, "alpha", 1f, 0f)
            .setDuration(android.R.integer.config_longAnimTime);
    transition.setAnimator(LayoutTransition.APPEARING, appearAnim);
    transition.setAnimator(LayoutTransition.DISAPPEARING, disappearAnim);
    mNotesListView.setLayoutTransition(transition);

The delete note method
 @Override
    public void deleteNote(final String noteId) {
        new Thread() {
            @Override
            public void run() {
                super.run();
                mNotesTable.deleteNote(mDb, noteId);
                int notebookNumber = mNoteBookFragment.getNotebookNumber();
                final Cursor cursor = mNotesTable.notesQuery(mDb, notebookNumber);
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        mNoteBookFragment.refreshNoteList(cursor);
                        Toast.makeText(BlocNotes.this,
                                getString(R.string.delete_note_toast), Toast.LENGTH_LONG).show();
                    }
                });
            }
    }.start();
}

and refreshing the list
public void refreshNoteList(Cursor cursor) {
        mNoteAdapter.changeCursor(cursor);
        mNoteAdapter.notifyDataSetChanged();

        setNewNoteText(""); //clear the text

    }

Edited Refresh Method
 public void refreshNoteList(Cursor cursor) {
        mTransition.removeChild(mNoteAdapter.getParent(), mNoteAdapter.getView());
        mNoteAdapter.changeCursor(cursor);
        mNoteAdapter.notifyDataSetChanged();

        setNewNoteText(""); //clear the text

    }

A: I've run into the same problem. You should call removeChild(parentView, childView) on Transition before you refresh the ListView. This might not be the best way, but it works.
I'd use a Loader here by the way: http://developer.android.com/guide/components/loaders.html
UPD: You need to run the rest of your code after the animation is finished (otherwise it will be interrupted). Something like this:
public void refreshNoteList(Cursor cursor) {
    transition.removeChild(ListView mNotesListView, View mNotesListView.getChildAt(int position);
    new Handler().postDelayed(new Runnable(){
        public void run() {
            mNoteAdapter.changeCursor(cursor);
            mNoteAdapter.notifyDataSetChanged();

            setNewNoteText(""); //clear the text
        }
    }, disappearAnim.getDuration());
}


text:
Q: Use ratio test to test for convergence or divergence I have online hw and it tells me if my answer is correct or not. It said that my answer for this problem is incorrect:

Can someone tell me what I did wrong?
Also I might be asking alot of these questions later since I am new to this concept.

A: If $\lim_{n\to\infty}a_{n+1}/a_n<1$ the series converges,  if $\lim_{n\to\infty}a_{n+1}/a_n>1$ the series diverges.
The test gives no information if $\lim_{n\to\infty}a_{n+1}/a_n=1$.

A: There are many mistakes.

*

*The series in not equal to the limit in the first line.

*Limit of the ratio of  in the second line is probably from de l'Hospital's rule, but $n$ is discrete.

*If this limits is equal to 2, the series diverges (d'Alembert test).


text:
Q: DHCP: broadcast flag I'm looking at some DHCP packets through wireshark. I notice that in the bootp section, there is a broadcast flag.
However, the dest IP is 255.255.255.255. Isn't it enough to indicate that it's broadcasted? Why is the flag needed?
Thanks,
lang2

A: DHCP flag serves a completely different purpose. It is set by a client to indicate to a server how the reply should be sent to back to the client. DHCP client sends its request by broadcast, initially, since it doesn't know the server's IP address. However, since the server knows the client's IP (it just provided it with one), server can send the reply back by unicast even if the request was sent by broadcast. Per RFC2131:

A client that cannot receive unicast IP datagrams until its protocol
     software has been configured with an IP address SHOULD set the
     BROADCAST bit in the 'flags' field to 1 in any DHCPDISCOVER or
     DHCPREQUEST messages that client sends.  The BROADCAST bit will
     provide a hint to the DHCP server and BOOTP relay agent to broadcast
     any messages to the client on the client's subnet.  A client that can
     receive unicast IP datagrams before its protocol software has been
     configured SHOULD clear the BROADCAST bit to 0.

A: These are at different layers in the ISO stack.  A destination IP of 255.255.255.255 makes the packet a broadcast IP packet at the IP level.  Setting the broadcast flag inside the DHCP packet would not do this.
The flag itself can be considered information to the DHCP server - it is telling the server that it should reply by broadcast.  This is most often the case where the client does not yet have an IP address and so requires a broadcast reply as there no IP yet to unicast to.  The DHCP server shouldn't need to inspect the packet headers to figure out how to respond, it is up to the dhcp protocol to make this clear.
You could conceivably have a DHCP request sent as a unicast packet, sent directly to the DHCP server - but the broadcast flag could still be set inside the DHCP flags to let the dhcp server know that it needs to reply by broadcast no matter what the headers looked like.
In summary, the IP and UDP headers tell the IP and UDP layers of the stack know what is going on, whereas the DHCP content is application layer, and let the DHCP application know what is going on.


text:
Q: Google Earth Engine band did not match any bands error I am trying to composite S2 images by different technique but the composites for the 25 and 33 percentiles  (ee.Reducer.percentile([XX])) its giving an error :
p33: Layer error: Image.select: Pattern 'B2' did not match any bands.
p25: Layer error: Image.select: Pattern 'B2' did not match any bands.

This is the code I'm using:
//Se define la variable del CPC determinado y extent
var fires = table
//********************************************************************************************************//
//Extensión del raster en que se desea descargar los indices (metros a partir del CPC)
var extent_raster = 10000 ;
var b5km_fires = fires.geometry().buffer(extent_raster);
    b5km_fires = b5km_fires.bounds();

//1.- Indicar Zona UTM a la que corresponde el CPC
var Zona_utm = '13'; // ---> INDICAR ZONA UTM EN DOS DIGITOS (p.e. 11,12,13,14,15,16)
//2.- Fechas de inicio y término en AAAA-MM-DD (AAAA = 4 digitos año, MM = 2 para el mes y DD = 2 para el dia)
var FECHA_INICIO =  ee.Date(fires.aggregate_first('FECHA_INI'));// ---> INDICAR FECHA DE **INICIO** DEL INCENDIO
var FECHA_TERMINO = ee.Date(fires.aggregate_first('FECHA_TER')); // ---> INDICAR FECHA DE **TERMINO** DEL INCENDIO
//3.- Se define el periodo de análisis entre pre y post
var dw = 30; // ---> INDICAR NÚMERO DE DÍAS del COMPUESTO PRE Y POST (30,60,90)
//4.- Indicar el nombre de la carpeta donde se van a guardar los raster (se debe crear primero en su drive) (L204)
var carpeta = 'incendios';

  //Fecha del periodo PRE a partir del atributo "FECHA_INI" en el CPC
var prefire_end = ee.Date(FECHA_INICIO);
var prefire_start = prefire_end.advance(-dw,'day');
  //Fecha del periodo POST a partir del atributo "FECHA_TER" en el CPC
var postfire_start = ee.Date(FECHA_TERMINO);
var postfire_end =  postfire_start.advance(dw,'day');
  //Nombre del incendio
  print(ee.String('Incendio: ').cat(ee.String(fires.aggregate_first("ID_CPC"))));
  print(ee.String('Zona UTM seleccionada: ').cat(ee.String(Zona_utm)));
  //Fechas en que ocurrio el incendio y días de los periodos pre y post
  print(ee.String('Ocurrió entre: ').cat(prefire_end.format('YYYY-MM-dd', null)).cat(' y ').cat(postfire_start.format('YYYY-MM-dd', null)));
  print(ee.String('Ventana de días (pre y post): ').cat(ee.Number(dw)).cat(' días'));
  print(ee.String('Periodo pre: ').cat(prefire_start.format('YYYY-MM-dd', null)).cat(' a ').cat(prefire_end.format('YYYY-MM-dd', null)));
  print(ee.String('Periodo post: ').cat(postfire_start.format('YYYY-MM-dd', null)).cat(' a ').cat(postfire_end.format('YYYY-MM-dd', null)));
//========================================================================================================
//Function to mask clouds using the Sentinel-2 QA band
function maskS2clouds(image) {
  var qa = image.select('QA60');

  // Bits 10 and 11 are clouds and cirrus, respectively.
  var cloudBitMask = 1 << 10;
  var cirrusBitMask = 1 << 11;

  // Both flags should be set to zero, indicating clear conditions.
  var mask = qa.bitwiseAnd(cloudBitMask).eq(0)
      .and(qa.bitwiseAnd(cirrusBitMask).eq(0));

  return image.updateMask(mask).divide(10000)
  .copyProperties(image, ['system:time_start']);
}

var s2_clear_sky = function(image){
  // 1.Locate SCL product
  var B1Band = image.select('B1');
  var scl = image.select('SCL');
  // 2.Apply mask to the image
  // Select values:
  var wantedPixels = scl.eq(4)        //Vegetation
                 .or(scl.eq(5))       //Not vegetated
                 .or(scl.eq(7))       //Unclassified
                 .or(B1Band.lt(2000))
  ;
  return image.updateMask(wantedPixels)
   .copyProperties(image, ['system:time_start']);
};

// This is the Sentinel 2 collection (all the possible available Sentinel-2 imagery)
var S2SR = ee.ImageCollection('COPERNICUS/S2_SR_HARMONIZED')
            .filterBounds(b5km_fires)
            .filterDate(prefire_start, postfire_end)
            .map(maskS2clouds);

var S2_collection = S2SR.map(s2_clear_sky);

// Bands that we want to be displayed
var S2_bands = ['B2','B3','B4','B5','B6','B7','B8','B8A','B11','B12'];

// This turns the whole S2 collection into one image, finding the middle value for each pixel
var S2pr_min = S2_collection.filterDate(prefire_start, prefire_end).sort('GENERATION_TIME', false)
          .min().select(S2_bands).clip(b5km_fires);
var S2pr_ave = S2_collection.filterDate(prefire_start, prefire_end).sort('GENERATION_TIME', false)
          .mean().select(S2_bands).clip(b5km_fires);
var S2pr_p33 = S2_collection.filterDate(prefire_start, prefire_end).sort('GENERATION_TIME', false).reduce(ee.Reducer
          .percentile([33])).select(S2_bands).clip(b5km_fires);
var S2pr_p25 = S2_collection.filterDate(prefire_start, prefire_end).sort('GENERATION_TIME', false).reduce(ee.Reducer
          .percentile([25])).select(S2_bands).clip(b5km_fires);

// This controls how we want the S2 image to be displayed
var visualization = {
  min: 0.0,
  max: 0.3,
  bands: ['B8', 'B4', 'B3'],
};

Map.addLayer(S2pr_min, visualization,'min');
Map.addLayer(S2pr_ave, visualization,'ave', false);
Map.addLayer(S2pr_p33, visualization,'p33', false);
Map.addLayer(S2pr_p25, visualization,'p25', false);

//Establecer parametros de simbología para el CPC
var cpcVis = fires.style({
  color: '0000FF',
  width: 5,
  fillColor: '00000000',  // relleno transparente
  lineType: 'solid'
});

// This automatically pans the map to the middle of our area of interest
Map.centerObject(b5km_fires);
Map.addLayer(cpcVis, null, 'CPC'); //Agregar a "layers" en el visualizador el CPC (var "fires")

A: Please, include a link to your script in the code editor in future questions (using the Get Link button). Here, we're missing table, and that required some useless effort on my part to get this running.
The error message is pretty spot on - the problem is that you're selecting band names that doesn't exist. The percentile reducer appends _p33 and _p25 to your band names.
print(
  S2_collection
    .filterDate(prefire_start, prefire_end).sort('GENERATION_TIME', false)
    .reduce(ee.Reducer.percentile([33]))
    .bandNames()
)

Another improvement you could make is to combine the reducers and have the collection reduced in a single operation. Performance will be better. It could look something like this:
var reduced = S2_collection
  .filterDate(prefire_start, prefire_end)
  .select(S2_bands)
  .reduce(
    ee.Reducer.min()
      .combine(ee.Reducer.mean(), null, true)
      .combine(ee.Reducer.percentile([25, 33]), null, true)
  )

var S2pr_min = reduced.select('.*_min').rename(S2_bands)
var S2pr_ave = reduced.select('.*_mean').rename(S2_bands)
var S2pr_p33 = reduced.select('.*_p33').rename(S2_bands)
var S2pr_p25 = reduced.select('.*_p25').rename(S2_bands)

https://code.earthengine.google.com/7f4102a5d2ebeb1458a70fd73d8cb9b4

A: That is the error you get if select after a reducer.
After a reducer, the layers change the name. i.e. a mean reducer may turn B8 to B8_mean.
So select before the reducer, and you will be good!
For example, in your code:
var S2pr_min = S2_collection.filterDate(prefire_start, prefire_end).sort('GENERATION_TIME', false)
          .min().select(S2_bands).clip(b5km_fires);

After .min() the select(S2_bands) will give you an error. Maybe define a new S2_bands_min and it should have _min after all the elements in S2_bands.
I hope it helps!


text:
Q: Cambiar imagen de ImageView desde FIle chooser JAVAFX No consigo que se vea la imaen cargada en la ImageView.
@FXML
void cambiarImgPerfil(ActionEvent actionEvent) throwsjava.io.IOException{

    FileChooser chooser = new FileChooser();
    chooser.setTitle("Open File");
    chooser.setInitialDirectory(new File(System.getProperty("user.home")));
    chooser.getExtensionFilters().addAll(new FileChooser.ExtensionFilter("Image Files","*.bmp", "*.png", "*.jpg", "*.gif"));
    File file = chooser.showOpenDialog(new Stage());
    if(file != null) {
            //String imagepath = file.toURI().toURL().toString();

            Image image = new Image(file.toURI().toString());
            imgPerfil = new ImageView(image);

                                                                                System.out.println("height:"+image.getHeight()+"\nWidth:"+image.getWidth());
           imgPerfil.setImage(image);
           System.out.println(imgPerfil.isVisible());
    }
    else
    {
        Alert alert = new Alert(Alert.AlertType.INFORMATION);
        alert.setTitle("Information Dialog");
        alert.setHeaderText("Please Select a File");
    /*alert.setContentText("You didn't select a file!");*/
        alert.showAndWait();
    }

}

A: Intenta hacerlo de esta forma:
byte[] btImagen = Files.readAllBytes(file.toPath());
Image img = new Image(new ByteArrayInputStream(btImagen), 199, 199, false, false);
imgPerfil.setImage(img);


text:
Q: Rendering DataTable rows from json file I am trying to render DataTable-rows from a json file, placed on the same directory. But unfortunately, the DataTable-Body stays empty, and no error is displayed in the console.
Here is the (reduced) HTML-Code:

ID	ShortName	DisplayName	LogoUrl	Incent	JTS-URL

Here is the JavaScript I am using to load the data from the json file:

and here is a sample of my json file:
{
"partnerList": [
         {
            "shrname": "bchan",
            "Dplayname": "bchang-Shop",
            "pId": "id12345",
            "featured": "0",
            "lgo": "https://url.here.com/url",
            "inc": "1 to 1",
            "dets": {
                "tmage": "someUrl/here",
                "desp": "desciption",
                "jturl": "jtUrl/here",
                "jtbut": "Shop",
                "termy": [
                    {
                        "heady": "",
                        "body": ""
                    }
                ]
            }
        },
         {
            "shrname": "hereIsIt",
            "Dplayname": "HereIs-Shop",
            "pId": "id65432",
            "featured": "0",
            "lgo": "https://url.here.com/url",
            "inc": "2 to 1",
            "dets": {
                "tmage": "someUrl/here",
                "desp": "desciption",
                "jturl": "jtUrl/here",
                "jtbut": "Shop",
                "termy": [
                    {
                        "heady": "",
                        "body": ""
                    }
                ]
            }
        }
  ]
}

I am becomming this error now.. See the image below.

A: try this

var t = [{
  "shrname": "bchan",
  "Dplayname": "bchang-Shop",
  "pId": "id12345",
  "featured": "0",
  "lgo": "https://url.here.com/url",
  "inc": "1 to 1",
  "dets": {
    "tmage": "someUrl/here",
    "desp": "desciption",
    "jturl": "jtUrl/here",
    "jtbut": "Shop",
    "termy": [{
      "heady": "",
      "body": ""
    }]
  }
}, {
  "shrname": "hereIsIt",
  "Dplayname": "HereIs-Shop",
  "pId": "id65432",
  "featured": "0",
  "lgo": "https://url.here.com/url",
  "inc": "2 to 1",
  "dets": {
    "tmage": "someUrl/here",
    "desp": "desciption",
    "jturl": "jtUrl/here",
    "jtbut": "Shop",
    "termy": [{
      "heady": "",
      "body": ""
    }]
  }
}];
$(document).ready(function() {
  $('#opTable').DataTable({
    "aaData": t,
    "columns": [{
      "data": "pId"
    }, {
      "data": "shrname"
    }, {
      "data": "Dplayname"
    }, {
      "data": "lgo"
    }, {
      "data": "inc"
    }, {
      "data": "featured"
    }]
  });
});

<link href="https://cdn.datatables.net/1.10.11/css/jquery.dataTables.min.css" />

      ID
      ShortName
      DisplayName
      LogoUrl
      Incent
      JTS-URL

A: Based on one of the links Turnip provided in the comments, Datatables Ajax Data Source (objects), your data should look like this:
{
  "data": [
        {
            "shrname": "bchan",
            "Dplayname": "bchang-Shop",
            "pId": "id12345",
            "featured": "0",
            "lgo": "https://url.here.com/url",
            "inc": "1 to 1",
        },
         {
            "shrname": "hereIsIt",
            "Dplayname": "HereIs-Shop",
            "pId": "id65432",
            "featured": "0",
            "lgo": "https://url.here.com/url",
            "inc": "2 to 1",
        }
    ]
}

I'm not sure what you're trying to do with the "dets" part of your data though


text:
Q: Sql unequal data sets in a access-table I'm working since two weeks on a VBA-Application in Access 2016. For this I need to purge a Table on inconsistent data sets. To find out which Datasets are inconsistent, I need a SQL-query. So my Table looks like this:
ID        Description      User           Comment              Date

1         Example1         sht3454        This is a comment     10/17/2017
1         Example2         sht3454        This also             10/15/2017
2         Example3         hdjfur198      ;)                    10/11/2017

I have to find out which Datasets are inconsistent, in my Example the Datasets with the ID 1 because they have a different Description.
The Tablefield ID is in this example no primary key.
I thought about something like
SELECT Count(ID), Description From DB_Data  group by ID,Description having (count(ID) > 1)
but it is not the solution of my Problem.
Do someone of you have an idea for this?

A: If I understand correctly:
select dd.*
from db_data dd
where exists (select 1
              from db_data dd2
              where dd2.id = dd.id and dd2.description = dd.description and
                    dd2.user <> dd.user
             ) or
       exists (select 1
              from db_data dd2
              where dd2.description = dd.description and dd2.user <> dd.user and
                    dd2.id <> dd.id
             ) or
       exists (select 1
              from db_data dd2
              where dd2.user = dd.user and dd2.id = dd.id and
                    dd2.description <> dd.description
             ) ;

This assumes that if two of the columns -- id, description, user -- are the same, then the other should be the same as well.

A: Based on your question, the only inconsistency is that some records share their ID. You can those id-s with this query:
SELECT id FROM DB_Data GROUP BY id HAVING 1 < COUNT(id)

Moreover, you can select the related records if you use the previous query as a subquery:
SELECT DB_Data.*
FROM DB_Data
  INNER JOIN (SELECT id FROM DB_Data GROUP BY id HAVING 1 < COUNT(id)) inconsistent
    ON (example.id = inconsistent.id)

Are there any other rules for inconsistent records?


text:
Q: How to upgrade from 19.10 to 20.04? There are many similar questions: this one is about "why do the recommended answers not work in 2021" ?  Based on many similar questions I ran the following:
sudo apt-get update && sudo apt-get upgrade -y && sudo apt-get dist-upgrade && sudo do-release-upgrade

That downloaded a lot of packages- many of them for 18.04 for some reason. But then at end the result was:
...
Setting up libnvidia-ifr1-435:i386 (455.45.01-0ubuntu0.18.04.1) ...
Setting up libnvidia-gl-435:amd64 (455.45.01-0ubuntu0.18.04.1) ...
Setting up libnvidia-gl-435:i386 (455.45.01-0ubuntu0.18.04.1) ...
Setting up nvidia-dkms-435 (455.45.01-0ubuntu0.18.04.1) ...
.. Setting up nvidia-utils-435:amd64 (455.45.01-0ubuntu0.18.04.1) ...
Setting up nvidia-driver-435 (455.45.01-0ubuntu0.18.04.1) ...
Setting up nvidia-compute-utils-435:amd64 (455.45.01-0ubuntu0.18.04.1) ...
Processing triggers for mime-support (3.63ubuntu1) ...
Processing triggers for gnome-menus (3.32.0-1ubuntu1) ...
Processing triggers for libc-bin (2.30-0ubuntu2.2) ...
..Processing triggers for initramfs-tools (0.133ubuntu10) ...
update-initramfs: Generating /boot/initrd.img-5.3.0-64-generic
Checking for a new Ubuntu release
Your Ubuntu release is not supported anymore.
For upgrade information, please visit:
http://www.ubuntu.com/releaseendoflife

I then tried:  sudo do-release-upgrade
$ sudo do-release-upgrade
Checking for a new Ubuntu release
Your Ubuntu release is not supported anymore.
For upgrade information, please visit:
http://www.ubuntu.com/releaseendoflife

Please install all available updates for your release before upgrading.

Is there a procedure to upgrade from 19.10 to 20.04 that actually works?


text:
Q: "Git checkout branch1" suddenly merges changes from branch2 to branch1 instead of warning me to commit first Let's say I'm working on branch1 and create a branch2 from branch1.
Up until recently, when I did some changes to branch2 and didn't commit them without changing to branch1, the IntelliJ console warned me that I first need to commit my changes or I wouldn't be able to change.
But now, when using git checkout branch1 while I'm on branch2 without commiting my changes on branch2, for some reason all my changes get automatically commited AND transfered to branch1.
For example:
I'm on branch2 and modify some files. I forget to commit the changes and try to switch to branch1. This is what happens...
git checkout branch1
Switched to branch 'branch1'
M       src/main/java/Test.java
Your branch is up to date with 'origin/branch1'.

...and all the changes I made in branch2 are transfered to branch1!
I don't want this behaviour. I don't want to transfer all the changes I made in branch2 to branch1 when I'm using git checkout. It should warn me that I forgot to commit instead of adopting the changes.
EDIT:
Previously, I'd get an error message like the following one:
git checkout branch1
error: Your local changes to the following files would be overwritten by checkout:
    Test.java
Please, commit your changes or stash them before you can switch branches.
Aborting

And now the message is ignored and the changes are just automatically merged/transfered from branch2 to branch1 like in the example above, without showing me an error.

A: The changes you describe as "on branch2" are not actually on branch2. They are changes to your working set and have not been staged nor committed to any branch.
If your working set has changes, and you check out a branch, those changes remain in the working set if they do not conflict with the other branch.
To avoid this problem you can check for uncommitted changes before checking out a branch (I do git status -sb before any checkout).  And even if you forgot to do this, you can always just return to branch2 with git checkout branch2 and then commit the changes.

A: That's default git behavior. When there are conflicts between uncommitted changes and the branch been checked out, git refuses to say you should commit changes first.
When there are no conflicts, uncommitted changes are left intact in the working tree. There is no way of changing this. You could read about it in details e.g. here
IntelliJ just handles the case offering you Smart checkout (Stash changes - Checkout - Unstash) when possible.


text:
Q: Imageview attributes lost after setting animation I am trying to set frame animation to Imageview.
imageAnim =  (ImageView) rootView.findViewById(R.id.orderCards);
imageAnim.setBackgroundResource(R.drawable.image_switcher_anim);
imageAnim.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.MATCH_PARENT));
anim = (AnimationDrawable) imageAnim.getBackground();
anim.start();

All the Image view attributes like height width, scale type are lost.
I understood this happens because of setting animation as background resource and images will be displayed without scaletype.
I see two possibilities
Is there a way to set animation without setting it as background to avoid this problem ?
OR
Can the attributes like height width etc be set for image background.

A: Try this:
imageAnim.invalidateDrawable(anim);

this will redraw the image view.

A: I found answer on another link
Android animation with multiple jpeg files?
We need to set the animation file in anim folder, set it as source to the imageview, getdrawable instead of getResourceBackground and assign it to animationDrawable and start animation. With this all the layout attributes of the imageview will be maintained.
xml code
<ImageView android:id="@+id/orderCards
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:scaleType="fitCenter"
            android:adjustViewBounds="true"
            android:src="@anim/image_switcher_anim"/>

Java Code
imageAnim = (ImageView) rootView.findViewById(R.id.orderCards);
                anim = (AnimationDrawable) imageAnim.getDrawable();
                imageAnim.post(run);

Runnable run = new Runnable() {
        @Override
        public void run() {
            anim.start();
        }
    };


text:
Q: jQuery Clone Issues Can someone check this out and tell me what's wrong...I just don't see it:
function getStates(){
var stateData;

$.getJSON("getStateData.php", function(data) {
    stateData = data;
    var theLastGroup = "";

    $("#groupList").empty();
    $("#stateList").empty();

    $.each(stateData, function(i,jsonData) {
        if( theLastGroup != jsonData.groupName )
        {
            $("#listModel").clone(true).removeAttr("id").attr("id", "Group_" + i).removeClass("hidden").appendTo($("#groupList"))
                .find(".url").attr("href", "#"+jsonData.groupName).end()
                .find(".groupName").html(jsonData.groupID);

            $("#groupModel").clone(true).removeAttr("id").removeClass("hidden").attr("id", jsonData.groupName).appendTo($("#stateList"));
        }

        $("#stateModel").clone(true).removeAttr("id").attr("id", jsonData.stateName).removeClass("hidden").appendTo($("#"+jsonData.groupName))
            .attr("sname", jsonData.stateName).attr("lat", jsonData.centerLat).attr("lon", jsonData.centerLon)
            .attr("zom", jsonData.zoom).html(jsonData.stateName);

        if( theLastGroup != jsonData.groupName )
        {
            theLastGroup = jsonData.groupName;
        }
    });
    $("#tabs").tabs();
});

}

...and the HTML that ends up calling the getStates() above:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />

<title>My Page</title>

<link href="js_src/css/cupertino/jquery-ui-1.8.11.custom.css" rel="stylesheet" type="text/css"/>

MyPage

select a state...

The getStates() function is called from the mapNull.js script when the page loads...
Any ideas?

A: This part of your  code is between  and .... that is, OUTSIDE the  tag:

Placing it inside  would be a good first step toward making this work :)


text:
Q: Azure functions V2 startup method not firing I'm trying to setup dependency injection with Azure functions but for whatever reason I can't get the web jobs start up method to fire.
[assembly: WebJobsStartup(typeof(PersonalBlog.Functions.Content.RefreshContentStartup))]
namespace PersonalBlog.Functions.Content {
    public class RefreshContentStartup : IWebJobsStartup {
        public void Configure(IWebJobsBuilder builder) { }
    }
}

The project is .net Framework 4.7.1 due to the fact that it has a dependency on a few libraries that haven't been converted to dot net core yet...
Is there something I'm missing here? Do I have to add a setting for it to pick up on my startup file?

A: As @Kirklarkin and @silent mentionned, Azure Functions v2 supports .NET Core whereas Azure Functions v1 supports .NET Framework. You can't run Azure Functions on any languages/runtime, there is a list of supported  languages with the associated runtimes. The point of using Azure Functions is mostly to do serverless which means autoscaling, no infrastructure to manage, and paying resources per use.
Concerning dependency injection, it is not supported out-of-the box in Azure Functions at the time of writing but the team is currently implementing it and it's one of their top priorities so we should have it soon.


text:
Q: Does wrapping a node.js sync function make it perform the same as its async equivalent? Simple example without error handling:
var fs = require('fs');

function read(filename, cb) {
  return cb(fs.readFileSync(filename));
}

Would this be the same, performance-wise with regards to the event loop, as:
fs.readFile(filename, cb);

The reason I ask is that some of the async functions in the crypto library still throw errors instead of passing them to the callback. I would like to just make a custom async function that does error handling the way I want it, but am worried about using the Sync versions of the native methods due to the bad reputation they have in the node community for bad performance. So, is it safe to go about this the way I proposed by just making a wrapper function?

A: No.
The whole point of async is that the actual work, which is done by readFileSync(), happens off the event loop.
It is completely impossible to call a synchronous function and make it async.

A: You cannot in any way make an asynchronous function suddenly behave synchronously in native node.js (e.g. without creating another process or using third party libraries that do some threading).  It just cannot be done.
This does not help you at all:
function read(filename, cb) {
  return cb(fs.readFileSync(filename));
}

It just implements a synchronous callback which doesn't really solve any problem.  The code is still all synchronous so you get none of the benefits of async I/O.  The important async I/O benefit you're after here is that you want the main JS event loop to not wait for the file I/O to happen.  You want the node.js event loop to be able to do other things while the file I/O is happening in native code.  As long as you use fs.readyFileSync(), this will never be the case, no matter what you put around it.

If you have some async crypto methods that are throwing exceptions synchronously rather than passing the error through to their callback, that is poorly designed code and I'd think twice about even using that code.
But, you can work around it by wrapping the crypto functions in your own try catch handlers that will call the callback if an error is thrown.
Let's suppose you have a crypto function like this:
function badCryptoFunc(arg1, arg2, callback)

You can wrap is like this:
function myCryptoFunc(arg1, arg2, callback) {
    try {
        badCryptoFunc(arg1, arg2, callback);
    } catch(e) {
        callback(e);
    }
}

If the functions throws asynchronously, then even this won't catch the exception and the code is just bad and can't be safely used as there is no way to catch an async exception in most circumstances before it's called by the system, not by your code.


text:
Q: Android Retrofit AES encrypt/decrypt POST and Response I am using Retrofit 2.0
I want to encrypt my @body example the User Object
@POST("users/new")
Call<User> createUser(@Body User newUser);

and then decrypt the response .
what is the best way to do it ?

A: Use Interceptors to encrypt the body.
public class EncryptionInterceptor implements Interceptor {

    private static final String TAG = EncryptionInterceptor.class.getSimpleName();
    private static final boolean DEBUG = true;

    @Override
    public Response intercept(Chain chain) throws IOException {
        Request request = chain.request();
        RequestBody oldBody = request.body();
        Buffer buffer = new Buffer();
        oldBody.writeTo(buffer);
        String strOldBody = buffer.readUtf8();

        MediaType mediaType = MediaType.parse("text/plain; charset=utf-8");
        String strNewBody = encrypt(strOldBody);
        RequestBody body = RequestBody.create(mediaType, strNewBody);
        request = request.newBuilder().header("Content-Type", body.contentType().toString()).header("Content-Length", String.valueOf(body.contentLength())).method(request.method(), body).build();

        return chain.proceed(request);
    }

    private static String encrypt(String text) {
        //your code
    }
}

Then add the Interceptor to the Retrofit:
client = new OkHttpClient.Builder().addNetworkInterceptor(new EncryptionInterceptor()).build();
retrofit = new Retrofit.Builder().client(client).build();

More about Interceptors: https://github.com/square/okhttp/wiki/Interceptors


text:
Q: SSRS report from cube parameter: text input field instead of drop-down menu Good afternoon,
I'm very new to MDX. Using Report Builder I created SSRS report based on cube data. All looks good and I'm able to add a parameter for this report too, but the problem is that I only managed to get it working as a drop-down menu. What I really need is it to work in a typical SSRS way - text input field.
So searching for an information I got an impression that the only way to achieve this is to amend dataset's MDX query and set the desired field as StrToMember. The most relevant example that I found was this one. Other examples on the internet weren't too helpful to me with the knowledge I have.
My question is: having this query, where/how should I use StrToMember to be able to use the field [Inventory information].[Parent Item].[Parent Item] as a free text parameter?
SELECT { } ON COLUMNS, {
    ([Inventory information].[BOM].[BOM].ALLMEMBERS *
    [Inventory information].[Item number].[Item number].ALLMEMBERS *
    [Inventory information].[Line number].[Line number].ALLMEMBERS *
    [Inventory information].[Parent Item].[Parent Item].ALLMEMBERS *
    [Inventory information].[Product name].[Product name].ALLMEMBERS *
    [Inventory information].[Quantity].[Quantity].ALLMEMBERS *
    [Inventory information].[Sequence].[Sequence].ALLMEMBERS )}
        DIMENSION PROPERTIES MEMBER_CAPTION, MEMBER_UNIQUE_NAME ON ROWS
        FROM [Inventory analysis] CELL PROPERTIES VALUE

This query doesn't return any errors, but at the same time it removes all fields from a dataset.
SELECT { } ON COLUMNS, {
    ([Inventory information].[BOM].[BOM].ALLMEMBERS *
    [Inventory information].[Item number].[Item number].ALLMEMBERS *
    [Inventory information].[Line number].[Line number].ALLMEMBERS *
    StrToMember ('[Inventory information].[Parent Item].[Parent Item].&[' + @InventoryinformationParentItem + ']') *
    [Inventory information].[Product name].[Product name].ALLMEMBERS *
    [Inventory information].[Quantity].[Quantity].ALLMEMBERS *
    [Inventory information].[Sequence].[Sequence].ALLMEMBERS )}
        DIMENSION PROPERTIES MEMBER_CAPTION, MEMBER_UNIQUE_NAME ON ROWS
        FROM [Inventory analysis] CELL PROPERTIES VALUE

A: Your dataset is not identifying fields returned by your MDX script. I think you did not define the parameter in the designer. Add the parameter from the designer.

Try your query without an associated parameter.
SELECT { } ON COLUMNS, {
    ([Inventory information].[BOM].[BOM].ALLMEMBERS *
    [Inventory information].[Item number].[Item number].ALLMEMBERS *
    [Inventory information].[Line number].[Line number].ALLMEMBERS *
    StrToMember ("[Inventory information].[Parent Item].[Parent Item].&[" + "SomeString" + "]") *
    [Inventory information].[Product name].[Product name].ALLMEMBERS *
    [Inventory information].[Quantity].[Quantity].ALLMEMBERS *
    [Inventory information].[Sequence].[Sequence].ALLMEMBERS )}
        DIMENSION PROPERTIES MEMBER_CAPTION, MEMBER_UNIQUE_NAME ON ROWS
        FROM [Inventory analysis] CELL PROPERTIES VALUE

Also I am unsure about your syntax in the Parent Item attribute you posted.
Try this:
StrToMember ("[Inventory information].[Parent Item].&[" + "SomeString" + "]")

Let me know if this can help you.


text:
Q: Can I preview skins in-game (weapons, abilities) before purchasing them? Is there a way to perhaps try out any skin in the game without paying for them? Essentially, what I'm looking for is a way to preview a skin without purchasing them, as coins are hard to come by and I'd like to be content with a skin before buying it.
I don't want to look at just the visuals. The Torbjorn skins don't show what his Turret will look like, only his Rivet Gun, and I can't find a way so far to preview them.
Is there a way to preview the in-game skins, such as weapon models and ability looks?

A: You can see all the skins by clicking on "Hero Gallery" in the menu, then click on the hero you want, then "Skins" and see a preview of all their skins by clicking on it. Furthermore, you can rotate them by holding left mouse button and moving your mouse.


text:
Q: Anonymous function references in Javascript I'm currently in the process of building out a VERY simple Observer class for a project I'm working on. I have successfully implemented the subscribe, unsubscribe, and notify methods. Everything works exactly as expected when using "regular" functions (i.e: var f = function()).
However, when I pass an anonymous function to the subscribe method and then try to unsubscribe passing the "same" anonymous function it (as expected) doesn't remove the function from my array (they are different, after all).
Here's my subscribe and unsubscribe methods:
this._subscribers = {};
subscribe: function(type, callback) {
    if ( isUndefined(this._subscribers[type]) ) {
        this._subscribers[type] = [];
    }
    this._subscribers[type].push(callback);
},
unsubscribe: function(type, callback) {
    if ( this._subscribers[type] instanceof Array ) {
        var index = this._subscribers[type].indexOf(callback);
        if ( index >= 0 ) {
            this._subscribers[type].splice(index, 1);
        }
    }
},

And here's the code I'm testing with:
var o = new gaf.events.Observable();
o.subscribe('testEvent', function(event) { alert('Got It!'); });
o.notify('testEvent');
// Correct alerts 'Got It!'
o.unsubscribe('testEvent', function(event) { alert('Got It!'); });
o.notify('testEvent')
// Incorrectly alerts 'Got It!'

I know I could using an object (i.e.: _subscribers[event] = {}) and then when something subscribes I could add a new property equal to the callback and the value equal to the callback. This will cause Javascript to convert the callback to the string. I could then look it up (provided the methods passed in sub/unsub are exactly the same) using that string.
However, this is a mobile project and I'm very leery about storing strings that could be hundreds of characters long as properties as we could end up with a lot of subscribers.
Are there any other ways of doing this? Are there any SMALL (tiny, even) hashing libraries I can use to maybe hash the string value of the function and use that as the property? Would it be better to store the string value of the callback (so I can compare against it) in the array (rather then the actual callback) and use eval() on it?
EDIT
First, thanks all for the replies!
Per all the questions about "Why even pass anonymous" functions -
There really is no reason one COULDN'T use named functions. In fact, I agree with everyone that named functions are going to be the better solution. I'm simply gathering information and looking for a solution so that I can build out an implementation that handles the most scenarios as best as possible.
The other reason for this is what happens if a user (co-worker) of this Observable class passes it an anonymous function and then unsubscribes. That function won't actually be unsubscribed and therefore won't be cleaned up. I have a thing against orphaned data :)
Maybe another question I should as is, is it possible to test if the callback is anonymous or not? I'm going to assume no but doesn't hurt to ask.

A: There is nothing wrong with storing the entire string; premature optimization is evil.
However, this sounds like an incredibly bad idea.
If someone changes the function, but forgets to change the unsubscribed copy, the code will be subtly broken with no warning whatsoever.
Instead, you can require the user to store the anonymous function in a variable if they want to unsubscribe from it.
Alternatively, you can pass an optional name with each subscriber, then unsubscribe by that name.

A: the clients that use the Observer should store the reference to the function.
   var obsCallback = function() {

   }
   o.subscribe('test', obsCallback);
   ....
   o.unsubscribe('test', obsCallback);

in other words, keep a reference to the function around...

A: What is the reason for passing in anonymous functions rather than named ones, or keeping references that you can use for unsubscribing later?
Alternatively you could allow for an optional 'id' argument but this would require unnecessarily complex bookkeeping to avoid duplicates.

A: Perhaps a better solution is to modify the code using your library
var f = function() { alert('Got It!'); };
o.subscribe('testEvent', f);
o.notify('testEvent');
o.unsubscribe('testEvent', f);
o.notify('testEvent');

You could even return the function from the subscribe method
var f = o.subscribe('testEvent', function() { alert('Got It!'); });
// ...

then if you want to store a hash or some other identifier for subscribed functions, it is opaque to the calling code meaning that you just use the returned value to unsubscribe and the library hides the implementation detail.


text:
Q: Issue with Group By in LinQ Query I want to make a LinQ query against an array with and return multiple columns. I can't seem to get it working correctly, and I've tried various things.
First off, the array contains a type and a version from a table such as:
TypeID-------VersionID-------Text
1            1               "Version 1.1"
2            1               "Version 2.1"
3            1               "Version 3.1"
3            2               "Version 3.2"

This is a SQL table, and I could easily get the latest version with this query:
SELECT
        V.*
FROM Table V
WHERE V.VersionID IN (SELECT MAX(VersionID) GROUP BY TypeID)

However, I want to do this in LinQ and it's killing me. I can't figure it out. I want all the values. Therefore:
public MyStruct
{
   public int TypeID,
   public int VersionID,
   public string Text
}

MyStruct[] array = new MyStruct[4];
array[0].TypeID = 1;
array[0].VersionID = 1;
array[0].Text = "Version 1.1";
array[1].TypeID = 2;
array[1].VersionID = 1;
array[1].Text = "Version 2.1";
array[2].TypeID = 3;
array[2].VersionID = 1;
array[2].Text = "Version 3.1";
array[3].TypeID = 3;
array[3].VersionID = 2;
array[3].Text = "Version 3.2";

Now, I want a resultant array that only has three elements containing Version 1.1, Version 2.1, and Version 3.2. Since Version 3.1 is an "older version", I want to ignore it.
My LinQ is like this:
var myArrayQuery = from arr in array
group arr by arr.TypeID into arrGroup
select new
{
   TypeID = arrGroup.Key,
   VersionID = (int)arrGroup.Max(mx=>mx.VersionID)
   // -- GET THE TEXT HERE ---
};

I can't figure out how to get the text!
I have tried:
var myArrayQuery = from arr in array
group arr by new{ arr.TypeID, arr.VersionID, arr.Text} into arrGroup
select new
{
   TypeID = arrGroup.TypeID,
   VersionID = (int)arrGroup.Max(mx=>mx.VersionID),
   Text = arrGroup.Text
};

But then, it returns all four of my array elements. Therefore, no good. I don't get the MAX like I want.
Please help!
Thanks.

A: Use
Text = arrGroup.OrderByDescending(mx=>mx.VersionID).First().Text

full query:
var myArrayQuery = from arr in array
group arr by arr.TypeID into arrGroup
select new
{
   TypeID = arrGroup.Key,
   VersionID = (int)arrGroup.Max(mx=>mx.VersionID),
   Text = arrGroup.OrderByDescending(mx=>mx.VersionID).First().Text
};


text:
Q: can't make a trigger update only the relevant rows I'm working on a school project and my trigger gives me a hard time.
Its' purpose is to update the Rating field of an updated Product, but it updates all rows in Products instead.
CREATE TRIGGER Update_Rating
ON  dbo.Reviews
FOR Insert
as
Update dbo.Products
set Rating=(Select [avarage_rating]=avg(r.Rating)
            From dbo.Reviews as r join inserted  on r.ItemNumber = inserted.ItemNumber
            where r.ItemNumber = Inserted.ItemNumber)

Your help is much appreciated

A: What you are trying to do is calculate the average of a column, which is a number. There will not be a unique average per row. Hence the Rating column in your desired table gets updated with this value. Try changing your update condition and it should work.


text:
Q: Can you talk to people while you're spectating in Hardcore Team Deathmatch? In Hardcore Team Deathmatch, when you die, you have to wait some time before re-spawing. While waiting, you are spectating another player on your team.
Can they hear you? Is it useless to try to warn them about danger?

A: I'm not 100% sure about the in-game chat, because I infrequently use it.  However, I'm sure that you can use secondary chat channels (ie, Xbox Live Party Chat) while you are playing Hardcore Team Deathmatch, and that you can talk on them even while you are waiting to respawn.
This is different from Modern Warfare 2, where your chat options were limited.  A spokesperson for Infinity Ward said:

"The only place where Party Chat should be blocked is Search & Destroy, and won't be blocked for modes like Dom[ination]."

I would test the in-game chat channel, but I'm going to go ahead and say that it's highly likely that it works regardless of your current state.
If you're playing on PC, and you want to communicate always, you might look into Ventrilo or TeamSpeak, both are options that the game itself has little control over and the both integrate well with FPS games.


text:
Q: Click action Button HTML generated by a servlet I have a single servlet java file.
this is my code:
            out.append("
");
            out.append("<input type=\"text\" name=\"fname\">	");
            out.append("<input type=\"text\" name=\"lname\">	");
            out.append("<input type=\"text\" name=\"date\">	");

            out.append("<input type=\"submit\" value=\"Submit\">	");
            out.append("
");

3 text input and a button.
the java servlet creates that HTML, i need to read the content of the 3 inputs, and when the button is pressed i need to call a function with the 3 inputs as parameters.
Thanks for help.
EDIT: code test:
    out.append("<form>");
    out.append("
");
    out.append("<input type=\"text\" id=\"fname\" name=\"fname\">	");
    out.append("<input type=\"text\" name=\"lname\">	");
    out.append("<input type=\"text\" name=\"date\">	");

    out.append("<button type=\"submit\"  value=\"Submit\">Submit</button>	");

    out.append("
");
    out.append("</form>");

    String fname = null;

    if(request.getParameter("fname")!=null){
    fname=request.getParameter("fname");
    //FUNCTION
    }

A: You need to write a form tag and on click of the submit button , submit the html form.


text:
Q: dcc.store for live-dating data table DASH I implemented a live-update feature to the add column function based on the documentation on editable DataTable https://dash.plotly.com/datatable/editable such that a new column is added to the datatable when the CSV file is updated. I've got the callback working and I need to save the state of the datatable in a dcc.store, which was kindly recommended to me, so that I store the current number of columns, and add only the newly updated columns based on the new CSV data. I need to do this because users input data the table, and if I live update the whole table the data is lost. I do not know if I can access the user input data in dcc.store, so instead I only wish to add on new columns to the datatable thereby preserving using input.
My question: is there a way I can assess the current number of columns in an existing data
table?
app.layout = html.Div([
            dcc.Store(id='mystore'),
            html.Div([dash_table.DataTable(
                id='editing-columns',
                columns=[{
                    'name': 'Parameter',
                    'id': 'column1',
                    'deletable': True,
                    'renamable': True
        }],

    },
                data=[
                    {'column1': j}
                    for j in table_contents
        ],

    ]),
])

@app.callback(Output('mystore', 'data'),
              Input('graph-update', 'n_intervals'),
              State('editing-columns', 'data'))
def serve_layout(n,data):
   print(data)
   data2 = json.dumps(data)

    return data2

Output

A:
is there a way I can assess the current number of columns in an existing data table?

Yes, you can read in the table's data prop as State. That will give you everything in the table, and you can easily pull the column count from there.


text:
Q: Не подается питание на кулер Разобрал ноут (sony pcg-6h4l) из-за того, что перегревался, потом понял что кулер вообще не работает. Заменил мультиметром питание на выходе для него, было 0.9v чего явно маловато, потом питание и вовсе пропалоНа этом мои знания заканчиваются. Думаю, полетел какой-нибудь регулирующий транзистор, как его найти я без понятия, кто может подсказать?
A: найти схему, и тогда уже по ней...без этого - сложно будет


text:
Q: Problema con switch en JS una consulta he estado teniendo problemas con un segmento de código, cada vez que lo intento con un método diferente obtengo un resultado diferente, y usando switch es donde mas cerca estoy de conseguirlo.
tengo un pagina con varios formulario, dos de ellos se envían en todos los casos y un tercero de acuerdo a una selección en uno de los campos, los datos de cada formulario se almacenan en tablas diferentes.
se debe ejecutar el submit en un orden especifico, la idea inicial era esta:
$(document).on('click','#grabarSalir', function(){
var cat = document.getElementById("selectCat").value;
document.getElementById('fechaalta').value = document.getElementById('date').value;
datosFacAf.submit();
datosActivoGral.submit();

  if(cat == 'AUDVI' || cat == 'COM' || cat == 'HARD' || cat == 'CIEN'){
     tipoElectronico.submit();
  } else if (cat == 'CAMP' || cat == 'MUEB' || cat == 'LAB') {
     tipoDescripcion.submit();
  } else if (cat == 'VEH') {
     tipoVehiculo.submit();
  }
});

pero por alguna razón que no he podido identificar no guarda los datos enviados en el segundo submit, pero si guarda los del primero y el tercero, como he notado que ejecutando los dos primeros no hay inconveniente e optado por enviar los datos del tercer submit por AJAX, y funciona pero solo para el primer grupo de case, para el segundo y el tercero falla
   switch (cat) {
     case "AUDVI": case "COM": case "HARD": case "CIEN":

     var marca = document.getElementById('inputMarcaE').value
     var modelo = document.getElementById('inputModeloE').value
     var serie = document.getElementById('inputSerieE').value
     var espec = document.getElementById('inputEspecificacionesE').value

     $.ajax({
        url: "activos_electronicoguardar.php",
        method: "POST",
        data:{marca:marca, modelo:modelo, serie:serie, espec:espec},
     });
     break;

     case "CAMP": case "MUEB": case "LAB":

     var marcad = document.getElementById('inputMarcaD').value
     var modelod = document.getElementById('inputModeloD').value
     var descd = document.getElementById('inputDescripcionD').value
     var detalled = document.getElementById('inputDetalleD').value

     $.ajax({
        url: "activos_descripcionguardar.php",
        method: "POST",
        data:{marcad:marcad, modelod:modelod, descd:descd, detalled:detalled},
     });
     break;

     case "VEH":

     var nombrev = document.getElementById('inputNombreV').value
     var motor = document.getElementById('inputMotor').value
     var chasis = document.getElementById('inputChasis').value
     var placa = document.getElementById('inputPlaca').value
     var yearv = document.getElementById('inputYear').value
     var marcav = document.getElementById('inputMarcaV').value
     var modelov = document.getElementById('inputModeloV').value
     var cilindrada = document.getElementById('inputCilindrada').value
     var cappeso = document.getElementById('inputCapPeso').value
     var cappas = document.getElementById('inputCapPa').value

     $.ajax({
        url: "activos_vehiculosguardar.php",
        method: "POST",
        data:{nombrev:nombrev, motor:motor, chasis:chasis, placa:placa, yearv:yearv, marcav:marcav, modelov:modelov, cilindrada:cilindrada, cappeso:cappeso, cappas:cappas},
     });
     break;
  }
});

Sugerencias?


text:
Q: DispatcherTimer and real time WP7 I am creating a slot game. When I get the win I want to make it show in my TextBlock from 0 to win count. To create that I am using DispatcherTimer.
The problem is when e.g my integer win = 50 and after I use DispatcherTimer in my TextBlock i see over 50, like 54, 56.
DispatcherTimer timer = new DispatcherTimer();

 timer.Interval = new TimeSpan(0, 0, 0, 0, 200);
            timer.Tick += new EventHandler(Timer_Tick);
            if (win != 0)
            {
                timer.Start();
            }

 private void Timer_Tick(object sender, EventArgs e)
        {
           if (timerCount == win)
           {
            timer.Stop();
           }

        WinTextBlock.Text = timerCount.ToString();
        timerCount++;

        }

A: Make sure that timerCount is assigned to 0 at the beginning


text:
Q: Performance issue with UIGraphics ImageContext I have written a simple 2D animation application on the iPad using Sprite Kit.  The only difficult part of this application is to clip an image (.png) with a calculated polygon (a shadow).  Upon investigation, it appeared to me that the only way to accomplish this was to use UIImage and a UIBezier path (Note: my path does not require the full capabilities of a Bezier path, a simple CGPath will work in my case.).  I wrote the following method to accomplish this clipping:
- (UIImage *) maskImage: (UIImage *)originalImage toPath: (UIBezierPath *)path
{
    UIGraphicsBeginImageContextWithOptions (originalImage.size, NO, 0.0f);
    [path addClip];
    [originalImage drawAtPoint: CGPointZero];
    UIImage *maskedImage = UIGraphicsGetImageFromCurrentImageContext ();
    UIGraphicsEndImageContext ();
    return maskedImage;
}

The results of this operation are eventually passed to:
SKSpriteNode *node = [SKSpriteNode spriteNodeWithTexture: [SKTexture textureWithImage: [self buildShadowMask]]];

When this code is executed using the iOS simulator, it runs extremely quickly, in fact, in real time.  However, when I run this on an actual iPad (iPad Air or iPad 4G), it runs extremely slowly.  So, my questions are: Why is this method of clipping an image so slow on the actual iPad device?  Is there anyway to clip an image (with a simple path) that would be faster?  Is this an issue with UIGraphicsContext or Sprite or both?  I would greatly appreciate any advice or guidance that anyone can give me.  Thanks very much!


text:
Q: Trying to get download link via Selenium Trying to get the download link from this website to download the CSV file straight to a pandas dataframe with read_csv, however, having trouble scraping the link (from the href code).
To get to the csv download button, an initial click on the "Download Data" button is needed to open up another window.
The python code I have put together so far is:
driver = webdriver.Chrome(executable_path=r'/usr/local/bin/chromedriver')
URL = 'https://statisticsnz.shinyapps.io/covid_19_dashboard/'
driver.get(URL)

try:
    element = WebDriverWait(driver, 15).until(
        EC.presence_of_element_located((By.XPATH, '//*[@id="download_data-show"]'))
        )
    element.click()

    element = WebDriverWait(driver, 15).until(
        EC.presence_of_element_located((By.XPATH, '//*[@id="download_data-downloadData"]'))
        )

    outer = element.get_attribute('outerHTML')

finally:
    driver.quit()

link = outer.find('a',href=re.compile('download_data-downloadData')).get('href') #I don't think this code line will work, but essentially trying to find the link to download with

df = pd.read_csv(URL + link)

The outer object returns the following html code and is missing the link that I need (href field is empty) to use directly in the read_csv file:
In[]: print(outer)
Out[]:

          Download

When I inspect the 'Download' button from chrome, it gives me the following html code with the link in the href field:

          Download

Any ideas why the link isn't showing when I scrape through Selenium, or maybe there is a better way of doing this?

A: Try to get the link directly of your download element like this:
try:
    element = WebDriverWait(driver, 15).until(
        EC.presence_of_element_located((By.XPATH, '//*[@id="download_data-show"]'))
        )
    element.click()

    element = WebDriverWait(driver, 15).until(
        EC.presence_of_element_located((By.XPATH, '//*[@id="download_data-downloadData"]'))
        )

    link = element.get_attribute('href')

finally:
    driver.quit()

df = pd.read_csv(link)


text:
Q: How to merge multiple audio files at specific time to a video file in android? What I want to do is merging multiple audio files to video file at specific time in my android project.
For example, having two audio files: a1 with 5 seconds length, a2 with 5 seconds length and video V1 with 20 seconds length. So I want to merge audio a1 to video V1 at time 00:01s to 00:05s, audio a2 to video V1 at time 00:10s to 00:15s. "Merge" here I meant the video file will add voiceover from audio files a1 and a2 at specific time, not append.
After searching around Google and StackOverflow, I found Mp4Parser library, but unfortunately, I can only merge fully audio track to video track. My question is how to merge it at specific time and from multiple audio tracks ?
Here is code I used:
    public boolean mux(String videoFile, String audioFile, String outputFile) {
    Movie video;
    try {
        video = new MovieCreator().build(videoFile);
    } catch (RuntimeException e) {
        e.printStackTrace();
        return false;
    } catch (IOException e) {
        e.printStackTrace();
        return false;
    }

    Movie audio;
    try {
        audio = new MovieCreator().build(audioFile);
    } catch (IOException e) {
        e.printStackTrace();
        return false;
    } catch (NullPointerException e) {
        e.printStackTrace();
        return false;
    }
    Track audioTrack = audio.getTracks().get(0);
    List<Track> tracks = new ArrayList<Track>();
    tracks.add(video.getTracks().get(0));
    tracks.add(audioTrack);
    video.setTracks(tracks);
    Container out = new DefaultMp4Builder().build(video);
    FileOutputStream fos;
    try {
        fos = new FileOutputStream(outputFile);
    } catch (FileNotFoundException e) {
        e.printStackTrace();
        return false;
    }
    BufferedWritableFileByteChannel byteBufferByteChannel = new BufferedWritableFileByteChannel(fos);
    try {
        out.writeContainer(byteBufferByteChannel);
        byteBufferByteChannel.close();
        fos.close();
    } catch (IOException e) {
        e.printStackTrace();
        return false;
    }
    return true;
}

private static class BufferedWritableFileByteChannel implements WritableByteChannel {
    private static final int BUFFER_CAPACITY = 1000000;

    private boolean isOpen = true;
    private final OutputStream outputStream;
    private final ByteBuffer byteBuffer;
    private final byte[] rawBuffer = new byte[BUFFER_CAPACITY];

    private BufferedWritableFileByteChannel(OutputStream outputStream) {
        this.outputStream = outputStream;
        this.byteBuffer = ByteBuffer.wrap(rawBuffer);
    }

    @Override
    public int write(ByteBuffer inputBuffer) throws IOException {
        int inputBytes = inputBuffer.remaining();

        if (inputBytes > byteBuffer.remaining()) {
            dumpToFile();
            byteBuffer.clear();

            if (inputBytes > byteBuffer.remaining()) {
                throw new BufferOverflowException();
            }
        }

        byteBuffer.put(inputBuffer);

        return inputBytes;
    }

    @Override
    public boolean isOpen() {
        return isOpen;
    }

    @Override
    public void close() throws IOException {
        dumpToFile();
        isOpen = false;
    }
    private void dumpToFile() {
        try {
            outputStream.write(rawBuffer, 0, byteBuffer.position());
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}

Any helps would be very appreciate! Thanks so much.