Update com base em um select

Question: Tenho que atualizar o campo custo da tabela pedidos com base no campo valor da tabela produtos_pedidos.
Sendo que o a.id da tabela pedidos tem que ser igual ao campo b.id_pedido da tabela produtos_pedidos.
Estou tentando fazer assim:
UPDATE
pedidos a
SET
custo = (
    SELECT
        b.valor
    FROM
        produtos_pedidos b
    WHERE
        b.id_pedido = a.id
    )

Estou tendo esse erro:
Coluna 'custo' não pode ser vazia

Comment: Esse é o update inteiro? pode ser o select retornou algum registro com null na coluna valor.
Comment: Provavelmente é isso que esta acontecendo.
Answer: Eu sugiro utilizar INNER JOIN:
UPDATE
    pedidos a
    INNER JOIN produtos_pedidos b on b.id_pedido = a.id
SET
    a.custo = b.valor

O problema no comando original na pergunta parece ser a existência de itens na tabela pedidos para os quais não há item correspondente na tabela produtos_pedidos. Então, para um pedido sem produto corresponente, ocorrerá erro. O INNER JOIN garantirá que somente pedidos com registro corresponente em produtos_pedidos serão obtidos para a atualização de custo.
P.s.: caso o campo custo não possa aceitar valores  nulos, você ainda pode utilizar uma função como COALESCE para substituir nulo por zero, ou incluir uma clausúla where para filtrar apenas quando os registros de produtos_pedidos tiverem valor.
Comment: se o campo custo não aceita valores nulo e no campo valor aceita o erro vai continuar acontecendo.
Comment: @MarconcilioSouza bem lembrado, valeu.
Answer: Pode acontecer dele não esta achando nenhum valor que bata com o a.id.
Tente assim:
UPDATE
pedidos a
SET
custo = (
    SELECT
        coalesce(b.valor, 0)
    FROM
        produtos_pedidos b
    WHERE
        b.id_pedido = a.id
    )

onde o coalesce(b.valor, 0) retorna um valor padrão se for nulo, nesse caso coloquei 0
Comment: Da sua forma deu o mesmo erro.
Comment: não esta dando certo, olha o exemplo que eu fiz.http://sqlfiddle.com/#!9/0bdaef
Comment: tente colocar o coalesce no custo = coalesce (select)
Answer: Você pode usar um valor default caso b.valor seja null ou verificar se o b.valor é null.
UPDATE
pedidos a
SET
custo = (
    SELECT
        b.valor
    FROM
        produtos_pedidos b
    WHERE
        b.id_pedido = a.id
        and b.valor is not null
    )

Eu usaria uma query assim.
UPDATE a
SET custo = case when b.valor is null then 0 else  b.valor end
FROM pedidos a
join produtos_pedidos b
on b.id_pedido = a.id

Comment: Não deu certo de nenhum forma amigo. Na primeira continua o erro falando que o custo não pode ser nulo, e na segunda da um erro de sintaxe

Update com base em um select


Missing Microsoft.SharePoint.dll in asp.net web application

Question: I am working on a asp.net Web Application that can access SharePoint sites. I have referred the documentation of SharePoint
When I try to instantiate SPSite object it says;
The Type or namespace does'nt exist.

Then I tried to add reference of the Microsoft.ShairPoint.dll by Solution  Explorer -> Add References option,  but could not found any Microsoft.ShairPoint.dll.
There is Microsolft.ShairPoint.client/ClientProfile available, but not the desired one i.e. Microsoft.ShairPoint.dll.
How to resolve this problem?
Comment: which .Net framework you use?
Comment: I am using 4.5 framework
Comment: Simple Man have you found no answer
Comment: Have you installed SharePoint? Which version?
Comment: Yes i install ShairPoint 2013
Comment: This should be the path : C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\14\ISAPI\Microsoft.SharePoint.dll
Comment: Hi Inside Microsoft Shared there is no folder exist Web Server
Comment: Hi Inside Microsoft Shared/Web Server Extensions/15 or 16 / ISAPI  inside these folder's Microsoft.ShairPoint.client.dll or many more files same like that exist but no one file Microsolft.ShairPoint.dll exist What Should I do! Please help
Comment: I think in order to get this dll you have to install Windows SharePoint Service which can be install on server only. In your case if you are running client os like windows 7, you can get this dll from Office installation folder.
Answer: You can use download and use SharePoint Client Object Model and connect to a SharePoint site
Refer related discussion here
We can also use SharePoint Client SDK to connect to SharePoint site
Answer: You must right click on your project and then add reference ..
select Microsoft.Sharepoint.Client.
Comment: Hey i just discovered that you if u want to use the server side objects i.e. for example SPSite then you must have Sharepoint installed on your server. Unless you install it , you wont find Microsoft.sharepoint.dll, If however you dont have it installed , u can use client object model for sharepoint , provided you have the user credentials , and the user has Sharepoint access rights. If have any doubts,  please ask .
Answer: You can also try this :right click the project, go to properties --> change the target Framework to 4.0. and then again add references . and build the solution.


Going against the conventional $\alpha$?

Question: I have a general statistics question on $\alpha$.
Conventionally, $\alpha$ is set at $p < 0.05$. Are there cases where by alpha is set at $p < 0.3$ instead? If so, why?
Also, I understand that by changing the $\alpha$ value, it gives rise to a larger risk of encountering Type $1$ errors (false positive). Thus, how should I interpret the results for such a scenario?
Comment: A smaller $\alpha$ means that one is seeking stronger support for the hypothesis. If one could quantify the cost of a Type I error (or Type II), this would be made into a rational choice. 0.05 Would I guess in absence of cost considerations be categorised subjectively as 'fairly strong'.
Answer: Yes, there are reasons to adjust alpha.  The simplest way to explain these is to note what Type I and Type II errors are, and that sometimes a Type II error is much worse than a Type I.  (And to realize that by increasing the chance of one, you decrease the chance of the other).
Suppose, for example, that you develop a drug that treats a previously incurable and terminal disease. Now a Type I error would mean saying the drug works when it doesn't and a Type II error would be saying it doesn't work when it does. In the first case, we give a useless drug to people who are dying; in the second, we fail to treat people who are dying.  I'd say the second is much worse.
Of course, sometimes it's the other way around.
The blind acceptance of 0.05 and 0.20 for type I and type II errors is one of the hardest things to get PHBs to give up.  (PHB = Pointy Haired Boss from Dilbert and could be a journal editor, a boss, a PhD committee or whatever).
Comment: Hey Peter, thank you so much for helping me! I agree that the blind acceptance portion is a big issue in academia. On another note, am I right to say that by adjusting the power, I can reduce the probability of type 1 error, but this will cause my type 2 error to increase? For that matter, do I use an estimation rather than a hypothesis testing framework? i.e. Either using frequentist confidence intervals and effect sizes or using Bayesian statistics with slightly informative priors (because you have only a small sample).
Comment: Yes, lower power = more type II errors, fewer type I errors. Whether to use estimation or confidence intervals depends on what you are trying to find out.


Time series with additional features

Question: Hello everyone!
I have dataset that contains columns:

date
feature1
feature2
Y

I need Y prediction to next several values (date, feature1, feature2).
Y tends to fall over time (maybe exponentially) and Y(date) to some extent is a time series.
It is desirable to obtain a simple model solution based on statistics.
It is really ? Or for best predictions need use machine learning methods ?
Answer: A "simple model solution based on statistics" may give you the best predictive performance.
You can evaluate and compare different approaches. It's a good idea to start with naïve baselines, then try out "statistical" models (e.g. Exponential Smoothing, ARIMA or Theta), and finally see if more complicated machine learning models help improve predictive performance.

Time series with additional features


How to get each registration type from the array?

Question: I have an array with the request data that has these name and surname arrays:
"name" => array:2 [▼
        1 => array:1 [▼
          1 => "Jake"
        ]
        4 => array:1 [▼
          1 => "John"
        ]
      ]
      "surname" => array:2 [▼
        1 => array:1 [▼
          1 => "W"
        ]
        4 => array:1 [▼
          1 => "K"
        ]
      ]
      ]

I want to insert each participant name, surname and registration_type_id where the participant is being registered in the participants table. Like this it seems that is possible to store the name and surname of each participant. But how to get the registration_type_id of each participant (in this case 1 for Jke and 4 for John)?
foreach ($request->all()['name'] as $key => $name) {

            $participant_result = Participant::create([
                'name' => $name[1],
                'surname' => $request['surname'][$key][1],
                'registration_type_id' => how to get this???
            ]);

        }

The registration_tpye_id for the participant Jake is "1" and for John is "4" as it is in the array:
"name" => array:2 [▼
        1 => array:1 [▼
          1 => "Jake"
        ]
        4 => array:1 [▼
          1 => "John"
        ]
      ]
      "surname" => array:2 [▼
        1 => array:1 [▼
          1 => "W"
        ]
        4 => array:1 [▼
          1 => "K"
        ]
      ]

Additionally Provided sample data
"name" => array:2 [
    1 => array:2 [
        1 => "Jake"
        2 => "John"
        ]
    4 => array:1 [
        1 => "Adam"
        ]
    ]
    "surname" => array:2 [
        1 => array:2 [
            1 => "W"
            2 => "K"
            ]
    4 => array:1 [
        1 => "L"
        ]
    ]

Comment: `'registration_type_id' => $key` ??
Comment: Thanks, like that it works for the example in the question wtih 2 participants, the participant John being registered in the registration type with id "1" and participant Jake being registered in the registration type "4". But if the user is registering 2 participants in the registration type with id "1" and 1 participant in the registration type "4" the array is like ""name" => array:2 [▼ 1 => array:2 [▼  1 => "Jake"  2 => "John" ] 4 => array:1 [▼ 1 => "Adam"]]
  "surname" => array:2 [▼ 1 => array:2 [▼  1 => "W" 2 => "K" ] 4 => array:1 [▼ 1 => "L"]
  ]".
Comment: But in that case only Jake and Adam are registered. The participant John is not inserted in database. Do you know why?
Answer: Just use the $key variable in the foreach loop.
...
'registration_type_id' => $key
...

UPDATE:- As per your provided Data set, you shall have to parse it as below.
foreach ($request->all()['name'] as $key => $nameArray) {
    foreach ($nameArray as $nameKey => $name) {
        $participant_result = Participant::create([
                    'name'                 => $name,
                    'surname'              => $request['surname'][$key][$nameKey],
                    'registration_type_id' => $key
        ]);
    }
}

WHY:-  Since the users are grouped under the registration_type_id as a sub array with their user-ids as keys (I suppose, not sure though so named them $nameKey), we have to also loop through the sub-array.
Comment: Thanks, do you know why if the user is registering 2 participants in the registration type with id "1" and 1 participant in the registration type "4" the array is like ""name" => array:2 [▼ 1 => array:2 [▼ 1 => "Jake" 2 => "John" ] 4 => array:1 [▼ 1 => "Adam"]] "surname" => array:2 [▼ 1 => array:2 [▼ 1 => "W" 2 => "K" ] 4 => array:1 [▼ 1 => "L"] ]".  only Jake and Adam are registered. The participant John is not inserted in database. Do you know why?
Comment: @John Updated my answer.


Are passwords entered in the login form encrypted?

Question: In the user login page, is the value entered for the password encrypted to avoid it can be sniffed by a hacker?
Comment: With great respect, it sounds like you're unfamiliar with how HTTP works. Drupal cannot impose itself between the browser and the server, where the request happens, and where man-in-the-middle and other attacks occur. The only way to ensure a password is transmitted across the network with a reasonable amount of safety, is to use TLS
Comment: Ok, no, Drupal doesn't do any password encryption out of the box. Whether a "hacker" can gain access to the password before any request gets to Drupal, of course, is a completely different matter. Also if such a person has gained access to your database or server separately, it's a moot point. If you're asking this question as part of some sort of security audit, you're probably not asking the right thing
Comment: If you encrypt with JS on clientside it's breakable by design... you should not think about security as long as you use http - it's never secure. Use TLS (https) then you're on the right path. If you're on low budget, use let's encrypt - it's free.
Comment: Encrypted in what sense? At what part of the process?
Comment: I mean it can not be sniffed by a hacker
Comment: I just want to improve the security of a website without https. I was thinking to this module: https://www.drupal.org/project/password_encrypt I assume it will allow drupal to not send the password in plain text.
Comment: ok, thank you... Thus, the password_encrypt  module is not usefull...
Comment: It does have its uses, but not really applicable to what you're looking for, no
Comment: Many thanks. Maybe i am completly wrong but we could imagine a password field encrypted with javascript on the client side, then decrypted on the server side.
Answer: When you submit the form on /user/login, the fields are both sent in plaintext in the POST body.  If you use a browser debugger (like Chrome Inspector), you can look at the network traffic and see this.
Then, on the server side the submitted password is hashed with the current algorithm. (I think it's a stretched SHA-512 right now; see the PhpassHashedPassword class for more details.) The hash value is then checked against the value in the database.
Comment: Personally, no.  I am not familiar with that module author, and I don't trust many people with crypto.  And, that doesn't totally prevent the plaintext.  I would be more worried about keyloggers (either malware or JS injection).  Multi-Factor Authetication (MFA) would be a better route to explore for authentication hardening.
Comment: ok, many thanks for this clear explaination. Do you think it is a good idea to install something like: https://www.drupal.org/project/password_encrypt


Identfying natural isomorphisms using Yoneda's lemma

Question: Let us denote the covariant functor $C\rightarrow Mor(A,C)$ from $\mathcal{C}\rightarrow Sets$ by $h^A$ (We are assuming $\mathcal{C}$ is a locally small category). For a given $A,B \in \mathcal{C}$ We know there is a bijection between natural transformations $h^A \rightarrow h^B$ and $Mor(B,A)$ by mapping $\eta$ to $\eta_A(id_A)$. In fact, even more is true. Natural isomorphisms between $h^A$ and $h^B$ correspond to the isormorphisms in $Mor(B,A)$. This allows us to identify the subcategory of natural isomorphisms between $h^A$ and $h^B$ as a subset of $Mor(B,A)$.
Now let's take it one step further. Given a covariant functor $F:\mathcal{C}\rightarrow Sets$, we have a bijection between natural transformations $h^A\rightarrow F$ and $F(A)$ (by Yoneda's lemma).
Is there a way to identify the set of natural isomorphisms between $h^A\rightarrow F$ as some subset of $F(A)$ (as we did above)?
Answer: Yes, this is the set of universal elements of $F$ (on $A$). It is non-empty iff $F$ is representable by $A$. Let me spell this out: $x \in F(A)$ is universal iff for every other $y \in F(B)$ there is a unique $f : A \to B$  such that $y=F(f)(x)$. (Of course this is just a tautology, but finding universal elements is something which really depends on the specific choice of $F$ and may be very hard, so that in this generality nothing more can be said about this.)
Comment: @Sergio: This question is too broad. Finding universal elements is really doing mathematics. At Ittay: Yes.
Comment: isn't the definition of universal element simply saying that the corresponding natural transformation is a natural iso?
Comment: This is the name for elements of $F(A)$ corresponding to representations of $F$, but is it well understood how to find universal elements?
Comment: @MartinBrandenburg :I can assume then that finding universal elements is not an easy task and is the subject of research? Thanks for your comments.
Comment: Yes. Essentially the question is how to determine whether a functor is representable. In rather algebraic situations, we may use Freyd's criterion. In more geometric situations, it is much more subtle. One of the most famous examples is probably Grothendieck's proof that the Hilbert scheme is representable.
Answer: A satisfactory characterization is unlikely. The reason that you get a nice characterization (i.e., natural iso correspond to isos) in the case of $h^A\to h^B$ is that both domain and codomain are of the same type, and thus Yoneda works both ways. But, when you turn to general $h^A\to F$, for which Yoneda works, you are now interested in knowing when will there be an inverse natural transformation $F\to h^A$, and here Yoneda does not work.
Also, since $F(A)$ is nothing but a set, it is impossible to characterize those elements in it that correspond under Yoneda to natural isos without looking outside of the particular value $F(A)$. So, you must really look at the case at hand and can't expect to get a characterization for free, by so called general abstract nonsense. It's where you would stop using general abstract nonsense and start analyzing what's going on in the particular case you are looking at.
Comment: Thanks for your comment. It really explains why a nice characterization for my first example works and why this doesn't work for general situations.


javascript timestamp from years ago and consider leap years

Question: I store user date of birth in timestamp. I calculate timestamp with javascript.
day = $("#birthday-day").val();
year = $("#birthday-year").val();
month = $("#birthday-month").val()-1;
date = new Date(Date.UTC(year, month, day));
birthdateTimestamp = Math.round(date.getTime() / 1000);

In Search page I have only age field. Depend on this field I need to display users that match this age. I calculate from age field value timestamp so I can use it in database as condition.
now = new Date();
age = $("#age").val();
date = new Date(Date.UTC(now.getFullYear()-age));
timestampYearsAgo = date.getTime()/1000;

My question:
Are these methods leap years safe or can I have any problems because of leap years? I am quite sure the first part is ok (correct me if not please), but for second part when I calculate timestamp from age, I am not sure how could be done to be leap years also considered. Does anybody have any idea?
Tnx
Answer: The date you create in the second sample corresponds to 1/1 the given year (since you only supply year, day and month default to 0). This is probably not what you want.
If you want people who is a certain age today, you should create a date which corresponds to today and then substract the years, e.g.:
var lowDate = new Date;
lowDate.setFullYear(lowDate.getFullYear() - age));
lowTimestamp = lowDate.getTime()
var highDate = new Date;
highDate .setFullYear(highDate .getFullYear() - age + 1));
highTimestamp = highDate.getTime()

If a birthday timestamp is between lowTimestamp and highTimestamp the age is correct.
Answer: It's ok, the Date object will account for leap years for you but not leap seconds :)
If you are playing around with dates a lot you may want to look at something like http://tempus-js.com/ which includes api methods such as isLeapYear().


Convert text content to JSON using CSV node in NODE_RED?

Question: Can any one help me how can we pass input with multiple lines to CSV node which has different columns/elements for each line.
I have a text file with below content
<code>H|1|2|3|$|4|4
D|3|4|5
D|4|4|6
D|2|3|4
</code>
Here,how can we pass columns names for H-header,D-details differently to CSV node which generated JSON.
Thanks in advance!!
Answer: The best you can do is to use a switch node to split lines based on the first character and then run those lines through 2 separate CSV nodes.

The 2 CSV node can contain the header names for different line types.
The switch node should be configured something like this:

You can then combine the 2 legs of the flow again to consume the different messages for the output of the CSV nodes.


Confidence band for the ROC curve

Question: How would you construct a confidence band for the ROC curve?
I do not mean a confidence interval for the AUC or for other parameters that can be derived from the ROC curve, but a confidence band for the curve itself.
I came across this paper from Macskassy, Provost & Rosset, but it is relatively old paper (from 2005), and also this paper by Kerekes from 2008 (but it does not provide a methodology which was not considered by Macskassy et. al.
I was thinking about using bootstrap, but then the question is how to order the bootstraped curves to get the 2.5% and 97.5% percentiles. One possibility is to order the curves by their respective AUCs, or another one-dimentional parameter (e.g. Youden index).
Any idea will be welcomed.
Answer: I would use bootstrap, as I have done in Robin et al. 2011.
I would select a set of specificities, bootstrap the, and calculate the confidence interval of the specificities at each selected specificity, no ordering of the curves needed.

Confidence band for the ROC curve


Select para criar saldo com base no valor do mês anterior

Question: Estou com a seguinte situação. Tenho uma base Mysql onde uma das colunas (liquido_dia) traz o valor diário gerado (positivo ou negativo), já estou montando nela um demonstrativo por mês do valor gerado no mês usando o GROUP BY MONTH(data).
O que estou precisando agora é gerar uma nova coluna (imagem abaixo) com saldo acumulado, pegando sempre o valor do mês anterior e somando ao novo mês. Estou programando em PHP com o banco em Mysql
SQL que já estou fazendo
SELECT * FROM operacoes WHERE id_usuario = '{$codigoUser}' GROUP BY MONTH(data)

Tela que já estou trazendo alguns dados, mais notem que a coluna ACUMUALDO esta vindo a suma errada, é o que estou tentado corrigir no select
Isto será usado para verificar se o usuário esta com saldo positivo ou negativo no mês e saber se ele deve gerar DARF de imposto ou fazer compensação do negativo para os próximos meses.
Obrigado a todos
Answer: obrigado por sua resposta.
Rodei sua consulta no meu banco para testar, veja como ele retornou

Somente ajustes para os nomes das minhas colunas e deu um GORUP BY para trazer a soma de cada mês
set @csum := 0;
select data, liquido_dia, (@csum := @csum + liquido_dia) as acumulado from operacoes GROUP BY month(data);

Answer: Você pode usar uma variável Mysql
Exemplo no SQLFIDDLE: http://sqlfiddle.com/#!9/5ed061/4
CREATE TABLE `operacoes` (
  `id` bigint(20) NOT NULL PRIMARY KEY AUTO_INCREMENT,
  `mes` date NOT NULL,
  `valor` decimal(10,2) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

INSERT INTO `operacoes` (`id`, `mes`, `valor`) VALUES
(1, '2020-01-01', '670.04'),
(2, '2020-02-01', '453.00'),
(3, '2020-03-01', '154.00'),
(4, '2020-04-01', '543.00')

set @csum := 0;
select mes, valor, (@csum := @csum + valor) as acumulado
from operacoes
order by mes;

Isso calcula a soma parcial de forma corrente


How to show $p_n < p_1 + p_2 + \cdots + p_{n-1}$?

Question: How do you show that, if $p_n$ denotes the $n$th prime, $n > 3$, then
$$p_n < p_1 + p_2 +\cdots + p_{n-1}$$
using the Bertrand conjecture and induction?
Here is what I've come up with, but I'm not sure if it's correct:
Let $n=4$. Then, $p_4 = 7$, so we have:
$$7 < 2+3+5 = 10.$$
Assume that the statement is true for $n$ so that $p_n < p_1 + p_2 +\cdots + p_{n-1}$.
We want to prove that this is true for $n+1$.
$$p_{n+1} < p_1 + p_2 +\dotsc + p_{n-1} + p_n.$$
But we assumed that $p_n < p_1 + p_2 +\cdots + p_{n-1}$, so we have:
$$p_{n+1} < p_1 + p_2 +\cdots + p_{n-1} + p_n < p_n + p_n = 2p_n.$$
We know that $p_n < p_{n+1}$, so we have:
$p_n < p_{n+1} < 2p_n$, which is true by the Bertrand conjecture. $\blacksquare$
Comment: You have a good idea about relating this problem to Bertrand's "postulate", but you get some steps out of order toward the end of your argument.  Go through the next to last line a little slower, and keep in mind that you know $p_{n+1} \lt 2 p_n $, and are trying to prove $p_{n+1} \lt p_1 + \ldots +p_n $.
Answer: You seem to have the right basic idea, but where you wrote
$$p_{n+1} < p_1 + p_2 +\dotsc + p_{n-1} + p_n < p_n + p_n = 2p_n$$
the second inequality is wrong.  It would be better to first invoke Bertrand's postulate to establish $p_{n+1}\lt 2p_n$ and then apply the inductive hypothesis to get
$$p_{n+1}\lt2p_n=p_n+p_n\lt p_1+p_2+\cdots+p_{n-1}+p_n$$


How to dynamically modify a text file on a php site in real time

Question: I'm currently displaying a txt file on my website which is constantly being modified. Is there any way to display the modifications to the text file on the page in real time so I don't need to set a page refresh timer to see changes?
The full code for my site can be found here.
https://pastebin.com/JauZurS7
<code>if (isset($_GET['enSubmit']) && isset($_GET['uname']) && isset($_GET['rname'])){
echo'<meta http-equiv="refresh" content="10">';
$room=$_GET['rname'];
$uname=$_GET['uname'];
if (!is_dir($room)) mkdir($room);
$files = scandir($room);
foreach ($files as $user){
    if ($user=='.' || $user=='..') continue;
    $handle=fopen("$room/$user",'r');
    $time = fread($handle, filesize("$room/$user"));
    fclose($handle);
    if ((time()-$time)>1) unlink("$room/$user");
}
$contents='';
$filename="$room.txt";
if (file_exists($filename)){
    $handle = fopen($filename, "r");
    $contents = fread($handle, filesize($filename));
    fclose($handle);
}
$handle = fopen("$room/$uname", "w");
fwrite($handle, time());
fclose($handle);

$files = scandir($room);
$users='';
foreach ($files as $user) if ($user!='.' && $user!='..') $users.=$user."\n";

if (isset($_POST['Send'])){
    $text=$_POST['txt'];
    $contents.="$uname: $text";
    $handle = fopen("$filename", "a");
    fwrite($handle, "$uname: $text\n");
    fclose($handle);
}
</code>
Currently, the chat system works by people sending text which is appended to a text file. The text file is updated but in order for users to see the changes from others they have to refresh the page. To combat this I set up a 10 second refresh timer, however the problem is that people who are typing at that time will have their work removed. I'm thinking of using filemtime to append the txt file but I'm not sure how to do that.
Answer: You would generally want to use javascript(Ajax more specifically) to dynamically load data in the background of the page. This would allow for you to not have to refresh the page etc.. to view and get/send content
Comment: Welcome to StackOverflow. While this answer may solve the question, including an explanation of how and why this solves the problem would really help to improve the quality of your post, and probably result in more up-votes. Remember that you are answering the question for readers in the future, not just the person asking now. Please edit your answer to add explanations and give an indication of what limitations and assumptions apply.


Upload a https-link to a DataStore

Question: I have a direct link to a 4GB file.
How can I download it to a DataStore at vSphere 4? (without downloading it to my computer)
Thanks in advance
Answer: You need SSH access to the ESX console as ESX/ESXi comes with BusyBox and BusyBox has a slim wget. You can enable SSH access from the vSphere Client, in Configuration > Security > SSH Server.
First, SSH to the ESX host (use PuTTY if you're on Windows)
$ ssh email@example.com

Change directory to the datastore you want to put the file in
~ # cd /vmfs/volumes/datastore1

Then ,simply wget the file
~ # wget http://example.com/file.iso

Now mount/use the file from the vSphere client.
Comment: +1 Thanks it seems to work good - the problem is, the 'wget' don't support SSL
Comment: Ah I see, I'm currently not at my desk, so I can't check if ESXi has cURL or not, or if that's the old ESX. Either way, you can always try it by doing `~ # curl http://example.com/file.iso -o file.iso`
Answer: He asked about HTTPS link, not HTTP.
HTTPS links cause this error:
wget: not an http or ftp url
Solution:
Compile own wget, with SSL support,
or download curl binary (static compiled) for ESX.

Upload a https-link to a DataStore


Problemas Embarrassingly parallel?

Question: Estava procurando problemas chamados de "embaraçosamente paralelos", que são problemas que não existem dependências entre tarefas, podendo as mesmas serem divididas paralelamente.
Poderia me dar alguma sugestão de algum algoritmo?
Answer: Renderização de imagens
Um algoritmo desse gênero é a renderização de cenas tridimensionais, em que cada pixel é renderizado por completo sem depender em nada da renderização dos outros pixels.
É por isso que as GPUs atuais ampliam cada vez mais o número de processadores chamados de shaders, que são responsáveis por calcular a cor final de cada pixel, de forma independente um dos outros.
Uma menção importante nesse conjunto é o ruído de Perlin (Perlin noise em inglês), que é usado para gerar ruído pseudo-aleatório.
Simulações físicas com partículas
Outro exemplo são simulações físicas, em que cada partícula tem suas características alteradas levando em conta o estado anterior da simulação. Ou seja, em cada passo, as partículas não interagem entre si, mas sim com as partículas do estágio anterior.
Também por isso, muitos jogos usam a GPU para fazer simulações físicas com um número muito maior de partículas, obviamente a GPU tem que oferecer suporte para isso.
Problemas que não paralelizam por completo
Problemas da categoria "Dividir para conquistar", não são tão paralelizáveis para árvores pequenas. Mas a medida que o conjunto de informações cresce, a solução vai se tornando cada vez mais paralelizável.
Exemplos:

somar todos os números de uma lista gigante... é possível subdividir o problema, dividindo a lista gigante em listas menores e delegar a solução parcial para processadores distintos.
buscar todas as alternativas em um jogo de xadrez (terá de definir a profundidade máxima da busca, pois é impossível calcular todas... o número de alternativas é absurdamente grande)
Answer: Alguns problemas clássicos de algoritmos relativamente simples e bons de paralelizar são:
Cálculo de Pi usando o Método de Monte Carlo
Considere a seguinte imagem com um quadrado e um círculo cujo diâmetro tem a mesma medida do lado do quadrado.

Agora imagine que o círculo é um alvo. Você jogará dardos aleatoriamente dentro do quadrado.
Agora considere a fórmula abaixo:

Isso significa que se você pegar a quantidade de dardos que acertaram dentro do círculo,  dividir pela quantidade que acertou fora do círculo e multiplicar por quatro, obterá um valor de Pi aproximado.
A teoria diz que a aproximação melhora de acordo com o número de dardos lançados. Logo, um programa em paralelo pode "jogar dardos" aleatoriamente no quadrado e contabilizar a quantidade de dardos dentro e fora do círculo. Ao final, basta somar os resultados e aplicar na fórmula.
Aproximação de integral pela regra trapezoidal
Você quer o valor aproximado da integral de uma função f(x) no intervalor de a a b.
Uma forma bem simples (e imprecisa) de resolver isso é calcular a integral de uma função linear que passa pelos pontos f(a) e f(b).
Veja o exemplo:

Em azul você tem a função real e em vermelho a função linear usada para calcular a aproximação.
Bem, uma função linear vai resultar numa aproximação ruim. Porém, aumentarmos a quantidade de pontos da função de aproximação, o resultado será mais preciso, certo? Quanto mais pontos calcularmos, melhor.

Então, podemos usar um programa paralelo e dividir o intervalo [a, b] pelo número de threads ou processos e cada um calcular a integral parcial daquele trecho.
No final, basta somar os resultados.

Problemas Embarrassingly parallel?


What does "Mm." in this case mean?

Question:
I don't know what Mm. means. It can't be beats per minute because it's not possible to have 4-6 beats per minute.
Comment: Well, it **is** possible, it's just supremely unlikely.
Comment: Is it possible that this is an excerpt from another exercise? It definitely means "measures" as a previous answer has said, but I'm curious about the background of this exercise.
Comment: Is there another piece of music in the book where these rhythms occur in measures 4,5 and 6? This page is a rhythm workshop on those rhythms using the right hand (notes above the line) and left hand (notes below).
Answer: We need context.  Maybe this method has its own system of speed categories.  Maybe it's just 'Measures'.  Maybe it's a misprint.  I can't see any connection with figured bass and chords though.   Pity about the dumb '8ths = triplets' notation when doubtless they want Swing.  If this is percussionist training, they ought to know the difference between swing and triplet shuffle.
(EDIT:After reading the comment below from @JimM)
OK, problem solved.  It's the rhythm of measures 1 & 2 of the music that follows.  Thanks, Jim.
Comment: As I suspected in my (six-month old!) comment to the OP. Nice work, Laurence and JimM.
Comment: Does this shed any more light on it?  [link](https://books.google.co.uk/books?id=eATmCAAAQBAJ&pg=PA14&lpg=PA14&dq=rhythm+workshop+Mm&source=bl&ots=cGXRU7_NJI&sig=9VM7nP-pdui5lnuspW5gGzhehFk&hl=en&sa=X&ved=0ahUKEwj647vN-YDWAhXjKMAKHRACBiwQ6AEILTAB#v=onepage&q=rhythm%20workshop%20Mm&f=false)
Answer: At least according to https://en.wikipedia.org/wiki/Bar_(music), "Mm." can also stand for measure numbers. Presumably, the rhythm workshop wants you to repeat measures 4-6 when you practice.
Comment: mm is definitely the abbreviation for "measures," as m is it for the singular.  (As pp means pages, etc.)
Comment: Unless the picture shows Measures 4-5, I assume that the only reason why "Mm. 4-6" is mentioned is because they contain the rhythm that should be "Tap(ped)...3x daily".
Comment: But what makes it say 'repeat bars 4-6'? And why would you?
Comment: @L3B and _qq. v._ is the plural of _q. v.,_ and the Spanish abbreviation for _Estados Unidos_ is, because it is plural, _EE. UU._

What does "Mm." in this case mean?


How to optimise this query?

Question: i am new to XQuery.
please suggest a way to optimse below query.
i have tried below query it is taking more time than expected.
<code>Select
A.a_name,
I.p_type,
SUM(P.c_n_amount) AS c_n_amount,
CASE  WHEN SUM(ABS(M_value)) = 0 THEN 0
ELSE SUM(ABS(Price) * ABS(M_value)) / SUM(ABS(M_value)) END AS
[price],
SUM(M_value) AS m_value,SUM(N50) [-50],SUM(P50) [50]
from  position P
INNER JOIN COUNT AS A ON P.a_id = A.a_id
INNER JOIN I_VIEW AS I ON P.i_id = I.i_id
inner join (
select R_C.p_id,M_value,Price,N50,P50
from(
select j.p_id,
C.value('(Result[@resultName = "m_value"]/resultValue)[1]', 'float') as M_value,
C.value('(Result[@resultName = "price"]/resultValue)[1]', 'float') as Price
from  jyothi_xml j CROSS APPLY resultkeys.nodes('/Results')  T(C)
where r_set='POLY' and r_category ='sk')  R_Category,
(select j1.p_id,
C.value('(Result[@resultName = "rate_shock_n50"]/resultValue)[1]', 'float') as N50,
C.value('(Result[@resultName = "rate_shock_p50"]/resultValue)[1]', 'float') as P50
from jyothi_xml j1 CROSS APPLY resultkeys.nodes('/Results')  T(C)
where result_set='POLY' and result_category ='rate_shocks')  R_S_Category,position p
where p.p_id=R_Category.p_id and p.p_id=R_S_Category.p_id) XMlData  on p.p_id=XMlData.p_id
WHERE P.as_of_date = '2012-10-10'
GROUP BY A.a_name, I.p_type
</code>
Comment: What is the data you operate on? And what is your expected result? In general, in XQuery it is benefical to have predicates as early as possible, i.e. instead of (Result[@resultName = "m_value"]/resultValue)[1] use (Result[@resultName = "m_value"][1]/resultValue).
However, I guess that XQuery is not the bottleneck here. Instead, you have a quite costly SQL with joins, aggregations and subquerys. In comparison, your XQuery seems to be simple data extraction. Please check first, that XQuery is really the problem here.
Answer: If you have a lot of XML to parse through, it is very beneficial to first limit which rows with XML you need, then parse through them.  So, if you can, figure out what you need from your Position, Count, and I_View tables and then just search for those IDs in the jyothi_xml table.  I found that this helps a lot with my queries.

How to optimise this query?


How to handle multiple sprites' zPositions as they move around each other?

Question: I'm new to programming in Swift. I'm trying to create a game where I have a bunch of sprites that move randomly around the screen. Let's say I have a bunch of simple 2D image sprites. As a sprite move upwards (as in y position is increasing) I want it to appear to move further back behind other sprites, so I want the zPosition to decrease in comparison to the other sprites. How do games handle this? What if I have 100 sprites on the screen that are all moving around randomly? I don't really even have a general idea of how this is handled, so any help would be much appreciated.
Second more advanced concept. So let's say each sprite has multiple layers of child sprites, like arms, legs, clothes, weapons, etc. (My sprites are highly customizable.) Then each sprite walks around randomly and needs to appear in the correct zPosition as they move behind other sprites. How would I make sure all the arms, legs, clothes, and other layers of sprites appear correctly in front or behind every other sprite? What if I have a sprite with 20 layers of sprite children and it needs to move seamlessly in front and behind other sprites with 20 sprite children? This might be the wrong direction, but can I somehow make one sprite and its children layers into 1 layer (or make all the left arm sprites into 1 layer and the right arm sprites into another layer)? I see games that handle this, but what's the concept behind how this is handled? (One game I see that kind of does what I want is Fallout Shelter, where each person has arms, legs, weapons, etc and they walk in front of or behind other people and all the sprites appear in the correct manner, but unlike Fallout Shelter my game has completely flat looking 2D imagery and that's how I want it to stay.)
Third even more advanced concept. What if I wanted these sprites to interact like one sprite's arms grab around another sprite (so one arm will be behind a second sprite person, but the opposite arm will be completely in front of the other sprite person)? How are the layers handled to appear in the correct zPosition? Maybe this is not possible? Okay I'm done. Sorry for putting a million questions into one post. I'm looking for the concept behind these questions so I can start planning and programming. Thanks for any help.
Comment: You have nine sentences with a question mark.  This isn't really a Q & A site.  If you want to have all those questions answered, you should probably consult somebody paying a consultation fee.
Comment: Technically, you can override `SKNode`'s property `var zPosition: CGFloat` and return a value calculated based on the sprite's z position. Further considerations are specific to the game you want to make, and I really think you should just sit down to think what effect you want to achieve, and determine an algorithm to achieve it.
Answer:
1) As a sprite move upwards (as in y position is increasing) I want it to appear to move further back behind other sprites, so I want the zPosition to decrease in comparison to the other sprites. How do games handle this?

This can simply be done by creating a custom class (I would not recommend extending this) and overriding the zPosition to be the inverse of Y
E.G.
class Player : SKSpriteNode
{

    override var zPosition : CGFloat
    {
        get
        {
             //Yes it looks weird to be setting zPosition on get, but we want to ensure the variable storing zPosition is also changed in case any property reads it
             super.zPosition = -super.position.y
             return super.zPosition
        }
        set
        {
            //do nothing
        }
    }
}

2)What if I have 100 sprites on the screen that are all moving around randomly?

Overriding this will handle every sprite on the screen (that is of type 'Player' in my example) the y position determines the zPosition

3)How would I make sure all the arms, legs, clothes, and other layers of sprites appear correctly in front or behind every other sprite?
  Now this gets a little tricky.  zPosition is relative to its parent, so you would need to account for how many layers deep your sprite can get zPosition wise, and plan accordingly.  Say we have a sprite with shirt pants and a belt.

If we structured the sprite like this:
    body
    ->shirt
    ->pants
    ->belt
Then we can set all the zPositions to 0 of those child nodes, because the rendering order would use the zPosition followed by tree order, and nothing would change:
But if we structured it like this:
    body
    ->shirt
    ->pants
    --->belt
and we want to give the affect of the shirt being between the pants and belt,  then we would need to compensate by setting a zPosition of 1 to both shirt and belt.

4)What if I have a sprite with 20 layers of sprite children and it needs to move seamlessly in front and behind other sprites with 20 sprite children?
  Now we have a problem with battling other sprites, so we need to apply some math to our zPosition on the Player to fix it.
      class Player : SKSpriteNode
      {

    override var zPosition : CGFloat
    {
        get
        {
             //Yes it looks weird to be setting zPosition on get, but we want to ensure the variable storing zPosition is also changed in case any property reads it
             super.zPosition = -super.position.y * 2 //(We need at least 2 zPosition slots reserved for every sprite)
             return super.zPosition
        }
        set
        {
            //do nothing
        }
    }
}

5)But can I somehow make one sprite and its children layers into 1 layer (or make all the left arm sprites into 1 layer and the right arm sprites into another layer)?
  6) I see games that handle this, but what's the concept behind how this is handled?
  Yes, you can use view.texture(from:) to convert any node to a texture, then create a new sprite out of the texture.
7)What if I wanted these sprites to interact like one sprite's arms grab around another sprite (so one arm will be behind a second sprite person, but the opposite arm will be completely in front of the other sprite person
  8)How are the layers handled to appear in the correct zPosition
  9)Maybe this is not possible?

This part now gets tricky,  instead of doing the multiplication, we would need every nodes zPosition to change.
We also would need to calculate the absolute position of every sprite to know where we are on the y axis
In order to do that, we have at least 3 options,
a)we can make a custom protocol + custom classes for every node we place on the scene
b) can write extensions for the the node types we place on scene (e.g. SKSpriteNode and SKShapeNode) with the exception of SKNode because that is the base node class
c) we can do something called Key Value Observation, and we need to listen to when the position changes on a sprite.  The reason why we need to do KVO is because your sprite may be structured where you have SKNodes, and we can't override position on this.
All three of these methods would require extensive work and would require optimizations unique to your game environment to run efficiently, which i am not going to write in detail how to do this.
Comment: Thanks for taking the time to answer all my questions! This is awesome! I just needed help wrapping my head around these concepts so that I could decide how to move forward. Your answer is very helpful. Thank you for the guidance.


converting a base 64 string to an image and saving it

Question: Here is my code:
protected void SaveMyImage_Click(object sender, EventArgs e)
        {
            string imageUrl = Hidden1.Value;
            string saveLocation = Server.MapPath("~/PictureUploads/whatever2.png") ;

            HttpWebRequest imageRequest = (HttpWebRequest)WebRequest.Create(imageUrl);
            WebResponse imageResponse = imageRequest.GetResponse();

            Stream responseStream = imageResponse.GetResponseStream();

            using (BinaryReader br = new BinaryReader(responseStream))
            {
                imageBytes = br.ReadBytes(500000);
                br.Close();
            }
            responseStream.Close();
            imageResponse.Close();

            FileStream fs = new FileStream(saveLocation, FileMode.Create);
            BinaryWriter bw = new BinaryWriter(fs);
            try
            {
                bw.Write(imageBytes);
            }
            finally
            {
                fs.Close();
                bw.Close();
            }
        }
}

The top imageUrl declartion is taking in a Base64 image string, and I want to convert it into an image.  I think my set of code only works for images like "www.mysite.com/test.jpg" not for a Base64 string.  Anybody have some suggestions?  Thanks!
Comment: Try to use:    byte[] bytesContent = Convert.FromBase64String(Str64File);
Answer: Here is an example, you can modify the method to accept a string parameter.  Then just save the image object with image.Save(...).
public Image LoadImage()
{
    //data:image/gif;base64,
    //this image is a single pixel (black)
    byte[] bytes = Convert.FromBase64String("R0lGODlhAQABAIAAAAAAAAAAACH5BAAAAAAALAAAAAABAAEAAAICTAEAOw==");

    Image image;
    using (MemoryStream ms = new MemoryStream(bytes))
    {
        image = Image.FromStream(ms);
    }

    return image;
}

It is possible to get an exception A generic error occurred in GDI+. when the bytes represent a bitmap.  If this is happening save the image before disposing the memory stream (while still inside the using statement).
Comment: Yes this is a black pixel: R0lGODlhAQABAIAAAAAAAAAAACH5BAAAAAAALAAAAAABAAEAAAICTAEAOw==
Comment: @katmanco I would think the black pixel was provided as an example. Try replace the example base64 string with your own base64 string
Comment: You may need to add a reference to the System.Drawing DLL
Comment: @Bibin did you try saving the image inside the using statement?
Comment: This method gives me black rectangle , do you have any idea ?
Comment: @klingdigital Hello , here we had a misunderstanding . and also I found that when sending base64 data from javascript I had some errors  that is why my desired image was black .
Comment: I get the same error A generic error occurred in GDI+ what we do
Comment: @CRice Thanks I am use other one save the image is successfully
Comment: Yes if you don't need to 'convert it to an Image' instance first it can go straight to disk (as the other answers demonstrate).
Comment: Could you, please, specify the full name of the `Image` class?
Comment: @SasukeUchiha System.Drawing.Image. If you don't need to convert to an Image first  you can go straight to disk and not take this dependency.
Comment: This violates a specification in MSDN for `Image.FromStream()`, where it says "You must keep the stream open for the lifetime of the Image."
Answer: You can save Base64 directly into file:
string filePath = "MyImage.jpg";
File.WriteAllBytes(filePath, Convert.FromBase64String(base64imageString));

Comment: I tried both this and @CRice's solution (using `Image.Save()`). Both work, but for some reason this version makes my file size 30% smaller with no discernible change in image quality
Comment: This is an excellent solution in my case where I was using mono on Linux and experienced some odd behavior with gdi+ in Image.Save. This solution completely bypasses Image / Gdi+ (See http://stackoverflow.com/questions/35783690/mono-on-centos-6-7-gdi-exception-saving-img)
Answer: Here is what I ended up going with.
    private void SaveByteArrayAsImage(string fullOutputPath, string base64String)
    {
        byte[] bytes = Convert.FromBase64String(base64String);

        Image image;
        using (MemoryStream ms = new MemoryStream(bytes))
        {
            image = Image.FromStream(ms);
        }

        image.Save(fullOutputPath, System.Drawing.Imaging.ImageFormat.Png);
    }

Comment: This gave me an error `A generic error occurred in GDI+` described [here](http://stackoverflow.com/q/336387/345659). Moving the `image.Save` inside the using block fixed it for me.
Comment: @JumpingJezza - Of course it did... The memory stream was already disposed of...
Answer: I would suggest via Bitmap:
public void SaveImage(string base64)
{
    using (MemoryStream ms = new MemoryStream(Convert.FromBase64String(base64)))
    {
        using (Bitmap bm2 = new Bitmap(ms))
        {
            bm2.Save("SavingPath" + "ImageName.jpg");
        }
    }
}

Comment: what's the difference between converting via bitmap or without bitmap ? thx
Answer: In my case it works only with two line of code. Test the below C# code:
String dirPath = "C:\myfolder\";
String imgName = "my_mage_name.bmp";

byte[] imgByteArray = Convert.FromBase64String("your_base64_string");
File.WriteAllBytes(dirPath + imgName, imgByteArray);

That's it. Kindly up vote if you really find this solution works for you. Thanks in advance.
Comment: It's copy of my answer (see below https://stackoverflow.com/a/35160048/4190593) :)
Comment: -1 because `dirPath` has to have an `@` sign before the string i..e. `@"C:\myfolder\"` or you have to escape the backslashes in the string i.e. `"C:\\myfolder\\"`
Comment: you should provide reference to that other answer instead of taking whole credit....
Answer: Here is working code for converting an image from a base64 string to an Image object and storing it in a folder with unique file name:
public void SaveImage()
{
    string strm = "R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7";

    //this is a simple white background image
    var myfilename= string.Format(@"{0}", Guid.NewGuid());

    //Generate unique filename
    string filepath= "~/UserImages/" + myfilename+ ".jpeg";
    var bytess = Convert.FromBase64String(strm);
    using (var imageFile = new FileStream(filepath, FileMode.Create))
    {
        imageFile.Write(bytess, 0, bytess.Length);
        imageFile.Flush();
    }
}

Answer: In a similar scenario what worked for me was the following:
byte[] bytes = Convert.FromBase64String(Base64String);
ImageTagId.ImageUrl = "data:image/jpeg;base64," + Convert.ToBase64String(bytes);

ImageTagId is the ID of the ASP image tag.
Answer: If you have a string of binary data which is Base64 encoded, you should be able to do the following:
byte[] encodedDataAsBytes = System.Convert.FromBase64String(encodedData);

You should be able to write the resulting array to a file.
Comment: **No?** I'm sorry, this is _incorrect_. Converting a Base64 string to its _binary equivalent_ does not make it an image. (Thanks @elliotwesoff for pointing that out!) And, _why_ are you mentioning _binary data_? This question in no way mentions _binary_, or even how to convert it.
Comment: This doesn't work. It just converts the base64 string to its binary equivalent. Writing that to a file with an image extension doesn't make it an image.
Answer: public bool SaveBase64(string Dir, string FileName, string FileType, string Base64ImageString)
{
    try
    {
        string folder = System.Web.HttpContext.Current.Server.MapPath("~/") + Dir;
        if (!Directory.Exists(folder))
        {
            Directory.CreateDirectory(folder);
        }

        string filePath = folder + "/" + FileName + "." + FileType;
        File.WriteAllBytes(filePath, Convert.FromBase64String(Base64ImageString));
        return true;
    }
    catch
    {
        return false;
    }

}

Comment: While this code may resolve the OP's issue, it is best to include an explanation as to how your code addresses the OP's issue. In this way, future visitors can learn from your post, and apply it to their own code. SO is not a coding service, but a resource for knowledge. Also, high quality, complete answers are more likely to be upvoted. These features, along with the requirement that all posts are self-contained, are some of the strengths of SO as a platform, that differentiates it from forums. You can edit to add additional info &/or to supplement your explanations with source documentation.
Answer: Using MemoryStream is not a good idea and violates a specification in MSDN for Image.FromStream(), where it says

You must keep the stream open for the lifetime of the Image.

A better solution is using ImageConverter, e.g:
public Image ConvertBase64ToImage(string base64)
    => (Bitmap)new ImageConverter().ConvertFrom(Convert.FromBase64String(base64));

Comment: That's correct. good solution exactly when you want to use image without saving in local storage
Answer: In NetCore 6.0, you can use HttpClient and the async methods in the new File class.
The implementation is very simple:
static async Task DownloadFile(string imageUrl, string pathToSave)
{
    var content = await GetUrlContent(url);
    if (content != null)
    {
        await File.WriteAllBytesAsync(pathToSave, content);
    }
}

static async Task<byte[]?> GetUrlContent(string url)
{
    using (var client = new HttpClient())
    using (var result = await client.GetAsync(url))
        return result.IsSuccessStatusCode ? await result.Content.ReadAsByteArrayAsync():null;
}

Usage:
await DownloadFile("https://example.com/image.jpg", @"c:\temp\image.jpg");

Answer: you can convert a base64 string to an image and save it using the following code. This example assumes you're working with a console application, but the core logic can be adapted for other types of projects.
using System;
using System.Drawing;
using System.IO;

class Program
{
     static void Main()
       {
    // Replace this string with your actual base64-encoded image
    string base64String = "your_base64_encoded_string_here";

    // Convert base64 to bytes
    byte[] imageBytes = Convert.FromBase64String(base64String);

    // Convert bytes to image
    Image image = ConvertBytesToImage(imageBytes);

    // Specify the path to save the image
    string filePath = "path_to_save_image.png";

    // Save the image to the specified path
    SaveImage(image, filePath);

    Console.WriteLine($"Image saved at: {filePath}");
}

static Image ConvertBytesToImage(byte[] imageBytes)
{
    using (MemoryStream ms = new MemoryStream(imageBytes))
    {
        Image image = Image.FromStream(ms);
        return image;
    }
}

static void SaveImage(Image image, string filePath)
{
    image.Save(filePath, System.Drawing.Imaging.ImageFormat.Png);
}

}


How to get the dimensions of an Icon from its handle?

Question: I have a handle to the icon (HICON) and have to find out the dimensions of the icon that it represents. How do I get this information?
Answer: Pass it to GetIconInfo() then pass either the returned colour or mask HBITMAP to GetObject() to get a BITMAP struct that has height/width members.
Comment: It is important to note that both icons returned in `ICONINFO` must be freed using `DeleteObject` API to prevent resource leak.
Comment: My icon is 16x16 but the `BITMAP` width/height properties are saying 32x32...


Immersing punctured torus

Question: I am looking for a proof (as elementary as possible) of the fact that punctured n-dimensional torus admits an immersion to $\mathbb{R}^n$. The 2-dimensional case seems to be evident, but I haven't got the idea how to give an explicit construction in the n-dim case.
Answer: The general case is very much like the 2-dimensional case, it just takes time to process the picture, to see how you could do the same constructions in the higher-dimensional case.
A punctured $S^1 \times S^1$ looks like a wedge of two circles, but fattened up a little bit.  Precisely, around each circle you have an annulus neighbourhood.  To immerse the punctured torus into $\mathbb R^2$ what you do is you embed the first annulus, and then embed the 2nd annulus so that it overlaps the first in the same way that the two annuli live in the torus itself.  In doing this you create an extra overlap, but that's fine as we're only looking for an immersion.
A punctured $S^1 \times S^1 \times S^1$ has the same kind of decomposition.  It looks like the union of three "annuli" , precisely, $[0,1] \times S^1 \times S^1$, $S^1 \times [0,1] \times S^1$ and $S^1 \times S^1 \times [0,1]$, where here $[0,1]$ is shorthand for a small interval in $S^1$.  Each of these spaces you can embed in $\mathbb R^3$ as tubular neigbhourhoods of embedded tori.  You just have to make the embeddings overlap in the same way they overlap in $S^1 \times S^1 \times S^1$ -- and that is to make $[0,1] \times S^1 \times S^1 \cap S^1 \times [0,1] \times S^1 = [0,1]^2 \times S^1$, i.e they intersect along one of the coordinate circles.  So the idea is to draw a picture of an embedded torus, then along each of the two coordinate (longitude/latitude) axis, draw the boundary of a tubular neighbourhood of that axis.  Suitably interpreted, you can think of this picture as the image of the coordinate tori under your immersion.
The general picture goes like that.

Immersing punctured torus


Document click not in elements jQuery

Question: Using jQuery how does one detect clicks not on specific elements, and perform an action consequently?
I have the following JavaScript
$('#master').click(function() {
    $('#slave').toggle();
});

$(document).not('#master','#slave').click(function() {
    $('#slave').hide();
});

and I cannot see where I am going wrong logically. You can see a live example here
Comment: binding an instance of your click handler to every DOM element (except two) is going to be awful on performance.
Comment: The reason why your version doesn't work is because you're testing whether the `document` element doesn't have `master` or `slave` as its ID. This is always true (IIRC `document` can't have an ID), so the handler is bound to the `document` and every click will cause `slave` to be hidden. Then, because of event propagation, the `click` event from `#master` will bubble up to the `document` where it will hide `#slave`, even though `#master` just toggled it. You need to test `event.target` to make this work.
Answer: Since you're binding to the click event on the document, you can use event.target to get the element that initiated the event:
$(document).click(function(event) {
    if (!$(event.target).is("#master, #slave")) {
        $("#slave").hide();
    }
});

EDIT: As Mattias rightfully points out in his comment, the code above will fail to identify click events coming from descendants of #master and #slave (if there are any). In this situation, you can use closest() to check the event's target:
$(document).click(function(event) {
    if (!$(event.target).closest("#master, #slave").length) {
        $("#slave").hide();
    }
});

Comment: If `#master` or `#slave` have child elements, you need to use `closest` instead of `is` to make it work on those children.
Comment: This is a poor substitute for [`delegate`](http://api.jquery.com/delegate) which is already implemented in jQuery.
Comment: @zzzzBov, not really, the goal here is to delegate all the `click` events to the document and to special-case two elements and their descendants. Are you sure you can achieve the same thing with `delegate()` (or rather `on()`, which supersedes it in recent releases)?
Comment: @FrédéricHamidi, easily, see my answer.
Answer: Does this code do what you want? (not entirely sure if I understood correctly)
$('body').on('click', '*:not( #master, #slave )', function() {
    $('#slave').hide();
});

http://jsfiddle.net/gZ4Hz/8/
Answer: Event delegation has long been supported natively by jQuery. The difficulty lies in creating the appropriate selector. Originally, delegate was used, but more recently the delegate form of on should be used.
The purpose of event delegation is to listen to events on child elements and invoke the bound event handlers on those elements as though they had been bound to the child element, instead of the parent. This means that instead of binding handlers to every element in the DOM, you're binding a handler to every element in the initial selection (document is a single element). This also makes for a simple way to use a single selector to bind to an ever changing set of elements, as new elements will propagate their events to document whether or not they existed when the initial event handler was bound:
$(document).on('click', '*:not(#master, #master *, #slave, #slave *)', function (e) {
    //this will reference the clicked element
});

Additionally, note that I not only said the elements must not be #master or #slave, they must not be children of #master or #slave either.
Comment: Very interesting. I usually avoid `*` selectors both in CSS (cascading is sufficient most of the time) and in jQuery (matching a whole subtree can be costly), but I agree this should work at least as well as `event.target` combined to `closest()` on modern browsers. Now I'm curious about the perfs, maybe I'll set up a benchmark in my copious free time. Cheers :)
Answer: Another thought, it may not be working because your browser may not be rendering body at 100% height; Try adjusting your base css to fix height of body and then a couple other thoughts.
e.stopPropagation(): Prevents the event from bubbling up the DOM tree, preventing any parent handlers from being notified of the event.
So if you change the first click code to the following:
$('#master').click(function(e) {
    e.stopPropagation();
    $('#slave').toggle();
});

Then you could change the call sign of the second too:
$("body, body *").not('#master, #slave').click(function(e) {
    $('#slave').hide();
});

And that should cover it. Give it a try! or see this jsFiddle
Comment: Binding event handlers to every other elements isn't a good idea. Frédéric Hamidi's solution is better.
Comment: That is a horrible solution. You're binding that second handler separately to **every single element in the DOM**. Not only is this terribly inefficient, it won't even work with dynamically inserted elements added to the DOM afterwards. Frédéric's solution is much more elegant and (more importantly) works in every situation.
Comment: I never said it was the best solution and it's not "horrible". I simply showed him how to achieve what he was trying to achieve. So many "professors" on here. lmao
Answer: Fredrik's answers works for elements already present in the document, but it didn't work for elements fetched by ajax calls.
I tried the following and it works for me. Sharing the code for future ajax coders.
    $(document).on('click',function(event) {
        if (!$(event.target).closest("#selector").length) {
            if ($('#selector').is(":visible"))
                $('#selector').slideUp();
        }
    });

Would have posted it as a comment but I don't have enough reputation for that.
Answer: $('.clickable-row').on("click",function(){
  window.location = $(this).data('href');
  return false;
});
$("td > a").on("click",function(e){
  e.stopPropagation();
});

or
jQuery(document).ready(function($) {
    $('.clickable-row').on("click",function(){
      window.location = $(this).data('href');
      return false;
    });
    $("td > a").on("click",function(e){
        e.stopPropagation();
    });
});

Document click not in elements jQuery


How to display Monday as first day CalendarView

Question: With:
Calendar cal = Calendar.getInstance();
cal.setFirstDayOfWeek(Calendar.MONDAY);

you just set Monday's integer value to 0, but I want to have Monday displayed as first day (at the left end, and Sunday at the right)
Answer: Use xml parameter android:firstDayOfWeek with value from Calendar. 2 - is Monday.
    <CalendarView
    android:id="@+id/calendarView1"
    android:firstDayOfWeek="2"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_alignParentBottom="true"
    android:layout_centerHorizontal="true"
    android:layout_marginBottom="157dp" />

Or you can specify it from code
    CalendarView calendarView = findViewById(R.id.calendarView1);
    calendarView.setFirstDayOfWeek(Calendar.MONDAY);

Answer: String[] days = null;
DateFormatSymbols names = new DateFormatSymbols();
days = names.getWeekdays();

for (int i=1; i<8; ++i) {
    system.out.println(days[i]);
}

Comment: where do i have to implement this?


Transform YYYYMM to DD-MM-YYY SQL Server

Question: I have a column in sql server like 201801. How can I transform this in DD-MM-YYYY?
Thank you!
Comment: What date is that? Datatype? And any chance you fix the schema and use a date datatype instead of strings or ints?
Comment: What came up on Google when you researched transforming strings to datetimes?
Comment: It's a string and I need to transform in a date format but to keep it as a string.
Comment: Again....what date is that? And why oh why are sticking with using strings? This should be a date and the front end should handle the presentation.
Answer: Assuming date column has varchar type, then you can do :
select convert(varchar(12), cast(col+'01' as date), 105)
from table t;


rendering with multiple vertex and index buffer objects (ios - OpenGLES 2.0)

Question: I am not able to render my all objects using more than 1 pair of vertex and index buffer objects. To check everything, I initialized just 3 objects and render them. This results in a distorted geometry for the first two and the third objects geometry renders somewhat fine (not perfect).
When I just initialize all of the 3 but render just first, it again shows distorted geometry and somehow the third geometry is more visible (even when I am not rendering it).
However, If I am initializing and rendering any one of them, it renders just fine (perfect).
here is my code:
float tempAngles[4] = {0, 60, 180, 360};
pieOne = [[IVNode alloc]initWithPieGeometry:0.75 thickness:0.20 startAngle:tempAngles[0]*M_PI/180   andEndAngle:tempAngles[1]*M_PI/180];

glGenBuffers(1, &vertexBuffer1);
glBindBuffer(GL_ARRAY_BUFFER, vertexBuffer1);//vertexBuffer[i]);
glBufferData(GL_ARRAY_BUFFER, [pieOne.pie getVertexSize]*sizeof(GLfloat), [pieOne.pie returnVertexArray] , GL_STATIC_DRAW);

glGenBuffers(1, &indexBuffer1);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, indexBuffer1);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, [pieOne.pie getIndicesSize]*sizeof(GLushort),[pieOne.pie returnIndexArray], GL_STATIC_DRAW);

pieTwo = [[IVNode alloc]initWithPieGeometry:1.0 thickness:0.20 startAngle:tempAngles[1]*M_PI/180 andEndAngle:tempAngles[2]*M_PI/180];

glGenBuffers(1, &vertexBuffer2);
glBindBuffer(GL_ARRAY_BUFFER, vertexBuffer2);//vertexBuffer[i]);
glBufferData(GL_ARRAY_BUFFER, [pieTwo.pie getVertexSize]*sizeof(GLfloat), [pieTwo.pie returnVertexArray] , GL_STATIC_DRAW);

glGenBuffers(1, &indexBuffer2);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, indexBuffer2);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, [pieTwo.pie getIndicesSize]*sizeof(GLushort),[pieTwo.pie returnIndexArray], GL_STATIC_DRAW);

pieThree = [[IVNode alloc]initWithPieGeometry:0.75 thickness:0.20 startAngle:tempAngles[2]*M_PI/180 andEndAngle:tempAngles[3]*M_PI/180];

glGenBuffers(1, &vertexBuffer3);
glBindBuffer(GL_ARRAY_BUFFER, vertexBuffer3);//vertexBuffer[i]);
glBufferData(GL_ARRAY_BUFFER, [pieThree.pie getVertexSize]*sizeof(GLfloat), [pieThree.pie returnVertexArray] , GL_STATIC_DRAW);

glGenBuffers(1, &indexBuffer3);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, indexBuffer3);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, [pieThree.pie getIndicesSize]*sizeof(GLushort),[pieThree.pie returnIndexArray], GL_STATIC_DRAW);

//#define BUFFER_OFFSET(i) ((char *)NULL + (i))
glEnableVertexAttribArray(GLKVertexAttribPosition);
glVertexAttribPointer(GLKVertexAttribPosition, 3, GL_FLOAT, GL_FALSE, 6*sizeof(GLfloat), BUFFER_OFFSET(0));
glEnableVertexAttribArray(GLKVertexAttribNormal);
glVertexAttribPointer(GLKVertexAttribNormal, 3, GL_FLOAT, GL_FALSE, 6*sizeof(GLfloat), BUFFER_OFFSET(12));

Now In my rendering function I have:
-(void)glkView:(GLKView *)view drawInRect:(CGRect)rect
{

glClearColor(0.77f, 0.88f, 1.0f, 1.0f);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

float yellow[3][4] = {1.0f, 1.0f, 0.0f, 1.0f,
    1.0f, 0.0f, 0.0f, 1.0f,
    1.0f, 1.0f, 1.0f, 1.0f};

glUseProgram(_program);
//1st
GLKMatrix4 model = GLKMatrix4Identity;// GLKMatrix4MakeTranslation(1.5, 0, 0);
_modelViewProjectionMatrix = GLKMatrix4Multiply(_modelViewProjectionMatrix, model);

glUniformMatrix4fv(uniforms[UNIFORM_MODELVIEWPROJECTION_MATRIX], 1, 0, _modelViewProjectionMatrix.m);
glUniformMatrix3fv(uniforms[UNIFORM_NORMAL_MATRIX], 1, 0,_normalMatrix.m);
glUniform4f(uniforms[COLOR_VECTOR], yellow[0][0], yellow[0][1], yellow[0][2], yellow[0][3]);

//bind corresponding buffer before drawing
glBindBuffer(GL_ARRAY_BUFFER, indexBuffer1);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, indexBuffer1);
glDrawElements(GL_TRIANGLES, [pieOne.pie getIndicesSize], GL_UNSIGNED_SHORT, (void*)0);

//2nd
model = GLKMatrix4MakeTranslation(0, -1, 0);
_modelViewProjectionMatrix = GLKMatrix4Multiply(_modelViewProjectionMatrix, model);

glUniformMatrix4fv(uniforms[UNIFORM_MODELVIEWPROJECTION_MATRIX], 1, 0, _modelViewProjectionMatrix.m);
glUniformMatrix3fv(uniforms[UNIFORM_NORMAL_MATRIX], 1, 0,_normalMatrix.m);//
glUniform4f(uniforms[COLOR_VECTOR], yellow[1][0], yellow[1][1], yellow[1][2], yellow[1][3]);

//bind corresponding buffer before drawing
glBindBuffer(GL_ARRAY_BUFFER, indexBuffer2);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, indexBuffer2);
glDrawElements(GL_TRIANGLES, [pieTwo.pie getIndicesSize], GL_UNSIGNED_SHORT,(void*)0);

//3rd
model = GLKMatrix4MakeTranslation(-1.5, 0, 0);
_modelViewProjectionMatrix = GLKMatrix4Multiply(_modelViewProjectionMatrix, model);
glUniformMatrix4fv(uniforms[UNIFORM_MODELVIEWPROJECTION_MATRIX], 1, 0, _modelViewProjectionMatrix.m);
glUniformMatrix3fv(uniforms[UNIFORM_NORMAL_MATRIX], 1, 0,_normalMatrix.m);
glUniform4f(uniforms[COLOR_VECTOR], yellow[2][0], yellow[2][1], yellow[2][2], yellow[2][3]);

//bind corresponding buffer before drawing
glBindBuffer(GL_ARRAY_BUFFER, indexBuffer3);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, indexBuffer3);
glDrawElements(GL_TRIANGLES, [pieThree.pie getIndicesSize], GL_UNSIGNED_SHORT, (void*)0);

}

getIndicesSize returns the number of elements in indexArray.
getVertexSize return the number of elements in vertexArray.
returnVertexArray returns the vertex array of the geometry.
returnIndexArray returns the index array of the geometry.
vertex array is of type GLfloat.
index array is of type GLushort.
Number of elements in vertex array generated is 24522.
Number of elements in Index array generated is 22680.
On the internet, only examples of multiple VBO/IBO I found were not using GLkit and they did exactly what I am doing here in terms of initializing buffers and rendering.
I have spent almost 2 days on this issue. I feel there is some very basic thing missing. Somehow the last bound buffer affects all other geometries I feel (based on my results as I explained above). Could it be a simulator issue (I don't think so)? Fast response will be appreciated. Thanks
Answer: You seem to have some confusion about how the glVertexAttribPointer functions are supposed to work. When you call glVertexAttribPointer, it tells OpenGL:

On the next draw call, render starting from the address of the currently bound buffer plus the provided buffer offset.

After this, it doesn't matter if you change what buffer is bound, because the pointer still points to the buffer that was bound at the time of the function call.
Therefore in this code:
glBindBuffer(GL_ARRAY_BUFFER, indexBuffer1);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, indexBuffer1);
glDrawElements(GL_TRIANGLES, [pieOne.pie getIndicesSize], GL_UNSIGNED_SHORT, (void*)0);

Calling glBindBuffer(GL_ARRAY_BUFFER) does absolutely nothing here, because you're not updating the pointer.
glBindBuffer(GL_ARRAY_BUFFER, indexBuffer1);
//need to set glVertexAttribPointers here
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, indexBuffer1);
glDrawElements(GL_TRIANGLES, [pieOne.pie getIndicesSize], GL_UNSIGNED_SHORT, (void*)0);


Using Wifi module ESP8266 to send UDP broadcast message

Question: I need to communicate Arduino module with my Phone through ESP8266 wifi module
They all link to the local LAN network and didn't know the IP address of each other, so I plan to send UDP broadcast message from my phone, but ESP8266 module seems doesn't receive the message
The ESP8266 library I use is from here:
https://github.com/itead/ITEADLIB_Arduino_WeeESP8266
and use the function registerUDP() and recv()
Can somebody help me?
Answer: I don't have enough reputation to leave a comment so I will make an answer.
I have a feeling that your registerUDP() need to specify an IP address and I guess you are supplying your DHCP assigned IP address. Where as the UDP broadcast is sent using a multicast or broadcast IP.
You can modify the initiator code to send UDP packet to all IP within the same subnet (e.g. 192.168.1.1 to 192.168.1.254) and see if it works.
Comment: Hi~ Thank you!  It works when I sending the broadcast message using 192.168.1.255. And the another question is: Is it possible to send by 255.255.255.255?
Comment: broadcast addresses support often depends on the router and the device. And wireless support for broadcast on router maybe even worse. But if it works for you and that is your deployment scenario, I guess it is fine.


Why does E7 sharp 9 have a G?

Question: For the E7 sharp 9 chord, I don't understand how it has a G in it.
The ninth note on the E scale is F, so that would be F sharp.  How is it G?
Comment: 9th note of the E scale is F#. F# is the 9. F## is the sharp nine. Of course to play it, it would be a G under your fingers.
Comment: Very related: [this question](https://music.stackexchange.com/q/30165/9724).
Comment: As a comment because this is minor (no pun intended), but E7#9 is roughly Ealt, and the E altered scale has G and Ab. See it also as substituable with a Bb lydian dominant chord (your 9# becomes the 13 of that chord)
Comment: But technically, as said elsewhere, 9# here is F double sharp...
Answer: An E9 would have an F♯ in it. An E7♯9 doesn't have a G in it, it has an F (double sharp) rather than a G.
While those are enharmonic equivalents, they are very different in connotation. When double sharps are introduced, there are some lines of thought where it's better to write an enharmonic equivalent that may be less accurate that go into double sharps or flats and you may have encountered it in this scenario.
Comment: Or you can just call it the Hendrix chord, and no talk about double sharps and enharmonic equivalents is needed. ;) But looking at it as "G" is good because then you can see a possible re-interpretation. If you lock down "F##" as the only "correct" name, you need an extra step of thought to see the reinterpretation.
Comment: @s-k-y-e---c-a-p-t-a-i-n Mindfulness is my goal. ;) Raising an F# yields a G, so the E7#9 is almost a Bb13. I have no use for an F##, it's a potential extra pitfall for the unexpected, rubbish to be cleaned so it becomes an actual common note. ;) For similar mindfulness reasons, I don't like to use the "m7-5" chord name, because in practice it will be played wrong. Many players will unfortunately not know that "Bm7-5" contains a Dm and they play it without the "-5", ruining the whole thing. Similar thing with double sharps. :) Btw, your "E-G#-B-G" is missing the dominant seventh! :D
Comment: Sorry , but giving chords eponymous titles is not good imho , especially for generic , ubiquitous ones. In some cases e.g 'Tristan chord' it's appropriate due to the sheer amount of highbrow analysis it has received. Oh and because that;s my given name ! :-)
Comment: @piiperi it is always interesting to look for re-interpretations. Of course you know that E-G♯-B-G would not be called E7♯9 (it would be something like E7-b10. I think that the two different interpretations of the identical sound depend on context. If someone spelled E7#9 (ie: using Fx), I think they are emphasizing the upward push of the 9. If E7-b10, the emphasis is on the G♯ vs G-natural/major vs minor, and so is more of a modal context. We can think whatever we want when playing, but I think it helps "the next person" if we're mindful of these things if we're writing/transcribing. Yes/no?
Comment: @DrTris just the other week I told a young enthusiastic guitarist to play "E9" in a song ... he was like, "huh? never heard of such a thing", so I asked, do you know the Hendrix chord? "Yeah of course!" kid immediately plays 0-7-6-7-8-x... Ok, just lift off your pinky and extend the ring finger on the 7th fret as a barre on the three highest strings. Done! The "Hendrix chord" is a very common name to hear particularly among guitar players. :) I've even heard things like "D Hendrix" or "C# Hendrix".
Comment: @pilperi - I get it , it's just I'm a bit snobby about some things. :-)  The add9 could be the 'Summers Chord' , major first inversion - the "May Chord" , inverted power chord (5-R-5) - "Angus Chord" ..... can't think of any others just now !
Comment: @piiperi:

> Btw, your "E-G#-B-G" is missing the dominant seventh!
Oops! Now THAT would qualify as "ruining the whole thing." I think that, for me, if I encounter an F## I am going to quickly be thinking G ... if I'm performing. But if I'm composing, that's a different deal, to me at least. Sharps that are not part of the key (and double-sharps) are fighting to go up and flats/double-flats want to go down. I just can't wipe all the double-sharps and double-flats out. It feels too much like an extremely minor genocide.  :)
Answer: E7#9 should have (E, G#, B, D, F##), in general (1, 3, 5, b7, #9).  It has an F##, or Fx.  Many music students equate enharmonic tones but the fact is this is not always correct.  It works in Equal Tempered Tuning but not all tuning systems.  A proper music text should not equate these.  The #9 is not the same thing as a b3.  My question to you would be where are you getting this info?  If you have a book or sheet music that lists it can you upload a pic of it so we can see.  It's possible that you just got a resource with a typo in it.
Thanks to b3ko for correcting my mistake.
Answer: This has already been answered correctly twice, so I will instead try to add a new perspective. Yes it is technically inaccurate to perceive the #9 as a minor 3rd scale degree, and so F## or Fx is how I teach it to my students. However, the G is practical. Many accomplished Blues and Jazz players will spell it [as a G] to ease real-time improvisation, harmonization, or even when songwriting to understand potential modulations and voice leading.
G is also the relative major scale to E minor, as you may already know. For this reason, it is not uncommon to see a G chord after an E7#9 chord in Rock and Blues genres.
Often you'll see this chord described as "the Hendrix chord" (or some other modern artist attribution). Perhaps the most famous usage example is Hendrix's "Purple Haze" ... in which the chord progression is E7#9, G, A (not E, Fx, A).
Know the correct way, but don't close your mind to other ways.
Edited to add: One more thing! The altered chord (the one we're discussing) can also be spelled with a b9 (flat nine). Sometimes both are indicated, sometimes neither are indicated (it will simply say E ALT). But regardless which notes the chord symbol calls for, it is totally fine to play both when improvising over that chord. So feel free to experiment with F natural over that E7#9 if you like.
Comment: Your last paragraph only applies to the use of E7(#9) as a dominant chord resolving down a perfect fifth. If it is used as a I chord (as Hendrix and many blues players would use it), it wouldn't be appropriate to add a b9.
Comment: +1 I think you should say "correct" with big quotes and sarcastic tone, because I think all this thinking about correctness does more harm than good. The double-sharp being "correct" only makes the notes fit some very specific culture and way of thinking, which might not make sense in other contexts. It's the same with people trying to see everything in terms of roman numerals and functional analysis. If you don't play the B note (like in the Hendrix chord you don't) and move the bass to Bb, is "F##" still the "correct" name for the note? Too much theory and youtube videos, too little playing!
Comment: @piiperi - the first version of the 'Hendrix chord' that I played *did* have a B. It was (still is!) 0 2 2 1 3 3(Bot>top)
Comment: @Tim interesting! Does Jimi actually play it like that on a recording? Anyway, IMO talking about double sharps is not very useful for pop music. If on some suitable instrument someone wants to fine-tune their intonation, they'll do it anyway. Another thing that's more on the harmful side is using the word "correct" without explicitly naming the point of view, as if there was some kind of a universal law-of-nature music context. The assumption of there being universal correctness is a common myth I'd like to debunk.
Comment: @piiperi - we know nothing is in stone with music, especially pop! But since we usually 'stack thirds', that might as well be perpetuated. Whatever thirds they happen to be... That said, I guess a lot of guitarists (yes, I'm one too...) would simply see that as a G, rather than Fx. To them, aren't Fx in those little pedals..?
Comment: @piiperi I believe Jimi played (low to high) 0-7-6-7-8-x
Comment: @MattL. The double-diminished scale fits over the chord (with b9) regardless of its function. "Hendrix and many blues players" like myself often use dominant 7th chords in place of regular triads, so a pattern or "lick" containing the b9 need not only be used when the harmonic function of the chord is a true dominant or secondary dominant. That being said, as with all things, season to taste. If you don't like it don't play it :)
Comment: @NickGrooves: Of course, can you always play whatever you like, but I wouldn't say the the double-diminished scale (or any other scale with a b9 for that matter) fits the blues vocabulary in the style of Hendrix, SRV and the like.
Comment: @MattL. First of all, I never said that scale was used in Blues music but since you brought it up, yes there are in fact many Blues recordings in which the turnaround is (in A, for example) E7#9, E7b9, A. The OP does not specify any context. I used one Hendrix example where he used the exact chord mentioned followed by a G chord. Then, separately, I offered another widely-accepted (and often expected, in Jazz) way to spell "E ALT."  That does not mean I believe Hendrix played b9.
Answer: As the other answers point out, that 'G' is in fact Fx. Given the fact that the chord is called E7♯9, and the 9th note in E is F♯, then that note gets sharpened again. thus F♯♯, or Fx.
I think the misnaming comes from the fact that m3 is used a lot in Blues (and jazz), and that actually is called 'G'. Since in 12tet it sounds exactly the same as Fx, that note ends up being named G, partially out of convenience, partly ignorance. I used to consider it E7 with a m3, (wrongly), and I'm sure some guitarists regard it the same. There are also sites out there that provide us with spurious information, which tend to re-inforce certain inaccuracies, and those don't help.
Answer: By now you should be convinced that the #9 in a chord with root E is an F## (or Fx), which is enharmonically equivalent to a G.
However, I think the real question is whether that chord should be called E7(#9) - as is very common, at least in the English speaking part of the world -, or if it should be called E7(b10), which is also used, and definitely not only by people who don't understand the issue. If you accept the b10 notation, then that note is indeed a G.
I personally think it's completely pointless to discuss which of the two is more correct. You can find arguments for both. I always use #9 (because everybody does, and for me it's about communicating chord symbols efficiently), but if you ask me what I hear, I'd probably say that I hear a b10. One important argument for me is that that note virtually never resolves upwards. More arguments (which are not mine) can be found in this answer to a very related question.
Comment: Generally speaking, chords get built on thirds. So, 1,3,5,7,9 would be the notes concerned. No 10 there! (Not my dv).
Comment: If you do want to specify a minor third and not an augmented 9th why not simply write E7addG instead of E7(♭10)?

Why does E7 sharp 9 have a G?


how to integrate soap xml api with web service in php

Question: I am new to PHP. I have a busBooking soap api and i want to integrate it in my php application.
I have the following details
Login URL : http://api.tektravels.com/BusBookingAPI/Service.asmx
and login name and password
and i have the six sampleXML set like the below:
BusBookRequest,
BusBookResponse,
BusSearchRequest,
BusSearchResponse,
BusSeatDetailRequest,
BusSeatDetailResponse
the following is BusBookRequest XML
<?xml version="1.0" encoding="utf-16"?>  <WSBookRequest xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">    <ProductTypeId xmlns="http://192.168.0.131/TT/BusBookingAPI">0</ProductTypeId>    <ProductId xmlns="http://192.168.0.131/TT/BusBookingAPI">0</ProductId>    <BookingMode xmlns="http://192.168.0.131/TT/BusBookingAPI">Auto</BookingMode>    <ProductType xmlns="http://192.168.0.131/TT/BusBookingAPI">Bus</ProductType>    <BusId xmlns="http://192.168.0.131/TT/BusBookingAPI">0</BusId>    <SourceId xmlns="http://192.168.0.131/TT/BusBookingAPI">1492</SourceId>    <DestinationId xmlns="http://192.168.0.131/TT/BusBookingAPI">1135</DestinationId>    <SourceName xmlns="http://192.168.0.131/TT/BusBookingAPI">Delhi</SourceName>    <DestinationName xmlns="http://192.168.0.131/TT/BusBookingAPI">Manali</DestinationName>    <DateOfJourney xmlns="http://192.168.0.131/TT/BusBookingAPI">2014-09-26T00:00:00</DateOfJourney>    <BusSource xmlns="http://192.168.0.131/TT/BusBookingAPI">RedBus</BusSource>    <IsDomestic xmlns="http://192.168.0.131/TT/BusBookingAPI">true</IsDomestic>    <RouteId xmlns="http://192.168.0.131/TT/BusBookingAPI">201653313640000758</RouteId>    <BusType xmlns="http://192.168.0.131/TT/BusBookingAPI">Volvo A/C Seater Semi Sleeper (2+2)</BusType>    <TravelName xmlns="http://192.168.0.131/TT/BusBookingAPI">Royal Travels</TravelName>    <NoOfSeats xmlns="http://192.168.0.131/TT/BusBookingAPI">1</NoOfSeats>    <DepartureTime xmlns="http://192.168.0.131/TT/BusBookingAPI">2014-09-26T17:00:00</DepartureTime>    <ArrivalTime xmlns="http://192.168.0.131/TT/BusBookingAPI">2014-09-27T07:00:00</ArrivalTime>    <TotalFare xmlns="http://192.168.0.131/TT/BusBookingAPI">1450.00</TotalFare>    <BoardingPointdetails xmlns="http://192.168.0.131/TT/BusBookingAPI">      <CityPointId>21533</CityPointId>      <BusId>0</BusId>      <CityPointName>Paharganj</CityPointName>      <CityPointLocation>Paharganj</CityPointLocation>      <CityPointLandmark>Opp Paharganj Police Station</CityPointLandmark>      <CityPointAddress>Shop No. BG 16,Ground Floor,RG City Centre,Opp. Paharganj Police Station,Delhi</CityPointAddress>      <CityPointContactNumber>011-43074720/9899199491/9953733177/9873787138</CityPointContactNumber>      <CityPointTime>2014-09-26T17:00:00</CityPointTime>    </BoardingPointdetails>    <CancelPolicy xmlns="http://192.168.0.131/TT/BusBookingAPI">      <WSCancellationPolicies>        <BusId>0</BusId>        <TimeBeforeDept>0$15</TimeBeforeDept>        <CancellationChargeType>Percentage</CancellationChargeType>        <CancellationCharge>100</CancellationCharge>      </WSCancellationPolicies>      <WSCancellationPolicies>        <BusId>0</BusId>        <TimeBeforeDept>15$-1</TimeBeforeDept>        <CancellationChargeType>Percentage</CancellationChargeType>        <CancellationCharge>10</CancellationCharge>      </WSCancellationPolicies>    </CancelPolicy>    <PaxDetail xmlns="http://192.168.0.131/TT/BusBookingAPI">      <BusId>0</BusId>      <PaxId>0</PaxId>      <Title>Mr.</Title>      <LastName>kjhj</LastName>      <FirstName>hkhjk</FirstName>      <Age>21</Age>      <PhoneNo>9876543211</PhoneNo>      <EMail>firstname.lastname@example.com</EMail>      <Gender>male</Gender>    </PaxDetail>    <SeatsDetail xmlns="http://192.168.0.131/TT/BusBookingAPI">      <WSBusSeatDetail>        <SeatId>0</SeatId>        <BusId>0</BusId>        <SeatName>27</SeatName>        <SeatType>sleeper</SeatType>        <RowNo>003</RowNo>        <ColumnNo>006</ColumnNo>        <SeatStatus>1</SeatStatus>        <SeatFare>725.00</SeatFare>        <priceId>0</priceId>        <Width>1</Width>        <Height>1</Height>        <IsLadies>false</IsLadies>        <IsUpper>false</IsUpper>        <Price>          <TdsCommission>3.62</TdsCommission>          <PriceId>0</PriceId>          <PublishedFare>725.00</PublishedFare>          <AgentCommission>36.25</AgentCommission>          <SeviceTax>0.00</SeviceTax>          <Tax>0</Tax>          <Currency />          <RateOfExchange>1.0</RateOfExchange>          <CurrencyCode>INR</CurrencyCode>          <Discount>0</Discount>          <TdsRate>0</TdsRate>        </Price>      </WSBusSeatDetail>      <WSBusSeatDetail>        <SeatId>0</SeatId>        <BusId>0</BusId>        <SeatName>28</SeatName>        <SeatType>sleeper</SeatType>        <RowNo>004</RowNo>        <ColumnNo>006</ColumnNo>        <SeatStatus>1</SeatStatus>        <SeatFare>725.00</SeatFare>        <priceId>0</priceId>        <Width>1</Width>        <Height>1</Height>        <IsLadies>false</IsLadies>        <IsUpper>false</IsUpper>        <Price>          <TdsCommission>3.62</TdsCommission>          <PriceId>0</PriceId>          <PublishedFare>725.00</PublishedFare>          <AgentCommission>36.25</AgentCommission>          <SeviceTax>0.00</SeviceTax>          <Tax>0</Tax>          <Currency />          <RateOfExchange>1.0</RateOfExchange>          <CurrencyCode>INR</CurrencyCode>          <Discount>0</Discount>          <TdsRate>0</TdsRate>        </Price>      </WSBusSeatDetail>    </SeatsDetail>    <Currency xmlns="http://192.168.0.131/TT/BusBookingAPI">INR</Currency>    <SessionId xmlns="http://192.168.0.131/TT/BusBookingAPI">57f27951-0018-411b-b0a1-d23cdb366c04</SessionId>  </WSBookRequest>
please help me how to integrate it with this details and how to access the response with PHP.
Answer: Start reading SoapClient.
Start with:
$wsdl = 'http://api.tektravels.com/BusBookingAPI/Service.asmx?WSDL';
$client = new SoapClient($wsdl);
print_r($client->__getFunctions());

Comment: its showing error Fatal error: Class 'SoapClient' not found ?
Comment: check in your php.ini file whether it is enabled or not


Blocking a specific external IP:Port connection in RedHat?

Question: I know that in RedHat, in the IP tables I can block incoming connections to a local port. I can also block connections from a specific IP.
But is it possible to block a connection from a specific IP address and the connection attempt is made from a service running at a specific port on the external IP?
So if I had something like,
iptables -A INPUT -s 18.104.22.168 -j DROP
iptables -A OUTPUT -d 18.104.22.168 -j DROP

Can I specify more specificity for that particular IP address and select a specific port to block? Let's say the service is running on port 5000 at 18.104.22.168, can I be that specific? Note that this service may not attempt to connect to port 5000 on the server, so just blocking that port on the server isn't what I am after.
Answer: Yes, you can specify conditions on both (source) IP and (source) port in a single rule, both of which conditions must be satisfied in order to prevent communication, eg
iptables -I INPUT -s 18.104.22.168 -p tcp --sport 5000 -j DROP

Note that you must specify a protocol in order to use sport or dport, so if you wanted to block both TCP and UDP, two rules would be needed.


Is Multivariate Regression right for my study?

Question: I am trying to plan the following experiment;
I am examining the perceptual effects of a tutor's voice on distance learning students and their evaluation of the course.
My SV is 'perceived voice pleseantness'; distance learning students rate a tutors voice on a scale of 1 - 5, 1 = very unpleasant 5 = very pleasant.
The DV's I would like to use (to help me link it to a previous study) are;

Learning outcome (module mark)
Motivation
Satisfaction
Perceived expertise

My teacher has recommended I carry out multivariate regression anaysis to get my answers.
Please can someone explain to me why I can't just do a MANOVA in this situation? I haven't learned multivariate regression yet so I'm struggling with this.
I'm also using SPSS, I have read it is not possible to do this analysis in SPSS, is this correct?
Comment: Do you want to use Learning outcome (module mark), Motivation ,Satisfaction, Perceived expertise as dependent variables, I mean take them all as dependent variables?
Comment: There must be a bit more clarification about the problem to answer the question and please post the reference to the dataset if possible
Comment: Yes Erik, they will all be dependent variables. I don't have a data set, I just need to design this experiment for university.
Comment: If this is a work for a class or something like that, please read the description of the tag [tag:self-study] and add it to the question.
Answer: I'm a bit confused by the recommendation to do multivariate regression. That would be appropriate if your independent/predictor variable were continuous, but yours only has 5 levels. It might be appropriate if you thought that each step along the "perceived voice pleasantness" scale was likely to have the same influence on outcomes, but there's no way to know that a priori. So on that basis I don't see why multivariate regression would be preferred to multivariate ANOVA.
That said, the basic concept is the same for either, in that the analysis considers the correlation structure among your dependent/outcome variables. So if you are comfortable with MANOVA, the extension to multivariate regression shouldn't be too much of a conceptual stretch. If this is work for a class, the reasons for choosing multivariate regression over MANOVA and how to implement the multivariate regression would seem to be an issue to discuss with your teacher.
One potential problem with your design is that the independent variable might not be "independent"; for example, someone who did poorly or didn't like the course might simply tend to rate the tutor's voice more unfavorably as a result, so that you could have the inferred causality backwards. In that case looking at the correlation structures as @user25459 suggested might be appropriate, instead of either multiple regression or MANOVA.
Answer: Your proper test statistic should be Somers' D, based on how I understand your scales.  I think your professor has misunderstood that your four variables are predicted by the fifth. That requires either using Somers' D as a measure of correlation or a probit model, each done four times.
Since you have yet to learn multivariate regression, probit is way out of sight for you, but Somers' D is not.
Somers' D is an asymmetric measure of association among two variables.  This differs from Spearman's rho, which is a symmetric measure, by how it handles tied observations.
Consider the two statements, "if it is raining, then it is cloudy," and "if it is cloudy, then it is raining."  Under Spearman's rho, these are equivalent statements because it is symmetric.  If it is correlated in one direction, then it is equally correlated in the other.
Under Somers' D, the correlation for the first statement would be 1 because if water is falling from the sky then there is a cloud up there.  In the other direction it would have a much lower level of association, probably equal to the percentage of time that it rains when it is cloudy.  Let's set an imaginary correlation of 0.30.  Spearman's rho might be 0.40.
Now you will have to make adjustments because there are four hypotheses tests without a master F test to cover them.  So you would do the Holm-Bonferroni correction to eliminate spurious significance.  Its not the only way to make the correction, but it is reasonable for what you are doing.