A fundamental solution for the Laplacian from a fundamental solution for the heat equation

Question: Here is a heuristic reasoning.
Suppose that the function $u(x, t)$ solves
$$\partial_t u = \Delta u.$$
Integrating in $t$ we can define a new function $v$:
$$v(x)=\int_0^\infty u(x, t)\, dt.$$
Applying the operator $-\Delta$ to $v$ we get
$$-\Delta v(x)=\int_0^\infty -\partial_t u (x, t)\, dt = u(x, 0).$$
In particular, if $u_0=\delta$, that is if $u(x, t)$ is a fundamental solution for the heat equation, then $v$ is a fundamental solution for the Laplace equation.

Question Is there some truth in the above reasoning? Can it be formalized somehow?

Thank you.
EDIT:   I asked the owner of the local course in PDE. He replied that there is some truth in this and suggested to look for the keywords "subordination principle".
Answer: This is indeed correct and can be made rigorous, assuming that the integral converges sufficiently well for all $u_0$, which in turn depends on the boundary conditions that are imposed for the Laplacian.
Assume that $\int_0^\infty \Vert u(\cdot,t) \Vert dt < \infty$ for all $u_0$, for a suitable norm (e.g. the $L^2$ norm). By a theorem of Datko and Pazy, this implies that the spectrum of $\Delta$ is contained in the left half plane and bounded away from the imaginary axis. Now write formally $A = \Delta$ and $u(\cdot,t) = e^{At}u_0$. You are then computing
$$
\int_0^\infty e^{At} u_0 dt = (-A)^{-1} u_0  = (-\Delta)^{-1} u_0 \, .
$$
More generally, for  $\lambda$ in a suitable right half plane,
$$
\int_0^\infty e^{At} e^{-\lambda t} dt = (\lambda I - A )^{-1}
$$
that is,  Laplace transforms of the operator semigroup $\left( e^{At} \right)_{t \ge 0}$ are resolvents of the generator $A$ of the semigroup.
All this can be made rigorous using semigroup theory.
Comment: (...) The method doesn't work, because I am not able to find a solution of the evolution equation which is integrable in time. On the contrary, if I try to do the same with the Bessel equation $(-\Delta +1 )u=0$, everything goes fine. Why is that sign so important, in a semigroup-theoretical sense?
Comment: The reason, in a nutshell, is that $\Delta$ is like a diagonal matrix with all negative entries and therefore $e^{(\Delta - 1)t}$ can be expected to converge. On the other hand, $e^{(\Delta + 1)t}$ may contain contributions that behave like $e^{ct}$ with $c>0$, leading to divergence. All this can also be made rigorous, most easily if you consider the case where the domain $\Omega$ is $\mathbb{R}^n$. In that case you can apply the Fourier transform. The equation $u_t = \Delta u - u$ becomes $\hat u_t = (- |\xi|^2 -1)\hat u$ and  $u_t = \Delta u + u$ becomes $\hat u_t = (- |\xi|^2 +1)\hat u$.
Comment: Thank you, I think I found some references to the results you are mentioning. For example, Goldstein's book *Semigroups of linear operators and applications* mentions this operator-valued Laplace transform in his Chapter 0 (equation 0.5).
Comment: That's a very good reference.
Comment: Your post completely answered the given question. Now I'd like to ask you another little thing, if you don't mind. I tried to apply the present method to the Helmholtz equation $(\Delta + 1)u=0$, but ran into a difficulty. (...)
Comment: @Hans Engler I like your clear explanation! If you could help out with my question , that'll be great too :) https://math.stackexchange.com/questions/2754019/fundamental-solution-of-the-four-dimensional-laplacian


What is the value of the $A$?

Question: The sets $A$ and $B$ is sets of the same universal set. $A\cap B$ and $A\cup B$ is in order of $4$ and $128$.  $|A| = 2.|B|$ What is the value of $A$?
We know that
$$4 = 2^2$$
$$128 = 2^7$$
Which means
$$A \cap B = 2$$
$$A \cup B = 7$$
However, I'm so confused.
Comment: the cardinal of $A$ is $88$
Comment: Can someone take a look?
Answer: If I understand your formulation correctly, then note:
$$|A \cup B| = |A| + |B| - |A \cap B|$$
Plugging in what you know, we get:
$$128 = 2|B| + |B| - 4 \Rightarrow 3|B| = 132$$
And the size of $|A|$ follows easily.
Comment: Also, thanks for your great answer. I got everything.
Comment: Where did that $4$ come from?
Comment: @maxime You said $|A \cap B|$ is 4?
Comment: Yes, you are right. Sorry ;)
Answer: Highly confusing problem statement and deduction. The nomenclature for the sets and cardinalities are used interchangeably. Perhaps it is a good idea to separate the cardinalities from the sets themselves. Intersection or union of sets are in turn sets themselves and cannot be a cardinality/number (of elements in a set). So, the final question, what is the value of A is not right. It is just a set.
Further, the problem statement says, the union and intersection cardinalities (I am assuming) are 4 and 128. So, what exactly is the final deduction where you say, union is 7 and intersection is 2?
Comment: This is an (appropriate) comment, not an answer.
Comment: This is my first time here. Yes, it was a comment.

What is the value of the $A$?


Python float comparison

Question: I have a problem to understand the following python if clause.
key = '033411943470228118020044104711300230269019812152152'
my_secret = hex(int(key[0:3]))[2:].zfill(2) + hex(int(key[4:7]))[2:].zfill(2) + hex(int(key[8:11]))[2:].zfill(2) + hex(int(key[12:15]))[2:].zfill(2) + hex(int(key[16:19]))[2:].zfill(2)

    if float(my_secret) == 4.74678e+018:

Can anybody tell me how I can construct the my_secret that causes the if clause to be true?
Comment: Floating point arithmetic strikes again.
Comment: `my_secret = "4.74678e+018"` works for me, although comparing floats for equality is general doesn't necessarily do what you might expect.
Comment: possible duplicate of [Floating point equality in python](http://stackoverflow.com/questions/4028889/floating-point-equality-in-python)
Comment: my_secret is '217715be4b4', that is not in base 10 or 12. For example, int(my_secret, base=16) returns 2299709351092, but it is probably wrong.
Answer: my_secret = 4.74678e+018

Except when it's not: don't use floats for exact quantities!
Not all numbers can be represented as floats, so you might have rounding errors, which will lead to unexpected results when making exact comparisons.
Comment: i just added to my code how my secret is derived thats the reason why i don't understand it
Comment: @Martin In the code you're showing, `my_secret` is a  string, it's not the best idea to compare that to a float..
Comment: @Martin No, you didn't. For that being complete, you'd have to tell us what `key` is.
Comment: thats an existing coding i got that i reverse engineered
Comment: just added the key definition

Python float comparison


jquery mobile scripts does not work after page refresh

Question: Im using JQM and JSF.
In page, after i trigger a h:commondbutton and it's action retruns string null '',
page refresh and any scprits not work.
i put breakpoints in ready functions and mobile pageinit functions, but none of them works.
when i remove jquerymobile library it works.
Any idea for this..

   $(document).ready(function(){
    //some codes here
});

But this instead (in an appropriate place):

Comment: i tried it but does not work.. :( the problem is all scripts don't work, in ready and pageinit.
Comment: I finally found problem and dont know what is the reason but have a workaround.
Answer: i have work around but don't know what is the reason of the problem.
  $(document).on('mobileinit', function() {
    $.mobile.defaultPageTransition = 'slide';
    $.mobile.hashListeningEnabled = false;
  });

this is above funksion works while page load. but my project after refresh they not work. Thefefore there is means this page does not reload again.
it brings me think the ajax methods. After ajax process, any script of page are called and so the ready, pageinit, mobile init function are not called.
So i put the code below, in mobileinit seen above.
$.mobile.ajaxEnabled = false;

the solution is that
  $(document).on('mobileinit', function() {
    $.mobile.defaultPageTransition = 'slide';
    $.mobile.hashListeningEnabled = false;
    $.mobile.ajaxEnabled = false;
  });

and i again though how can this page use the ajax?


How are 13th chords with alterations "shorthand" written?

Question: My question is a general curiosity because on StackExchange and other sites I haven't found a complete answer that I can get my head around. I've read through the existing 13th discussions and am still just not getting what I'm after.
I get basic major and minor 13ths but when I get to something like this:
[1 ♭3 5 ♭7 9 11 ♭13]
Which in C is [A C E G B D F]
Is this an:

Amb13 (A-♭13) which seems to fit with Am11 adding a ♭13
Am11add♭13 (A-11?13) no idea what a shorthand for add might be as +
is usually augmentation as I understand it so Am11+♭13 wouldn't make
sense
Am11b13 (A-11b13) (reading as Am11 with a flat 13th on top and no
"add" required)
some kind of mutant hybrid like Am7dim13 A-7o13  (reading as A C E G + B D F)
A minor-major 11♭13 (A-^11♭13)
An ever stranger slash chord like Am/G7

I know these aren't in common practice but is there any standard guidance on naming of 13ths with varying mods to the upper tones? I'm coming at this assuming it's all the tones starting with the root through to the 13th and you aren't playing with inversions.
Are these alterations? Extensions?
When naming do you:

stop at the 7th and treat it like a 4+3 note polychord even though I
believe that is generally reserved for two triads?
stop at the 9th and add alterations to the 11th and 13th?
stop at the 11th and add alterations to the 13th?

Apologies for the mind dump. Just throwing out a list of every direction my mind has gone in with this topic.
Any reference or guidance would be appreciated.
Answer: It would be Am11♭13. Alterations are always placed at the end of a chord after the base chord symbol.
If you look at the notes, you have all the notes for an Am11 A - C - E - G - B -D. For it to be an Am13 you would need an F#, but since you have an F instead you denote it as a ♭13 after the first part of the chord symbol hence the Am11♭13.
Comment: @dwoz in my experience alterations never imply any extensions due to how the alteration changes the relationship between notes in a chord. I also can't find any source that states an Am7b13 contains an implied 9 and 11. I'd be interested to see if you can find one.
Comment: In the "boston school" way of looking at this, I would call it an "Amin7b13", in which notation the intermediate tensions between 7 and the altered 13 would be the "natural" available tensions...so the 9 and 11 would be considered incorporated by convention...and you'd deign to mention them only if you explicity wanted them voiced, or if they were also altered (i.e. b9, #11)
Comment: this has been my experience through 30 years of reading charts as a bassist and writing arrangements.  Your answer is correct, but as has been mentioned elsewhere, there are as many conventions as there are cities/regions/genres.  The thing about the notation is that it's all about pragmatically conveying as much info as possible to the player.  If, for example, I saw an Amin7b9...I'd infer that a b13 was probably the rule of the moment as well, unless otherwise notated.  If a CONVENTION is established, then it's more compact to notate the exception.
Comment: But when playing with others that ask you to play a Amin7b9 that may not be the intention as the chord symbols are well defined. It may work it may not, but the bigger point is be explicit with what you want.
Comment: Again, Dom, it's all about convention.  I daresay that the LESS information you have to notate (in something like a chord symbol, which is itself already a kind of shorthand) the more efficient it is for the player.  In exactly the same kind of way that we notate a key signature at the left of the bar, and then ONLY notate deviations from that within the note stream, we rely on a "convention."  if this convention I mentioned...that everyone on the bandstand has a common experience that we play XYZ when we see ABC notated on the sheet...then it all works.  Clearly, not a universal thing.
Comment: @dwoz that will lead to people guessing what you want which is not a good thing. For example, while 99% of players will see a C11 and omit the 3rd, the notation does not say the 3rd is omitted and in fact states the opposite. To clearly state you don't want anyone to play a 3rd use C9sus4 instead which conveys that idea exactly.
Comment: Dom, I'd say that if I saw a "C11" chord, I would have exactly the reaction you stated:  the 11 tension is added to the chord, and likely I have some voicing gymnastics to do to avoid the b9.  A C11 is a far cry from a Csus.
Answer: Though Dom's answer is a good one, I thought I could contribute by saying, be open to making adjustments to common chord naming systems if it makes life easier for you (although your personal system shouldn't be too ambiguous to other musicians).
You may have noticed by now that there are many different chord naming systems (albeit many of them having similar conventions, like using a 7 to represent a dominant chord). The lack of a sole chord naming system, however, is proof that music is an evolving artform, and this is a good thing.
For the sake of brevity sometimes musicians exclude chord alterations from the chord symbol entirely, with the understanding that said exclusions are still applicable. For instance, some jazz musicians represent the chord
[1 3 5 b7 b9 #9 #11 13]
by simply the symbol 7b9, even though the 9 and 11 are also sharped, and the notes look like they spell out a 13th chord rather than just a 7th chord. In your example of A-11(b13), however, it is probably best to be explicit and not worry about this type of shorthand.
The point is you're making the first step to understanding chord names by seeing what systems other musicians are using, and to that end I would suggest picking up a book on the subject and seeing what system the author uses too. The next step, in time, is finding a system that's right for you.
Comment: Joeb, thank you. I agree and often resort to my own devices when notating something. More than anything I always like to investigate to see if I'm overlooking a standard approach to something. When it comes to chord naming, even the books I own conflict at times on the subject. Theory and standards... always open to interpretation it seems.
Answer: There are plenty of variations on chord naming, but I find the most commonly used to be either:

greedy extension seeking
lazy extension seeking

Your chord 1 ♭3 5 ♭7 9 11 ♭13 has all degrees available, so it's not the best chord to use as an example. Let's use 1 ♭3 5 ♭7 11 ♭13 instead.
Greedy
Take the highest natural added note as extension 11. Use alterations for the any added note that has accidentals b13. Natural added notes are implied unless omitted from the chord 9. Omissions may or may not be specified in the chord name. long: Amin11 b13 no9 short:

Am11(b13)

Lazy
Take the highest natural added note as extension, without skipping any functions, or take the quality if no such higher extension available b7 (since the 9 is skipped, we have to resort to the quality). Add all other added notes with the add syntax 11, b13. long: Amin7 add11 add(b13) short:

Am7(11b13)


Searching values from dataframe1 to dataframe2 in pandas

Question: let's say I have a my source dataframe:
A B C
a 1 string1
b 1 string1
b 4 string2
c 2 string4
d 2 string2

and I have my input dataframe
A B C
a null string1
b null string2

How am I able to cross check values from my input dataframe to my source I want to find which rows in my source dataframe that has values from my input dataframe. I tried isin but its returning a dataframe full of nan values
Result would be a df:
A B C
a 1 string1 #Ref to a null string1
b 1 string1 #Ref to b null string2
b 4 string2 #Ref to b null string2
d 2 string2 #Ref to b null string2

Comment: What values are you checking from both? I don't quite understand how you got your resulting df.
Comment: It seems that you are searching column 'C'
Comment: @vikrantrana im searching for all columns
Answer: It looks like you are filtering your source df keeping only rows that have values in column C that are in your input df column C. If that is the case, you can use input_df['C'].unique() to give you an array of the unique values in column C in your input df, and you can use isin to filter your source df:
source_df[source_df['C'].isin(input_df['C'].unique())]

which gives an output of:
    A   B   C
0   a   1   string1
1   b   1   string1
2   b   4   string2
4   d   2   string2

Comment: how do we do this for all columns?
Comment: You could merge on the columns you wish to match. One of the suggested links goes into depth on merging.


How to do groupby filter in Dask

Question: I am attempting to take a dask dataframe, group by column 'A' and remove the groups where there are fewer than MIN_SAMPLE_COUNT rows.
For example, the following code works in pandas:
import pandas as pd
import dask as da

MIN_SAMPLE_COUNT = 1

x = pd.DataFrame([[1,2,3], [1,5,6], [2,8,9], [1,3,5]])
x.columns = ['A', 'B', 'C']

grouped = x.groupby('A')
x = grouped.filter(lambda x: x['A'].count().astype(int) > MIN_SAMPLE_COUNT)

However, in Dask if I try something analogous:
import pandas as pd
import dask

MIN_SAMPLE_COUNT = 1

x = pd.DataFrame([[1,2,3], [1,5,6], [2,8,9], [1,3,5]])
x.columns = ['A', 'B', 'C']

x = dask.dataframe.from_pandas(x, npartitions=2)

grouped = x.groupby('A')
x = grouped.filter(lambda x: x['A'].count().astype(int) > MIN_SAMPLE_COUNT)

I get the following error message:
---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
~\AppData\Local\Continuum\anaconda3\lib\site-packages\dask\dataframe\groupby.py in __getattr__(self, key)
   1162         try:
-> 1163             return self[key]
   1164         except KeyError as e:

~\AppData\Local\Continuum\anaconda3\lib\site-packages\dask\dataframe\groupby.py in __getitem__(self, key)
   1153         # error is raised from pandas
-> 1154         g._meta = g._meta[key]
   1155         return g

~\AppData\Local\Continuum\anaconda3\lib\site-packages\pandas\core\base.py in __getitem__(self, key)
    274             if key not in self.obj:
--> 275                 raise KeyError("Column not found: {key}".format(key=key))
    276             return self._gotitem(key, ndim=1)

KeyError: 'Column not found: filter'

During handling of the above exception, another exception occurred:

AttributeError                            Traceback (most recent call last)
<ipython-input-55-d8a969cc041b> in <module>()
      1 # Remove sixty second blocks that have fewer than MIN_SAMPLE_COUNT samples.
      2 grouped = dat.groupby('KPI_60_seconds')
----> 3 dat = grouped.filter(lambda x: x['KPI_60_seconds'].count().astype(int) > MIN_SAMPLE_COUNT)

~\AppData\Local\Continuum\anaconda3\lib\site-packages\dask\dataframe\groupby.py in __getattr__(self, key)
   1163             return self[key]
   1164         except KeyError as e:
-> 1165             raise AttributeError(e)
   1166
   1167     @derived_from(pd.core.groupby.DataFrameGroupBy)

AttributeError: 'Column not found: filter'

The error message suggests that the filter method used in Pandas has not been implemented in Dask (nor did I find it after a search).
Is there a Dask functionality which captures what I am looking to do? I have gone through the Dask API and nothing stood out to me as what I need. I am currently using Dask '1.1.1'
Thank you for your help.
Answer: Fairly new to Dask myself. One way to achieve you are trying could be as follows:
Dask version: 0.17.3
import pandas as pd
import dask.dataframe as dd

MIN_SAMPLE_COUNT = 1

x = pd.DataFrame([[1,2,3], [1,5,6], [2,8,9], [1,3,5]])
x.columns = ['A', 'B', 'C']
print("x (before):")
print(x)  # still pandas
x = dd.from_pandas(x, npartitions=2)

grouped = x.groupby('A').B.count().reset_index()

grouped = grouped.rename(columns={'B': 'Count'})

y = dd.merge(x, grouped, on=['A'])
y = y[y.Count > MIN_SAMPLE_COUNT]
x = y[['A', 'B', 'C']]
print("x (after):")
print(x.compute())  # needs compute for conversion to pandas df

Output:
x (before):
   A  B  C
0  1  2  3
1  1  5  6
2  2  8  9
3  1  3  5
x (after):
   A  B  C
0  1  2  3
1  1  5  6
1  1  3  5

How to do groupby filter in Dask


Function composition, invertibility, domain of functions.

Question: Finding the domain is easy; the rest I don't understand how to do.
Let $f(x)=x-6\sqrt[]{x}+9$. Find the domain of $f$. Show that $(f \circ f)(x) = x$ for $x \in [0, 9]$. Is $f$ invertible with $f^{-1}=f$?
Comment: Hint: $f(x)=(\sqrt{x}-3)^2$ then $(f \circ f)(x)=\cdots\;$.
Comment: **Hint 2**: If $(f \circ f)(x) = x$ then $f$ is invertible with $f^{-1}=f$
Answer: \begin{equation}
(f∘f)(x)=(\sqrt{x-6\sqrt x +9}-3)^2\\=x-6\sqrt x +9+9-6\sqrt{x-6\sqrt x +9}\\=x-6\sqrt x +18-6\sqrt{(\sqrt{x}-3)^2}\\=x-6\sqrt x +18-6|\sqrt x-3|
\end{equation}
For $x\in [0,9]$, $\sqrt x-3$ is negative so we can write:
\begin{equation}
x-6\sqrt x +18-6|\sqrt x-3|\\=x-6\sqrt x +18-6[-(\sqrt x-3)]\\=x-6\sqrt x +18+6\sqrt x-18\\=x
\end{equation}
We can say that $f$ is invertible with $f^{-1}=f$ when $x\in [0,9]$.


Como utilizar o onBlur do Angular?

Question: Quero que seja exibido no console o valor cep que digitei no campo input após o campo perder o foco.
Porém, esse meu código não está fazendo isso.
html:

    <form>
        CEP

        <input type="text" ng-model="endereco.cep" ng-blur="pegaCep(endereco)">

        Estado

        <input type="text" ng-model="endereco.estado">

    </form>

Angular:
app.controller('appController', function ($scope, $http){
    var pegaCep = function (data) {
        console.log(data);
    }
    pegaCep()
});

Comment: Gustavo, imagino que sua pergunta já possui uma resposta aqui: http://pt.stackoverflow.com/questions/108712/duvida-com-angularjs-input-e-metodo-onblur/108713#108713.
Comment: O código desse outro post, pra mim, não deu certo... Ficava aparecendo no console que o meu pegaCep não tinha sido definido.
Answer:

var app = angular.module('myApp', []);

app.controller('appController', function ($scope, $http){
  $scope.pegaCep = function () {
    console.log($scope.endereco.cep);
  }
});

    <form>
        CEP

        <input type="text" ng-model="endereco.cep" ng-blur="pegaCep()">

        Estado

        <input type="text" ng-model="endereco.estado">

    </form>

Como utilizar o onBlur do Angular?


Intel® iSCSI Remote Boot Intel X540-T2

Question: I have an Intel X540-T2 Dual port 10GB Ethernet adapter. DEV ID: 8086/1528
I am trying to setup a workstation to boot from a SAN using iSCSI.
Everything I have read about this card says that Intel® iSCSI Remote Boot is supported.
Yet, I cannot enable it, nor configure it using any of the boot utilities I have found, including the DOS utility or the BOOTUTILW64E.EXE command line utility that Intel released just last year.
If I perform the command:
BOOTUTILW64E.EXE -NIC=2 -BOOTENABLE=ISCSIPRIMARY

I get the following error:
ERROR: Invalid argument for command line parameter -BOOTENABLE: ISCSIPRIMARY
Select value from 'iscsiprimary', 'iscsisecondary','pxe', 'fcoe', or 'disabled'

If I do pxe instead of iscsiprimary, it works. foce gives me the same error.
The only options that work are PXE and DISABLE.
It appears that my card does not have the correct image flashed to it to support Intel® iSCSI Remote Boot.
However, Intel's site and documentation leads a person on a wild goose-chase more of than Cisco's website.
Has anyone set Intel® iSCSI Remote Boot up before?
Am I just missing something simple?
For extra clarity, here is the output of BOOTUTILW64E.EXE -E
Port Network Address Location Series  WOL Flash Firmware                Version
==== =============== ======== ======= === ============================= =======
1   B06EBF3A4213     0:31.6 Gigabit N/A FLASH Not Present
2   A0369F21EACC   179:00.0 10GbE   N/A UEFI,PXE Enabled              2.2.02
3   A0369F21EACE   179:00.1 10GbE   N/A UEFI,PXE Enabled              2.2.02

I have been considering flashing iPXE to this card, but I want to get the stock firmware working before I go the nuke-all solution, plus I don't know if that would even work, or if I could go back if I did, and it failed.
Answer: The NIC is flashed with only legacy PXE and UEFI option roms, this is why you cannot configure iSCSI.
To use iSCSI you must reflash your NIC with at least iSCSI option ROM. You may be able to flash it together with UEFI option ROM (on Intel branded and other brands OEM Gen designs) or with so called "combo" image which also contains legacy PXE and possibly - legacy FCoE - on certain server brands (likely Dell and HP).
Please note that legacy FCoE is end of life. Legacy iSCSI is also heading this way (if not EOL already - it is not available in release 27.8). And I have a motherboard which only supports CSM (legacy BIOS compatibility mode) only with add on graphic card (which obviously must support legacy video option rom), so legacy iSCSI is a no-go on such design.
You will be better off with UEFI iSCSI - if your BIOS is UEFI and has iSCSI initiator embedded. The crash dump driver supports this scenario.
EDIT:
Flashing iPXE should work for this NIC (it WILL NOT be possible on anything newer than that, X540 and I210 were the LAST Intel NICs to allow flashing unsigned option ROM images). It should also be possible to flash back Intel option roms.
Disclosure: I work for Intel and used to maintain legacy networking option ROMs.
Comment: Thank you very much for that. Now, IF I can actually manage to find the UEFI and iSCSI ROM for this card, I think I'll be set.
For the record, my board is an Asus x299 TUF Mark II. It supports UEFI, but not Legacy. Which explains why I cant even get the option rom to boot during post.
Comment: You should be able to find UEFI drivers on Intel's website, they are supported and they should still work on this NIC. UEFI iSCSI initiator should be a part of the motherboard UEFI BIOS. If it is not there - no Intel driver is going to help you.
Comment: Just head for "Intel® Ethernet Adapter Complete Driver Pack", unzip and go to APPS direcotry. Grab BootIMG.FLB file and one of the executables (for your platform) from the subdirectory and you should be good to flash your NIC. The one for UEFI is probably what you should get, boot to UEFI shell (you may have to disable secure boot) and flash.

Intel® iSCSI Remote Boot Intel X540-T2


Loading Data from Behance API in React Component

Question: I am trying to load Behance project data via their API. Whether its localhost or prod, I am getting the following error --

Fetch API cannot load XXX. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:5000' is therefore not allowed access. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

Not sure how to solve for this.
My code in the Portfolio component below --
<code>getPortfolio = () => {

const USER_ID = `XXX`,
      PROJECT_ID = `XXX`,
      API_KEY = `XXX`;

const BEHANCE_URL = `https://api.behance.net/v2/users/${USER_ID}/projects?client_id=${API_KEY}`;
console.log(BEHANCE_URL);

fetch(BEHANCE_URL, {
  method: 'get',
  dataType: 'jsonp',
  headers: {
      'Accept': 'application/json',
      'Content-Type': 'application/json'
  }
}).then((response) => {
  return response.json();
}).then((responseData) => {
  return responseData;
}).catch((err) => {
  return err;
});

}
</code>
UPDATE: Instead of fetch, using jQuery ajax works. --
<code>$.ajax({
  url: BEHANCE_URL,
  type: "get",
  data: {projects: {}},
  dataType: "jsonp"
}).done((response) => {
  this.setState({
    portfolioData: response['projects']
  });
}).fail((error) => {
  console.log("Ajax request fails")
  console.log(error);
});
</code>
Comment: Did you figure out why with jquery it does not throw the CORS error? Because that should not be the case. Look at this, stackoverflow.com/questions/25923796/cors-error-with-jquery. I am curious to know how was jquery working in place of fetch.
Comment: I just implemented this in a project and it sure enough works. I have heard that with `fetch()` and `jQuery`, you can circumvent CORS errors and sure enough you can, apparently.
Answer: This seems to have do less with React and more with Behance. What you are getting is a CORS error as you probably figured out. The short explanation is that CORS is a security measure put in on the browser so that websites cannot request other websites from the browser to appear to be the second website. It is a safety measure in place to protect from some phishing attacks.
CORS can be disabled by the server (in this case, Behance) but they decide not to, for legitimate reasons.
Behance would probably allow you to make the request you are trying to make from a server instead. Once you do that, you will need to get the information from your server to your React application, and you will be good to go!
Comment: whats odd is, the introduction of jQuery and doing a $.ajax works to pull the data
Comment: You mean using jQuery instead of Fetch? That is indeed odd.
Comment: yea, this works --

$.ajax({
      url: BEHANCE_URL,
      type: "get",
      data: {projects: {}},
      dataType: "jsonp"
    }).done((response) => {
      this.setState({
        portfolioData: response['projects']
      });
    }).fail((error) => {
      console.log("Ajax request fails")
      console.log(error);
    });


How do I use CLX/XLIB from Common Lisp after installing it from my package manager?

Question: I'm trying to use CLX while learning common lisp, because I figure it's more effective to learn if I have an actual, tangible, practical result. Unfortunately, I can't get CLX to work. I followed the first bit of this tutorial, after installing the clisp and clisp-module-clx packages in debian.
I think I'm just horribly misunderstanding clisp's package / module / etc. loading system, but I can't find any resources for how to do this.
foo.lisp:
(defun pop-up-window (life-time &optional (host ""))
  (let* ((display (xlib:open-display host))
         (screen (first (xlib:display-roots display)))
         (root-window (xlib:screen-root screen))
         (my-window (xlib:create-window
                      :parent root-window
                      :x 0
                      :y 0
                      :width 200
                      :height 300)))
    (xlib:map-window my-window)
    (xlib:display-finish-output display)
    (format t "it should be here ~%")
    (sleep life-time)
    (xlib:destroy-window my-window)
    (xlib:close-display display)
)

(pop-up-window 10)

output: there is no package with name "XLIB"
Edit:
I tried (require "clx") at the start of my code, but I get #<PACKAGE COMMON-LISP> is locked.
Comment: That tutorial seems a bit out of date. Nowadays you should use [quicklisp](https://www.quicklisp.org/beta/) to install libraries. I'd also recommend using SBCL on Linux (the package manager version is probably old).
Comment: `(ql:quickload "library" :silent t)` and there won't be any messages
Comment: @jkiiski Thanks, that's so much easier! Though, I don't like that the ql:quickload command produces a few lines of "Loading" messages at the top of my script each time it runs :/
Answer: The CLX system was most likely not installed. You could download the archive yourself and configure ASDF to load the system, but the easiest route is to first install Quicklisp. Then, you can execute:
(ql:quickload :clx)

This downloads, compiles and loads the desired system and all its dependencies. This step should be executed each time you restart your Lisp environment. As soon as you need more than one libraries, you should also define your own system (for example in ~/quicklisp/local-projects/) and load that one instead.


Update SSBO in Compute shader

Question: I am currently trying to update a SSBO linked/bound to a Computeshader. Doing it this way, I only write the first 32byte into the out_picture, because i only memcpy that many (sizeof(pstruct)).
Computeshader:
#version 440 core

struct Pstruct{
  float picture[1920*1080*3];
  float factor;
};

layout(std430, binding = 0) buffer Result{
  float out_picture[];
};
layout(std430, binding = 1) buffer In_p1{
  Pstruct in_p1;
};
layout(local_size_x = 1000) in;

void main() {

    out_picture[gl_GlobalInvocationID.x] = out_picture[gl_GlobalInvocationID.x]  +
                                           in_p1.picture[gl_GlobalInvocationID.x] * in_p1.factor;

}

GLSL:
struct Pstruct{
   std::vector<float> picture;
   float factor;
};

Pstruct tmp;
tmp.factor = 1.0f;
for(int i = 0; i < getNUM_PIX(); i++){
   tmp.picture.push_back(5.0f);
}

SSBO ssbo;
glGenBuffers(1, &ssbo.handle);
glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 1, ssbo.handle);
glBufferData(GL_SHADER_STORAGE_BUFFER, (getNUM_PIX() + 1) * sizeof(float), NULL, GL_DYNAMIC_DRAW);

...

glBindBuffer(GL_SHADER_STORAGE_BUFFER, ssbo.handle);
Pstruct* ptr = (Pstruct *) glMapBuffer(GL_SHADER_STORAGE_BUFFER, GL_WRITE_ONLY);
memcpy(ptr, &pstruct, sizeof(pstruct));
glUnmapBuffer(GL_SHADER_STORAGE_BUFFER);

...

glUseProgram(program);
glDispatchCompute(getNUM_PIX() / getWORK_GROUP_SIZE(), 1, 1);
glMemoryBarrier(GL_SHADER_STORAGE_BARRIER_BIT);

How can I copy both my picture array and my float factor at the same time?
Do I have to split the memcpy call into array and float? and if yes how? I can copy the first part, but I am not allowed to add an offset to the ptr.
Answer: First of all,

float picture[1920*1080*3];

clearly should be either a texture (you're only reading from it anyway) or at least an image.
Second:

struct Pstruct{
   std::vector<float> picture;
   float factor;
};

This definition does not match the definition in your shader in any way. The std::vector object will just be a meta object internally managing the data storage used by the vector. memcpy that to a GL buffer and passing that to the GPU does not make sense at all.
The correct approach would be to either copy the contents of that vector separately into the appropriate places inside the buffer, or to just us a struct definition on your client side which actually matches the one you're using in the shader (and taking all the rules of std430 into account). But, as my first point already was, the correct solution here is most likely to use a texture or image object instead.
Comment: wouldn't making it into an image2d reduce the numeric accuracy? image2D takes RBGA8 maximum? otherwise that would be absolutely the right call, didn't think of it.
Comment: No, you can have full 32 bit float per channel texture and images, see `GL_RGBA32F` format.

Update SSBO in Compute shader


Will 208v Hurt My Servers?

Question: I've decided to move most of my servers out of our closet at work and into a datacenter. All of our servers are 110v, however we're starting to purchase some new ones, and the datacenter tech recommended we opt for the 208v since it was cheaper for the cage we are getting.
I've looked up on most of our servers that we traditionally use 110v for, however they SEEM to all support 208v as well (HP DL360 g4, Dell 2850's, and Dell 2650's).
Is there anything wrong with putting all of these servers on 208v??
Answer: DL360's should handle 208v with no problems. They have auto-switching power supplies which'll handle the switch for you. Also, running at 208v is slightly more efficient than running at 120v. A few percentage points gained, which can add up for a server that routinely burns 300+ watts.
Comment: Yup, I'm currently running two brand new DL360 G7s on 208, along with a gaggle of other server/storage equipment. For the most part, all modern computing equipment (including monitors, laptop power supplies, cell phone chargers, etc.) all have switching power supplies and as such, should be able to handle either voltage.
Comment: @sysadmin1138: Happen to have any references for 208 being a little bit more efficient wattage wise than 120?
Comment: @KyleBrandt You can see it in most of the Anandtech power-supply reviews, but a good example is [here](http://www.anandtech.com/show/5931/in-win-greenme-650w/5). The 115VAC test shows 87.4% efficiency at 50% load, and the 230VAC test 88.12% efficiency at 50% load. As I said, it's small but measurable. That trend has been there for several years in their reviews.
Answer: If the servers support 208v (and most do these days) then you'll be fine. The datacenter tech is correct, this will save you money as most data centers charge per amp for power and running your servers at 208v will reduce the number of amps you'll need to power the servers.
Comment: I don't think datacenters really charge just by the amp, do they? They must charge by the watt, which conveniently reduces to amps if the voltage is constant (that is, all 110v or all 208v). It certainly doesn't cost *them* half as much to use the higher voltage for the same amount of work. As sysadmin1138 says, the power supplies are slightly more efficient running at higher voltages, so there's the savigns.
Comment: Every DC I've seen charges per kWh (just like the power company), or power is rolled into the monthly cost. At 208v the server will probably run a bit more efficiently, so they're still ahead on the power bill.
Comment: All the datacenters I've ever talked to charge for power per amp. I get billed a flat monthly rate for a 30amp circuit, regardless of the actual power consumed during that month. With a 208v circuit I would only need a 20amp circuit instead of a 30amp circuit and thereby reduce my monthly cost.
Comment: If they're charging that way, they are either eating the costs on 208V, or else overcharging you on 110V, because they're sure not getting billed that way by the power company.
Answer: 208v vs 220 v is a factor of how the voltage is derived from the transmission line; whether or not it's delivered as single-phase or three-phase.
Answer: I'm wondering why exactly 208 volt - from where came this digit 208 ?
In most of the Europe the voltage is 220 volt and this is a standart. As a standart it allows you to have a little deviation for example as a low minimum 200 volt and as a maximum 240 volt, but now one speaks about 208 volt as a standart voltage for equipment.
Why do you think that power supplies at higher voltage are more effective ?
If we speak only for the voltages (ignoring ampers) I think that more effective will be conversion from 110 to 3, 5, 12 volt compared to 220 to 3,5,12 volt. When the gap between two voltages is low you will have low losses caused by conversion.
Comment: 208v is a standard voltage because when you have 3Φ240v and use any two legs of it, you get 208v. It's called 3Φ240v in the first place because the maximum swing in voltage away from ground is -120v to +120v.
Comment: @Sirex, it's easier to think of as water in a pipe. Volts = Pressure and Amps = cross section (area). Using a higher voltage allows you to get more electricity through a smaller wire and with less resistance, thus it's more efficient.
Comment: (total guess). As a kid i was told voltage is basically how big the jolts of electricity are, and amps are how fast you shove them through a wire ("volts jolt, mils kill"), consequently high ampage makes a lot of heat - which is why overhead lines run at huge voltages rather than huge ampages. Soooo armed with that comically dodgy knowledge, I'm guessing maybe they run cooler at a slightly higher voltage rather than a high throughput ?
Comment: Here in the US, the standards that one is most likely to see in a datacenter are 120v, 208v, and 240v.  Pretty easy to tell 120 apart since the plug is different (actually, there's 2 similar plug designs for 120v depending on if it's 15a or 20a) from 2xxv.  Have to be careful with 208/240 as the plug is the same and some equipment will handle one, but not the other!
Comment: In these posts/comments few people talk about 110V other 120V - why is this discrepancy ?
Comment: Over here, it refers to the same thing.  The old handyman type guys usually call it 110v.  The professional electricians usually call it 120v these days.  My understanding is that the specification is a nominal 120v (max 125v) but that in the past the actual delivered voltage was closer to 110v.  I recall as a child that our delivered voltage was always 115v.  Nowadays, there's 120v at the outlets in my area.
Answer: While 208v is definitely OK for most recent Dell hardware, and probably most Cisco, etc., double check everything you're planning to add to the cabinet.  We've had two ugly surprises with 110v-only equipment on a 208v circuit.
One, an off-brand chassis hosting our voicemail system, simply couldn't take 110v.  Nice smoky smell, and a weekend without voicemail.
The other was an older Dell workstation-used-as-a-server which had a physical switch that nobody noticed, which was still set at 110v.  The guy who hooked that up connected the power cord to the strip first, then connected the cord to the machine.  Bright flash and cracking sound right in his face.  He was unharmed but seriously shaken.

Will 208v Hurt My Servers?


Django UserCreationForm neither gives error message nor registering user

Question: I am beginner to python Django. And trying build an posting article website with the help of tutorials. I got stuck at UserCreationForm. I have created a form using UserCreationForm, but when I am submitting the form I am not able to neither submit the form nor getting any error message on the page.
My views.py code
 from django.shortcuts import render_to_response
 from django.contrib.auth import authenticate
 from django.http import HttpResponseRedirect
 from django.contrib import auth
 from django.template.context_processors import csrf
 from django.contrib.auth.forms import UserCreationForm

 def register_user(request):
     if request.method == 'POST':
        form = UserCreationForm(request.POST)
        if form.is_valid():
           form.save()
           return HttpResponseRedirect('/accounts/register_success')

    args = {}
    args.update(csrf(request))

    args['form'] = UserCreationForm()
    print args
    return render_to_response('register.html', args)

 def register_success(request):
    return render_to_response('register_success.html')

register.html
 {% extends "base.html" %}

 {% block content %}

Register

    <form action="/accounts/register/" method="post"> {% csrf_token %}

      {{form}}

      <input type="submit" value="Register"/>

   </form>

  {% endblock %}

register_success.html
  {% extends "base.hml" %}

  {% block content %}

You have registered!

Click Here to login again

 {% endblock %}

Comment: Have you debugged your HTML to see if  method is POST? What about adding `else return HttpResponse('Not from POST method')` on **register_user**
Comment: is not `{{ args.form }}` ?
Comment: @AndrésPérez-AlbelaH. It gives me"Not from post"
Comment: @NeerajSharma I've updated my answer
Comment: @AndrésPérez-AlbelaH. I am receive the following error                          "The view django_demo.views.register_user didn't return an HttpResponse object. It returned None instead."
Answer: The problem is that you are always creating a blank form.
args['form'] = UserCreationForm()

This means that you do not see any errors for POST requests when the form is invalid.
Instead, you should only create the blank form for GET requests.
from django.shortcuts import render

def register_user(request):
    if request.method == 'POST':
        form = UserCreationForm(request.POST)
        if form.is_valid():
           form.save()
           return HttpResponseRedirect('/accounts/register_success')
    else:
        form = UserCreationForm()
    args = {'form': form}
    return render(request, 'register.html', args)

Note that I have simplified the view by using render instead of the obsolete render_to_response. That means you don't need to handle csrf manually.
Answer: You can use Django Generic Views, specifically CreateView, it will make your life a lot easier. You can use it like so:
from django.views.generic import CreateView

class CreateUserView(CreateView):
    template_name = 'register.html'
    form_class = UserCreationForm
    success_url = '/accounts/register_success'

Add this to your urls.py and you are good to go:
from mysite.views import CreateUserView

# add this url pattern
url(r'^sign_up/$', CreateUserView.as_view(), name='signup'),


Is it correct to have nested random effects when you have multiple questions per item?

Question: Let's imagine a study where people study 50 images. After each image they get get 5 true/false questions about the image (different questions for each image; e.g., was there a tree in the image you just saw).
The DV is accuracy on these questions. The predictor is study time (within subjects, they see half of the images for five seconds, half for ten seconds). Images can appear in either level, counterbalanced across participants. This example is just made up to get to my question...
Does it make sense to have a random effects structure with question nested within image?
Edit: Changed predictor in the example.
Comment: Do all people get the same images?  Is question order randomized?  Do all subjects get the same five questions for each image?
Comment: Everyone gets the same images, but they can appear in either level of the predictor (I've updated the question to say this). Order is randomized. All subjects get the same questions for each image.
Answer: Since there are different questions for each image, this would meet the definition of nested random effects, provided that each question belongs to one and only one image. Since all subjects see all images, then subject is crossed with image (and question). Since the research question concerns study time, one approach using a mixed model would be:
accuracy ~ study_time + (1|subject) + (1|image/question)

Comment: Does this answer your question ? If so please consider marking it as the accepted answer. If not, please let us know why. Also, if you haven't already, please consider upvoting it.


density of roots of a family of polynomials: $(1-x^2)^{v+n}$

Question: My research has brought me to the following, very general problem.
Given a fixed, but arbitrary, natural number, $\displaystyle v$, consider the following family of polynomials: The $\displaystyle (n-1)^{th}$ derivative of
$$\displaystyle (1-x^2)^{v+n} \ \ \forall n \in \mathbb{N} $$
I would like to prove (or disprove) that the roots of this entire family of polynomials forms a dense subset of the interval $\displaystyle [0,1]$ for any value of $\displaystyle v$ (I am not interested in roots outside the interval $\displaystyle [0,1]$).
In other words, given any subinterval, $\displaystyle [a,b]$,no mater how small, at least one of these polynomials has at least one root in the interval $\displaystyle [a,b]$ (for any fixed value of $\displaystyle v$).
I realize my question is very general and will happily accept any partial solutions.
Comment: Presumably this is related to your previous question about roots of Legendre polynomials; one technique that might be adaptable to this particular variant of the question is to prove minimal-separation results for the roots.  I don't know if I've seen this even for Legendre polynomials, but it ought to be well within reach; lower bounds on the second derivative between two adjacent roots would force a separation between those roots, and those bounds might be accessible by exploiting the differential equation and the Sturm-iness...
Comment: There's a proof of the interlacing of Legendre polynomial roots in Chihara; have you by any chance been able to see the book?
Answer: First note that this family of polynomials is orthogonal, on the interval $[-1,1]$, with the weight factor $(1-x^2)^{-(v+1)}$.  This is not much of a surprise since the definition is very similar to that of the traditional Legendre Polynomials, which are orthogonal.  Next, we use the following deep result involving orthogonal polynomials:
If $\{p_n\}$ is a family of orthogonal polynomials with roots in $[-1,1]$ and $N(a,b,n)$ represents the number of roots of $p_n$ in [$\cos(b),\cos(a)$] then
$$\lim_{n\to \infty}\frac1{n} N(a,b,n)=\frac{b-a}{\pi}$$
Thus for any small subinterval [$\cos(b),\cos(a)$], there exists $n$ sufficiently large such that $N(a,b,n)>1$ implying that the roots of these polynomials do form a dense subset of $[-1,1]$.
Comment: Where does this result come from?


Replacement on Reaper for garageband's virtual drummer?

Question: Recent versions of garageband have a "virtual drummer" that can "follow" a midi song and provide accompaniment in one of several styles (e.g., "rock", "pop", "reggae", ..), and with a 2-dimensional high-level control ("complexity" and maybe "volume"?).  It's really simple if you want a scratch backing track.
Does Reaper (or maybe another VST-plugin-accepting system) have a replacement that works with this same high-level control?
All the drummer plugins I've seen are about the recording quality of the instrument, and have you program them with MIDI, which is a lot lower level.
Answer: I don't know what the virtual drummer does, but the new Band-in-a-Box 2019 has a DAW plugin (VST/AAX) that might do what you want.
Update 11/2019: there now seems to be a VST/AU/AAX plugin version for the Mac as well, though apparently only 64 bit  https://www.pgmusic.com/bbmac.htm
Here it is demonstrated in Reaper:

Some other virtual drummer software that comes to mind, with random Youtube videos showing them in or with Reaper.
Drumcore (a free version shown here)

Jamstix

EZ Drummer

In addition to those, Steven Slate Drums aka SSD, and other drum software have drum grooves, which might help you do what you want.


Debug DNS time out for Nginx application deployed on Azure VM

Question: I have an application deployed on an Azure VM using an Nginx web server. The application uses supervisor to set up the Nginx and gunicorn servers. I have checked all configuration and log files and all seems to be working OK. However when I point a browser at the website the browser times out for the www.mydomain.com and for mydomain.com returns:
This site can't be reached
mydomain.com's server DNS address could not be found.

On Azure I have set up a DNS zone containing:
Name: @ TYPE: NS TTL: 120 VALUE: relevant azure name servers.
Name: www TYPE: CAME TTL 60 mydomain.com

On the domain registrar I have set the DNS names as per the azure DNS names.
On my local machine I have:
Flushed the cache on the browser.
checked nslookup www.mydomain.com
Server:         127.0.1.1
Address:        127.0.1.1#53

Non-authoritative answer:
Name: www.mydomain.com
Address: xxx.xxx.xx.xx

tried traceroute, xxx.msn.net addresses were located without any [closed] so I presume the server was found.
tried:
host -t A www.mydomain.com
>>www.mydomian.com is an alias for mydomain.themsazureaddress.com
>>mydomain.themsazureaddress.com has address xxx.xxx.xx.xx

On the web server I have:
tried netcat:
Proto Recv-Q Send-Q Local Address           Foreign Address         State
tcp        0      0 *:http                  *:*                     LISTEN
tcp        0      0 *:ssh                   *:*                     LISTEN
tcp        0      0 *:https                 *:*                     LISTEN
tcp        0      0 localhost:8000          *:*                     LISTEN
tcp        0      0 localhost:6379          *:*                     LISTEN

and netstat:
tcp        0      0 0.0.0.0:80              0.0.0.0:*               LISTEN      62133/nginx
tcp        0      0 0.0.0.0:443             0.0.0.0:*               LISTEN      62133/nginx

checked the nginx config:
upstream app_server_wsgiapp {
     server localhost:8000 fail_timeout=0;
}

server {
 listen 80;
 server_name myapp.com;
 rewrite ^(.*) https://$server_name$1 permanent;
}

server {
  server_name           myapp.com;
  listen                443 ssl;

Checked nginx error and access logs:
access logs are empty, error log just contains:
epoll add event: fd:11 op:1 ev:00000001

I also checked processes and supervisor, gunicorn, redis, celery are all running OK. I am just using sqlite so I don't need to worry about the database setup.
Any other suggestions for dubugging why I cant see the application?
Comment: Please edit your question to include the domain in question.
Comment: From all your info, I couldn´t find anything about your nsg/firewall configuration. Another question, what is your Linux distribution?
Comment: The problem lies somewhere between your client computer and the DNS settings. You get a time-out trying to resolve the DNS name, so at that stage you didn't try to contact your Azure deployment yet. If the issue reappears I'd recommend doing some DNS troubleshooting locally (fire up wireshark to take a trace, try some manual nslookup, maybe try from another place like www.digwebinterface.com .. etc)
Comment: @BrunoFaria Adding port 80 and 443 in/out rules to the nsg worked, I had no idea about Azure NSG's. Please add this as an answer and I will accept
Comment: @DonSmythe great! A simple fix to a big problem :)
Answer: NSG was missing in the user VM configuration.

A network security group (NSG) contains a list of access control list
  (ACL) rules that allow or deny network traffic to your VM instances in
  a Virtual Network.
NSGs can be associated with either subnets or individual VM instances
  within that subnet. When a NSG is associated with a subnet, the ACL
  rules apply to all the VM instances in that subnet. In addition,
  traffic to an individual VM can be restricted further by associating a
  NSG directly to that VM.

Configuring NSGs in Azure Portal:
https://docs.microsoft.com/en-us/azure/virtual-network/virtual-networks-create-nsg-arm-pportal


How to make a UIView's subviews' alpha change according to it's parent's alpha?

Question: I'm having trouble setting the alpha of some of my subviews.
Using Storyboard, I have a UIView,  viewA in my View Controller, with subView1, subView2, & subView3 as subviews inside viewA.
When I change viewA's alpha to 0.5, viewA's alpha changes but it's subviews' alphas remain the same.
By default, shouldn't it's subview's alpha's change according to it's parents? What am i doing wrong?
Answer: Here you go:
self.view.layer.allowsGroupOpacity = YES;

This will work for all subviews, subviews of subviews and all that.
From the docs:
 * The default value of the property is read from the boolean
 * UIViewGroupOpacity property in the main bundle's Info.plist. If no
 * value is found in the Info.plist the default value is YES for
 * applications linked against the iOS 7 SDK or later and NO for
 * applications linked against an earlier SDK. */

Your project might not be linked against the iOS 7 SDK. If you want this change to work for all views, I'd do this:

Go to your .plist
Add a row titled "Renders with group opacity"
Set it to YES

From Apple's docs:
UIViewGroupOpacity
"Renders with group opacity"
Specifies whether Core Animation layers inherit the opacity of their superlayer. See "UIViewGroupOpacity" for details.
iOS 3.0 and later

Answer: What about subView1.alpha = subView1.superview.alpha?
Answer: You should check on this
UIKit keys for Info.plist, specifically UIViewGroupOpacity.
Answer: Take a look at allowsGroupOpacity, which can be set on the layer. There is also a global info.plist key for changing this behavior app-wide.

When the UIViewGroupOpacity key is not present, the default value is
  now YES. The default was previously NO.
This means that subviews of a transparent view will first be
  composited onto that transparent view, then the precomposited subtree
  will be drawn as a whole onto the background. A NO setting results in
  less expensive, but also less accurate, compositing: each view in the
  transparent subtree is composited onto what's underneath it, according
  to the parent's opacity, in the normal painter's algorithm order

https://developer.apple.com/library/ios/releasenotes/General/RN-iOSSDK-7.0/index.html


Erro apos atualizar o Android Studio para versão 3.0.1

Question: Olá, acabei de atualizar minha versão de 2.1 para 3.0.1 e esta aparecendo esse erro

Information:Gradle tasks [:app:generateDebugSources, :app:generateDebugAndroidTestSources, :app:mockableAndroidJar] Error:java.util.concurrent.ExecutionException: com.android.tools.aapt2.Aapt2Exception: AAPT2 error: check logs for details Error:Execution failed for task ':app:mergeDebugResources'. > Error: java.util.concurrent.ExecutionException: com.android.tools.aapt2.Aapt2Exception: AAPT2 error: check logs for details Information:BUILD FAILED in 44s Information:2 errors Information:0 warnings Information:See complete output in console

Não está aparecendo a tela do smartphone do activity_main.xml que montamos a interface dos apps
Comment: Eu focaria na parte que diz *"check logs for details"*, e talvez em *"See complete output in console"*.
Answer: Com a versão 3.0 do AndoridStudio, temos o AAPT2 habilitado por padrão em todos os projetos.
Esse problema acontece em alguns projetos anteriores ao AS 3.0 quando o Manifesto do aplicativo não está corretamente estruturado. O AAPT2 obriga que o manifesto siga uma estrutura padrão.
Então, verifique o AndroidManifest.xml do seu aplicativo e tente corrigi-lo. Você também pode consultar esse guia da estrutura do arquivo do manifesto.
Basicamente, ele deve seguir essa estrutura (nem todas as TAGs são obrigatórias):
<?xml version="1.0" encoding="utf-8"?>

<manifest>

    <uses-permission />
    <permission />
    <permission-tree />
    <permission-group />
    <instrumentation />
    <uses-sdk />
    <uses-configuration />
    <uses-feature />
    <supports-screens />
    <compatible-screens />
    <supports-gl-texture />

    <application>

        <activity>
            <intent-filter>
                <action />
                <category />
                <data />
            </intent-filter>
            <meta-data />
        </activity>

        <activity-alias>
            <intent-filter> . . . </intent-filter>
            <meta-data />
        </activity-alias>

        <service>
            <intent-filter> . . . </intent-filter>
            <meta-data/>
        </service>

        <receiver>
            <intent-filter> . . . </intent-filter>
            <meta-data />
        </receiver>

        <provider>
            <grant-uri-permission />
            <meta-data />
            <path-permission />
        </provider>

        <uses-library />

    </application>

</manifest>

Se mesmo assim não funcionar, você pode desabilitar o AAPT2 no gradle.properties adicionando/alterando a linha:
android.enableAapt2=false

Comment: Perfeito, muito obrigado ao adicionar o código android.enableAapt2=false funcionou
Comment: Fico feliz em saber que pude ajudar. Mas gostaria de reforçar que essa solução não resolve o problema, apenas o esconde. Recomendo que você procure saber mais sobre o AAPT2 e tente corrigir definitivamente essa falha.


What is the best way to make a parent program that runs and manage multiple child programs in Python?

Question: I have a Python program that runs facial recognition service. The program comes with a Tornado server that serves a UI so I can see the recognition result. I have a few IP cameras and I want each of these cameras to have separate recognition service.
What I did right now is:
import subprocess
import user_config

port = 9000
for cam in user_config.CAMERA_ID:
    command = "python recognition.py -camid "+cam+" -port "+str(port)
    p = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE)
    port = port+1

Is this a good way to do this? If let say one of the processes died, how do I check and bring it back up?
Comment: Not too surprisingly, using the [multiprocessing](https://docs.python.org/3/library/multiprocessing.html#module-multiprocessing) module would be good approach.
Comment: You can use [`Popen.poll()`](https://docs.python.org/3/library/subprocess.html#subprocess.Popen.poll) to check if a subprocess is still running and, if not, respawn it. But given that you're running a Python process, why not just import the file and run it directly via [`multiprocessing`](https://docs.python.org/3/library/multiprocessing.html), or even [`threading`](https://docs.python.org/3/library/threading.html) if its main function is I/O bound.
Answer: You have two options:

multiprocessing

run a function in an other process, you can give args through args and kwargs.
you can use shared Variable and Array with this strategy

subprocess

run an other script with the command line, you can pass args in the string and get them back through sys.argv


Qual objeto tem melhor desempenho? SqlDataSource ou DataTable?

Question: Em questão de desempenho, velocidade, ou ate segurança, qual o melhor objeto para ser utilizado como um DataSource?
Exemplo, Estou criar um DataSource, para popular um GridView:
Por SqlDataSource:
this.sqlDataSource1.ConnectionName = "sql brayton max";
        this.sqlDataSource1.Name = "sqlDataSource1";
        columnExpression7.ColumnName = "id";
        table3.MetaSerializable = "0|0|125|100";
        table3.Name = "NotaFiscal.Cidades";
        columnExpression7.Table = table3;
        column7.Expression = columnExpression7;
        columnExpression8.ColumnName = "cd_uf";
        columnExpression8.Table = table3;
        column8.Expression = columnExpression8;
        columnExpression9.ColumnName = "ds_cidade";
        columnExpression9.Table = table3;
        column9.Expression = columnExpression9;
        selectQuery3.Columns.Add(column7);
        selectQuery3.Columns.Add(column8);
        selectQuery3.Columns.Add(column9);
        selectQuery3.Name = "NotaFiscal_Cidades";
        selectQuery3.Tables.Add(table3);
        this.sqlDataSource1.Queries.AddRange(new DevExpress.DataAccess.Sql.SqlQuery[] {
        selectQuery3});
        this.sqlDataSource1.ResultSchemaSerializable = resources.GetString("sqlDataSource1.ResultSchemaSerializable");

Por DataTable:
DataTable cli = new DataTable();

        string sqconn, _sql;

        sqconn = ConfigurationManager.ConnectionStrings["sql brayton max"].ConnectionString;

        _sql = @"SELECT id,cd_uf,ds_cidade FROM NotaFiscal.Cidades";

        SqlConnection con = new SqlConnection(sqconn);

        try
        {
            SqlCommand cmd = new SqlCommand(_sql, con);

            con.Open();

            cmd.CommandType = CommandType.Text;

            SqlDataAdapter da = new SqlDataAdapter(cmd);

            da.Fill(cli);
        }
        catch
        {

        }

Comment: Apenas para sua informação: [DataTable: A Inimiga Oculta](http://thiagolunardi.net/2015/03/datatable-a-inimiga-oculta/);
Answer: Na verdade depende. Eu diria que usar um DataSource (vai usar com DataReader, né?). O jeito de usar um ou outro vai determinar mais sobre a performance. DataTable é um objeto muito complexo e muita gente nem usa mais. Se usar errado qualquer um pode ser lento.
A única forma de saber é preparar testes de acordo com o que vai utilizar e verificar por conta própria de acordo com sua necessidade. Sempre é assim, se fizer diferença, porque é provável que nem faça. Problemas de performance se resolvem com técnicas específicas, dificilmente uma tecnologia fará tanta diferença (até faz, mas em casos extremos, quando todo o resto já foi feito).
Comment: Não estamos falando de segundo, talvez nem de milissegundo.
Comment: Depende :P Não vi, pode por na pergunta, pode fazer uma resposta (desde que não seja só o *link*)
Comment: Entendo. agora me surgiu uma duvida, hoje utilizo o DataTable, para popular alguns GridView, é melhor utilizar um DataReader com Dictionary?
Comment: Então, depende do que precisa. O `DataTable` pode ser mais fácil, mas ligeiramente mais lento. Faz diferença? Acho que não. Eu nunca o usei.
Comment: Perfeito, estou utilizando banco em nuvem, então todo segundo é questionável, vou realizar alguns testes obrigado.
Comment: Certo, uma duvida, achei uma pagina na que descreve bem detalhado essa duvida, seria melhor somente deixar o link? ou fazer uma respostar colocando a fonte de dados?
Comment: @ThomasErichPimentel O DataReader tem uma função bem específica que é processar um grande volume de dados, somente à frente, somente leitura. Ele é rápido nesta função porque você pode começar a processar os registros antes mesmo de eles terem sido completamente retornados do banco, e você não precisa de uma RAM do tamanho da quantidade de registros porque eles podem ser descartados assim que processados. O DataTable tem uma função completamente distinta: trabalhar com todos os dados em memória, de maneira desconectada. Usar datareader p/ mandar todos os registros para um grid não faz sentido.
Answer: A questão é desempenho/velocidade? Então a resposta é NENHUM.
Ambos são extremamente lentos e custosos para serem alocados, resolvidos, populados, lidos, etc. São objetos muito completos, porém com complexos metadados.
O melhor? Listas! Definitivamente.
Acesso seu banco de dados apenas com ADO.NET, usando apenas um IDataReader. Popule sua lista e finalize o DataReader e passe sua lista para o GridView.DataSource.
Escrevi um artigo sobre isso: DataTable - A Inimiga Oculta. Título careta, mas o conteúdo é muito relevante. Tudo explicando porquê deve-se evitar usar DataTable.
Comment: Thiago obrigado, vou ler seu artigo.


ML test accuracy higher than training? Small unbalanced samples were stratified by class

Question: My background is in ecology, it is common to have smaller sample sizes and class imbalances and ML approaches are still increasingly adopted. My specific dataset: training set is 49 sample, my test set is 16 samples - total 65 samples. I have also used loocv (not reported in the table) where I observed similar pattern.
My class proportions are as such across 6 classes, when I stratify it 75-25%, it is to make sure class 5 (rare class) is represented in training-test split and stratified k-folds as well for loocv and 5-fold cv:
class 1: 19 samples
class 2: 9 samples
class 3: 9 samples
class 4: 15 samples
class 5: 5 samples
class 6: 8 samples
I know accuracy is low in general - I have attempted to optimize it better using different variable selection methods, etc. I understand its not suitable for ML in general but technically, I was curious what the issue could be - just the size of samples, should stratification be done different for training-test split, etc.
All analysis in R programming environment.
Thank you in advance.
Answer: I am almost certain this is just pure luck. With only 16 samples, there is very little stability in results. Another way to think about it is that the improvement from train to test is not statistically significant (probably).
I would be curious to see the CV results, where you would at least have 65 samples. With such a small data set, I would a) stick with simpler, regularized models (don't do ANNs), and b) inject as much subject matter expertise as you can. Maybe you can just pick features based on your intuition on which ones should be important, since you don't have the luxury of extra validation data to do variable selection (and even if you did, differences in the results of different feature sets could just random noise).


Datatable Server Side não faz paginação, ordenação nem pesquisa

Question: beleza? Então, estou passando o processamento da minha datatable para serverside, devido a lentidão extrema com alto volume de dados. Os dados estão sendo retornados via json encode perfeitamente, porém, a paginação, ordenação e a pesquisa da datatable não estão funcionando. Alguém poderia me ajudar? Segue códigos abaixo.
Código Html + Jquery

      Id Empresa
      Cidade
      Estado

Código PHP da página table_server_processing.php
<?php
/**
 * Script:    DataTables server-side script for PHP 5.2+ and MySQL 4.1+
* Notes:     Based on a script by Allan Jardine that used the old PHP mysql_* functions.
*            Rewritten to use the newer object oriented mysqli extension.
* Copyright: 2010 - Allan Jardine (original script)
*            2012 - Kari Söderholm, aka Haprog (updates)
* License:   GPL v2 or BSD (3-point)
*/

mb_internal_encoding('UTF-8');

/**
 * Array of database columns which should be read and sent back to DataTables. Use a space where
 * you want to insert a non-database field (for example a counter or static image)
 */

$aColumns = array( 'id_empresa', 'cidade', 'estado' );

// Indexed column (used for fast and accurate table cardinality)

$sIndexColumn = "id_empresa";

/* DB table to use */
$sTable = "cadastro_fornec";

/* Database connection information */
$gaSql ['user'] = "connect@cubo";
$gaSql ['password'] = "4c3sso4lm0xcub0c0nn3ct";
$gaSql ['db'] = "voucher";
$gaSql ['server'] = "192.168.20.16";

// Input method (use $_GET, $_POST or $_REQUEST)

$input =& $_GET;

/** * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
 * If you just want to use the basic configuration for DataTables with PHP server-side, there is
 * no need to edit below this line
 */

/**
 * Character set to use for the MySQL connection.
 * MySQL will return all strings in this charset to PHP (if the data is stored correctly in the database).
 */
$gaSql['charset']  = 'utf8';

/**
 * MySQL connection
 */

$db = new mysqli($gaSql['server'], $gaSql['user'], $gaSql['password'], $gaSql['db']);
if (mysqli_connect_error()) {
    die( 'Error connecting to MySQL server (' . mysqli_connect_errno() .') '. mysqli_connect_error() );
}

if (!$db->set_charset($gaSql['charset'])) {
    die( 'Error loading character set "'.$gaSql['charset'].'": '.$db->error );
}

/**
 * Paging
 */
$sLimit = "";
if ( isset( $input['iDisplayStart'] ) && $input['iDisplayLength'] != '-1' ) {
    $sLimit = " LIMIT ".intval( $input['iDisplayStart'] ).", ".intval( $input['iDisplayLength'] );
}

/**
 * Ordering
 */
$aOrderingRules = array();
if ( isset( $input['iSortCol_0'] ) ) {
    $iSortingCols = intval( $input['iSortingCols'] );
    for ( $i=0 ; $i<$iSortingCols ; $i++ ) {
        if ( $input[ 'bSortable_'.intval($input['iSortCol_'.$i]) ] == 'true' ) {
            $aOrderingRules[] =
            "`".$aColumns[ intval( $input['iSortCol_'.$i] ) ]."` "
                    .($input['sSortDir_'.$i]==='asc' ? 'asc' : 'desc');
        }
    }
}

if (!empty($aOrderingRules)) {
    $sOrder = " ORDER BY ".implode(", ", $aOrderingRules);
} else {
    $sOrder = "";
}

/**
 * Filtering
 * NOTE this does not match the built-in DataTables filtering which does it
 * word by word on any field. It's possible to do here, but concerned about efficiency
 * on very large tables, and MySQL's regex functionality is very limited
 */
$iColumnCount = count($aColumns);

if ( isset($input['sSearch']) && $input['sSearch'] != "" ) {
    $aFilteringRules = array();
    for ( $i=0 ; $i<$iColumnCount ; $i++ ) {
        if ( isset($input['bSearchable_'.$i]) && $input['bSearchable_'.$i] == 'true' ) {
            $aFilteringRules[] = "`".$aColumns[$i]."` LIKE '%".$db->real_escape_string( $input['sSearch'] )."%'";
        }
    }
    if (!empty($aFilteringRules)) {
        $aFilteringRules = array('('.implode(" OR ", $aFilteringRules).')');
    }
}

// Individual column filtering

for ( $i=0 ; $i<$iColumnCount ; $i++ ) {
    if ( isset($input['bSearchable_'.$i]) && $input['bSearchable_'.$i] == 'true' && $input['sSearch_'.$i] != '' ) {
        $aFilteringRules[] = "`".$aColumns[$i]."` LIKE '%".$db->real_escape_string($input['sSearch_'.$i])."%'";
    }
}

if (!empty($aFilteringRules)) {
    $sWhere = " WHERE ".implode(" AND ", $aFilteringRules);
} else {
    $sWhere = "";
}

/**
 * SQL queries
 * Get data to display
 */
$aQueryColumns = array();
foreach ($aColumns as $col) {
    if ($col != ' ') {
        $aQueryColumns[] = $col;
    }
}

$sQuery = "
    SELECT SQL_CALC_FOUND_ROWS " . str_replace ( " , ", " ", implode ( ", ", $aColumns ) ) . "
    FROM `".$sTable;

$rResult = $db->query( $sQuery ) or die($db->error);

// Data set length after filtering

$sQuery = "SELECT FOUND_ROWS()";
$rResultFilterTotal = $db->query( $sQuery ) or die($db->error);
list($iFilteredTotal) = $rResultFilterTotal->fetch_row();

// Total data set length

$sQuery = "SELECT COUNT(`".$sIndexColumn."`) FROM `".$sTable."`";
$rResultTotal = $db->query( $sQuery ) or die($db->error);
list($iTotal) = $rResultTotal->fetch_row();

/**
 * Output
 */
$output = array(
        "sEcho"                => intval($input['sEcho']),
        "iTotalRecords"        => $iTotal,
        "iTotalDisplayRecords" => $iFilteredTotal,
        "aaData"               => array(),
);

while ( $aRow = $rResult->fetch_assoc() ) {
    $row = array();
    for ( $i=0 ; $i<$iColumnCount ; $i++ ) {
        if ( $aColumns[$i] == 'version' ) {
            // Special output formatting for 'version' column
            $row[] = ($aRow[ $aColumns[$i] ]=='0') ? '-' : $aRow[ $aColumns[$i] ];
        } elseif ( $aColumns[$i] != ' ' ) {
            // General output
            $row[] = $aRow[ $aColumns[$i] ];
        }
    }
    $output['aaData'][] = $row;
}

echo json_encode($output);

Comment: Já viste os exemplos deles? Não estás a conseguir adaptar?https://datatables.net/examples/data_sources/server_side.html,https://datatables.net/extensions/scroller/examples/initialisation/server-side_processing.html
Comment: Este exemplo que estou usando retirei da documentação do Datatable. Ele só não está fazendo a ordenação, paginação e pesquisa, mas o retorno dos dados está funcionando ok.
Answer: Você precisa utilizar na sua query principal as partes do SQL que o script monta e que vão efetivamente fazer suas devidas funções, algo como:
$sQuery = "
    SELECT SQL_CALC_FOUND_ROWS " . str_replace ( " , ", " ", implode ( ", ", $aColumns ) ) . "
    FROM `".$sTable . $sWhere . $sOrder . $sLimit;

Comment: Jader, primeiramente, obrigado pela ajuda. Essas partes seria o que? Não entendi muito bem...
Comment: @TiagoMartins elas complementam a consulta com a busca, ordem e paginação, procure as variáveis $sWhere, $sOrder e $sLimit no código e veja como elas são definidas para entender melhor...
Comment: consegui resolver seguindo sua dica, valeu! A minha variável `$sQuery` funcionou da seguinte maneira.

`$sQuery = "SELECT SQL_CALC_FOUND_ROWS ".str_replace(" , ", " ", implode(", ", $aColumns))."
FROM $sTable
$sWhere
$sOrder
$sLimit";`


User View List in Drupal filter by taxonomy

Question: In a social website powered by Drupal, Users are allowed to add interest tags into a taxonomy terms by autotagging.
My problem is how to create a view page to list all users based on a certain interest in the term list.
Say, I need to display user interested on PHP.
Comment: Is your tagging done on your profile by a term relationship field ?
Answer: You can accomplish this using the views module. Its the Drupal GUI way to build queries so you will be able to crate a page that lists all users based on the field you need.
Here goes a really good reference that may help you with that:
http://nodeone.se/en/taming-the-beast-learn-views-with-nodeone
If you prefer to get your hands dirty you can use the Entity Field Query
Comment: Here goes a question about views tutorials that may be helpful too: http://drupal.stackexchange.com/questions/673/where-is-a-detailed-tutorial-on-views


Is anybody already reviewing edits?

Question: For review you need 1000 rep - but we do not have any user so far with such reputation.
What is currently happening to edits?
Comment: I had an edit made to one of my questions and it was accepted by a few different users.  I'll try and find their usernames.  I also submitted an edit and it was accepted but I'm not sure by who.
Comment: Looks like this was just a tag edit: http://magento.stackexchange.com/posts/419/revisions
Answer: The reputation requirements are lowered both during the private and the public beta to allow more users to bootstrap these activities. But while the most avid users are building up reputation (even at these reduced levels), the Community Team at Stack Exchange takes care of these functions for the early community.
That's why we say it is so important to Vote Early, Vote Often. A site needs on-going, sustained voting to build a class of core users who help run and govern the site. Voting, editing, closing, and other self-moderation privileges are the primary mechanism through which the community governs the site on a day to day basis.

Is anybody already reviewing edits?


Can I use a two proportion z-test?

Question: I have a response, "Satisfaction" that goes on a scale from 0-10 (where 0=dissatisfied and 10= very satisfied), and I have a predictor variable that also uses the same scale. I recoded the response so that 0-5 is "not satisfied" and 6-10 is "satisfied". I did the same for the predictor variable. I used SPSS to get the frequencies for each (there are 4 different combinations). My question is, can I use a two proportion z-test to test whether there is a significant difference in the predictor at the two different levels of my response?
Thank you
Comment: Closely related: [What is the relationship between a chi square test and test of equal proportions?](http://stats.stackexchange.com/q/2391/930)
Comment: In general, it's best to perform analysis with the highest resolution data available. By regrouping your 0-10 data into binary categories, you're losing out on the more textured data in the 0-10 scale.
Comment: @DJE I agree, but this is how they evaluate customer satisfaction here.
Comment: The logical follow-up would be to ask why they collect the 0-10 data in the first place, if the data will inevitably be collapsed into binary categories during the analysis... but I understand that one is sometimes constrained by structural circumstances.
Comment: @DJE That's a valid point, I guess they use it for other analysis. Would a two proportion z-test be appropiate in this case?
Comment: @chl You beat me to it.
Comment: See [this](http://stats.stackexchange.com/questions/2391/what-is-the-relationship-between-a-chi-square-test-and-test-of-equal-proportions) question (edit: ah, @chi already mentioned it), and [this](http://stats.stackexchange.com/questions/52927/alternative-nonparametric-test-for-chi-square-test-for-independence), [this](http://stats.stackexchange.com/questions/60916/chi-square-with-unbalanced-design) ... & others. There's also some potentially relevant information [here](http://stats.stackexchange.com/questions/57104/p-value-and-confidence-interval-for-two-sample-test-of-proportions-disagree/)
Answer: Yes. Indeed, a two-proportion z-test in this case is the same as a chi-square test on a 2x2 a contingency table where the cells are the number of events satisfying the pair of conditions. Alan Agresti, An Introduction to Categorical Data Analysis provides further information.

Can I use a two proportion z-test?


Returning single records per month

Question: I have a use case function that needs to returns a single row only for every end of month.
I tried using select distinct and it is showing multiple records for the same end of month
SELECT DISTINCT CASE
        WHEN eff_interest_balance < 0.01 THEN trial_balance_date
        WHEN date_paid < trial_balance_date THEN date_paid
    END as A
    , period
FROM dbo.Intpayments[enter image description here][1]
WHERE loan_number = 60023
ORDER BY period ASC

Each row should return single date for each month
Comment: . . Tag your question with the database you are using.  Also, provide sample data and desired results.
Answer: Distinct is returning unique rows, not grouping them.  You are looking to aggregate rows.  This means using some combination of aggregate functions and group by.
What your current query is missing is some sort of logic for aggregating the rows that are in the same period.  Do you want to compare the sum of these values?  The min, the max?
In any case, the basic idea of aggregating and grouping would look like this - I don't think this summing is what you want, but the query shows the basic idea of aggregating and grouping:
SELECT
    period
    , SUM(eff_interest_balance) AS SumOfBalance
FROM dbo.Intpayments
WHERE loan_number = 60023
GROUP BY period

Comment: Hi Snow, thank you I was thinking of using Max too because it needs to get the last payment date for the month
Comment: The important thing is that you need to consider that you are (potentially) operating on multiple rows.  So, everything you select needs to either be part of the grouping (listed in the group by) or aggregated in some way (sum, avg, min, max, etc....)
Comment: Here is the updated query... SELECT DISTINCT

 period, case when max (eff_interest_balance) < 0.01 THEN max (trial_balance_date)

when max (date_paid) < max (trial_balance_date) THEN max (date_paid) END as A

from dbo.Intpayments where loan_number =60023

group by period
Comment: Now the column is returning all nulls when it is suppose to be a date
Comment: again, you don't need distinct.  Though, this probably isn't the issue with your results.  You really need to provide some sample data in your original question.
Comment: Also, there seems to be a hole in your case logic - you specify two cases, but there is no default case for when the data doesn't meet the first two - this is likely the source of your nulls
Comment: Thanks Snow, I got the query to work now by taking out distinct and using GROUP. Next problem is I could not add that query to a view I created.

Returning single records per month


Cosmos DB fan out query issue

Question: I recently started moving our CosmosDB single partitioned collection to new logical partitioned collection. I am doing this in Phases, where I have already covered the all the create and update operation with the support of the transaction.
Now currently, I am going to fan out a query for all read operations and I will fix this fan out in few coming weeks. However, In my current scenario, I am having one issue in the query. Below is the code sample of my select using C# LINQ and then I will explain u my issue in few steps
Code without Partition key
using (var query = _client.CreateDocumentQuery<User>(_documentCollectionUri,
                    new FeedOptions { EnableCrossPartitionQuery = true })
                                          .Where(u => u.Email == emailAddress.ToLower())
                                          .AsDocumentQuery())
                {
                    if (query.HasMoreResults)
                    {
                        var response = await query.ExecuteNextAsync<User>();
                        return response.FirstOrDefault(); //always returning null
                    }
                }
                return null;

Now in the code above where no partition key is provided with cross partition query enabled it goes inside the if block but returning null all the time. To make sure that I have got the data in my collection, I checked the client query by doing the query.ToString() and ran the query in Azure DB explorer and it worked and returned the record but it is always returning null in my code above which tells me that something is wrong with the client or it is not working with cross partitioned query.
Code with Partition key
using (var query = _client.CreateDocumentQuery<User>(_documentCollectionUri,
                    new FeedOptions { EnableCrossPartitionQuery = true, PartitionKey = new PartitionKy("firstname.lastname@example.com") })
                                          .Where(u => u.Email == emailAddress.ToLower())
                                          .AsDocumentQuery())
                {
                    if (query.HasMoreResults)
                    {
                        var response = await query.ExecuteNextAsync<User>();
                        return response.FirstOrDefault(); //always returning null
                    }
                }
                return null;

Now this code given above is working fine.
Code to get client instance is below
_client = new DocumentClient
                        (
                            new Uri(Configuration["azureSettings:documentDb:endPoint"]),
                            Configuration["azureSettings:documentDb:key"],
                            _jsonSerializerSettings,
                            new ConnectionPolicy
                            {
                                EnableEndpointDiscovery = false,
                                ConnectionMode = ConnectionMode.Direct,
                                ConnectionProtocol = Microsoft.Azure.Documents.Client.Protocol.Tcp,
                            }
                        );

Answer: After waiting for a while and reply from the Azure Cosmos DB team. I now understand why my fanout query was not working. All I have to do is change the code a little bit to make sure it will keep looking for the data until the end and then bail out with a result or no result. So to get it to work I have changed the code below
if (query.HasMoreResults)
{
   var response = await query.ExecuteNextAsync<User>();
   return response.FirstOrDefault(); //always returning null
}

With the code
 var results = new List<MyClass>();
 while(query.HasMoreResults)
 {
     results.AddRange(await query.ExecuteNextAsync<MyClass>());
 }
 return results.FirstOrDefault(x => x.MyProp== propValue.ToLower());

Cosmos DB fan out query issue


Carrinho de compra armazenar no cliente ou server?

Question: Qual melhor forma de armazenar os itens de um carrinho de compra?
No próprio javascript, no lado cliente ou numa sessão no server, seja usando $_SESSION(php) ou Session["sessao"](C#)
Qual seria melhor? mais seguro e melhor usual para o usuário?
Comment: Qual linguagem de programação você está usando? PHP ou C#?
Answer: Na sessão ou em um cookie.
Se você salva no JavaScript, primeiro não vai funcionar se o usuário tiver desabilitado JavaScript, segundo se o browser ou o computador "travar" ele perde todo o seu carrinho (você pode mitigar isso usando localStorage - quando suportado).
Se você usa a sessão, aí depende: o que acontece se o usuário fecha o browser (intencionalmente ou não - mesmo caso acima)? Se todos os dados forem apagados ao final da sessão, então há o mesmo problema. E a performance pode ser pior, se você precisar acessar o banco de dados cada vez que o usuário incluir um item novo.
Usabilidade
Um problema comum com carrinhos de compra é o que acontece quando o usuário abre mais de uma aba ao mesmo tempo, ou usa o botão "Voltar" - nesses casos, o que está aparecendo na tela é uma coisa, o que realmente está no carrinho pode ser outra coisa. Pessoalmente, não sei qual será a expectativa do usuário: a) que o carrinho esteja exatamente igual ele está vendo na tela; ou: b) que o que ele fez numa aba esteja "salvo" de alguma forma, mesmo quando ele mexe na outra. A forma como você implementa tem impacto em um ou outro cenário.
O melhor que tenho a sugerir nesse caso é incluir um token aleatório nos formulários de submissão (por exemplo, como um hidden input) e sempre comparar esse token com aquele do carrinho antes de executar uma ação. Se forem diferentes, mostre a mesma página de novo pro usuário, atualizada - de modo que ele esteja vendo o carrinho correto antes da ação ser feita de fato.
Segurança
Se você estiver usando https como espero que esteja, não faz muita diferença como é armazenado. Você pode assinar os dados do cookie, no servidor, se quiser evitar que o cliente mexa nos valores inapropriadamente (inclusive, é assim que muitas frameworks fazem para manter dados da sessão num cookie - e não no BD - sem comprometer a segurança do site), mas isso pode nem ser necessário.
Comment: Muito boa sua explicação @mgibsonbr, só em relação aos cookie, se ele tentou fazer uma compra e fechou o site, é por que não quis naquela hora, então não vejo motivo dele deixar salvo sua ultima tentativa de compra, além que teria que expirar esse cookie depois de X tempo.

Acho a sessão uma forma bem válida, mas eu poderia usar objeto anonimo não ? para não ter que buscar sempre no banco aquele produto, o que acha? No mais muito bacana sua resposta
Comment: @Rod Pois é, eu não sei responder o que os usuários esperariam: manter salvo ou apagar tudo. Acho que cada um espera uma coisa diferente dos sites/programas... Quanto a usar "objeto anônimo", desculpe mas não sei do que se trata. Fala de alguma coisa na cache, em memória?
Answer: No server.
Um dos motivos seria que a variável Session evapora quando o usuário sai do site ou fecha o browser. Neste caso, seria interessante que o site "lembrasse" da última tentativa de compra feita pelo usuário.


LSI updater appears to have updated my Intel SSD, now cant recognise it - what to do?

Question: I have an LSI 9211 HBA and an Intel 910 SSD. I updated the firmware on the HBA, using LSI's usual sas2flash utility. I removed all other LSI/HBA cards first.
Unfortunately it now looks like the SSD also has the same controller internally, which I had no realistic way to know in advance, and now Intel's SSD toolkit won't recognise the SSD so I can't figure how to put it back as it was. Sas2flash -listall shows the SSD with P20 LSI bios.
What do I do?
Answer: That's unfortunate.
The Intel 910 PCIe SSD is comprised of multiple Intel SSDs behind an LSI2008 SAS controller. This is the same controller used by the LSI 9211 HBAs, so at some point in your flashing process, you were probably presented with a warning asking you which adapters should be flashed.
Did you ignore this? Did you just flash everything that came up during device discovery?
The best suggestion is to try to flash Intel software over the relevant card, or contact Intel support.
Comment: There wasn't any warning. If there had been, I'd have known immediately - and probably the updater would have aborted too. No warning - I checked I'd removed other HBAs and that my 9260 wasn't in there by mistake (I knew it wasn't but still checked), the only cards were an LSI HBA, an SSD and a Chelsio NIC, so I went ahead and updated. The command used for flashing is -fwall which flashes to all cards (and saves looking up a specific identifier when not needed), so its clearly important to remove any other HBAs and especially LSI cards, which I did. Nothing said "Intel card here, are you sure"
Answer: Apparently the correct answer was "talk to LSI, get told nothing will be done; talk to Intel, get told it can be replaced under warranty, send off 910 SSD, receive top-of-line P3700 in return" :)
The answer above got the key point though which was to speak to Intel