How to solve LEFT JOIN in SQL?

Question: I made query like this:
select a.NIM
     , k.IPK
     , m.nama Mayor
  from kelanjutanstudi k
  left
  join mahasiswamagister a
    on k.ID =a.MahasiswaID
  left
  join mayor m
    on m.ID = a.MayorID

when I tried to run it, the result is not as I expected. Because the result is like this

Actually, NIM and Mayor have their own value, but when I run the query, NIM and Mayor had NULL value. Maybe, there are something wrong with my sql code. Here is my tables:
mahasiswamagister table

kelanjutanstudi table

mayor table

Please help me to solve that problem. Thankyou
Comment: One way is change `LEFT JOIN` to `INNER JOIN`. But IMO I think you should check the relationship between your tables again (join column).
Comment: could you please show me where is the error in my join column? Because I couldn't find it @PhamX.Bach
Comment: The query itself has no error, but as in `LEFT JOIN` when it has no rows matches then in result all columns not from main table will be NULL, so either you data is mismatch, or you join with wrong columns
Comment: Make sure that both your IDs are of the same type and collation (in case of strings). Usually these issues appear when your columns look identical yet are physically different.
Comment: Refer this [answer](http://stackoverflow.com/a/20602850/7012137)
Comment: See http://meta.stackoverflow.com/questions/333952/why-should-i-provide-an-mcve-for-what-seems-to-me-to-be-a-very-simple-sql-query
Answer: change left join to Inner Join:
select
`mahasiswamagister`.`NIM` AS `NIM`,
`kelanjutanstudi`.`IPK` AS `IPK`,
`mayor`.`Nama` AS `Mayor`
from ((`kelanjutanstudi`
inner join
`mahasiswamagister`
 on((`kelanjutanstudi`.`ID` = `mahasiswamagister`.`MahasiswaID`)))
inner join
 `mayor`
on((`mayor`.`ID` = `mahasiswamagister`.`MayorID`)))

How to solve LEFT JOIN in SQL?


What motivates the dissonant minor third in the beginning of Respighi's Notturno?

Question: Ottorino Respighi's Notturno is a Nocturne that begins in the key of F#. A melody is played atop the chords, however in bar 7 the melody hits the A note, which is the minor 3rd of the F# scale:

This immediately creates dissonance and seems fully "out of context". I don't see an obvious "reason" for this dissonance.

What motivates this note in the composition?
Comment: Umm...that's not in F sharp is it.  Its in G flat.  So the A natural is actually a sharpened second not a minor third.
Answer: As JimM said in a comment, this piece is not in F♯ but in G♭. The A is thus the scale degree A♭, chromatically raised. It wants to resolve upwards to B♭.
If you want more motivation: the last harmony under the A is a chord with pitches (from lowest to highest) C♭E♭F A. Rearranging these to make a stack of thirds: F A C♭E♭. The A is, as I said, just A♭, chromatically raised. So without that chromatic alteration, we have F A♭C♭E♭, which is vii7. Or, if you prefer, V9 but rootless. Although it is not actually the chord of the dominant (it has no D♭), it resolves the way the dominant resolves, namely, to I.
And all this duly happens in the next bar after the passage you quoted.


Kerberos Event 4 servername showing username

Question: We have a .Net Windows Service that uses a Httplistener and authenticates requests using Kerberos. When users are connecting via their browser, an error in the users event log shows a Kerberos Event ID 4:

The Kerberos client received a KRB_AP_ERR_MODIFIED error from the
  server $username$. The target name used was HTTP/$servername$.$domain$.com.au.
  This indicates that the target server failed to decrypt the ticket
  provided by the client. This can occur when the target server
  principal name (SPN) is registered on an account other than the
  account the target service is using. Ensure that the target SPN is
  only registered on the account used by the server. This error can also
  happen if the target service account password is different than what
  is configured on the Kerberos Key Distribution Center for that target
  service. Ensure that the service on the server and the KDC are both
  configured to use the same password. If the server name is not fully
  qualified, and the target domain ($domain$.COM.AU) is different from the
  client domain ($domain$.COM.AU), check if there are identically named
  server accounts in these two domains, or use the fully-qualified name
  to identify the server.

For some reason the server that it is reporting is the user that is running the service. The first line:

The Kerberos client received a KRB_AP_ERR_MODIFIED error from the
  server $username$.

Every website (including Server Fault) has fixes for this error to do with SPN problems, but it always has a servername in the error. I cannot find the above message with a username.
We have tried different users and it changes the above part of the error message. All domain accounts have the same problem. If we run the service as the local system account we do not have this problem, but that causes us other problems with the service (it needs domain account for other permissions). We don't have, have never had, any servers with the same name as the usernames we've tried.
Has anyone seen this problem with the username appearing here before? What is the fix?
All of the servers are Windows 2012 (not R2).
Answer: Glad you solved your own problem, but it doesn't sound like you understand why what you ran solved the problem.
Bottom line, the SPN needs to be set on the appropriate object.  It sounds like you had the SPN set on the computer's object in AD that was running the service. That's why things started working if you changed the service to run as SYSTEM.  But if you change it to run as a domain user, you need to move the SPN to that user.  And it's important that you move it (read: delete it from the computer account) and not just copy it.  Duplicate SPNs will break things.
Comment: Thanks Ryan. We did revisit the problem a few days after the fix, and it came down to user permissions. I'm not 100% sure yet what permissions are required, but if we run the service as a domain admin then it registered the SPN properly. Once the SPN is registered we then set the service back to it's normal user account. Probably doesn't need to be a domain admin but we didn't bother working out what it did need.
Answer: Found the solution here: http://blogs.technet.com/b/dcaro/archive/2013/07/04/fixing-the-security-kerberos-4-error.aspx
I ran:
<code>setspn -A HTTP/$servername$.$domain$.com.au $username$
</code>
and that fixed the problem


(Vocal) Harmonizer Pedals: How do live performers use them?

Question: I've seen plenty of live musicians singing with a guitar, but recently I've been noticing that some of them were singing in harmony with themselves! Obviously, I soon realised it was the work of a stomp pedal. I assume it just took the input of the singer's voice and pitch-shifted it up or down by an interval (not the trivial intervals of octaves and fifths). My question is about how performers use those pedals.
Do they have to set it to a new key for every new song, since not all thirds are equal? How much control do the performers typically have over what notes are actually outputted? What kinds of scales can be chosen for the harmony?
Answer: The old way people use these pedals is to create a preset that specifies one key and how many harmony notes should be added and in some cases which diatonic intervals to add. So a preset might be in C major and always add a diatonic third above and fourth below (making a second inversion diatonic triad). When changing songs or changing keys in the middle of a song, you have to change presets.
The new way (made possible by newer technology) is to take a copy of your guitar signal and route it into an auxiliary input of the harmonizer that is there for exactly this purpose. The harmonizer analyzes the chord being played on the guitar and creates vocal harmonies that match the chord. This technology usually supports MIDI keyboard inputs also or instead. Some harmonizers let you play the exact harmony chord you want on the keyboard and it creates the other vocal doubles necessary to create that chord.
Of course if you prefer the preset method, you can still use that on modern harmonizers.
Comment: The harmonizer pedals don't really know or care if the harmony source instrument is a guitar, or if the "vocal" is really a vocal or a sax or a lawnmower. A keyboard works just as well as the harmony source and can give the harmonizer more notes to snap to. If the harmony source only plays a power chord and the "vocal" only sings the chord's root note, then the harmonizer won't be able to generate a third, because it won't know if it should be a major or minor third. It also won't be able to add a constant third (or any other interval) above/below, if/when it doesn't know what the scale is.
Comment: @eric_kernfeld By analyzing the sound, they don't have optical sensors to "see" the frets. Also, as pointed out, they can analyze the sound from other instruments besides guitar. It's a little bit like how autotune works, except instead of the pitch detection being used to change a pitch, it's used to generate new pitches.
Comment: @eric_kernfeld The harmonizer includes no microphones, only two separate inputs. One input is designed to accept the microphone for the voice, so it is usually an XLR input (for a mic cable). The other input is usually a 1/4" TS input to accept a guitar cable or cable from a keyboard. If you want to use a guitar that has no electronics, you could put up a mic and then plug that into a mic preamp and the plug that into the harmonizer, but there's a problem. The guitar mic will pick up other sounds that may confuse the harmonizer, so it's not recommended to use a guitar without a pickup.
Comment: Does it work by looking at where your hand is on the frets, or by parsing the sound coming from the guitar?
Comment: That makes sense. Are there two separate microphones then? One to fetch the chord from the guitar/piano and another to fetch the main note from the vocalist?
Answer: The early machines needed the song's key to be inputted. That in itself was problematic, in that then, it would only reproduce diatonic notes. Which was fine for most harmony - thirds, fifths, octaves. I worked with a band once that used one, and at a certain place in a song it sounded off. The singer accused the other two singers of being out of tune, until it was pointed out that the song had modulated slightly, and needed a M3 which was being 'sung' by the machine as m3, as it couldn't produce that!
Newer, much more successful machines have the guitar (usually) plugged into it as well. That gives it all or any of the notes that could be used as harmony at any point. So, if the song changes key, even, the machine 'hears' the chord played, and produces appropriate harmony on that basis - once it's been told there's a need for thirds, etc. Provided the guitarist plays exactly the correct chord...


Desmarcar todos os checkboxes ao voltar à página anterior

Question: Estou desenvolvendo um software e percebi uma falha: quando o usuário volta a página anterior, os checkboxes continuam marcados.
Como eu desmarco todos eles?
Comment: No checkbox adicione: `autocomplete="off"`
Comment: @juniorb2ss obrigado!! resolveu
Answer: Uma simples adição de código jQuery desmarca tudo, tanto no carregamento da página quanto em voltar à ela:
$("input[type='checkbox']").prop('checked', false);

Se os checkbox tiverem uma class em comum:
$("input.class").prop('checked', false); ou $(".class").prop('checked', false);
Ou pertencerem a uma div com um id:
$("#div input[type='checkbox']").prop('checked', false);

Ou num único form na página:
$("form input[type='checkbox']").prop('checked', false);

Vale lembrar que os métodos .removeAttr e .attr não funcionam para
  alterar propriedades checked ou disabled em versões mais recentes
  do jQuery.
Comment: @I_like_trains :D.. valeu!
Comment: Sua resposta é muito detalhada `up`
Answer: Como não informou se está utilizando jquery como framework em seu projeto estou considerando que sim, caso contrário edite o código as suas necessidades
<input type="checkbox" checked='true' class='check' name="tecnologia" value="java"/>JAVA
<input type="checkbox" checked='true' class='check' name="tecnologia" value="html"/>HTML
<input type="checkbox" checked='true' class='check' name="tecnologia" value="css"/>CSS
<input type="checkbox" checked='true' class='check' name="tecnologia" value="javascript"/>JAVASCRIPT

Após a leitura do DOM executar uma função por callback para desmarcar :
$(document).ready(function(){
    $(".check").removeAttr("ckecked");
}

lembrando que deve usar no onready para não ter chance de tentar remover o atributo checked sem ter carregado o html corretamente.
Answer: Quando a página carrega, use o código abaixo na página
Para versão de jQuery < 1.6
$(document).ready(function(){
  $("checkbox").attr('checked', false);
});

Para versão de jQuery > 1.6
$('#myCheckbox').prop('checked', false);

Comment: @GuilhermeNascimentoP. Como restauro?
Comment: @GuilhermeNascimentoP. Feito


Base fields vs Config fields?

Question: I have an entity and I am not sure what I should use. On the one hand, configuration fields are easier to use via the UI, why should I consider base fields?
By using base fields everything is stored in the same table, would there be any kind of performance improvement if I have many entities?
I can't find anywhere where it is explained why to opt for one or the other.
Thank you very much
Comment: Yes, that's it. It's not only easier to configure fields in UI, it's also easier to deploy the changes. If you change a base field in a module you need to write an update hook.
Comment: You should add that as an answer 4k4. But maybe word it as a pros and cons of each, for people to determine which better suits their needs and skills. Even though base fields are more of a hassle to maintain, for certain entity types I prefer to use them due to the architectural paradigm of it actually being a fundamental field to the entity, as well as the ensuing performance benefits. But the config fields are much easier to work with, and with entity caching removes the difference after initial load anyways.
Answer: Your question contains already the key points to consider. It's not only easier to configure fields in UI, it's also easier to deploy the changes. If you change a base field in a module you need to write an update hook.
On the other hand, if changes to the fields are unlikely and you expect a very high number of entities then use base fields like core for the alias entity.

Base fields vs Config fields?


Como organizar corretamente o DP e DPI para cada tipo de tela no Android?

Question: Existe algum tipo de fórmula ou jeito de saber os seguintes quesitos sem precisar ficar "buildando" toda hora para verificar?

Como saber se aquela Imagem/Texto/Botão ou seja o que for fica visivelmente bom para o usuário na determinada tela que tem um tipo de dpi?
Como saber qual é o dp que eu preciso para alinhar a Imagem/Texto/Botão ou seja oque for para ficar corretamente no (Header, Footer, Centro, Direita ou Esquerda) corretamente para cada tela.

O conhecimento que eu tenho é o seguinte:

ldpi (baixa) ~ 120 dpi
mdpi (média) ~ 160 dpi
hdpi (alta) ~ 240 dpi
xhdpi (extra-alta) ~ 320 dpi
xxhdpi (extra-extra-alta) ~ 480 dpi
xxxhdpi (extra-extra-extra-alta) ~ 640 dpi

Pixel independente de densidade (dp): A conversão das unidades de pixel em pixels de tela é simples: px = dp * (dpi / 160)
Answer:
Existe algum tipo de fórmula ou jeito de saber os seguintes quesitos sem precisar ficar "buildando" toda hora para verificar?

Não existe "fórmula" mas existe um jeito de saber sem "precisar ficar "buildando" toda hora".
Na Toolbar da aba do Editor de layouts do Android Studio tem a opção de escolher o dispositivo usado para fazer o render do layout.

É assim possível verificar como o layout é apresentado em vários dispositivos. Existe também a possibilidade de escolher a orientação do dispositivo, a versão do Android e o Theme a aplicar.
O uso da unidade dp ou dpi(que são a mesma coisa) garante que views, margins, padding, etc sejam renderizadas com as mesmas dimensões, qualquer que seja a densidade da tela do dispositivo.
Isso garante que, por exemplo, um botão tenha as dimensões necessárias para poder ser clicado ou que o conteúdo duma imagem possa ser perceptível, qualquer que seja a densidade de tela.
Outra questão é a existência de diferentes tamanhos de tela. São as dimensões dela que determinam o número de views que se conseguem colocar tanto na vertical como na horizontal, podendo haver situações que será necessária a criação de layouts alternativos.
Como complemento veja Como suportar vários tipos de ecrãs/telas.
Comment: eu entendo em relação ao verificar sem compilar utilizando o preview do editor de layous no próprio Android Stúdio. Porém o problema é que estou utilizando um SDK de Realidade Aumentada chamada vuforia. E no layout a tela é toda preta, pois estou utilizando um layout de "camera" onde a camera do celular fica ligado. Não tenho como verificar pelo Layout e nem pelo AVD, pois o AVD ele builda certinho porém não abre o emulador, não acontece nada. Como consertar isto?
Comment: Não tenho nenhuma experiência com o vuforia, por isso não posso ajudá-lo. Exponha esse problema em uma nova pergunta.
Answer: Mas o conceito de DP é justamente feito pra isso, manter o mesmo tamanho das views entre diferentes resoluções de tela. Por exemplo, se você tem aparelhos com a mesma proporção de tela (por exemplo, 16:9) mas resoluções diferentes, as view sempre irão aparecer do mesmo tamanho. Claro que em aparelhos com proporções de tela diferente, tipo um tablet, que não necessariamente é 16:9, as views não irão mudar de tamanho, mas irá sobrar ou faltar tela em relação ao app rodando numa tela com proporção diferente.
Você pode testar diversas configurações de tela no próprio Android Studio sem compilar. Na tela de preview do editor de layouts você sempre pode trocar o aparelho target na combobox dessa janela que mostra o nome de um aparelho.
Comment: eu entendo em relação ao verificar sem compilar utilizando o preview do editor de layous no próprio Android Stúdio. Porém o problema é que estou utilizando um SDK de Realidade Aumentada chamada vuforia. E no layout a tela é toda preta, pois estou utilizando um layout de "camera" onde a camera do celular fica ligado. Não tenho como verificar pelo Layout e nem pelo AVD, pois o AVD ele builda certinho porém não abre o emulador, não acontece nada. Como consertar isto?


issue with sort data

Question: i am developing an app in which i get data from server and display in map. but before display it on map's balloon i have just sort data by one field name is "Destination" and there are method made na,e is ..GOTOSORT....
now problem is i got variables s with length 1 and there for the for loop are run only 1 time , but there are 42 data are come from webservices so please check it and tell me what is the problem
private void GOTOSORT() {

        Log.i(TAG, " SORT ");
        Map<Float, Integer> map = new TreeMap<Float, Integer>();

        for (int i = 0; i < lng_timeStamp.length; ++i) {
            map.put((float) lng_timeStamp[i], i);
        }
        Collection<Integer> indices = map.values();
        System.out.println("indices" + indices);
        Integer s[] = (Integer[]) indices.toArray(new Integer[0]);

        Log.i(TAG, "s.length"+s.length);
        for (int i = 0, n = s.length; i < n; i++) {
            System.out.println(s[i]);

            int_sort_MyhourGetTime[i] = int_MyhourGetTime[s[i]];
            int_sort_MyMinGetTime[i] = int_MyMinGetTime[s[i]];
            lng_sor_timeStamp[i] = lng_timeStamp[s[i]];
            arr_sort_ServiceNumber[i] = arr_ServiceNumber[s[i]];
            arr_sort_Destination[i] = arr_Destination[s[i]];

        }

Comment: Use `indices.size();` in foe loop
Comment: its not getting me any effect
Comment: here i have print indices size and it getting me 1
Comment: here case it i have take `lng_timeStamp` for sorting and all data of that are 302, suppose from 0 index to last index it getting me same and it come from webservices. now problem is.....
Comment: it is overwrite as per my think
Answer: If you want to sort your list , you should follow the Java's comparatorFollow here
It will return you a sorted list in any order.
All the best !! :)

issue with sort data


Getting contents of square brackets, avoiding nested brackets

Question: (first time poster, long time visitor via Google)
I'm trying to extract the contents of some square brackets, however i'm having a spot of bother. I've got it working for round brackets as seen below, but I can't see how it should be modified to work for square brackets. I would have thought replacing the round for square and vice versa in this example should work, but apparently not.
It needs to ignore brackets within brackets. So it won't return (11) but will return (10(11)12).
<code>$preg = '#\(((?>[^()]+)|(?R))*\)#x';
$str = '123(456)(789)(10(11)12)';

if(preg_match_all($preg, $str, $matches)) {
    $matches = $matches[0];
} else {
    $matches = array();
}

echo '<pre>'.print_r($matches,true).'</pre>';

This returns:

Array (
    [0] => (456)
    [1] => (789)
    [2] => (10(11)12)
)
</code>
Which is perfect. However, how can I get this working for a string with square brackets instead e.g:
<code>$str = '123[456][789][10[11]12]';
</code>
Comment: When I run this example on my machine, I actually don't get any matches.  PHP 5.2.6
Comment: Your example for rounded brackets doesn't work for me.
Comment: hmm you're right, i've obviously broken something in my testing, i'll recheck the curly brackets method, perhaps that's why I couldn't get it working for square brackets.
Comment: The working regex for curly brackets is '#\(((?>[^()]+)|(?R))*\)#x'. The one posted is one I took elsewhere from my Googling, my mistake in posting in the question.
Comment: Do you need to handle the case of multiple nested brackets, such as in "[12[34[56]78]90]"?
Comment: Yes, that's basically my problem. If it is [12][34[56]] I only want to return; [12] and [34[56]]. I don't want [56].
Answer: <code>$preg = '#\[((?>[^\[\]]+)|(?R))*\]#x';
</code>
Comment: That doesn't appear to work either, unless my test code is wrong somewhere. Here's the code and the response:

  $preg = '/\[(?:[^\[\]]+¦(?R))*\]/';
  $str = '123[456][789][10[11]12]';

  if($count = preg_match_all($preg, $str, $matches)) {
    $matches = $matches[0];
  } else {
    $matches = array();
  }

  echo $count.''.print_r($matches,true).'';

Returns:

0

Array
(
)
Comment: @Alix Axel: It is composed of `(?R)` and the `)*` on the end is a part of the larger expression.
Comment: I copy-pasted your sample and modified the parts necessary to handle the other braces. However, as you must have seen in the meantime (you fixed it), the code sample of yours had the wrong pipe character.
Comment: This regex works for me.  Testing it at http://www.spaweditor.com/scripts/regex/ yields exactly the result I expect.
Comment: Thanks that's perfect now. Sorry about the late reply. End of the day over here. For anyone finding this in the future, I don't know if it could be improved performance wise by making sure it only returns the one array, rather than the second as well. But apart from that perfect, answer accepted.
Answer: Try this:
<code>$str = '123[456][789][10[11]12]';
$pattern = '/(([\d]+)|(\[[\d]+\])|\[[\d\[\]]+\])/';
preg_match_all($pattern,$str,$matches);
print_r($matches[0]);
//or
$str = '123[456][789][10[11]12]';
$pattern = '/(([\d]+)|(\[[\d]+\]))/';
preg_match_all($pattern,$str,$matches);
print_r($matches[0]);
</code>
Comment: Thanks for this, but the first one appears to be limited to a certain depth. For instance try this: [123][456][789][10[11]12][141516][somethingelse].

The second one seperates nested brackets out. So doesn't work at all in that regard.


Merge rows with duplicated values into list in corresponding column

Question: How do I merge multiple rows into one row , where  duplicated values into one row and unique values list inside multiple columns
The input dataframe is as follows
Name  num1    num2   key  filter1  filter2
TOM    1.1     2.1    a      T      F
TOM    1.1     2.1    b      T      F
TOM    1.1     2.1    c      T      F
TOM    1.1     2.1    d      T      F
SAM    1.2     2.1    a      F      T
SAM    1.2     2.1    b      F      T

This is the code I have written, But it dont solve the issue. Help me write a simple code to get the final dataframe
df_temp = df.groupby(['Name','num1','num2'])['key'].apply(list).reset_index()
df_temp_2 = df.groupby(['Name','num1','num2'])['filter1'].apply(list).reset_index()
df_temp_3 = df.groupby(['Name','num1','num2'])['filter2'].apply(list).reset_index()

df1 = df_temp.merge(df_temp2)
final_df = df1.merge(df_temp3)

Output
Name  num1  num2  key           filter1         filter2
TOM    1.1   2.1  [a, b, c, d]  [T, T, T, T]    [F, F, F, F]
SAM    1.2   2.1  [a, b]        [F, F]          [T, T]

Answer: IIUC
df = df.groupby(['Name', 'num1', 'num2'], as_index=False, sort=False).agg(list)
  Name  num1  num2           key       filter1       filter2
0  TOM   1.1   2.1  [a, b, c, d]  [T, T, T, T]  [F, F, F, F]
1  SAM   1.2   2.1        [a, b]        [F, F]        [T, T]

Comment: Thank you, I get ValueError("no results") error. Should I convert any datatypes
Comment: @VamsiNimmalaV i  am not sure what kind of data type you have in your real data
Comment: I have object, float64 and bool dtypes. Should I convert any of them.


Is it possible to compute this using Euler? $\frac{(\cos 1 + \cos 89)(\cos 2+\cos 88)\cdots(\cos 44 + \cos 46)}{\cos 1\cos 2\cdots\cos 44}$

Question:
Is it possible to compute this using Euler?
$$\dfrac{(\cos(1) + \cos (89))(\cos(2)+\cos(88))...(\cos(44) + \cos(46))}{\cos(1)\cos(2)...\cos(44)}$$

I have easily computed this problem using trigonometric identities but I'm looking for a way where Euler is used. I used the fact that $\cos(x) = \dfrac{e^{ix} +e^{-ix}}{2}$. Surprisingly, there's no negative term.
Comment: Are these numbers supposed to be be in degrees or radians?
Comment: Use $\cos (a+b) + \cos (a-b)$ to simplify it...
Comment: In degree, exactly.
Answer: Use http://mathworld.wolfram.com/ProsthaphaeresisFormulas.html
$\cos x+\cos(90-x)=2\cos45\cos(45-x)$ for $1\le x\le44$
Alternatively
$\cos x+\cos(90-x)=\cos x+\sin x=\sqrt2\cos(45-x)$
Comment: Isn't $2 \cos 45$ also $\sqrt 2$?
Comment: @MohammadZuhairKhan, Where has it been refuted?
Comment: My apologies, I didn't notice `alternatively`


SQL Server - Second highest sales query

Question: I'm working on this question:

Show the manufacturer with the 2nd top sales in the year of 2009 and the manufacturer with the 2nd top sales in the year of 2010.

I tried finding the 2nd top manufacturer in terms of sales but I got a lot of errors. Can someone please explain where I went wrong?
Here is my code:
select
  top 1 dim_date.year,
  dim_model.idmanufacturer,
  sum(fact_transactions.totalprice)
from
  (
    select
      top 2 dim_date.year,
      dim_model.idmanufacturer,
      sum(fact_transactions.totalprice)
    from
      fact_transactions
      join dim_date on dim_date.date = fact_transactions.date
      join dim_model on dim_model.idmodel = fact_transactions.idmodel
    where
      dim_date.year = 2009
    Group by
      dim_date.year,
      dim_model.idmanufacturer
    Order by
      sum(fact_transactions.totalprice) Desc
  ) RESULT
Order by
  sum(fact_transactions.totalprice);

And here are the error messages:
Msg 8155, Level 16, State 2, Line 77
No column name was specified for column 3 of 'Result'.
Msg 4104, Level 16, State 1, Line 65
The multi-part identifier "dim_date.year" could not be bound.
Msg 4104, Level 16, State 1, Line 65
The multi-part identifier "dim_model.idmanufacturer" could not be bound.
Msg 4104, Level 16, State 1, Line 65
The multi-part identifier "fact_transactions.totalprice" could not be bound.
Msg 4104, Level 16, State 1, Line 77
The multi-part identifier "fact_transactions.totalprice" could not be bound.

Comment: give name to selected column sum(fact_transactions.totalprice) test
Comment: @DeepakKumar - this doesn't help still got errors
Answer: Use the below code and let me know if any error occur.
SELECT TOP 1 year,
             idmanufacturer,
             test
FROM   (SELECT TOP 2 dim_date.year,
                     dim_model.idmanufacturer,
                     Sum(fact_transactions.totalprice) test
        FROM   fact_transactions
               JOIN dim_date
                 ON dim_date.date = fact_transactions.date
               JOIN dim_model
                 ON dim_model.idmodel = fact_transactions.idmodel
        WHERE  dim_date.year = 2009
        GROUP  BY dim_date.year,
                  dim_model.idmanufacturer
        ORDER  BY Sum(fact_transactions.totalprice) DESC) RESULT
ORDER  BY test;

If there is any issue then please create SQL fiddle.
Comment: This ran properly just ORDER  BY Sum(fact_transactions.totalprice);  by Test

What is the reason for that as the codes look identical ?
Comment: Also if I add an IN operator          WHERE  dim_date.year = 2009  to where dim_date.year in (2009,2010) will it give me a result for both years ? Or still give me an error ?
Comment: There is difference of scope. In inner query you have all tables. But outer query you have one table(wrapper table) RESULT. So fact_transactions.totalprice will not work
Comment: In operator will work fine. No issue in that. Just identify the scope. Logic you know better than me. Cheers :)
Comment: Thanks a lot Deepak !
Answer: limit 1,1 for 2nd element, limit 2,1 for 3rd element and so on..
Can you please try this.
select dim_date.year, dim_model.idmanufacturer, sum(fact_transactions.totalprice) from fact_transactions join dim_date on dim_date.date = fact_transactions.date join dim_model on dim_model.idmodel =fact_transactions.idmodel where dim_date.year = 2009 Group by dim_date.year, dim_model.idmanufacturer Order by sum(fact_transactions.totalprice) Desc ) RESULT Order by sum(fact_transactions.totalprice) limit 1,1;

Comment: I think something is missing in the code
Msg 102, Level 15, State 1, Line 99
Incorrect syntax near ')'.
Comment: LIMIT is not valid in SQL Server, instead use TOP or ROW_NUMBER()
Answer: Just use offset/fetch:
select dim_date.year,
  dim_model.idmanufacturer,
  sum(fact_transactions.totalprice)
from
  fact_transactions
  join dim_date on dim_date.date = fact_transactions.date
  join dim_model on dim_model.idmodel = fact_transactions.idmodel
where
  dim_date.year = 2009
Group by
  dim_date.year,
  dim_model.idmanufacturer
Order by
  sum(fact_transactions.totalprice) Desc
offset 1 fetch first 1 row only;

This ANSI/ISO standard functionality has been available since SQL Server 2012.  Here is one place to learn more about it.
Answer: You're probably trying to do something similar to this :
SELECT
  [year]
, Manufacturer
, TotalPrice
FROM (
SELECT *
, ROW_NUMBER() OVER(PARTITION BY idmanufacturer ORDER BY [year] ASC, TotalPrice DESC) RN
FROM (
    SELECT
      dim_date.year
    , dim_model.idmanufacturer Manufacturer
    , SUM(fact_transactions.totalprice) TotalPrice
    FROM
        fact_transactions
    JOIN dim_date  ON dim_date.date = fact_transactions.date
    JOIN dim_model ON dim_model.idmodel =fact_transactions.idmodel
    where
         dim_date.year IN(2009,2010)
    GROUP BY
      dim_date.year
    , dim_model.idmanufacturer
 ) RESULT
) D
WHERE
    RN = 2

The steps :

Get the SUM of TotalPrice for each manufacture in year 2009 and 2010.
Order the results using ROW_NUMBER() to get an order number that can be selected easily.
Finalize the results by selecting the 2nd top sales for each Manufacturer.

Explanation :
The first query :
SELECT
  dim_date.year
, dim_model.idmanufacturer Manufacturer
, SUM(fact_transactions.totalprice) TotalPrice
FROM
    fact_transactions
JOIN dim_date  ON dim_date.date = fact_transactions.date
JOIN dim_model ON dim_model.idmodel =fact_transactions.idmodel
where
     dim_date.year IN(2009,2010)
GROUP BY
  dim_date.year
, dim_model.idmanufacturer

Will summarize all dim_model.idmanufacturer transactions in year 2009 and 2010 and would sum up total price for each idmanufacturer in that period.
Then, we enclose it in a sub-query so we can reorder the results to our advantage using ROW_NUMBER() and order the results (number them) by year and total price for each idmanufacturer.
SELECT *
, ROW_NUMBER() OVER(PARTITION BY idmanufacturer ORDER BY [year] ASC, TotalPrice DESC) RN
FROM (
    SELECT
      dim_date.year
    , dim_model.idmanufacturer Manufacturer
    , SUM(fact_transactions.totalprice) TotalPrice
    FROM
        fact_transactions
    JOIN dim_date  ON dim_date.date = fact_transactions.date
    JOIN dim_model ON dim_model.idmodel =fact_transactions.idmodel
    where
         dim_date.year IN(2009,2010)
    GROUP BY
      dim_date.year
    , dim_model.idmanufacturer
 ) RESULT
) D

This method would expand our chances from getting the results that we need in any position we want. For your request, we will get the second top sale (which is the second row) for each Manufacturer. So if they asked you to get the 3rd, 5th, or even the 10th. You can just reuse the same query and just change the rn from 2 to whatever position you want.
Comment: Could You please explain
"GROUP BY
      dim_date.year
    , dim_model.idmanufacturer
 ) RESULT
) D
WHERE
    RN = 2"
What is ")D" here ?
Answer: Use row_number()
select
  dim_date.year,
  dim_model.idmanufacturer,
  sum(fact_transactions.totalprice)
from
  (
    select
      row_number() over ( order by sum(fact_transactions.totalprice) desc ) as rowNumber,
      dim_date.year,
      dim_model.idmanufacturer,
      sum(fact_transactions.totalprice) as total
    from
      fact_transactions
      join dim_date on dim_date.date = fact_transactions.date
      join dim_model on dim_model.idmodel = fact_transactions.idmodel
    Group by
      dim_date.year,
      dim_model.idmanufacturer
  ) RESULT
where
  RESULT.rowNumber = 2

Answer: This should work for sql-server:
select
    res2.*
from
    (
    select
        *,
        DENSE_RANK() OVER (
    ORDER BY
        res1.price ) rank_price
    from
        (
        select
            dim_date.year,
            dim_model.idmanufacturer,
            sum(fact_transactions.totalprice) price
        from
            fact_transactions
        join dim_date on
            dim_date.date = fact_transactions.date
        join dim_model on
            dim_model.idmodel = fact_transactions.idmodel
        where
            dim_date.year = 2009
        Group by
            dim_date.year,
            dim_model.idmanufacturer ) res1 ) res2
where
    rank_price = 2;

SQL Server - Second highest sales query


Turn off "unreachable code after return statement" warning

Question: In JavaScript development, I frequently return from execution to have an inartificial breakpoint:
var args = arguments;
return console.log(args); // debug
criticalProcessing(args);

Chrome and others are okay with it, but unfortunately for debugging in Firefox:

Starting with Gecko 40 (Firefox 40 / Thunderbird 40 / SeaMonkey 2.37), a warning is shown in the console if unreachable code is found after a return statement.

Firefox' about:config provides quite some flags to adjust the development environment. Sadly, I didn't find a corresponding setting (nor a solution elsewhere).
Is there a way to turn of the "unreachable code after return statement" warning?
Comment: This is a problem because some libraries like bluebird optimize for Chrome and putting an eval after the return statement makes the V8 engine run faster.
Comment: @ForestG https://stackoverflow.com/questions/24987896/how-does-bluebirds-util-tofastproperties-function-make-an-objects-properties
Comment: @user2867288 can you show maybe any proof on this? We are facing the same issue but require some citation before closing bugtickets for the customer - but I fail to find any.
Answer: The only way I know of getting around this warning is to put a condition that's always true in the return line:
function myFun() {
     var args = arguments;

     if (1) return console.log(args);

    // unreachable code goes here
    criticalProcessing(args);

}

Turn off “unreachable code after return statement” warning


Multiple Date Argument Values with One Contextual Filter

Question: I have a pretty simple view in D7:
Fields

nid
title

Contextual Filters

nid
date (from date, monthly granularity)

Now I'd like to fetch some results for a specific node, but across multiple months. I was hoping to be able to pass in the contextual filter arguments via the url like so:
123/201302+201303

This isn't working for me though. Is this even possible with Date fields in Views ? I heard it was only possible with term ids right now.
Are there other techniques to accomplish this? Perhaps hook_views_query_alter() is in order here.
Comment: did you try views_embed_view('viewname', 'display_name', array(123,'201302+201303'))?
Comment: Thanks for the suggestion about views_embed_view, I will give that a try next time. For now, I ended up just going with a hook_views_query_alter and modifying the where condition to span across both months. I did this because I am using Panels to place the view on the page, and didn't want to render the view via code.
Answer: Try with the following method using views_embed_view():
views_embed_view('viewname', 'display_name', array(123,'201302+201303'));

Or by using a hook_views_query_alter and modifying the where condition to span across both months.


Using LVS (Linux Virtual Server) for doing DNS HA

Question: I have been trying to create an LVS DNS HA using CentOS 6.x:

Piranha GUI to configure the DNS
Pulse is the HA heart of CentOS LB
IPTables to configure marks on the packets since DNS uses TCP and UDP 53

After several days, I find that I can not figure out how to make it work - and I was hoping that someone has either the lvs.cf file avaiable along with all iptables rules necessary.  Or if someone has already used some other OpenSource & Free software that allows to do DNS LB (not round robine DNS A records - that's not what the purpose of this exercise is for).
If anyone has successfully made named DNS under LVS with two or more real-servers within the pool, work, I would greatly appreciate if the configurations could be posted:

lvs.cf
iptables rules to place

I am primarily looking for either Direct Server Return or NAT - either solution will work for me.
Thank you in advance.
Jim.
Comment: DNS is already HA (or at least it should be). You shouldn't need LVS. What is the problem you are trying to solve?
Comment: Have you attempted this setup? If so, you should post some more information about your setup (example configuration, network layout, obfuscated IP addresses).
Comment: Have a look [at this](http://serverfault.com/questions/669441/load-balancing-dns-servers-udp-tcp) as well.
Comment: I see value in doing this.  As mentioned, DNS is HA, sortof.  It depends on the client resolver timeout if a NS fails to respond.  This typically has a 1 to 5 second timeout.  Some folks understandably don't accept this timeout as a valid failure or degraded condition.   It realy depends on their needs.  With LVS or Anycast, you can make it appear that 1 IP never goes down.  I would personally go the Anycast route.
Answer: You should be able to configure DNS load balancing pretty easily with LVS in DR mode. Personally I would use Ldirectord rather than Piranaha (which is old and buggy), but either should work.
Like you said you will need to configure your firewall mark for the correct TCP and UDP ports, then load balance all packets that are marked to your backend server(s). I assume you won't need persistence for DNS (wouldn't work for UDP anyway).
I think the step you are probably missing is to allow the backend servers to respond to the traffic you are sending - commonly know as the ARP problem. If you have Windows servers then use this method. Or for Linux the simplest method is to use an iptables redirect:
<code>iptables -t nat -A PREROUTING -p tcp -d <VIP> -j REDIRECT
</code>
Its explained in more detail on page 21 of the http://loadbalancer.org quick start guide.
If you need any help, post your config and I'll take a look.
Comment: Why `tcp` in `-p tcp`?
Comment: Just habit, Most people use TCP, if you want to use UDP as well, then just remove the -p tcp bit.


Blueprint (XML DSL) in Apache Camel does not let me use PATCH

Question: I want to use a PATCH verb for my endpoint but I keep getting errors.
I'm replacing some of the links because SO is not letting me post the message because the filter thinks this is spam and I'm adding a pastebin link because I can't post the XML in any other way.
From what I've seen, my Camel version (2.15.1.redhat-621084) supports using PATCH (older versions prior to 2.11.X didn't allow it, from what I've read), although that shouldn't even be an issue because I think the problem is with the XML validation itself.
IntelliJ also warns me that I can't use PATCH there.
The error I have when I start the bundle in Fuse (karaf) is:
<code>Caused by: org.xml.sax.SAXParseException: cvc-complex-type.2.4.a: Invalid content was found starting with element 'patch'. One of '{"http://camel.apache.org/schema/blueprint":verb, SAMEURL:delete, SAMEURL:get, SAMEURL:head, SAMEURL:post, SAMEURL:put}' is expected.
</code>
My blueprint.xml (with some information redacted) is
https://pastebin.com/rd3Ukj65
I can get it to work if I change the endpoint definition to
<code>            <verb
                    uri="/users/{userId}/X"
                    method="PATCH"
                    produces="application/json"
            >
                <to uri="direct:updateX"/>
            </verb>
</code>
But I shouldn't have to define a new verb just to use a patch.
Can someone help me out understanding what I'm missing here?
Answer: No this is correct in that old Camel version. PATCH was not included at the time, and you can use the generic verb to define it yourself


Is there a limit to the number of DHCP scopes I can have?

Question: Some context:
Currently all devices in our remote sites are setup on 1 VLAN. We have 400 remote sites.
A project wants to split our sites into multiple VLAN's which on the whole seems like a good idea because they will be able to prevent PC's from talking to POS devices and so on.
In the current proposal, they have 5 VLAN's per site that will require DHCP.
We have 2 centralized DHCP servers for the entire environment which means I will go from having 400 scopes to 2000 scopes.  Each scope is part of a Windows Server 2012 R2 DHCP Failover cluster so the numbers actually double in each case.
My questions are:

Is there a limit to the number of DHCP Scopes I can deploy to a
Windows Server 2012 R2 server?  If there is, I'll need to consider adding more DHCP servers now.
Is there another way to do my DHCP config so I can cut down on the number of scopes?
Am I over thinking this considering we can now manage DHCP via PowerShell? We use PowerShell to manage the scopes already so we do have a level of automation we can apply.

Any advice or guidance will be appreciated.  Please let me know if I need to clarify anything.
Thanks,
Chris
Comment: `A project wants to split our sites into multiple VLAN's which on the whole seems like a good idea` - Well I'd say they better have some pretty solid justification for it, not just because `it seems like a good idea`. Don't implement things just because you think you should or because someone tells you that you should. What are the technical/business reasons for taking on a project of this size? This is going to require changes to your `entire` network infrastructure.
Comment: It'll be phased over 18 months or more and all that equipment is being refreshed so now is the time.  PCI and other local governance requirements are the one driver and some other business requirements are the others.
Answer: 1 - Is there a limit to the number of DHCP Scopes I can deploy to a Windows Server 2012 R2 server? If there is, I'll need to consider adding more DHCP servers now.
According to this: http://social.technet.microsoft.com/Forums/windowsserver/en-US/759becd0-9fbe-44e6-aac8-6f50036294c2/windows-2008-r2-x64-dhcp-server-maximum-scope-?forum=winserverNIS
There is no limit.
2 - Is there another way to do my DHCP config so I can cut down on the number of scopes?
This depends on your requirements. Do all sites have the same 5 VLAN's (Globally, 5 VLAN's), or are they separate each? (5x 400)? Do all sites need their own IP Space? How exactly are they connected? Depends on a lot of stuff.
3 - Am I over thinking this considering we can now manage DHCP via PowerShell? We use PowerShell to manage the scopes already so we do have a level of automation we can apply.
I'd definitely use PS in favor of Point on Click on this task :) And it should not be that complicated to do this using a script.
Comment: Thank you - you answered my main question.  To answer your question - it's 5 X 400 and each needs it's own IP space.  3 VLAN's in each site need DHCP.  I'm feeling a lot more comfortable now.
Answer: As answered earlier there no limit on number of scopes that may be added.
Microsoft DHCP server has been tested up to a maximum of 50,000 scope.
But again it depends on hardware capacity of your server. Please check following link more information regarding scalability options.
https://blogs.technet.microsoft.com/teamdhcp/2012/12/15/scalability-test-results-for-windows-server-2012-dhcp-server/


@RequiredRole com BaseCertLoginModule

Question: O meu sistema faz a autenticação do cliente (é um web service) por meio do BaseCertLoginModule, uma classe do JBoss baseada na especificação JaaS. Na verdade meu projeto estende essa classe, e essa extensão é chamada a cada requisição para decidir se o usuário tem acesso ou não ao web service. Faço isso pegando o serial da requisição (SSL two-way) e fazendo uma pesquisa no banco de dados com esse serial.
Isso tudo (autenticação) está funcionando legal. O que eu queria agora é resolver a autorização. Queria usar a anotação @RequiredRole, pois já defino os roles do usuário em meu LoginModule. Achei que seria só fazer isso:
@Override
@WebMethod
@RequiredRole("MASTER")
public void cancelarLaudo(CancelamentoLaudoRequest cancelamentoLaudoRequest)...

Aonde cancelarLaudo é uma operação de meu web service SOAP.
Mas não funcionou. :)
O que mais eu teria que fazer? Eu já li as documentações do Demoiselle, mas não ficou claro como eu faria isso funcionar junto com o esquema de LoginModule que eu já tenho.
Meu LoginModule:
package br.gov.serpro.sislvws.security.loginmodule;

import java.security.Principal;
import java.security.acl.Group;
import java.security.cert.X509Certificate;

import javax.persistence.NoResultException;
import javax.security.auth.login.LoginException;

import org.jboss.logging.Logger;
import org.jboss.security.SimpleGroup;
import org.jboss.security.SimplePrincipal;
import org.jboss.security.auth.spi.BaseCertLoginModule;

import br.gov.frameworkdemoiselle.util.Beans;
import br.gov.serpro.sislv.entity.CertificadoDigital;
import br.gov.serpro.sislv.entity.Entidade;
import br.gov.serpro.sislv.persistence.EntidadeDAO;

public class SislvLoginModule extends BaseCertLoginModule {

    private Logger logger = Logger.getLogger(this.getClass());

    private EntidadeDAO entidadeDAO;

    public SislvLoginModule() {
        entidadeDAO = Beans.getReference(EntidadeDAO.class);
    }

    @Override
    protected Principal createIdentity(String arg0) throws Exception {
        X509Certificate certificate = (X509Certificate) getCredentials();
        try {
            Principal principal = new SislvPrincipal(certificate);
            log.info("Usuário identificado: " + principal);
            return principal;
        } catch (Exception e) {
            String message = "Falha ao tentar autenticar o certificado " + certificate.toString();
            logger.error(message, e);
            throw e;
        }
    }

    @Override
    protected Group[] getRoleSets() throws LoginException {

        CertificadoDigital certificado = certificado();

        try {
            Entidade entidade = entidadeDAO.findBy(certificado);
            String role = entidade.getTipoEntidade().toString();
            SimpleGroup roles = new SimpleGroup("Roles");
            SimplePrincipal user = new SimplePrincipal(role);
            roles.addMember(user);
            return new Group[] { roles };
        } catch (NoResultException e) {
            String msg = certificado + " não autorizado a acessar o web service.";
            logger.error(msg);
            throw new LoginException(msg);
        } catch (Exception e) {
            logger.error("Erro inesperado durante a autenticação", e);
            throw new LoginException();
        }
    }

    private CertificadoDigital certificado() throws LoginException {
        SislvPrincipal identity = null;
        try {
            identity = (SislvPrincipal) getIdentity();
            CertificadoDigital cert = new CertificadoDigital();
            cert.setCommonName(identity.getCommonName());
            cert.setSerial(identity.getSerial());
            cert.setCommonNameEmissor(identity.getCommonNameEmissor());
            return cert;
        } catch (Exception e) {
            logger.error("Erro inesperado durante a autenticação", e);
            throw new LoginException();
        }
    }

}

Configuração do JBoss pra ativar o LoginModule:
            <security-domain name="SislvSecurityDomain">
                <authentication>
                    <login-module code="br.gov.serpro.sislvws.security.loginmodule.SislvLoginModule" flag="required">
                        <module-option name="verifier" value="org.jboss.security.auth.certs.AnyCertVerifier" />
                    </login-module>
                </authentication>
                ...

Answer: Opa, a principal coisa que tava faltando era ativar o interceptor RequiredRoleInterceptor no beans.xml. Além disso, eu estendi a classe ServletAuthorizer do Demoiselle para implementar o método hasRole. E, por fim, essa classe foi registrada no demoiselle.properties.
Agora a solução está funcionando, mas ainda queria melhorar um aspecto.
Eis a minha classe autorizadora:
    package br.gov.serpro.sislvws.ws.autorizacao;

    import javax.enterprise.context.RequestScoped;
    import javax.inject.Inject;

    import br.gov.frameworkdemoiselle.security.ServletAuthorizer;
    import br.gov.serpro.sislvws.security.loginmodule.RequestAutenticado;

    @RequestScoped
    public class RoleBasedAuthorizer extends ServletAuthorizer {

        private static final long serialVersionUID = 1L;

        @Inject
        private RequestAutenticado requestAutenticado;

        @Override
        public boolean hasRole(String role) throws Exception {
            String tipoEntidade = requestAutenticado.getEntidadeCliente().getTipoEntidade().toString();
            return tipoEntidade.equals(role);
        }

    }

Nessa solução, há uma repetição da lógica para se definir o papel do "usuário" logado. Essa lógica aparece getRoleSets do login module e no hasRole do autorizador. O que eu acharia melhor é se a definição do role ficasse apenas do login module, e se no autorizador eu conseguisse resgatar qual role já foi definido lá no login module.
Tentei buscas como "(jboss|jaas) retrieve role define on login module", mas ainda não consegui resolver.

@RequiredRole com BaseCertLoginModule


Fourier Transform of $v(x)=\frac{e^{ix}}{1+9x^2}$

Question: For a function $u(t)$, its Fourier transform is $\widehat{u}(x) = \int_{\mathbb{R}} u(t) e^{-itx} dt$.
I have to calculate a Fourier Transform of $v(x)=\dfrac{e^{ix}}{1+9x^2}$.
I know that the Fourier transform of $\dfrac{1}{1+x^2}$ is $\pi e^{-|x|}$. But it doesn't help me to calculate the Fourier transform of $v$. I really don't know how to do it.
Could someone help me ? Thank you in advance.
Comment: You could try substituting $3x$ for $x$ and then using a translation to deal with the complex $e$-power.
Answer: Let $\hat f$ be the Fourier transform of $f$.
$$f(x)=\frac{1}{1+x^2},~~~\hat f(\omega)=\pi e^{-|\omega|}$$
$$g(x)=f(3x)=\frac{1}{1+9x^2},~~~\hat g(\omega)=\frac1{|3|}\hat f\left(\frac\omega 3\right)=\frac{\pi e^{-|\omega|/3}}{3}$$
$$h(x)=g(x)e^{ix}=\frac{e^{ix}}{1+9x^2},~~~\hat h(\omega)=g(\omega-1)=\frac{\pi e^{-|\omega-1|/3}}{3}$$
This result is what also Mathematica says:
<code>Integrate[Exp[I x]/(1 + 9 x^2) Exp[-I t x], {x, -\[Infinity], \[Infinity]}]
ConditionalExpression[1/3 E^(-(1/3) Abs[-1 + t]) \[Pi], t \[Element] Reals]
</code>


Lilypond to MusicXML to Sibelius

Question: Is there any reliable program to convert a fully-fledge piece in Lilypond format to MusicXML, such that Sibelius can read the original Lilypond notation?
Basically, I need to edit a score which is written in Lilypond, but cannot import it in Sibelius. Frescobaldi is not an option, need graphical editing (I'm unfamiliar with the Lilypond notation).
Update: Frescobaldi 2.0.13 has an option to export as MusicXML, which has dissapeared in higher versions, but it fails to export the score I'm using.
Comment: @user1044 Except that since LilyPond's native syntax is an easy-to-understand text format, it's actually *not* a dead end. The native formats of Sibelius and Finale, OTOH, are proprietary binary formats, and are dead ends except to the extent that MusicXML export works. Now, I absolutely think that LilyPond should export MusicXML. But calling it a dead end because it doesn't is not accurate in this case.
Comment: @ToddWilcox, MusicXML isn't "owned" *per se* by MakeMusic any longer. Beginning last year, they are transitioning it over to "open-source" management and further development by the World Wide Web Consortium (W3C). https://www.w3.org/community/music-notation/
Comment: MusicXML is a "rosetta stone" that can be used to get a score document created in one music scoring program translated and ported into another different program. There are dozens of programs that can read and write MusicXML. However, Lilypond stands alone in that it cannot output MusicXML. While Lilypond undoubtedly produces excellent music scores, this is the reason that I've never used it. When you create an elaborate score in Lilypond, it's a dead-end. You can't port the document to any other platform. I do all my work in Sibelius and Finale and I can use MusicXML to go between the two.
Comment: Note that there is another standard for a UI markup language owned by Adobe called "MXML", so to prevent confusion some people refer to the free licensed music format owned by MakeMusic as "MusicXML".
Answer: from a terminal on your mac or linux box:

pip install python-ly
ly musicxml myscore.ly > myscore.musicxml

more information on ly:
http://python-ly.readthedocs.io/en/latest/command.html#commands
When I read that the state of the art workflow for this involves rendering your score to PDF and then scanning back in with music OCR, I kind of blew milk out my nose.
Comment: According to the documentation this is "in development, far from complete" and may only work for simple lilypond files. It totally fails with complex scores and also the conversion of simple scores does not necessarily lead to usable results. Maybe a solution is to put single voices into a simple lilypond score and copy this parts to the target program.
Comment: For simple scores this method works. Alternatively you can export to midi (from lilypond or frescobaldi) and direcly import the midi file into musescore and then export to musicxml
Answer: At the current point of time, the answer boils down to "no" for practical purposes.  Try going via Midi instead.
Unfamiliarity with the LilyPond notation, particularly if you already have access to a score for modification, can be cured by looking in the manual.  Graphical editors don't magically teach you everything either.
There is the note editor Denemo which uses LilyPond as its typesetting backend but I have no clue how much of a chance you'd have actually importing existing LilyPond source: LilyPond output and input are two different things.
Comment: @alephzero, No! I own both PDFtoMusicPro and the full version of PhotoScore. PDFtoMusicPro is a very poor quality product that produces lousy results and I regret having purchased it. PhotoScore is a much more capable product.
Comment: MIDI discards most of the expressiveness in the original score, not really an option. Graphical editors are way easier to use for musicians, you understand what's going on.
Comment: There is unlikely to be any useful information in the LilyPond input file which doesn't appear on the output score - Lilypond playback is (by design) rudimentary. So for practical purposes, you are starting from a PDF of the score, not from the LilyPond input. Siblelius comes with a "lite" version of PhotoScore which will  scan from the PDF, so you don't need MusicXML at all. Since you can easily get a PDF from LilyPond, http://www.myriad-online.com/en/products/pdftomusicpro.htm will probably work better than PhotoScore, and is cheaper!
Comment: @WheatWilliams I don't question your personal experience with PDFtoMusicPro, but there are several people on the Sibelius forum who claim it is more accurate than PhotoScore, *provided the PDF was created direct from a notation program* - i.e. the PDF is *not* just a set of raster-scanned page images. But PhotoScore does seem to have improved dramatically over the latest one or two releases. Maybe it has now caught up.
Comment: @alephzero, this is not my experience. I have owned PDFtoMusic Pro for **five years** and it has been useless to me from the start. I have tried many scores with it as each new update came out. I always get errors and glitches that are so severe that it would have taken me less time to simply type the score into Sibelius from scratch. I have owned PhotoScore Ultimate for **seven years** and it has *always* worked better than PDFtoMusic Pro.
Answer: Your goal is to get from Lilypond to Sibelius. MusicXML is an intermediary step.
I have had success by using an elaborate (and expensive) workaround: Take PDF scores created by Lilypond, or any other engraving program, and run them through music optical character recognition (OCR) using the commercial program Neuratron PhotoScore Ultimate. The output from PhotoScore is then sent to Sibelius, where you can edit it further.
PhotoScore Ultimate costs US $250.
(PhotoScore can output MusicXML, and Sibelius can input and output MusicXML, but with PhotoScore you can output directly to Sibelius, which works better. In this workflow, MusicXML is an optional extra step.)
The PhotoScore process is never perfect, and anything done with PhotoScore will require careful editing to correct inaccuracies in reading the images. One needs to develop some skill in using the process, finding the errors, and correcting them. I have been doing this for years and I am good at it. But first-time users of PhotoScore tend to be disappointed because they have unreasonable expectations about how it works.
I say it is worth a try. But it costs money, and it will only be worth your while if you have a lot of scores to convert on a regular basis.
Update
Sibelius comes bundled with a "lite" version of PhotoScore which is limited in its capabilities and can only scan simple scores. But you can try it out on what you have and see if you can get the hang of it. Then you can buy PhotoScore Ultimate for US $250 if you think it is worth it.
PhotoScore can use OCR to scan any printed paper score which has been put on a scanner and made into a bitmapped PDF (with variable results depending on the quality of the engraving and the quality of the scanned image). It can also work with a PDF which was generated directly from a music scoring program without going through paper and scanning (often with very good results).
There is a competing product called PDFtoMusic Pro made by Myriad Software which can only handle the latter case -- a PDF made directly from a music scoring program without going through paper and scanning. It cannot process bitmaps. Its output is MusicXML, and it has no features integrating it with Sibelius per se. I have owned PDFtoMusicPro for several years, through several updates, and I must say that it has always been inferior to PhotoScore Ultimate. PDFtoMusic Pro does a very poor job at what it is designed to do, and produces a great deal of errors and baffling glitches. I have never found a single score that PDFtoMusic Pro could handle anywhere near as well as PhotoScore could. I would not waste my time with PDFtoMusic Pro if I were you. I regret having paid US $200 for it.
Comment: While I agree with @welch that going via OCR is a very heavy-handed way of doing it, a friend has told me that ScoreMuse does a good job if you can afford it. But if you can afford Sibelius....
Answer: There is a better option now available for this (June 2021). The steps are as follows:

Clone this project to your local machine https://github.com/openlilylib/oll-core
Clone this project to your local machine https://github.com/openlilylib/lilypond-export
Set the include path for lilypond to point to the parent folder which contains the two projects above. In Frescobaldi this can be done by opening Preferences > Lilypond Preferences
Add the following lines at the top of the file:

\include "oll-core/package.ily"
\loadPackage lilypond-export

opts.exporter = #exportMusicXML

Update the \layout command to be like so:

    \layout{
            \FileExport #opts
    }

Now when running the file through Lilypond it should also produce a .xml file. I find the results to be better than the output from python-ly.
The developer of this plugin has some discussion about the challenges of allowing MusicXML export here:
Comment: Does anyone know how this is progressing? The GitHub files don't seem to have been updated since last year.
Comment: It doesn't seem to work for me using LilyPond 2.22.1 - I get an error: D:/Peter/Music/Lilypond/Toye/Silly/SillyS1.ly:228:5: error: not a context mod

    \FileExport #opts
Comment: I've added an example file here https://gist.github.com/xavriley/ec343c01eb2dd88de7982b85d265d673 which was working for me on 16th June 2021. @Peter can you double check that your file matches the structure in that example?
Comment: Thanks @xavriley. I found that I'd put the \FileExport inside a Score context in the layout block. I moved it outside but now get a different error message: init exportMusicXML: "SillyS1.xml"
init Staff 1
init Voice 1/soprano (1)D:/Peter/PC/Lilypond/OpenLilylib/lilypond-export/api.scm:278:48: In expression (ly:grob-properties grob):
D:/Peter/PC/Lilypond/OpenLilylib/lilypond-export/api.scm:278:48: Unbound variable: ly:grob-properties  I'll work out a small example and report back.
Comment: I've now got a tiny example and can't see any difference in layout between it and yours. \version "2.22.1"

\language "english"

\include "oll-core/package.ily"
\loadPackage lilypond-export

opts.exporter = #exportMusicXML

\score {
  \new Staff
  \new Voice
  {
    c'4 4 4 4
  }
}

\layout {
  \FileExport #opts

}
Comment: I copied your code into Frescobaldi,  updated it to the latest LP version, and I get the same error message. Something might have changed in LP but I've no idea what. If you can't help I'll try the LilyPond user mailing list to see if anyone there knows anything about it.
Comment: Thanks for the update - I'll have a look at this but it will be a couple of days before I'm back at the right computer. It sounds like something has changed in a recent LP version. If that's the case I'll try to track it down, otherwise I'll try to find a working version to pin to and edit the answer
Comment: I just tried it quickly - on my copy it initially threw an error about the Lilypond version. Changing it to `\version "2.19.0"` in your example script allowed it to work for me. I'm using commit `73029ae46` from `oll-core`
Comment: Thanks @xavriley I tried using 2.19.83 which is the earliest version of LP that I've got - I now get a completely different error - (lilypond-windows.exe:16628): Pango-CRITICAL **: pango_fc_font_lock_face: assertion 'PANGO_IS_FC_FONT (font)' failed   I think this has  nothing to do with the OpenLilyLib but is still not much use to me. It looks as if a later version of LP has broken the OLL code. Do you have a recent version of LP to try it on?
Comment: Brilliant, I have finally got a sensible MusicXML export from my simple Lilypond SATB score (though with Ukrainian lyrics). It's lost a few formatting things but that's all. (python-ly failed completely.) Thank you all very much.

Lilypond to MusicXML to Sibelius


Commerce module in not drupal commerce

Question: I have a website, built as a non Drupal commerce website. I want to add functionality to my website so customers can buy books, and add checkout page and cart.
I mean add commerce functionality in a not Drupal commerce site.
Can I do that?
Answer: Yes that is possible. Download the modules from: https://www.drupal.org/project/commerce
You can not install the install profile (https://www.drupal.org/project/commerce_kickstart) on top of an existing Drupal website.
Answer: You can just install commerce on top of a non-commerce drupal site in the beginning. Commerce for drupal core it is just another module that adds fields, views, rules, content types, functionality and so on.

Commerce module in not drupal commerce


Como incluir um botão em html a partir de um resultado em php

Question: REFORMULADO A PERGUNTA!
Gostaria da ajuda dos senhores, de como criar um botão, para copiar o resultado da função echo do PHP. Por exemplo:
Código em PHP
echo "Nome: " . $row_usuario['nome'] . "
";

Apareça isso para o usuário:
Nome: siclano da silva

Como poderia criar esse botão em HTML (podendo ser de outra forma) para copiar o resultado da saída da função echo da tela do navegador, onde esse copiar será para área de transferência, como se fosse CTRL + C / CTRL + V?
melhorando a minha pergunta, esse aqui é código em questão.
            Nome:
            <input type="text" name="nome" placeholder="Digite aqui">

            <input name="SendPesqUser" type="submit" value="Pesquisar">

        </form>

        <form>

        <input type="button" value="cadastra novo solicitante de crédito consignado" onClick="Nova()">

        <input type="button" value="Consultar crédito" onClick="Novo2()">

        <input type="button" value="Página Inicial" onClick="NovoInicial()">

        </form>

        <?php
        $SendPesqUser = filter_input(INPUT_POST, 'SendPesqUser', FILTER_SANITIZE_STRING);
        if($SendPesqUser){
            $nome = filter_input(INPUT_POST, 'nome', FILTER_SANITIZE_STRING);
            $result_usuario = "SELECT * FROM fornecedores WHERE nome LIKE '%$nome%'";
            $resultado_usuario = mysqli_query($con, $result_usuario);
            while ($row_usuario = $resultado_usuario->fetch_assoc()) {

                echo "Nome: " . $row_usuario['nome'] . "
";
                echo "Endereço: " . $row_usuario['endereco'] . "
";
                echo "Cep: " . $row_usuario['cep'] . "
";
                echo "E-mail: " . $row_usuario['email'] . "
";
                echo "Celular: " . $row_usuario['celular'] . "
";
                echo "Valor do crédito: " . $row_usuario['valor'] . "
";
                echo "Id: " . $row_usuario['id'] . "
";

                echo "Editar
";
                echo "Apagar

";
            }
        }
        ?>

https://ibb.co/h7b7TRb
O resultado seria isso como conforme a imagem do link acima, a pessoa iria fazer uma pesquisa pelo banco de dados, ai o resultado que aparecera na tela, gostaria que fosse copiado via clipboard por um botão, pois a intenção é a pessoa copiar esse dados e depois lança em mensagem no whatsapp.
obs: sou iniciante no ramo de programação, peço desculpa por não saber ainda como me expressar de uma forma adequada com as minhas dúvidas, agradeço profundamente a ajuda do senhores.
meu nível de conhecimento é de muito esforço em querer aprender e muitas coisas posso ainda não entender.
Comment: Em resumo, você quer que quando clique num botão, execute um código PHP e o retorno desse código PHP vá para a área de transferência do usuário? Sua pergunta ficou um tanto confusa
Comment: Pelo que entendi ele quer que ao clicar em um botão execute um código em javascript que copie o conteúdo de algum elemento html para área de transferência.
Answer: Boa noite Claudio,
Neste caso você precisa colocar dentro de um while e dentro colocar alguma condicional, assim sempre que a condicional for atendida o botão aparecera. Ex:
$query = "SELECT * FROM TABLE_1 WHERE USER =".$user."";
$row =($query,$db)//query e conexão com o banco de dados
while($row['user'] == ".$id."){
echo"
Vê usuario//Vê um modal bootstap
//Poe um modal e faz o select dentro.
";
}
}
Comment: eu refiz a pergunta. incluindo mais elementos, agradeço pelo seu comentário.
Answer: Pelo que entendi, você deseja copiar um elemento html para área de transferência ao executar a ação de clique.
Se sua aplicação lida com browsers modernos, esses browsers possuem uma nova api que possui compatibilidade com a api clipboard.
Para executar esta ação de uma maneira que ela possua compatibilidade com a maioria dos browsers o ideal seria que seja feita uma implementação que possua compatibilidade com novos browsers e antigos.
Supondo que temos a tag html label com id='meuelemento' e o conteúdo saída e desejamos copiar o texto saída para área de transferência.
saida
<button type="button" onclick="copyToClipboardAction()">Area transferência</button>

Neste caso o valor saida, será copiado para a área de transferência.
Repare que utilizando este fluxo se o seu browser não possui implementação da api do clipboard (browsers antigos) ocorrerá um erro.
Então a maneira ideal de tratar isso é fazer um try...catch e se ocorrer um erro devemos fazer um tratamento especial para manipular este caso.
Este fluxo está representado no catch:

Insere um elemento input novo no html
Setamos um id a este elemento para que ele possa ser encontrado no html.
pegamos este elemento pelo id adicionado no passo anterior.
adicionamos este elemento ao html atual
inserimos o valor a ser copiado ao elemento html inserido
inserimos o foco no elemento input html a ser inserido
selecionamos o text() do input adicionar.
executamos a função execCommand('copy'), que é o comando que copia valores para área de transferência.
removemos o elemento que inserimos, para deixar o html de acordo com quando iniciamos a modificação do html.

Segue o código:

Você pode validar que este fluxo foi bem sucedido se após implementar estas mudanças você apertar CTRL+V o conteúdo da variável meuelemento deve estar na área de transferência.
Comment: eu refiz a pergunta. incluindo mais elementos, gostaria de ver a possibilidade de ser analisado novamente.
Comment: realmente funcionou o script, mas agora meu desafio é, copiar, as informações que são mostrada no ECHO. mandei um link com a imagem, onde quando pesquiso um nome X no banco de dados, abaixo retorna o que tem, ex: na busca apareceu o id 61 (alem do nome, etc, e 69), gostaria de fazer agora esse script copiar esses dados.
Comment: Desculpa, não entendo de php. não sei dizer.


Standardisation when finding the start of the regularisation path

Question: I'm having some trouble understanding how standardisation plays into cross-validation with the lasso. Let's say we want to perform standardisation for the cross-validation process.
I can see why we shouldn't standardise before the train/test split, because that would be information leakage. On the other hand, when we run cross-validation for the lasso (or any high-dim method), we run the model along a regularisation path, starting at $\lambda^\text{max},$ which is the exact value at which the first coefficient enters the model.
This value is found using the data (an example is given in section 3.3 in the SGL paper). Hence, the question naturally arises whether we should standardise $X$ when calculating $\lambda^\text{max}$. I've tried looking at the code for the SGL package, but the authors standardise the data set right at the start of the CV function (even before the split), so I don't think this is quite correct anyway.
I've run some experiments and it seems that when I do standardise $X$ for the calculation of $\lambda^\text{max}$, the first model in the path isn't completely sparse. On the other hand, when I don't, the model is completely sparse, so this doesn't quite make sense to me.
Answer: I suspect that standardisation before doing anything (even splitting) is something of a standard, even though you are right that there is an information leakage problem. I haven't seen this discussed in the basic lasso literature, but then I don't know all the literature (in much literature variables are assumed to be standardised with no further discussion of the issue). Most people would probably think that the information leakage problem from standardisation is small. Also one could suspect that the leakage may lead to a certain overoptimism in general but wouldn't effect parameter selection of $\lambda$. I'm not sure about this, but let's say intuition doesn't tell me about any expected direction of bias when it comes to selecting $\lambda$ through standardisation of all data together. Of course there may be specific situations in which it makes a difference anyway.
In any case finding $\lambda^{max}$ requires standardisation (values of $\lambda$ are relative to whether data are standardised), unless you don't want to standardise at all. Of course if standardisation is done before anything else, this isn't a problem (apart from information leakage).
I think it is conceivable to do this within cross-validation in such a way that information leakage is avoided, but then obviously there would be different values of $\lambda^{max}$ for different cross-validation instances. I'm not sure how big a problem this is, probably it could be done but would be more complicated than just standardising everything before splitting, which I believe pretty much everyone is doing.
Comment: That all makes sense to me, thanks a lot. So if one were to standardise right at the start, would no further standardisation then be performed on the train split of the data when performing training within the CV loop?
Comment: @user19904 I don't think so. All data are standardised in the beginning, and are then treated as if they had come in this way.


window.location.href on Safari and Chrome

Question: This does not work in Safari and Chrome:
$(".myButton").click(function(){
    window.location.href('www.blahblahblah.com');
});

what's the solution?
Comment: Is there any browser where this works? Why do you assume `location.href` is a function? Have a look at the [MDN documentation](https://developer.mozilla.org/en/DOM/window.location).
Comment: Saying "does not work" does not work. Please explain what behaviour you need, and exactly what you find it actually does. Do you get an error message? Nothing at all happening? The wrong URL being opened? Demons flying out of your nose?
Comment: @FelixKling surprisingly, it works in IE
Comment: @Jack: Ah, this one again... thanks!
Comment: really? `href` is a method in IE? O_o
Comment: @Raminson It's defined as a property actually, but (at least in IE9) can be magically called as a method - http://msdn.microsoft.com/en-us/library/ie/ms533867(v=vs.85).aspx#CommunityContentHeader
Answer: window.location.href is not a function and therefor you cannot call it, you can however assign a value to it: (Also you should be using http:// when redirecting to another domain)
$(".myButton").click(function(){
    window.location.href = 'http://www.blahblahblah.com';
});

EDIT: Corrected my first statement and added the part about http://
Comment: Variables can contain functions as well. Your statement is not correct (actually, only `window` is a variable, `location` and `href` are properties (and if one wants to be pedantic, `window` is a property of the global object as well)). The only correct statement would be: `window.location.href` is not a function.
Comment: You also have to include `http://`, or it will try to navigate relative to the current page.
Answer: Had a similar problem. In chrome, return false; solved the problem.
if(confirm('Are you sure you wish to delete this order?'))
{
location.href='delete_order.asp?id=20'; **return false;**}
else
{return false;}

The above code works in Chrome and IE9
Comment: Geez Louise...I've been pulling my hair out over this.  How did you figure this out?  Have you figured out the source of the problem?  Thank you!
Comment: PS...I understand the OP's question contained a basic Javascript error, but I found this post nevertheless, and return=false solved the problem I was having in Chrome only (WITH correct Javascript)...
Answer: window.location.assign('http://www.google.com')

is the function you're looking for.
It's the equivalent of
window.location = 'http://www.google.com';


É possível usar Session em Windows Service?

Question: Tenho uma aplicação em Windows Service, e preciso guardar o estado enquanto um determinado método é executado, qual o melhor meio de fazer isso?
Comment: Seria interessante você detalhar melhor a pergunta. Você precisa guardar o estado de que? Quando? Por que? Tem como colocar o código para entendermos?
Comment: Tenho um Timer no serviço, que executa uma determinada rotina que pode demorar além da execução do próximo Timer, ai obviamente não quero deixar executar novamente enquanto esse primeiro Timer estiver sendo executado, não quero colocar isso no banco de dados, gostaria de alguma forma que identificasse isso na própria aplicação.
Comment: @Raí, gostaria de lhe sugerir a seguinte leitura: http://weblogs.asp.net/jongalloway//428303
Answer: Você pode armazenar em um objeto.
O "Serviço" é uma instância de sua classe, logo você pode armazenar qualquer coisa dentro dela.
<code>public class MyTask
{
    public void LongOperation()
    {
        // seu código que pode demorar aqui
    }

    public Task LongOperationAsync()
    {
        return Task.Run(delegate () { this.LongOperation(); });
    }
}

public class MyService : ServiceBase
{
    Timer _timer;
    MyTask _currentTask;
    bool _called;

    protected override void OnStart(string[] args)
    {
        base.OnStart(args);
        _currentTask = new MyTask();
        _called = false;
        _timer = new Timer(5000);
        _timer.Elapsed += TimerElapsed;
        _timer.Start();
    }

    private async void TimerElapsed(object sender, ElapsedEventArgs e)
    {
        // TODO:
        //      talvez você precise usar uma sincronização à nível de Thread (lock) aqui
        if (_called)
        {
            // função ja foi chamada
            return;
        }
        _called = true;
        await _currentTask.LongOperationAsync();
        _called = false;
    }

    protected override void OnStop()
    {
        _timer.Stop();
        base.OnStop();
    }
}
</code>


Give a Bijection between $\mathbb{R}\setminus\mathbb{Z}$ and $\mathbb{R}\setminus\mathbb{N}$

Question: Give a Bijection between $\mathbb{R}\setminus\mathbb{Z}$ and $\mathbb{R}\setminus\mathbb{N}$
I got a bijection between $\mathbb{N}$ and  $\mathbb{Z}$
Given by
$\phi(1)=0$
$\phi(2)=-1$
$\phi(3)=1$
$\phi(4)=-2$
$\phi(5)=2$
$\phi(6)=-3$
But I cannot figure how to find a bijection between $\mathbb{R}\setminus\mathbb{Z}$ and $\mathbb{R}\setminus\mathbb{N}$
Comment: Please don't ask for help and then "Bro" prospective helpers. Thanks.
Comment: Both of your sets are just a countable collection of disjoint intervals. Try thinking of your problem that way
Comment: I don't know who you are addressing your comment to, but @RocketMan 's comment gives you the solution, pure and simple.
Comment: Start with an identity map from reals to reals. Modify this map on the integers. Now drop the integers from the domain.
Comment: See [here](https://math.stackexchange.com/q/2433528/11619) for a more general result.
Answer: The identity function almost works for $\mathbb R\setminus\mathbb N \to \mathbb R\setminus \mathbb Z$, except that you need to avoid hitting the negative integers. Use Hilbert's Hotel to make room for each of them, e.g.
$$ f(x) = \begin{cases} x + c & \text{if }x=-(n+1)+mc\text{ for some }n,m\in\mathbb N \\ x & \text{otherwise} \end{cases} $$
for some appropriate constant $c$.
Which numbers would work as $c$?
Answer: Let's start with the identity $f(x)=x\quad \forall x\in\mathbb R-\mathbb Z$
$(\mathbb R-\mathbb Z)$ and $(\mathbb R-\mathbb N)$ differ by $\mathbb
N_{>0}$.
So to have a bijection you must basically make every positive integer disappear!
But the black hole $\mathbb N_{>0}\mapsto\varnothing$ is not a bijection.
Instead the idea is to hide them within the real numbers. We will send $1$ to a real which is not an integer, let say $\phi(1)=\frac 12$.
But location $\frac 12$ is already occupied by $f(\frac 12)=\frac 12$, so we will push it deeper with $\phi(\frac 12)=\frac 14$, and we have a conflict with $\frac 14$ now, so we will push it also $\phi(\frac 14)=\frac 18$ and so on...
Basically we shift the whole sequence $\frac 1{2^k}\mapsto\frac 1{2^{k+1}}$ a step deeper, that is freeing a hole in $\frac 12$ where we can put $1$.
Now where to put $2$ ?
Similarly we can shift the sequence of all $\frac 1{3^k}$, freeing a hole in $\frac 13$ and place $2$ there $\phi(2)=\frac 13$.
On so on, we shift the sequences of powers of primes numbers one step deeper $\phi(\frac 1{{p_n}^k})\mapsto\frac 1{{p_n}^{k+1}}$ this frees a hole in $\frac 1{p_n}$ where we can put $n$, i.e $\phi(n)=\frac 1{p_n}$

This is only one example. For instance you can shift the sequences $n+\frac 1{2^k}$ instead and send $n$ to the center of interval $]n,n+1[$ instead of using prime numbers.
More sophisticated sequences are possible, like the one by J.C.Santos for instance, but the principle is the same.
Answer: Something you can do is create extra gaps, and reduce the problem to a bijection between countable sets:
Take $\phi$ to be the identity on $\mathbb R - \frac12 \mathbb Z$. All you have to do then is find a bijection between $\frac12 \mathbb Z - \mathbb Z$ and $\frac12 \mathbb Z - \mathbb N$. On positive integers, take it to be the identity; on negative integers, construct a bijection between $-\mathbb N$ and $-\frac12\mathbb N$.
Answer: You can define a bijection $\psi\colon\mathbb{R}\setminus\mathbb{N}\longrightarrow\mathbb{R}\setminus\mathbb Z$ defining $\psi(x)=x$ if $x\not\in\left\{\frac1{n+1}\,\middle|\,n\in\mathbb N\right\}$ and then:

$\psi(0)=\frac12$;
$\psi(-1)=\frac14$;
$\psi(-2)=\frac16$

and so on. Besides

$\psi\left(\frac12\right)=\frac13$;
$\psi\left(\frac13\right)=\frac15$;
$\psi\left(\frac14\right)=\frac17$

and so on.
Answer: Rocket man commented that "Both of your sets are just a countable collection of disjoint intervals. Try thinking of your problem that way "
So $\mathbb R\setminus \mathbb Z = \cup_{z\in \mathbb Z} I_z$ where $I_z = (z-1,z)$
And $\mathbb R\setminus \mathbb N = \cup_{n\in \mathbb N} J_n$ where $J_n = (n-1, n)$ for $n>1$ and $J_1 = (-\infty, 1)$.
You found a bijection $\phi: \mathbb N \to \mathbb Z$.
Now if you can find a sequence of bijections $\psi_n: J_n\to I_{\phi(n)}$ we'd be done:  We'd just need to define $\psi:\mathbb R\setminus \mathbb N\to \mathbb R\setminus \mathbb Z$ as: $\psi(x) = \psi_n(x)$ when $x \in J_n$.
....
to spell it out:
Let $\psi: \mathbb R\setminus N\to \mathbb R\setminus Z$ be defined as follows:
If $x \in \mathbb R\setminus N$ and $x > 1$ then there exists an $n$ so that $n-1 < x < n$.  For this $x$ let $\psi (x) = x - n + \phi(n)$.  Now $\phi(n)-1< \psi(x) < \phi(n)$ so $\psi(x) \in R\setminus Z$.
If $x \in \mathbb R\setminus N$ and $x \le 1$ then $x < 1$. So $x-1 < 0$ and $1-x > 0$ and $0 < \frac {1}{1-x} < 1$ and $-1< \frac {1}{1-x}-1< 0$. For this $x$ let $\psi(x) = \frac 1{1-x}-1$. Now $-1 < \psi(x) < 0$ so  $\psi(x) \in R\setminus Z$
We can verify this is a bijection:
It's one to one:  If $x\ne y$.  $x < 1$ and $y < 1$ the $\psi(x) = \frac 1{1-x}$ and $\psi (y) = \frac 1{1-x}$.  $x= y\iff 1-x = 1-y \iff \frac 1{1-x}= \frac 1{1-y}$ so $\psi(x) \ne \psi (y)$.
If one of $x$ or $y$ (wolog $x$) is less than $1$ and the other (wolog $y$) is not then there is an $n>1$ so that $n-1 < y < n$.  And $\phi(n) \ne 0$. so  $\phi(n)-1 < \psi(y) < \phi(n)$ so $\psi(y) \not \in (-1,0)$. Whereas $\psi(x)\in (-1,0)$ so $\psi(x) \ne \psi(y)$.
If $n- 1 < x<n$ and $m-1< y < m$ and $m \ne n$, then $\phi(n) \ne \phi(m)$.  And $\phi(n)-1 < \psi(x)< \phi(n)$ while $\phi(m)-1 < \psi(y)< \phi(m)$.  So $\psi(x)\ne \psi(y)$.
Finally if $n-1<x,y< n$ then $x = y \iff x-n+\phi(n) = y-n+\phi(n) \iff \psi(x) = \psi (y)$.  So $\psi(x)\ne \psi(y)$.
$\psi$ is onto:  If $x\in \mathbb R\setminus Z$ then there is a unique $m$ so that $m-1< x < m$.  And there is a unique $n$ so that $\phi(n) = m$.
If $n \ne 1$ then $y =x-m + n$ will mean $n-1< x < n$ and $\psi(y) = x$.
If $n = 1$ then $m = 0$ and $-1 < x < 0$.  And $0 < x + 1< 1$ and  $\frac 1{x+1} > 1$ and let $y=1-\frac 1{x+1} < 0 < 1$. then $\psi(y) = x$.


Construction of $\exists x_i (\phi)$ in first order logic.

Question: How do we construct $\exists x_i(\phi)$ where $\phi$ a formula from first order language by using:

The logical symbols $(,),\neg,\to,\forall$
The variable symbols $x_i$
Comment: its supposed to be equivalent to $\neg\forall x_i(\neg\phi)$
Answer: There exists an x such that phi holds $\equiv$ It is not the case that for all x, phi does not hold.
ie. $\exists x_i(\phi) = \neg(\forall x_i(\neg\phi))$
Comment: Yes; if your language has only $\forall$ in the symbols-set, the only way to have $\exists$ is to introduce it as an *abbreviation*.


Lebesgue measure space

Question: Measure space $(X,\mathcal{B},\mu)$, $B_n\in \mathcal{B}$, $\mu(B_n) \le \infty, n=1,2,...,$.
(1) If $\sum\limits_{n=1}^{\infty} \mu(B_n) \le \infty $, then $\mu(\lim\sup_{n \to \infty} B_n)=0$.
(2) $A_n\in\mathcal{B}, A_n \supset A_{n+1},n=1,2,..., \mu(A_1)\le \infty$
(i) $B_n:= A_n\setminus A_{n+1}$, then $\sum\limits_{n=1}^{\infty} B_n$ converges.
(ii) $\forall n\in N, \cup_{k=n}^{\infty}(A_k\setminus A_{k+1})=A_n$, then show $\mu(\cap_{n=1}^{\infty} A_n)=0$.
Answer: (1) http://en.wikipedia.org/wiki/Borel%E2%80%93Cantelli_lemma
(2) Apply (1) for (ii), along with the definition of $\limsup$ (for (i), use $\mu(B_n) = \mu (A_n) - \mu (A_{n+1})$).
Comment: Very good,Thanks!

Lebesgue measure space


Gulp watch, running multiple tasks issue

Question: I'm trying to setup a Gulp task that converts Sass into CSS and then minifies it.
Here's my current gulpfile.js
// include gulp
var gulp = require('gulp');
var sass = require('gulp-sass');

var minifyCss = require('gulp-minify-css');

//gulp sass

gulp.task('sass', function () {
  gulp.src('./scss/main.scss')
    .pipe(sass().on('error', sass.logError))
    .pipe(gulp.dest('./css'));
});

gulp.task('minify-css', function() {
  return gulp.src('css/*.css')
    .pipe(minifyCss({compatibility: 'ie8'}))
    .pipe(gulp.dest('css'));
});

gulp.task('sass:watch', function () {
  gulp.watch('./scss/main.scss', ['sass','minify-css']);
});

I run gulp sass:watch and I expect it to convert main.scss into main.css which it does and then I see that it also runs minify-css, but it doesn't actually minify it.
If I run gulp minify-css, it works perfectly. Can someone please tell me how this needs to be adjusted so gulp.watch runs both tasks, one after another?
Thank you
Answer: Looks like I got this work, by removing the additional task and combining the css minify into the sass portion.
// include gulp
var gulp = require('gulp');
var sass = require('gulp-sass');

var minifyCss = require('gulp-minify-css');

//gulp sass

gulp.task('sass', function () {
  gulp.src('./scss/main.scss')
    .pipe(sass().on('error', sass.logError))
    .pipe(minifyCss({compatibility: 'ie8'}))
    .pipe(gulp.dest('./css'));
});

// gulp.task('minify-css', function() {
//   return gulp.src('css/*.css')
//     .pipe(minifyCss({compatibility: 'ie8'}))
//     .pipe(gulp.dest('css'));
// });

gulp.task('sass:watch', function () {
  gulp.watch('./scss/main.scss', ['sass']);
});


How do I do an .htaccess 301 redirect of a query string?

Question: I'm trying to redirect a url http://domain.com/?p=106 to http://domain.com/?p=110
My .htaccess file looks like this:
RewriteEngine On
RewriteCond %{QUERY_STRING} ^p=106
RewriteRule / http://domain.com/\?p=110 [L,R=301]

But I can't seem to get it to work.
Answer: RewriteRule / wouldn't match a request to / in htaccess.  The path you compare against is empty in that case (the prefix is stripped in htaccess rewriterule)
RewriteRule ^$ http://domain.com/?p=110

Answer: According to the docs, you need to check that Options FollowSymLinks is enabled before trying rewrite in a .htaccess. Then, you also have to note that the per-directory prefix is automatically removed, which means a pattern with ^/ never matches anything (I bet this is why your / doesn't work).
So, in your case, first check Options FollowSymLinks and then change the RewriteRule to be something as covener suggested, or my version:
RewriteRule ^$ /?p=110


How to use Image EXIF Autorotate?

Question: I have been trying to use the Image EXIF Autorotate Module. I have installed all the required modules like

Imagecache Autorotate
Original image with style

Also changed the image field property

Apply style to image after upload = Image EXIF Autorotate

Nothing is happening I upload the image and no changes and it just upload the image as it is and if I try to rotate it manually nothing happens.
My requirements are as the image is uploaded the user sees the image and if wants to rotate it by clicking on it to do so.
Comment: Note that this submodule requires the **Exif PHP extension to be enabled**.
Comment: and [Automatically rotate image on upload](http://drupal.stackexchange.com/questions/73698/automatically-rotate-image-on-upload)
Answer: The Exif Autorotate module

Automatically rotates any uploaded image file according to the EXIF
  orientation information.

This EXIF data is embedded into the photo by the camera (and is often lost in compression). It contains the author, aperture settings, shutter speed, camera position and much more.
So if your photo is not created by a camera, or is already in the upright position, or has been compressed or downloaded, nothing will happen.

My requirements are as the image is uploaded the user sees the image
  and if wants to rotate it by clicking on it to do so.

EXIF Autorotate does not rotate the photo by clicking on it, it rotates the photo to the position the camera shot it in (landscape or portrait).

How to use Image EXIF Autorotate?


$\Bbb{Z}/4\Bbb{Z}$ cannot possess a non-degenerate alternative bilinear pairing

Question: Why $\Bbb{Z}/4\Bbb{Z}$ doesn't have non-degenerate alternative bilinear pairing ?
Here,for abelian group $A$, bilinear pairing $A×A\to \Bbb{Q}/\Bbb{Z}, (a,a)\mapsto 〈a,a〉$ is called non-degenerate if only if $\forall a\in A, 〈a,b〉=0 \implies b=0$.
General theory implies abelian group $A$ which has non-degenerate alternative bilinear pairing should take the form $\Bbb{Z}/n\Bbb{Z}×\Bbb{Z}/n\Bbb{Z}$. So $\Bbb{Z}/4\Bbb{Z}$ cannot possess a non-degenerate bilinear pairing. But my question is, can we prove that without big tools ?
Comment: I took the liberty of adding that key word to the title as well. Lest future readers are instantly puzzled.
Comment: Surely there exists non-degenerate bilinear pairings. Such as $\langle \overline{m},\overline{n}\rangle=(mn/4)+\Bbb{Z}$. The extra requirement of the pairing to be *alternative* must play a role.
Answer: If $\langle\ ,\ \rangle:\Bbb{Z}_4\times\Bbb{Z}_4\to\Bbb{Q}/\Bbb{Z}$ is bilinear and alternative, then (by the rule $\langle a,b\rangle=-\langle b,a\rangle$)
$$\langle\overline{1},\overline{1}\rangle=-\langle\overline{1},\overline{1}\rangle.$$
It follows that  $\langle\overline{1},\overline{1}\rangle$ equals either $0+\Bbb{Z}$ or $(1/2)+\Bbb{Z}$. On the other hand, by bilinearity, for all intergers $m,n$ we must have
$$\langle\overline{m},\overline{n}\rangle=mn\langle\overline{1},\overline{1}\rangle.$$
Putting these together implies that for all $a\in\Bbb{Z}_4$ the pairing $\langle a,\overline{2}\rangle$ is an even multiple of $\langle\overline{1},\overline{1}\rangle$, i.e. equal to zero.
Comment: @Pont What's your definition of *alternative bilinear pairing*? I assumed it means that $\langle a,b\rangle=-\langle b,a\rangle$ for all $a,b$. In some contexts a bilinear form is called *alternating*, if $\langle a,a\rangle=0$ for all $a$.
Comment: Of course, if your definition flat out requires that $\langle\overline{1},\overline{1}\rangle$ vanishes, then the argument is even simpler.
Comment: Could you tell me why the rule $(alb)=-(bra)$ holds ?


DATE_ADD example for BigQuery returning error

Question: Running examples from BigQuery docs and getting errors for intervals.
SELECT DATE_ADD(DATE "2008-12-25", INTERVAL 5 DAY) as five_days_later;
Returns...
Error: Encountered " <STRING_LITERAL> "\"2008-12-25\" "" at line 1, column 22. Was expecting: ")" ... [Try using standard SQL (https://cloud.google.com/bigquery/docs/reference/standard-sql/enabling-standard-sql)]

What am I missing here? Legacy SQL is checked.
Answer: This example is for BigQuery Standard SQL
Try below
#standardSQL
SELECT DATE_ADD(DATE "2008-12-25", INTERVAL 5 DAY) AS five_days_later

... or just uncheck Legacy SQL :o)


Can't get around ImageResizer error: File may be corrupted, empty, or may contain a PNG image with a single dimension greater than 65,535 pixels

Question: Not sure what I'm missing.
Trying to take a jpg from a simple input[type=file] POST and scrub it into two versions (1800x1800) and (400x400).
Code:
stream.Position = 0;//probably only need one of these lines
stream.Seek(0, SeekOrigin.Begin);//i've tried both to no avail
ImageJob job = new ImageJob(stream, origStream,
    new Instructions("maxwidth=1800&maxheight=1800")).Build();

Throws:
File may be corrupted, empty,
or may contain a PNG image with a single dimension greater than 65,535 pixels.

stream comes from context.Request.InputStream I'm just passing it through a method call. and the other is MemoryStream origStream = new MemoryStream() from a wrapped using
I've read through some of the docs and some of the other SO posts that reference this error. All of the ones that I found on SO reference using a plugin, I'm using no plugins.
My best guess is that I'm missing some configuration to get ImageResizer to work, but I haven't been able to find that yet.
PS I am able to save the file if I skip the image processing step, so the image stream is good, I just can't use ImageResizer to change it.
Comment: Is this on the first or second call? Do other jpeg files work? Can you show more code?
Comment: This is the first call. I haven't set up the second call yet because I can't get the first resize to work.
Comment: I can't get any jpg files to work.
Comment: I'm using the Windows shipped jpgs to test with.
Answer: Problem was in the input stream.
context.Request.InputStream
should be:
context.Request.Files[0].InputStream
The InputStream hanging off of Request contains the entire body, form and all. NOT a valid image.


Streaming Server Network Performance

Question: I have server Linux based on
centos 6.5 final 64bit ,
ram 128 G.B
dual E5-2650 processor
Hard disk : 4 SSD Hard disk RAID-5
Network Speed 1/Gbps
Bandwidth Speed 500/Mbps up to 3/Gbps

My Wbebserv apache based on nginx engine
I have Problem playing videos on the server , the server play videos after 12 Seconds , i want to increase the performance so the videos load less than 5 Seconds
What is the best configuration i have to do in nginx , and sysctl configuration or other configurations so i can increase the bandwidth playing speed ?
Comment: I voted that way instead of **too broad/book answer** to at least give you some things to start down.  Your question isn't specific enough.  We don't know your server config, nginx config, webserver stats, performance metrics, etc.
Comment: @TheCleaner it's not duplicated , because i want to know the values i should set in the configuration files so i can had the best perforamnce for playing videos to the server , this link show u information generally
Comment: @TheCleaner i actually don't know what is the configuration REALTED to slow playing videos issue so i can put the configuration to see it
Comment: @user209827 ... well if you don't know, how/why do you expect us to be able to divine the answer for you?  We're not clairvoyant.
Comment: it's really nice to see u all mark the question as duplicated instead of telling the answer because with all do respect you guys mark questions duplicated , closed that u cannot HAVE the answer , and if my question not clear how could ewwhite answer it ? and how could u guys moderators in this site ?
Comment: @user209827 They're not moderators, they're normal users. See http://serverfault.com/help/privileges/
Comment: The answer from Ed is a very generic answer that he's used before - perhaps we should search his answers and close this as a dupe of that.
Comment: @iain Awwwwww :(
Answer: Here's what you can do to your base system:
# yum install tuned tuned-utils
# tuned-adm profile throughput-performance

See the chart below. These settings will at least make the I/O scheduler aware of what you're trying to do and help with some better sysctl and storage subsystem defaults. Can you test with this and report back? You can revert the settings to default with tuned-adm profile default

Streaming Server Network Performance