Incorporar últimas fotos Instagram

Question: Preciso incorporar em um site, as últimas 6 fotos de um perfil do Instagram.
Eu preciso de algo deste tipo:

Isso é possível?
Answer: É possível sim. Existe a API do instagram que você pode utilizar:
http://instagram.com/developer/
Até exemplos em diversas linguagens de programação.
Comment: Qual a linguagem que você está utilizando?

Nesta página há uma explicação sobre a autenticação e um link para OAuth 2.0. Independente da linguagem, você irá utilizar o OAuth 2.0 para autenticar sua aplicação.
Comment: Sim, porém não estou entendendo como faço para autorizar o meu app...

Incorporar últimas fotos Instagram


Cifra de vigenere

Question:  private static void algoritmo(String input, String chave, Boolean b)
    {
        Console.WriteLine("Digite a mensagem: ");
        input = Console.ReadLine();
        Console.WriteLine("Digite a chave: ");
        chave = Console.ReadLine();
        input = input.ToUpper();
        chave = chave.ToUpper();

        if (b)
        {
            // para cada caracter da entrada, com exceção do espaço, converterá para valor ascii
            for (int contaCar = 0; contaCar < input.Length; contaCar++)
            {
                if (input.Equals(" "))
                {
                    output += input;
                }
                else
                {
                    char carTex = (char)input[contaCar];
                    output += carTex;
                }
            }
            Console.WriteLine(output);
            // para cada caracter da chave, com exceção do espaço, converterá para valor ascii
            for (int contaCar = 0; contaCar < chave.Length; contaCar++)
            {
                if (chave.Equals(" "))
                {
                    codeKey += chave;
                }
                else
                {
                    char asciiChave = (char)chave[contaCar];
                    codeKey += asciiChave;
                }
            }
            Console.WriteLine(codeKey);
            // agora que a mensagem está transformada em ascii(output) assim como a chave (codeKey),
            // deverá ocorrer a codificação
            for (int i = 0; i < output.Length; i++)
            {
                for (int j = 0; j < codeKey.Length; j++)
                {
                    code = ((codeKey[j] + output[i]) - 65) % 26;
                }
            }
            Console.Write(code);
            Console.ReadKey();
        }

O objetivo seria fazer com que cada caractere da chave recebesse seu valor ASCII e retornasse como um array pra eu poder fazer algumas operações de soma entre cada valor ASCII de cada caractere. Por exemplo: valores ASCII da palavra "nome": [65, 67, ...] e valores ASCII da chave "cade": [65, 67, ...], assim eu somaria os valores de mesmo índice de array.
Como eu posso fazer para o output e do codeKey sair com os valores ASCII da entrada?
Comment: A resposta resolveu sua dúvida? Acha que pode aceitá-la? Veja o [tour] se não souber como faz. Isso ajudaria muito indicar que a solução foi útil para você. Também pode votar em qualquer pergunta ou resposta que achar útil no site todo.
Answer: Demorou pra eu entender o que o código deveria fazer. Agora gostei da brincadeira  e fiz o que deveria ter sido feito.
Separei a parte de interface do algoritmo, dei nomes melhores para tudo.
Eu falei na pergunta anterior que para o algoritmo não precisava do ToUpper(), usei só na interface por conveniência.
Idealmente deveria ter um método para cifrar e outro para decifrar. Isso eu não arrumei. Tem como aproveitar esse código para decifrar, só muda a fórmula.
Só um laço basta. Na verdade um aninhado no outro não produziria o resultado esperado.
Já filtrei os caracteres que são aceitos e promovi para maiúsculo dentro do laço para ganhar velocidade.
Pesquisei qual era a fórmula correta e apliquei. Não garanto que está feito da melhor maneira, mas isso também é uma pseudo-criptografia.
using static System.Console;

public class Program {
    public static void Main() {
        int escolha = 1;
        while (escolha != 0) {
            WriteLine("ESCOLHA UMA OPÇÃO");
            WriteLine("-----------------");
            WriteLine("1-Encriptar");
            WriteLine("2-Decriptar");
            WriteLine("0-Encerrar");
            WriteLine("-----------------");
            if (!int.TryParse(ReadLine(), out escolha) || escolha < 0 || escolha > 2) {
                WriteLine("Opção inválida");
                continue;
            }
            if (escolha != 0) {
                WriteLine("Digite a mensagem: ");
                var mensagem = ReadLine();
                WriteLine("Digite a chave: ");
                var chave = ReadLine();
                WriteLine(mensagem.ToUpper());
                WriteLine(chave.ToUpper());
                WriteLine(CifraVigenere(mensagem, chave, escolha == 1));
            }
        }
    }
    private static string CifraVigenere(string mensagem, string chave, bool flag) {
        if (flag) {
            var codigo = "";
            for (int i = 0, j = 0; i < mensagem.Length; i++, j++) {
                char c = char.ToUpper(mensagem[i]);
                if (c < 'A' || c > 'Z') continue;
                codigo += (char)((c + char.ToUpper(chave[j % chave.Length]) - 2 * 'A') % 26 + 'A');
            }
            return codigo;
        }
        return ""; //até criar o decript
    }
}

Veja funcionando no ideone. E no .NET Fiddle. Também coloquei no GitHub para referência futura.
Answer: Cabeçalhos private void Decifra(string cifra, string chave)
 private void Decifra(string cifra, string chave){
            var mensagem = "";
            for (int i = 0 ; i < cifra.Length; i++)
            {
                char c = char.ToUpper(cifra[i]);
                if (c < 'A' || c > 'Z')
                {
                    continue;
                }
            char cha = char.ToUpper(chave[i % chave.Length]);
                mensagem += (char)((26-(cha%65-c%65))%26+65);
            }
        c.Text = mensagem;

    }

Comment: Esta resposta foi sinalizada como de baixa qualidade devido ao tamanho ou conteúdo. Por favor, se possível e se esta for uma solução ao problema, explique melhor como você o resolveu. O código pode ser trivial para você, mas para outros usuários pode não ser.
Comment: é apenas um método de decifrar complementando o programa acima
Comment: e o resultado é enviado pra uma textbox
Comment: Você pode [edit] a resposta e adicionar essas informações direto nela.
Comment: foi mal, sou novo aqui.
Comment: Começando a programar agora

Cifra de vigenere


How to open p:dialog inside a js file?

Question: I want to open a p:dialog in a js file. My code is below:
<h:outputScript name="js/check.js"/>

In the js file I have written a function and inside that I have tried  ex.show(); but it says ex is undefined.
Similarly I also want to invoke a p:commandButton  in that file and I tried
document.getElementById("hformid:commandbuttonid").click(); and it says
document.getElementById("hformid:commandbuttonid") is null. How to solve it?
Answer: May be 'ex' is defined after your 'check.js' script is executed. Assuming your are using JQuery, try something like
$(document).ready ( function() {
    ex.show();
});

So 'ex.show();' will be executed after the whole page is parsed.

How to open p:dialog inside a js file?


What happens if I take a quotient over a reducible polynomial?

Question: I know that for adjoinging roots to a field, I need to find irreducible polynomials so that the ideal I am taking the quotion with will be maximal, hence the resut being a field.
Imagine I am working with $F=\mathbb{Z}_7$ and I take a look at the polynomial $g(x):=x^3+6 = (x-1)(x-2)(x-4)$.
What kind of structure is $F[x]/(g)$?
My attempt so far: I thought that there is no further information given by the reducible polynomial (all zeros are in the field $F$ already), so, by the degree-theorem of field-extensions, I thought that $[F(\alpha):F] = 1$, where $\alpha$ denotes a zero of the polynomial $g$.
Is this really a field, not just an integral domain (as a subset of $F[x]$)?
What happens if we consider a polynomial so that there is an irreducible with degree > 1, but which is still reducible?
I am aware that the minimal polynomial then will not be sent to 0, hence the "factorisation" will not be complete. But it is not clear what the "improper factorisation" looks like.
Thanks!
Answer: Let me first remind you the chinese remainder theorem:

Theorem. Let $R$ be a ring and let $I,J$ be ideal of $R$ such that $I+J=R$, then one has the following ring isomorphism: $$\left\{\begin{array}{ccc}R/(I\cap J)&\rightarrow&R/I\times R/J\\x\mod I\cap J&\mapsto&(x\bmod I,x\bmod J)\end{array}\right..$$

Proof. Adapt the proof you already know for $R=\mathbb{Z}$. $\Box$
Now let's see how we can apply this theorem for polynomial quotient rings.
Let $k$ be a field and $f$ be a polynomial with coefficients in $k$. Assume that $f=g_1\cdots g_n$ with $g_1,\dots,g_n$ irreducibles over $k[x]$, then for all $i,j\in\{1,\dots,n\},i\neq j$, using Bezout's theorem, one has: $$(g_i)+(g_j)=k[x].$$
Therefore, using the theorem, one gets: $$k[x]/(f)=\prod_{i=1}^nk[x]/(g_i).$$
In your case, one has: $$\mathbb{Z}_7[x]/(x^3+6)=\mathbb{Z}_7[x]/(x-1)\times\mathbb{Z}_7[x]/(x-2)\times\mathbb{Z}_7[x]/(x-4).$$
Answer: In general, you will get a vector space over $F$ of dimension $deg \, g$ that has a ring structure (via multiplication $\mod g$) and that has zero divisors. This is a bit like $\mathbb{Z}_m$ where $m$ is composite. For example if $g = g_1g_2g_3$ and the $g_i$ are irreducible, then $g_i \ne 0$ in $F[x]/g$ but $g_1g_2g_3 = g = 0$ in that set.
Don't confuse this with $F(\alpha)$ where $g(\alpha) = 0$. That is indeed again $F$.


PROLOG get name through condition

Question: I am stuck with the conditional or query to get the name of a student which age must be over "25" and teacher must be "jdoe".
I want a condition which takes 2 parameters (age, teacher). Such as:
?-find(26, jdoe).

My Prolog code looks like this:
/*student(name,studnumb,age,sex)*/

student(cax,1234,22,female).
student(sad,7839,26,male).
student(fads,1726,29,male).
student(rafa,1114,25,male).
student(gafrh,6654,36,female).
student(reads,4627,20,male).
student(hyqa,2563,25,female).
student(berat,9258,30,female).

find(S1, S2):-
    S1 > 25,
    S2 == jdoe,
    write(student(, _, S1, _)).

takes(1234,1111).
takes(7839,1111).
takes(1726,1111).
takes(1114,2345).
takes(6654,1111).
takes(4627,4588).
takes(2563,2222).
takes(9258,6534).

teaches(jdoe,1111).
teaches(bbuilder,2345).
teaches(tkailor,6789).
teaches(jdough,4588).
teaches(krain,2222).
teaches(slisterine,6534).

Unfortunately, I can not achieve the right query or conditional to print the right group of student names which are over "25" and have "jdoe" as a teacher.
Comment: You should use meaningful variables. What's `S1` and `S2`? Why not, `find_student(MinAge, Teacher, Student) :- ...`? You need the `Student` argument to "return" student names in. Don't use `write`. `write(student(, _, S1, _)).` does not run a query on `student`. It will just write out the term `student(, _, S1, _)`. I'm a little confused about the age. Are you passing the minimum age as the argument? Or are you supposed to check for age over 25 hard-coded in the predicate? If you're checking for 25 in the predicate, what's the point of the age argument?
Comment: If you query the student data, you can do so with `student(StudentName, StudentId, Age, _)` (if you don't care about gender). You need the `Age` to check against minimum age, you need the name to display as a result, and you need the student Id to look up subjects. With this, you can now enforce the condition, `Age > MinAge`, and you can get a subject Id using `takes(StudentId, SubjectId)`. Finally, you can check for `teaches(Teacher, SubjectId)`. These are all of the conditions that will give the resulting `StudentName` that you want.
Comment: More succinctly: your predicate `find/2` needs to call the database predicates to get the information.
Answer: I think next code.
find(YO, TN):-
  student(SN, IS, SY, SX),
  (var(YO)->true
  ;SY > YO),
  takes(IS, IT),
  teaches(TN,IT),
  writeln([TN,student(SN,IS,SY,SX)]),fail;true.

I try next test code.
main:-
  find(25,jdoe),
  find(20,krain).
[jdoe,student(sad,7839,26,male)]
[jdoe,student(fads,1726,29,male)]
[jdoe,student(gafrh,6654,36,female)]
[krain,student(hyqa,2563,25,female)]

Comment: Nice!! It worked.

I am using your logic to a similar exercise, I may need your help again :)

https://stackoverflow.com/questions/49060740/prolog-conditional-function
Comment: I like the simple code of prolog look like SQL. Thanks!.

PROLOG get name through condition


Writing text file with python with merge line operator "\"

Question: I am trying to automate a script in python to write the following command with it's options. I was able to do the following
foo -1 \
    -2 a \
    -3 b \
    -4 c \
    -5 d \
    -6 e \
    -7 f

Which seems right. However, when I use bash to source the file that contains this in a terminal, it complains that it does not have any options specified and bash doesn't recognize -2, -3, -4, -5 etc. How can I write this properly to ensure that when the file is being sourced, it'll read it right?
Code:
filehandle.write("foo\t-1 \ \n")
filehandle.write("-2 a \ \n")
filehandle.write("-3 b \ \n")
filehandle.write("-4 c \ \n")
filehandle.write("-5 d \ \n")
filehandle.write("-6 e \ \n")
filehandle.write("-7 f \ \n")

Comment: How is this related to Python?
Comment: Because I'm writing it with python.
Comment: Then what do you mean by "sourcing" this file? Python can't source files, but BASH can, with the `source` command. What Python code are you using to run this command?
Comment: Python is writing this file. Then I go in bash to source the .txt file that contains the command. However, bash is not seeing it as one entire command but as many.
Comment: Notice there are trailing spaces after your `\` in the output you generate. This tells bash to escape the *space* character, not the newline character that follows it.
Answer: I was able to get this to work by specifying that each new line with the arguments should start with \t:
>>> with open("test.sh", "w") as f:
...   f.write("ls \\\n\t-l\\\n\t-h\n")
...
14
>>>

Also, there mustn't be any spaces after the backslash that terminates each line, so this: "foo\t-1 \ \n" should become this: "foo\t-1 \\\n" (spaces before the backslash are fine).
Also note that this: "\\n" will write to the file literally backslash, "n" because the first backslash escapes the \n symbol, so you have to escape that first backslash with "\\\n".
So the file looks like this:
$ cat test.sh
ls \
    -l\
    -h
$

Comment: Thank you, the tripled backslash is what I was missing. I don't think I can give you the rep points now, but I will as soon as it lets me. Thank you
Comment: Tabs aren't necessary, any whitespace will do. The key point is that there can't be any whitespace between the backslash and the newline in the output.


Fixed field is a field

Question: Let $L/K$ be a algebraic field extension and let $G\subset Aut(L/K)$ be a subgroup. It is easy to check that the set of fixed points of $G$ is a field by checking, that it is closed under multiplication, addition and inverse elements.
But is there any more elegant prove of this?
Comment: *More elegant...and short and simple than that*? I don't think so...
Answer: There are some redundancies in your setting.

Let $F$ be a field and $\varphi$ an automorphism of $F$. Then the set of elements of $F$ fixed by $\varphi$ is a subfield of $F$.

This can be proved by showing closure under $0$, $1$, addition, multiplication and inverses. I see no "more elegant" way.
Consequently, if $X$ is a set of automorphisms of $F$, the set  $\operatorname{Fix}(X)$ of elements of $F$ fixed by all automorphisms in $X$ is a subfield (being the intersection of subfields).
More interesting is perhaps that $\operatorname{Fix}(X)$ equals  $\operatorname{Fix}(\langle X\rangle)$, where $\langle X\rangle$ is the subgroup of $\operatorname{Aut}(F)$ generated by $X$. Indeed, if $\varphi$ and $\psi$ are automorphisms of $F$, then
$$
\operatorname{Fix}(\{\varphi^{-1}\})=\operatorname{Fix}(\{\varphi\}),
\qquad
\operatorname{Fix}(\{\varphi,\psi\})\subseteq\operatorname{Fix}(\{\varphi\psi\})
$$
Since $\langle X\rangle$ consists of finite products of elements in $X$ and inverses thereof, we get $\operatorname{Fix}(X)\subseteq\operatorname{Fix}(\langle X\rangle)$. The converse inclusion is obvious, as $X\subseteq\langle X\rangle$.

Fixed field is a field


Woocommerce Show PDF attachment in Downloads tab as link

Question: I am trying to show a pdf in my downloads tab so that when someone is looking at my product they can open the pdf in a new window. I uploaded the pdf to the product via the media button. My callback looks like this and $attachments seems empty ideas?:
function woo_new_product_tab_content_downloads() {
global $woocommerce, $product, $post;
$product_id = $post->ID;
echo $product_id;
$product = new WC_Product( $product_id );
print_r($product);
// The new tab content
    $args = array(
    'post_type' => 'attachment',
    'orderby' => 'menu_order',
    'numberposts' => -1,
    'post_status' => null,
    'post_parent' => $product_id,
    'post_mime_type' => array( 'application/pdf')
    );

   $attachments = get_posts( $args );
   //print_r($attachments);
  if ( $attachments ) {

    foreach ( $attachments as $attachment ) {

       echo '
ID );
       echo '">';
       echo wp_get_attachment_image( $attachment->ID, '', true );
       echo '  ';
       echo apply_filters( 'the_title', $attachment->post_title );
       echo '';
       echo '
';
      }
 }
}

Comment: Your code looks correct and should work. Sorry for a stupid question, but have you attached the PDF to the same product that you are viewing?
Comment: indeed I have as it is showing when I look into the uploaded attachments for the product.  $attachments = get_posts( $args ); seems empty when I print it
Answer: as an answer to myself be sure to attach the correct filetype
Comment: Could you be more specific about what steps you took to solve your problem? This might help people facing the same problem in the future.
Comment: My code was correct from the get go I had mistakenly uploaded a png insteadd of a pdf to the post.


Strategy when working with imperfect Z values in a standard normal distribution

Question: So if you must find the X value greater than 10% in Z = (X - u) / σ. If you look up in the Z value table, there is the option 1.28 (0.1003) or 12.9 (0.0985), what if I want exactly 0.100, how would I calculate the Z value for this ..
Similarly if you're trying to find percentage for a Z value with 3 decimal places (table only shows 2), how would you go about this, the answer for this is here , but quite frankly I don't understand it (specifically how he/she gets the weighted sums o.3 and 0.7), surely there is a more concise explanation.
Thank you, let me know how I can improve on this question if neccessary.
Comment: [Method of false position](https://en.wikipedia.org/wiki/Regula_falsi), and [linear interpolation](https://en.wikipedia.org/wiki/Linear_interpolation).
Answer: If you want exactly $0.100$, the $Z$-value you want is very likely to be an irrational number, and hence not representable on a computer (or on a piece of paper, except indirectly, using a name like $\pi$ or $e$, or an unresolved computation, like $\arctan(1)$).
As for your "surely there is a more concise explanation," the explanation you point to is two sentences and about 200 characters!
Comment: Yes i understand it is very likely to be an irrational number, how do I calculate it though (considering I will round it off)?  I mean like a 'better' or clearer explanation
Comment: All my answers are wrong by a few 1/100th of decimal points compared to the answer sheet my professor gave me, but she doesn't explain how she finds these specific irrational Z values and etc. like I explain in my question. I hope you understand and can help me
Comment: I already *have* helped you: I've shown you that your uses of "exact" and "concise" are inappropriate and didn't communicate what you actually needed. You really can't expect us to be mind-readers and answer the question you *should* have asked. On the other hand, a 1-on-1 discussion with your professor might give you the insight you need on these particular problems, because *she* can ask you to clarify or re-state things in real time, and using the terminology that's part of the shared context of your particular course.
Comment: This isn't an answer at all (I wonder if you even read it properly), you haven't helped at all, why are you here if it's just to make petty observations and comments. One user commented two links with the calculation to my two questions in 3 words. The attitude on some people..
Comment: It's an answer to **exactly** what you asked for -- it's just one that you don't like. The first paragraph points out that you're asking for something it's impossible to provide, and the second shows that you already have the thing you've asked for.  But I can see how you'd be annoyed that someone would *volunteer* their time to do the very thing you asked. Seriously...the nerve of it!
Comment: I'm perfectly grateful for volunteers, but you can sniff a snobby StackExchange 'volunteer' from a mile away
Comment: Exactly what I asked for? "there is the option 1.28 (0.1003) or 12.9 (0.0985), what if I want exactly 0.100" , Please show me where you told me what z value to use? (this is quite literally the question), what you wrote should be put in a comment, it's not an answer the fact you put it in an answer alongside your attitude is enough proof to me you are being petty, I can't stand that


Feature Selection Methodology

Question: I have a question regarding methodology in Machine Learning.
Assume we have a classification problem, the size of training set is 100 every instance in training set is represented by 200 features. In order to eliminate meaningless features we evaluate Information Gain / Mutual Information of every feature and eliminate those with low mutual information. Then in order to evaluate the model we use 10-fold cross validation.
The question is after all these manipulation whether the calculated evaluation can be used as real evaluation, in other words, are we allowed to perform all these manipulation and get reasonable model with reasonable evaluation.
Ideas: Initially the entire process looked for me reasonable, but then I though if I am allowed to eliminate features based on the Infogain of train set or better to do it on validation set, on the other hand, in any case the trained model has access only to train set, so if features has low infogain it will have a minor weight in the model.
I would appreciate if you could share your thoughts.
Answer: Generally speaking, the problem of feature selection is computationally very hard to solve. What you are trying to do is to find an optimal subset out of $2^n$  possible sets (where $n$ is the number of features), which is an NP hard problem. As n grows, this problem is not solvable exactly due to it's computational complexity.
That said, there are ways to find approximate solutions. Using a simple greedy search approach such as forward-, or backward step-wise selection as you describe, will not guarantee an optimal solution and are not even stable, but will in some cases give you a reasonably good approximation. So the answer to your question (if I understand it correctly) is no. It is not viable to do this manipulation to get an optimal model. It is however common to use these methods to find a good model, even if it is not optimal.
If you are interested, there are other approaches to this problem. One is for example using L1-regularization (LASSO). As the LASSO uses an absolute shrinkage term it is possible for $\beta$-values to be pushed down to zero, essentially performing a subset selection. I would recommend Regression modeling strategies by Harrell and Elements of
Statistical Learning by Hastie et al. for further reference on the subject.
Comment: For what purpose? What do you mean with reasonable? The answer will depend on which model you use. It absolutely makes sense if you use a model sensitive to meaningless features (such as regression). Then you could potentially have variables without any information in your model which only add noise to your predictions. The question is then how you should go about to find a good subset of features which are meaningful. If you use a model which is *not* sensitive to meaningless variables (such as a random forest) then there is absolutely no point in removing any variables.
Comment: Thank you very much for your answer, in my case I don't want to find the optimal set of features, I simply want to eliminate features whose contribution to the model is not meaningful, in other words, go over all features, eliminate those with mutual information less than given threshold. The question is if it's reasonable to apply feature selection on training data.

Feature Selection Methodology


Expected Value and Variance of Estimation of Slope Parameter $\beta_1$ in Simple Linear Regression

Question: I am reading a text, "Probability and Statistics" by Devore. I am looking at 2 items on page 740: the expected value and variance of the estimation of $\beta_1$, which is the slope parameter in the linear regression $Y_i = \beta_0 + \beta_1 X_i + \epsilon_i$. $\epsilon_i$ is a Gaussian($\mu = 0, variance=\sigma^2$) random variable and the $\epsilon_i$ are independent.
The estimate of $\beta_1$ can be expressed as: $\hat{\beta_1} = \frac{\sum (x_i - \bar{x}) (Y_i - \bar{Y})}{\sum(x_i-\bar{x})^2} = \frac{\sum (x_i - \bar{x})Y_i}{S_{xx}}$, where $S_{xx} = \sum (x_i - \bar{x})^2$. So, my question is: how do I derive $E(\hat{\beta_1})$ and $Var(\hat{\beta_1})$? The book has already given the results: $E(\hat{\beta_1}) = \beta_1$ and $Var(\hat{\beta_1}) = \frac{\sigma^2}{S_xx}$.
My work in the derivation: $E\left(\frac{\sum (x_i - \bar{x})Y_i}{S_{xx}}\right) = E\left(\frac{\sum (x_i - \bar{x})(\beta_0 + \beta_1 x_i + \epsilon)}{S_{xx}}\right) = E\left(\frac{\sum (x_i - \bar{x})\beta_1 x_i}{S_{xx}}\right)$, since $\sum(x_i - \bar{x})c = 0$ and $E(c\epsilon) = 0$. But I am stuck.
Also, $Var\left(\frac{\sum (x_i - \bar{x})Y_i}{S_{xx}}\right) = Var\left(\frac{\sum (x_i - \bar{x})(\beta_0 + \beta_1 x_i + \epsilon)}{S_{xx}}\right) = Var\left(\frac{\sum (x_i - \bar{x})\epsilon}{S_{xx}}\right) = Var\left(\frac{\sum (x_i - \bar{x})}{S_{xx}}\right) \sigma^2$, but I am stuck.
Comment: In the situation being asked about, $X$ is being conditioned on, so it's treated as fixed rather than random
Comment: My comment on June 22, 2011 in user whuber's answer should include the subscript $i$ in the $\epsilon$'s, and should make use of the fact that the error terms $\epsilon_i$ are independent.
Comment: $\mathrm{Var}(\hat{\beta_1}) = \mathrm{Var}\left(\sum\frac{(x_i - \bar{x})y_i}{S_{xx}}\right) = \mathrm{Var}\left(\sum{\frac{(x_i-\bar{x})\epsilon_i}{S_{xx}}}\right) = \mathrm{Var}\left(\frac{(x_1 - \bar{x})\epsilon_1}{S_{xx}} + \frac{(x_2 - \bar{x})\epsilon_2}{S_{xx}} + \ldots + \frac{(x_n - \bar{x})\epsilon_n}{S_{xx}}\right) = \frac{(x_1 - \bar{x})^2 \sigma^2}{(S_{xx})^2} + \frac{(x_2 - \bar{x})^2 \sigma^2}{(S_{xx})^2} + \ldots + \frac{(x_n - \bar{x})^2 \sigma^2}{(S_{xx})^2} = \sigma^2 \left[\sum{\frac{(x_i-\bar{x})^2}{(S_{xx})^2}}\right] = \frac{\sigma^2}{S_{xx}}$
Comment: The standard "answer" is an underestimate, it ignores the variance of S_{xx}.
Comment: How can you get $Y_i = Y_i - \bar{Y}$
Answer:
$E\left(\frac{\sum (x_i - \bar{x})\beta_1 x_i}{S_{xx}}\right)$ = $\frac{\sum (x_i - \bar{x})\beta_1 x_i}{S_{xx}}$ because everything is constant.  The rest is just algebra.  Evidently you need to show $\sum (x_i - \bar{x}) x_i = S_{xx}$.  Looking at the definition of $S_{xx}$ and comparing the two sides leads one to suspect $\sum(x_i - \bar{x}) \bar{x} = 0$.  This follows easily from the definition of $\bar{x}$.
$Var\left(\frac{\sum (x_i - \bar{x})\epsilon}{S_{xx}}\right)$ = $\sum \left[\frac{(x_i - \bar{x})^2}{S_{xx}^2}\sigma^2\right] $.  It simplifies, using the definition of $S_{xx}$, to the desired result.
Comment: For the 2nd point, the variance, the equation should be: $Var\left(\frac{\sum (x_i - \bar{x})\epsilon}{S_{xx}}\right) = Var\left( \frac{(x_1 - \bar{x})\epsilon  + (x_2 - \bar{x})\epsilon + \ldots + (x_n - \bar{x})\epsilon}{S_{xx}}  \right) = \left( \frac{  \sum_i^{n} (x_i - \bar{x})^2}   {S_{xx}^2} \right) \times \sigma^2 = \frac{S_{xx}}{S_{xx}^2} \times \sigma^2 = \frac{\sigma^2}{S_{xx}}$
Comment: @jrand Yes, that's exactly what I wrote (although your first equality doesn't accomplish anything: it's just a more laborious way to write the summation).  The whole point--and the thing worth remembering--is that when $\varepsilon$ is a random variable with a variance and $\lambda$ is constant, $Var(\lambda \varepsilon)$ = $\lambda^2 Var(\varepsilon)$.
Comment: Unless I am getting the notation wrong, this is a false statement: $\sum_i^n (x_i)^2 = \left( \sum_i^n x_i \right)^2$. The quantity on the left hand side is the sum of squares, and the other is the square of the sum.
Comment: @jrand You are correct: there is a typographical error in my reply.  Thank you for pointing it out.  I have reformatted it to fix the error and make the logic clearer.


C# - Referência de objeto não definida para uma instância de um objeto

Question: Estou com esse erro no meu codigo:
 try
        {
            localhost.Agendamento a = new localhost.Agendamento();

            a.Cliente.Cpf = "1909009921";
            a.Servico.Cod_serv = 1;
            a.Data = Convert.ToDateTime("11/02/2017");
            a.Hora = Convert.ToDateTime("11:50");

            Service1 sv = new Service1();
            sv.CadastrarAgendamento(a);
            MessageBox.Show("Cadastrou!");
        }catch(Exception ex)
        {
            MessageBox.Show("Error" + ex.Message);
        }

O a exception ativa quando chega na linha
a.Cliente.Cpf = "1909009921";

A exceção que da é "Referência de objeto não definida para uma instância de um objeto"
Comment: Seu  objeto `Cliente` foi instaciado ? pode ser esse o problema ele esta tentando acessar `Cliente.cpf` enquanto `Cliente`  está `null`. tente debugar e verificar isso.
Answer: Precisa criar um objeto cliente em a.
a.Cliente = new CLiente();

Comment: Agora conseguir.
Answer: O que pode estar acontecendo e que na hora que seu código tenta acessar a.Cliente.Cpf ele encontra o seu Cliente nulo, assim gerando esta exceção,  então você teria que instaciar seu objeto Cliente.
Faça o seguinte:
a.Cliente = new CLiente();

Answer: Obrigado a todos que ajudaram eu consegui era só instanciar um objeto cliente e um objeto serviço dentro de Agendamento
a.Cliente = new CLiente();
a.Servico = new Servico();


How to easily transpose sheet music?

Question: I'm trying to get better at reading and writing standard notation.
I was wondering how to transpose a piece from one key to another on sheet music, so I wrote a 2-bar phrase and tried to do it myself.
The first bar is just natural notes, the 2nd bar contains alterations.
I quickly realised that, if there are no alterations, it is actually pretty easy. The problem seems to be that of transposing the sharps and flats.
In this first picture you can see the 2-bar phrase that I wrote, followed by the same phrase transposed through the circle of fifths (c major/g major/d major/a major/e major).

In this 1st picture the transpositions were done automatically by the software, and as you can see, the software accomplished this by adding lots of natural signs. I can see why that is correct, but if I were to do this by myself, it would take a long time since I'd always have to remember which sharps are in the key signatures, recognise them on the score and calculate the intervals in the piece, etc.
So when I tried to do it myself on paper, I came up with what you can see in picture 2.

All I did was to move the phrase up or down the staff until it was in the right key. This worked really well for the keys of G and D, but when I got to the keys of A and E (and I didn't notice this at first), I realised that I have to make those notes double sharp in order for the phrase to be correct.
I play guitar, and on most stringed instruments you could just move the passage up and down the fingerboard, and it would be automatically transposed.
Isn't there a simple way to do this on sheet music as well?
It seems that you can move the passage up and down the stave just fine, but the sharp/flats and key signature accidentals really make this more complicated than it should be.
Am I missing something obvious here?
Comment: Obviously not manually but by software, see [this question](https://music.stackexchange.com/q/103/2600).  If there is even the slightest chance, that you need to modify the sheet afterwards, this will be a real time-saver. See linked question for examples, MuseScore is a good choice for the beginning.
Comment: I'd be interested in which piece or chord progression this phrase  appears.
it could be in C resp. am:   F#7 B7 and B7 -E7 . this would be 6 fifths away from the tonic what is absolute possible, but then in E / c#m this circle ofsecondary dominants - (V) of (V) of (V) of (V) of V would be enharmonical be replaced.
Comment: Related question: [What are the exact steps of transposing a note?](https://music.stackexchange.com/q/113202/70803).
Answer: Good spelling is important. Unless there's a compelling reason in the harmony to do otherwise, it's best to try to give each note its own line/space in the staff. If you write an accidental and then have to cancel it later in the measure, that's a good sign that maybe the music should be spelled differently.
On your first line, you should use B♭ and E♭ (unless the choice of chord dictated A♯ and D♯). That would result in a B♭ on the second line as well, and then everything else in the computer-transposed version is good.
You shouldn't think of transposition as a mechanical act of sliding all of the notes the same direction by the same number of steps. You should try to think of it as recreating the music in a new key. But to do that effectively, you have to properly understand the music in its original key first. Picture the melody as scale degrees 6 7 1 6 ♭7 6 ♭3 2, and then it should be easy to apply that to any key. You could do the same with ♯6 and ♯2, but I think it's a little clearer in this form why that's less desirable.
Comment: The thing is that Eb is a better note than D# in an A minor context if it keeps being immediately followed by D naturals. I've encountered multiple pieces where this occurs. And it also occurs in the first line of the first picture of this question.
Comment: Good point about the Bb and Eb, which most times would be the expected note names. I'm trying to figure an easy 'rule' as to which would be more applicable where, and apart from something like *the note's contained in the chord at that point*, or *since Bb and Eb (here) come sooner in the #/b race than A# and D#*, is that a good enough reason to prefer them, given the tune's in C/Am?
Comment: It depends entirely on where the key is leaning. Obviously in the context above, the A-minor/C-major is moving towards E-minor/G-major and further along the circle, thus I'd clearly want to avoid mixing in those flats for better consistency.
Answer: The double sharps are correct.  If we take the first line as being in C major, the second-to-last note is D#, the sharpened second note of the scale.   The last line is in E major, the normal second note of that scale is F#, so sharpening it gives Fx (double sharp).    And that's the key (sorry!) to transposing, knowing where each note is in relation to the key. (It doesn't even matter which key you take as base, as long as you're consistent. You could take the first line as being in F major, the last line as A major. The result would be the same, as long as the first note was the third of each scale.)
Yes, it's all about knowing your keys and scales.
Now, there's correctness and there's expediency - "the quality of being convenient and practical despite possibly being improper or immoral" (love that 'immoral' :-))   We might be tempted to make the Fx 'easier' by re-writing it as G nat.  Once you're over the initial fear of a double sharp this can be unhelpful - it's much easier to read a scale when it LOOKS like a scale, a triad when it LOOKS like a triad.
Answer: The trick is to resolve sharps you don't need/want, to avoid double sharps. That's basically what the automatic transposition does. Whenever an added sharp would create a new natural pitch, it uses that instead (including the natural marker).
Thus you could add sharps ad infinitum without ever having more than one on any note.
Consequently I also think it's a terrible idea to add flats in the original phrase, as that would leave you with a mix of sharps and flats after transacriptions, which is usually something to avoid. You WOULD use flats if you were going into the other direction on the circle (F, Bb, Eb..)
Answer: I interpret this  melodic phrase of the two bars as: la ti do la, ta la ma re.
ta= ti flat and ma = mi flat (or what ever you will use as relative names for altered steps of do re mi)
it doesn' make sense to have here an A# followed by an natural A or a D# folloed by a natural D (except this was transposition were in 12 tone music where the enharmonic exchange wouldn't matter - but probably there wouldn't be a key assigned after the clef)
I agree with all those saying Bb and Eb instead of A# and D#, (etc. in all other keys) as they are leading tones solving to the I and IV  - if this examples are melodic phrases and not just single notes in a 4/4 measure.
But for a guitarist I would propose to note  both enharmonic names in the fret or tab.
Answer:
On most stringed instruments you could just move the passage up and down the fingerboard, and it would be automatically transposed. Isn't there a simple way to do this on sheet music as well?

The critical difference between stringed instruments and the written staff is that sliding up the fingerboard moves all of the pitches by the same interval, but this is not true when moving over the staff's lines and spaces.
Consider the guitar. Moving up one fret always raises each pitch a half step. On the staff, however, moving up one line or space could be a half step or a whole step.
For a melody having only notes within a given key, shifting the notes by equal numbers of lines and spaces, plus adjusting the key signature, will work fine. The key signature has the effect of reassigning where the half and whole steps are on the staff.
But this is only helpful for notes within the key. Notes outside the key are spelled according to their relationship to notes in the key. In the key of C, for example, we might have A# — as in the two-bar phrase of the OP — that is, "a raised sixth degree of the scale". Transposing to a key like G or D, having a sixth degree that, as in C, is a natural (E and B, respectively), it works just to add the same accidental: E# and B#. But for a key like A, in which the sixth degree is already a sharp, we need a double sharp (Fx). Likewise, in a key like Db, with a flat sixth degree (Bb), we need a natural sign (B-natural).

How to easily transpose sheet music?


How do I recognize notes in other key?

Question:
I have a relative pitch and I'm a beginner of jazz improvisation.
I have a problem in improvisation.
I used to follow the key when chord progression of key changed.
(like 'all the things you are' and other modulation chord progression)
so in your case, how do you recognize notes when key changed or in modulation?
and what should I do to fix this problem?
Comment: The jazz musicians I've known seem to be able to perceive things with duality -- they can recognize when a passage can be interpreted or perceived two different ways.
Answer: I personally use your second option of thinking of the modulated section in the new key. Modulations happen very frequently in jazz standards and it is much easier to think in the modulated key than to think of the notes and chords as part of the original key. Using the first melody note as an example, thinking of Fa in Ab is much more logical than Te in Eb when you are already in Ab at that point (the ii chord, Bbm7).
Your example of "All the Things You Are" is in Ab, C, Eb, G and E. It's much easier to just change the key temporarily than think in the original key. Classical music also has many modulations and they are approached and analyzed as such.
Comment: I agree with your position, but OP seems to have the entire sequence from Am7 leading back to EbMaj7 identified with Ab; I would just think of that as a sequence of ii-Vs (with a backdoor dominant thrown in if I was concerned about that F7). I guess the ii-Vs are _associated_ with different keys, but I don't think of those as modulating to new keys here.
Comment: @exnihilo even though the OP bracketed the entire bridge the focus seems to be on the first 4 bars so I responded in kind. I agree that the second 4 bars can be seen as a series of 2-5's back to the 1 chord minus the oddball F7. However, the harmony in the second 4 bars of the bridge of this chart is completely wrong, a contention I have made for years. It doesn't match either the Errol Garner version or the Johnny Mathis version, the two most recognized versions of the song. I addressed this in another question several months ago.
Comment: @exnihilo If you're curious about the actual changes to bars 5-8 of the bridge here Is the other question with my answer: https://music.stackexchange.com/questions/110361/when-does-a-jazz-tune-actually-modulate
Answer: In measure we 16 are in Eb. The whole note is Do. As we modulate to Ab I interchange Do to Sol: So la ti re mi fa fa fa (your 2nd version makes more sense to me: Db after the double barline becomes Fa.
But the greater challenge is the next line when the tune modulates to Gm:
I sing sol la do re mi fe (still in Ab)  and here I
reinterpret fe = mi (dominante of Gm) mi mi mi re sol mi re do (Bb = do in Gm becomes sol of Eb).
Answer: The whole of Misty is in key Eb. That's clear from the key signature - it stays at 3♭ all through. What does happen is modulation - as occurs in so many songs, including many classic ones - and indeed, classical music.
By thinking it 'changes' key, you're not going to improvise, or jazz your way through this, or many other standards. It's probably better to consider two or three bars at a time, where you'll inevitably discover ii-V-I going on. With that information, you can play through the changes, making the whole thing sound more cohesive. True, you'll be changing the set of notes (scales, if you like) more often that if yyou just 'changed key', but it's not going to work just 'changing key' for a middle eight, when several of those changes are only vaguely related to that 'change of key' - too many avoid notes are avaiable!

How do I recognize notes in other key?


how to count all results of foreach statement

Question: Let say we have following database table items
-----------------------------
ID |  ITEM  | PRICE | SALES |
-----------------------------
1  | item1  | 5.00  | 1     |
2  | item2  | 4.00  | 5     |
3  | item3  | 2.00  | 2     |
-----------------------------

This means item1 price was 5.00 and sold 1 times
how then we calculate total earning ! meaning for each item we will multpli its price with number of sale to get total earning for this item
$earning_per_item1 = $a1['PRICE']*$a1['SALES']; // for item1 = 5*1

But what if i want to get the total earning for all items?
This should be 29
Comment: is this a php or an sql question?
Comment: [http://stackoverflow.com/questions/16535630/sum-values-in-foreach-loop-php](http://stackoverflow.com/questions/16535630/sum-values-in-foreach-loop-php)
Answer: Try something like that:
SELECT sum(i.PRICE * i.SALES)
FROM items i;

SQLFIDDLE


How to stop domain users from installing any software?

Question: I was wondering which policies, etc I could setup to stop any installations from occurring in a server 2003 domain environment? I have 2003 RC2 and XP Pro clients.
I guess the quick easy way is to make everyone guests, but this also blocks them from other things that they might need to do/access. I've seen a lot of ideas but they do not fully block everything. I know there probably isn't a fix all but would like to get as close as possible.
Thank you all,
Answer: Remove local admin rights, remove local power user, spend hours debugging crappy and ill-architected software with access problems using sysinternals software to manually work around access issues.
Set up software shares for home directories, profiles, etc. and redirect select subdirs (like my docs) to a network share. Then use something like Faronics Deep Freeze to "reset" the computer back to a pristine state after each restart.
I think they also have software that can whitelist executables, but it will be a pain to set up and maintain if you have a large number of systems with diverse needs to attend to.
Get systems without CD drives and use a portable USB drive for installation of software.
Get HR to support policies that make it crystal clear what's allowed and what isn't on systems, that they're company property and that there's no expectation of privacy on them.
Use filtering software to monitor web use and you can block out downloads if need be.
How draconian do you want to get?
You could also use images of your systems and periodically re-image your computers to a clean state. Still takes maintenance though, as an image a month out of date needs a month of patch-tuesdays installed, plus users still need their own data accounted for on the server or if they're managing to "accidentally" save things locally you're going to hear grumbling.
You'll need to examine your policies and balance usability with how much of a PITA you're going to make it for employees to get their work done and how miserable you want to make your employees feel, if the employer expects a lot from the employees and at the same time won't give them any sense of empowerment or freedom at all...employees that feel a foot on the back and eyes over their shoulders have wonderfully creative ways of making your life more miserable and they won't feel bad in the least for it if they feel justified.
Comment: thanks for the reply btw, unfortunately we are lax in our company. But I hate when people install any apps. If they need something installed it needs to go through us. The re imaging is a good idea, but like you said if they save anything local there then they will be pissed. Someone mentioned that being just domain users that it will stop installation, am i missing something? I only have them as domain users, no local admin or domain admin privileges.
Comment: Local docs and such are an issue until user training takes over. Drill into them that documents can and will be lost if they don't save to the network; they'll lose them at some point anyway when the hard disk fails. THEN MAKE SURE YOUR NETWORK SHARES ARE SAFE with backups that are working. Otherwise, you tell them to save to XYZ so they'll be "safe" then you lose everything? They'll never trust you again.
Comment: And no, you're not missing something. It entirely depends on the program design and privileges needed to run. Otherwise you wouldn't have issues with malware sneaking into your systems; they're programs running quite easily with user privileges (or initially running with user privileges to get a foothold on the system).
Comment: The only way around it is to whitelist allowed exe files. A war of attrition can be waged using a Deep Freeze-like product, because users grow tired of reinstalling their pet programs each time they reboot. It's also a good training tool for users to save files where they're supposed to lest they lose them each reboot, but that's more of a BOFH perspective.
Comment: We have a script that backs up there desktop/mydocs etc, so that part isn't a problem. So I think I'm going to test out some re imaging software like you said, thanks for the idea.
Comment: we just end up killing the lusers, its the cheapest solution to these types of problems.  Truthfully you'd get fired for doing that around here!
Comment: lol, I wish I could that!
Comment: I know of a fortune 50 firm that within a certain department almost everybodys an admin on servers (thousands of servers)! Jezzus, of course to be truthful this is a department that needs to be real agile and anything that slows them down gets frowned upon!
Answer: The answer is to stop them from being administrators. If you are unwilling to do this, then there will always be a way for them to get around anything that you put in place.
Comment: Like Bart says if an app doesn't follow the rules stuff can happen!  Applocker is the best solution at this point!
Comment: They are only domain users, no local admin or domain admin rights, they are still able to install software.
Comment: Domain users are limited users unless they are made local admins or power users on their computers or are part of the Domain Admins group. There is something you are missing if they can install software.
Comment: I checked the groups and user profiles and they are only part of the domain users group, is there another spot where I am not looking? thanks for the reply
Comment: what groups\users are in the local administrators group on the workstations?
Comment: Even plain non-admin users can install some software, depending on the access rights the software needs. A simple game could be completely encapsulated in a subdir of the home directory; if it doesn't need to touch the system dir or access protected parts of the registry, policies won't stop them.
Comment: @tony roth, just ourdomain/Domain Admins and Administrators. Users do not have password to local admin. We only have one user on all workstations, administrator. No custom groups locally.
Comment: I understand, too bad I can't use it in my environment.
Comment: Installing software has little to do with being admin
Comment: @Jim B - Care to elaborate? A use cannot install software afaik unless they are in the Admin group, or there has been a group set up custom that has permission to the appropriate branches of the registry and application installation directory.
Comment: @mark you are operating under the assumption that the software you are installing requires registry access (to register DLLS et al).  Directory access is controlled by the directory owner so directory access is wherever the user installing the software wants to create it.  As an example you can install many clr based apps without registering anything, (so long as .net exists) and once java is installed it also usually requires no "install".  In addition most of the .exe files from pstools don't require an install and neither does any malware I can think of.
Comment: Most of those examples would be considered running an application as opposed to installing one.
Answer: Your first step will be to get buy-in from the business to actually allow you to do such a thing.  Even in giant corporate secure environemnts I've seen execs unwilling to set up appication whitelists.  After that you should look into software restriction policies.
This allows you to allow or block software based on:
Hash, Certificate, Path and Internet Zone.
Where Software restriction does not apply is:
Drivers or other kernel mode software.

Any program run by the SYSTEM
account.
Macros inside of Microsoft Office
2000 or Office XP documents.
Programs written for the common
language runtime.

For CLR lockdown you should use CASPOL.
The depoyment steps would be to set up a test machine and start locking down the policies.  Admin rights have no effect on this type of restriction (unless you choose to see the link for details).  Once you have locked down both regualr and CLR based software the only real source of worry is java.
Answer: They will always be able to "install" software that doesn't require admin access.  A lot of software doesn't need to write to the Program Files folder or make any system wide changes. Especially simple apps that are just EXEs or "portable apps."  Afterall, you allow them to run EXE files, right?
If they are truly non-admins and do not have write or modify rights to Program Files or Windows then I bet they're just running simple apps. There's a group policy setting that lets you whitelist which EXEs are allowed, but I would be very careful with playing with that as it can make all your machines inoperable.
Comment: I understand, I tried playing around with blocking exe's, but it gets a little crazy. Thanks for the reply.
Comment: No problem. I've noticed is that some installers will check for admin rights and if they don't have it, will then install themselves in the local profile.  As as admin that's always bothered me. This is typical of ad-supported 'freeware.' I've always just ignored it or uninstalled it next time I worked on their computer.


Repetição de código no mesmo método

Question: Tenho um método que gera algumas informações. Como eu tinha pressa para entregar, fiz e enviei. Bem, acontece, que vendo o código com mais cuidado, percebi o quanto está deselegante. Ele foi feito para atender uma especificação e como foi alterado isso tive que alterar o código. A regra atual é  seguinte:
Tenho um método que trata arquivos da FarmInterna. O mesmo vale para a FarmExterna. Acontece, que agora eu preciso criar antes da pasta FarmInterna, dois novos folders. Homologacao e Producao. Em cada pasta(Homologacao e Producao) deverá haver duas pastas: FarmInterna e FarmExterna. Vou falar apenas da FarmInterna, que vai valer também para a Externa. Os mesmos arquivos que gero no path: ...Homolagacao/FarmInterna/web/... são os mesmos para: ...Producao/FarmInterna/web/.... Isso deixou meu código extremamente feio e deselegante. Como eu faço para não duplicar o código como está? Existe algum pattern para isso? Abaixo meu código. Onde existe a letra H refere-se a Homolagação e P a produção.
private void CriaPastaFarmInterna()
        {
            string novo_path_H  = caminho_original + @"\Destino\Temp\Homologacao\FarmInterna\web";
            string novo_path_P  = caminho_original + @"\Destino\Temp\Producao\FarmInterna\web";
            string path_files   = caminho_original + @"\Destino\Temp";

            DirectoryInfo dirInfoH = new DirectoryInfo(novo_path_H);
            DirectoryInfo dirInfoP = new DirectoryInfo(novo_path_P);

            int indice = 1;

            if (dirInfoH.Exists == false)
                Directory.CreateDirectory(novo_path_H);

            if (dirInfoP.Exists == false)
                Directory.CreateDirectory(novo_path_P);

            List<String> myFiles = Directory.GetFiles(caminho_original + @"\Destino\Temp\web", "*.*", SearchOption.AllDirectories).ToList();

            List<String> myDirectoriesH = Directory.GetDirectories(caminho_original + @"\Destino\Temp\web").ToList();
            List<String> myDirectoriesP = Directory.GetDirectories(caminho_original + @"\Destino\Temp\web").ToList();

            var diretorios_H = myDirectoriesH.Where(d => !d.Contains("FarmInterna"));
            var diretorios_P = myDirectoriesP.Where(d => !d.Contains("FarmInterna"));

            try
            {
                foreach (string file in myFiles)
                {
                    FileInfo mFile = new FileInfo(file);
                    string newFileH = novo_path_H + (file.Replace(caminho_original + @"\Destino\Temp\web", ""));
                    string newFileP = novo_path_P + (file.Replace(caminho_original + @"\Destino\Temp\web", ""));

                    if (!Directory.Exists(newFileH))
                        Directory.CreateDirectory(Path.GetDirectoryName(newFileH));

                    if (!Directory.Exists(newFileP))
                        Directory.CreateDirectory(Path.GetDirectoryName(newFileP));

                    if (new FileInfo(newFileH).Exists == false)
                        mFile.CopyTo(newFileH);

                    if (new FileInfo(newFileP).Exists == false)
                        mFile.CopyTo(newFileP);
                }

                RenomearWebConfig(novo_path_H, "H");
                RenomearWebConfig(novo_path_P, "P");
            }
            catch(Exception ex)
            {}
        }

Comment: Minha idéia inicial, seria tirar as linhas duplicadas nesse código, tendo em mente que eles criam novos diretorios e o arquivo sendo repetição nos dois diretórios criados. Você iria mudar principalmente o desempenho e o número de linhas diminuindo consequentemente. Como o diretório é novo e os arquivos são novos faz uma verificação somente em uma das pastas. Você pode fazer o seguinte, rodar essa rotina para uma pasta e no final copiar os arquivos para a outra pasta também é uma idéia. Você pode usar [Adapter](http://www.dofactory.com/net/adapter-design-pattern), mas, não precisa ao meu ver
Answer: O refactoring para eliminação de código duplicado é bastante simples:

1) Declare um novo método (ele vai receber o código que generaliza a solução que hoje está duplicada).
2) Percorra o código do método original, movendo cada linha duplicada para dentro do novo método. Veja bem: movendo! Não é copiando e colando, é recortando e colando. Escolha um padrão de linhas a mover; por exemplo: mova para o novo método as linhas que tratam "homologação", deixando as linhas que tratam "produção" no método original.
3) As linhas que estruturam a execução (condições, loops, try-catch...) eventualmente não estão duplicadas - estas você copia para o novo método em vez de mover.
4) As linhas movidas para o novo método não vão compilar pois precisam de variáveis que não existem naquele contexto. Declare cada uma destas variáveis inexistentes como parâmetros deste novo método. Agora o novo método já compila.
5) No código do novo método, substitua por parâmetros as constantes e literais que sejam exclusivos de cada execução, de modo a tornar genéricas as linhas que usam estas constantes e literais.
6) Percorra novamente o método original e substitua as linhas que já foram replicadas no novo método por uma chamada a este novo método, passando os parâmetros conforme exigidos por ele (no caso, os parâmetros referentes a "produção").
7) Faça mais uma chamada ao novo método, passando como parâmetro as variáveis da outra chamada (no caso, os parâmetros referentes a "homologação").
8) Renomeie os parâmetros e variáveis internas do novo método para expressar sua natureza de solução genérica tanto para "produção" quanto para "homologação".

Pronto. Agora você tem o método original gerando os argumentos necessários para serem passados nas duas chamadas ao novo método.
Este passo a passo é genérico e pode ser utilizado para qualquer refactoring deste tipo.
Dica: Se você estiver disposto, acrescente o Passo Zero no começo da lista, que é um teste unitário cobrindo a funcionalidade e que vai garantir que ela continua produzindo os mesmos resultados depois do refactoring.
Seguindo este passo-a-passo, o código fica assim:
private void CriaPastaFarmInternaEExterna()
{
    string novo_path_H = caminho_original + @"\Destino\Temp\Homologacao\FarmInterna\web";
    string novo_path_P = caminho_original + @"\Destino\Temp\Producao\FarmInterna\web";

    List<String> myFiles = Directory.GetFiles(caminho_original + @"\Destino\Temp\web", "*.*", SearchOption.AllDirectories).ToList();

    CriaPastaFarm(novo_path_H, myFiles, "H");
    CriaPastaFarm(novo_path_P, myFiles, "P");
}

private void CriaPastaFarm(string novo_path, IEnumerable<string> files, string ambiente)
{
    DirectoryInfo dirInfo = new DirectoryInfo(novo_path);

    if (dirInfo.Exists == false)
        Directory.CreateDirectory(novo_path);

    List<String> myDirectories = Directory.GetDirectories(caminho_original + @"\Destino\Temp\web").ToList();
    var diretorios = myDirectories.Where(d => !d.Contains("FarmInterna"));

    foreach (string file in files)
    {
        FileInfo mFile = new FileInfo(file);
        string newFile = novo_path + (file.Replace(caminho_original + @"\Destino\Temp\web", ""));

        if (!Directory.Exists(newFile))
            Directory.CreateDirectory(Path.GetDirectoryName(newFile));

        if (new FileInfo(newFile).Exists == false)
            mFile.CopyTo(newFile);
    }
    RenomearWebConfig(novo_path, ambiente);
}

Obs: deixei de fora as variáveis indice e path_files que não estavam sendo utilizadas. Também deixei de fora o try-catch porque do jeito que você usou, limpando a exceção, pode causar problemas.
Obs2: Há várias coisas que podem ser melhoradas, como por exemplo substituir por um enum os literais "H" e "P" a fim de aumentar a expressividade do código; substituir a comparação (condição == false) pela negação da condição, (!condição), que é mais usual; eliminar as repetições de caminho de arquivo (@"\Destino\Temp\web"); etc.
Comment: Caffé, ainda não implementei a seu exemplo, mas foi extremamente útil para mim. Amanhã(terça-feira) vou fazer o que você sugeriu.
Comment: Caffé, como ficaria para a FarmExterna?
Answer: Amigo, centraliza o código repetido num novo método, e chama este método 2 vezes passando os parâmetros que alteram o comportamento do programa.
private void CriaPastaFarmInterna()
        {
            NovoMetodo(caminho_original + @"\Destino\Temp\Homologacao\FarmInterna\web", 'H');
            NovoMetodo(caminho_original + @"\Destino\Temp\Producao\FarmInterna\web", 'P');

}

private void NovoMetodo(string novoPath, char letra) {

    DirectoryInfo dirInfo = new DirectoryInfo(novoPath);

    if (dirInfo.Exists == false)
                Directory.CreateDirectory(novoPath);

    List<String> myFiles = Directory.GetFiles(caminho_original + @"\Destino\Temp\web", "*.*", SearchOption.AllDirectories).ToList();

    List<String> myDirectories = Directory.GetDirectories(caminho_original + @"\Destino\Temp\web").ToList();

    var diretorios = myDirectories.Where(d => !d.Contains("FarmInterna"));

    try
    {
        foreach (string file in myFiles)
        {
            FileInfo mFile = new FileInfo(file);
            string newFile = novoPath + (file.Replace(caminho_original + @"\Destino\Temp\web", ""));

            if (!Directory.Exists(newFile))
                Directory.CreateDirectory(Path.GetDirectoryName(newFile));

            if (new FileInfo(newFile).Exists == false)
                mFile.CopyTo(newFile);

        }

        RenomearWebConfig(novoPath, letra);
    }
    catch(Exception ex)
    {}

}

Answer: você pode tentar da seguinte forma:
private void CriaPastaFarmInterna(string oldPath, string newPath)
{
    var oldDirectory = new DirectoryInfo(oldPath);
    var newDirectory = new DirectoryInfo(newPath);

    if (!oldDirectory.Exists)
        return false;

    if (!diretorio.Exists)
        diretorio.Create();

    for (var subDirectory in oldDirectory.GetDirectories())
    {
        CriaPastaFarmInterna(subDirectory.FullName, newPath + @"\" + subDirectory.Name)
    }

    for (var oldFile in oldDirectory.GetFiles())
    {
        var newFile = new FileInfo(newDirectory.FullName + @"\" + oldFile.Name);
        if (!newFile.Exists)
            oldFile.CopyTo(newFile.FullName)
    }
}

private void CriaPastaFarmInterna()
{
    string oldPath   = caminho_original + @"\Destino\Temp\Web";
    string newPathH  = caminho_original + @"\Destino\Temp\Homologacao\FarmInterna\web";
    string newPathP  = caminho_original + @"\Destino\Temp\Producao\FarmInterna\web";

    try
    {
        CriaPastaFarmInterna(oldPath, newPathH);
        CriaPastaFarmInterna(oldPath, newPathP);

        RenomearWebConfig(novo_path_H, "H");
        RenomearWebConfig(novo_path_P, "P");
    }
    catch(Exception ex)
    {

    }
}

Repetição de código no mesmo método


Avoid data for being inserted into new rows in mysql database

Question: I have saved a source code .ccp type file under column 'file' in file_details table in a mysql database. It is done not by using a program but by directly inserting through localhost/phpmyadmin interface. The type of the data field is BLOB. Then by accessing saved codes I am calculating the number of spaces of each source codes and I want to insert the values to the database column called 'spaces' in the same table. Here I have given the query that I used.
<code>        Statement stmt = conn.createStatement();
        Statement count_to_db=conn.createStatement();

        String query = "SELECT prog_num,file FROM file_details";

        ResultSet rs = stmt.executeQuery(query);

       while (rs.next()) {

            String file_content = rs.getString("file");

            CalculatingSpaces calSpaces = new CalculatingSpaces();
            String num_of_Spaces= calSpaces.CalculatingSpaces(rs, pw, file_content);
            int spaces=Integer.parseInt(num_of_Spaces);

           String space_query="INSERT INTO file_details(spaces) VALUES ('"+spaces+"')";
           count_to_db.executeUpdate(space_query);

        }
</code>
But when I am inserting the spaces they are inserted to a new row but not for the same row where I have uploaded the BLOB files. Is there any way to insert the number of spaces in-front of the BLOB files which spaces related to.
PS : So the problem is Can't I insert data column by column to a database?
Answer: If you're adding your table row for the first time, you'll have to use the SQL INSERT command.
If you want to update an existent row, you have to use the SQL UPDATE command.
Don't forget that you need to know which row(s) you want to UPDATE, so you'll also need to define a way to uniquely identify your rows (aka the Primary Key).
See http://dev.mysql.com/doc/refman/5.0/en/update.html for details
Comment: Thanks for replying Leo. Got it.. Will do this and check.


Visual Studio 2013 só abre projetos 2012

Question: Sempre que vou criar um novo projeto no VS2013, não tenho opção de projetos, apenas a opção: WEB >> Visual Studio 2012. Aí sim, tenho várias opções de projetos como MVC 3 e 4 e assim vai. Como eu atualizo? Tentei pelo NuGet, mas continua a mesma coisa
Answer: O Visual Studio 2013 não fornece acesso a alguns templates que estavam disponíveis no Visual Studio 2012. Se você quiser usar um desses templates, você pode clicar em Visual Studio 2012.
Veja nesse link.
Comment: @pnet Conseguiu resolver? A resposta foi útil?
Answer: No Visual Studio 2013, o ASP.NET só usa MVC5, portanto só tem uma opção:

Na opção de Visual Studio 2012, há ainda a compatibilidade retroativa para MVC4, no máximo.


Google Maps Api v3 - Trabalhando com 2 arquivos Json

Question: Estou criando um mapa, para apresentar uma série de informações, usando o google maps v3.
Resolvi trabalhar com 2 arquivos Json, para preenchimento do mapa.
O primeiro arquivo contem as informações de Latitude e Longitude dos pontos do mapa, e o segundo contem as informações da InfoWindow.
Até aí tudo bem, consegui preencher o mapa e buscar as informações da InfoWindow no outro arquivo.
Agora gostaria de aplicar filtros neste mapa, para segmentar os dados.
É nesta parte que estou com problema, o filtro precisa ser aplicado no segundo arquivo, e com isto filtrar o primeiro, para setar apenas os pontos de interesse, irão existir mais de 1 filtro para o mapa.
Estou me batendo com isto, alguém já precisou fazer algo semelhante?
Alguma ideia? Fiz algumas tentativas mas sem sucesso até agora.
Segue meu fonte até agora (Preenchendo o mapa e setando a InfoWindow).
<!DOCTYPE html>

    <meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
    <title>TESTE</title>

Abaixo o exemplo dos Json:
var lat_long = [
      {
         "ARMARIO_SITE": "ACRBO_O1A01",
         "LONGITUDE": -67.80921,
         "LATITUDE": -9.971221
      },
      {
         "ARMARIO_SITE": "ACRBO_O1A02",
         "LONGITUDE": -67.81101,
         "LATITUDE": -9.960082
      },
      {
         "ARMARIO_SITE": "ACRBO_O1I01",
         "LONGITUDE": -67.81749,
         "LATITUDE": -9.969712
      }
];

var ards = [
    {
        "LOCALIDADE":"FEIRA DE SANTANA",
        "TIPO_CLIENTE":"Padrão",
        "TIPO_ACESSO":"METALICO",
        "UF":"BA",
        "DESC_MES_CRIACAO":"JANEIRO",
        "DESC_CLUSTER":"FEIRA DE SANTANA",
        "ARMARIO_ERB":"ACRBO_O1A01",
        "TIPO_RECLAMACAO":"TT",
        "CLIENTE_RECENTE":"N"
    },
    {
        "LOCALIDADE":"FEIRA DE SANTANA",
        "TIPO_CLIENTE":"Padrão",
        "TIPO_ACESSO":"METALICO",
        "UF":"BA",
        "DESC_MES_CRIACAO":"JANEIRO",
        "DESC_CLUSTER":"FEIRA DE SANTANA",
        "ARMARIO_ERB":"ACRBO_O1A01",
        "TIPO_RECLAMACAO":"TT",
        "CLIENTE_RECENTE":"N"
    },
    {
        "LOCALIDADE":"FEIRA DE SANTANA",
        "TIPO_CLIENTE":"Premium",
        "TIPO_ACESSO":"METALICO",
        "UF":"BA",
        "DESC_MES_CRIACAO":"JANEIRO",
        "DESC_CLUSTER":"FEIRA DE SANTANA",
        "ARMARIO_ERB":"ACRBO_O1A02",
        "TIPO_RECLAMACAO":"TT",
        "CLIENTE_RECENTE":"N"
    },
    {
        "LOCALIDADE":"FEIRA DE SANTANA",
        "TIPO_CLIENTE":"Premium",
        "TIPO_ACESSO":"CABO",
        "UF":"BA",
        "DESC_MES_CRIACAO":"JANEIRO",
        "DESC_CLUSTER":"FEIRA DE SANTANA",
        "ARMARIO_ERB":"ACRBO_O1I01",
        "TIPO_RECLAMACAO":"TT",
        "CLIENTE_RECENTE":"N"
    },
    {
        "LOCALIDADE":"FEIRA DE SANTANA",
        "TIPO_CLIENTE":"Residencial",
        "TIPO_ACESSO":"METALICO",
        "UF":"BA",
        "DESC_MES_CRIACAO":"JANEIRO",
        "DESC_CLUSTER":"FEIRA DE SANTANA",
        "ARMARIO_ERB":"ACRBO_O1I01",
        "TIPO_RECLAMACAO":"TT",
        "CLIENTE_RECENTE":"N"
    }
];

Obrigado.
Comment: Não seria mais fácil trabalhar com o conteúdo dos dois arquivos em uma mesma coleção, como objetos compostos?
Comment: @lbotinelly Como funcionaria este objeto composto? Desculpe minha ignorância, não sou programador.
Pensei nesta solução, pois para cada lat_long, posso ter 10~15 registros de conteúdo na Infowindow.. Aí fiz isto para não duplicar as localidades..
Comment: Posso tentar mostrar como se faz se você postar exemplos de conteúdo correlacionado de cada arquivo.
Comment: @lbotinelly adicionei no post um exemplo dos arquivos, a ligação deles é pelo ARMARIO_ERB e ARMARIO_SITE, no lat_long são únicos e no ards podem existir vários registros pra cada ARMARIO_SITE.
Answer: Consegui realizar multiplos filtros utilizando bases distintas.
Segui a ideia deste projeto Marker-Filtering-Google-Maps. Que trabalha de uma maneira muito bem organizada, fiz algumas adaptações apenas, para meus cenários.
Consegui vincular as bases fazendo buscas e setando novos arrays.
Exemplos:
//Para a InfoWindow usei assim.
var as=$(ards).filter(function (i,n){
     return n.ARMARIO_ERB===marker.getTitle();
});

//Para eliminar duplicados
$.each(results, function(index, value) {
    if ($.inArray(value.ARMARIO_ERB, armarios)==-1) {
        armarios.push(value.ARMARIO_ERB);
    }
});

//Buscar a lat_long unica
for(var j = 0; j < armarios.length; j++){
    $.grep( lat_long, function( n, i ) {
        if(n.ARMARIO_SITE===armarios[j]){
            localizacoes.push( n );
        }
    });
}

Funcionou perfeitamente.


Related to the oops concepts

Question: I am having a very basic question  that can even annoy you but that comes in my mind when In started reading the Visual c# e-book.
They have mentioned that::
Surprisingly, the Circle class is currently of no practical use. By default, when you encapsulate your methods and data inside a class, the class forms a boundary to the outside world. Fields (such as radius) and methods (such as Area) defined in the class can be seen by other methods inside the class but not by the outside world—they are private to the class. So, although you can create a Circle object in a program, you cannot access its radius field or call its Area method, which is why the class is not of much use—yet! However, you can modify the definition of a field or method with the public
and this is Circle class given
class Circle
{
    int radius;

    double Area()
    {
        return Math.PI * radius * radius;
    }
}

So, Private fields are not accessible but when I tried something like this in my Console project , I am running it successfully. Is it that we have main function in the class and that's why I can get my private fields accesed by the object of Program class?
class Program
    {

      int number;
       static void Main(string[] args)
        {
            Program ObjProgram = new Program();
            ObjProgram.number = 10;
            Console.ReadLine();

        }
   }

Answer: You can access private fields from within the same class - any instance of the class can access the private fields of any other instance.
So you can create a Program and access its private fields from within Program.Main.
If you tried it from a method in another class, it wouldn't work.
class Program
{
   int number;

   static void Main(string[] args)
   {
        Program ObjProgram = new Program();
        ObjProgram.number = 10;                // works fine
        Console.ReadLine();
   }
}

class SomeOtherClass
{
   void SomeMethod()
   {
        Program program = new Program();
        program.number = 10;                  // does not compile!
   }
}

Comment: Because `number` is in the Program class too.
Comment: I've added an example - is that what you were looking for?
Answer: Main method is member of Program class
hence it(main) can access Private members of Program Class ...
for example
class a
{
    int x;
    void somemethod1()
    {
        x=10;  //this will work fine
    }
}
class b
{
    int y;
    void somemethod2()
    {
       a a1=new a();
       a1.x=10; //this wont work because a1.x is private ... can only be accessible my members of class a
    }

}

Related to the oops concepts


dll load error in python due to insufficient stack size?

Question: I have a python code which imports dll's created by f2py (from fortran routines). Now the python program crashes if the arrays in fortran are too large. How do I manage with this? By increasing stack size? Or heap? I've tried to study the matter, but I still do not understand how I can increase the stack or should I use the heap instead and how I should do that..??? Python always crashes on the line where I try to import the dll, i.e., at line "import f90_routine". Someone also mentioned threads, but I do not know how to use them. Hope someone can help me!!
Comment: Are you sure this is a stack overflow problem? What makes you think it is?
Comment: please include information about the python version you're using, the Fortran and C compilers and the compilation flags which were used to produce the DLL.
Answer: Your basic problem is that you are storing large arrays of data on the stack. This is bad design and is probably due to the way the Fortran code is implemented.
Large arrays need to be stored on the heap and dynamically allocated there.  To solve this problem you will need to understand and modify your Fortran code accordingly.
The ALLOCATE keyword is how you create heap allocated data in Fortran 90.  However, many compilers have options that for arrays to be allocated on the heap and that may be the most expedient route for you right now.
Answer: There is a utility called EDITBIN shipped with Visual Studio (and maybe also the Windows SDK) which is exactly what you want. See http://msdn.microsoft.com/en-us/library/xd3shwhf%28v=vs.71%29.aspx for reference.
To check the stack size, use
dumpbin /headers python.exe

and look for "size of stack reserve" under "optional header values".
editbin /stack:size_in_bytes python.exe

Note that you will have to distribute the modified Python.exe to all people who want to run your code.
Comment: Modified Python exe sounds a rather drastic solution to the problem!
Comment: Great! Still works. Perfect as a temporary solution while the fotran-based sw is being refactored to use the heap-allocations...
Comment: I had to do something like that on site for a customer, because pythonservice.exe (from pywin32) used a smaller stack size than Python and I had my program crashing when running as a Windows service. When hit with a stack overflow in Python, you don't always have many other options and the trick above was a life saver for me. Note that recent versions of pywin32 should have the issue fixed.
Comment: I think the OP's problem will actually be that the arrays that are stack allocated are simply too huge to make sense to be placed on a stack.


Prove that $W^{1,p}$-functions are "$L^{p}$-Lipschitz".

Question: Let $U$ be open in $\mathbb{R}^{n}$ and $V\subset\subset U$. Let
$u\in W^{1,p}(U)$ for $p\in[1,\infty)$.
Want to show for $x\in V$ and $h\in\mathbb{R}$,
$$
\sup_{h}\int\left(\frac{u(x+he_{1})-u(x)}{h}\right)^{p}dx\leq C\|Du\|_{L^{p}(U)} ^p
$$
for some $C$ and $0<|h|<\frac{1}{2}$dist$(V,\partial U)$ where $Du$ : weak derivative of $u$.
I have no idea with this. Anyone gives me a hint for this? I've learnt Sobolev inequalities. Since $U$ is not surely bounded, I can't use partition of unity argument.
Comment: Actually this question is filtered by me so that the original question is not this. If anyone want to see the original one, just leave a comment here. Plus, In my opinion on above question, Maximal function should be used. and littlehood maximal function theorem is useful to this.. but.. I can't get any point to this.
Comment: PlusPlus, If anyone think I have to study more, tell me the theorem, books or name of chapter. I will study!
Comment: Read Evans' book, "Partial Differential Equations" and you will get the answer.
Comment: @xpaul Which part of the book should I read? I read just chapter 2 and 5. Do I have to read more?
Answer: I suppose $e_1$ is some unital vector, i.e. $|e_1| = 1$. Note that it is sufficient to show the inequality for $u \in C_{c}^{\infty}(\mathbb{R})$, because this implies the inequality for general $u \in W^{1,p}(U)$ by a standard density argument. For a classically differentiable function $u$, we have
\begin{align}
 u(x+he_1) - u(x) &= \int_{0}^{1} \frac{d}{dt}[u(x+the_1 )] dt \\
                  &= \int_{0}^{1} \nabla u(x+the_1)\cdot he_1 dt
\end{align}
As the function $x \mapsto |x|^p$ is convex for $p \geq 1$, this implies by Jensen's inequality
\begin{align}
\left|\frac{ u(x+he_1) - u(x)}{h}\right|^p \leq \int_{0}^{1} \left| \nabla u(x+the_1)\cdot e_1 \right|^p  \leq \int_{0}^{1} \left| \nabla u(x+the_1)\right|^pdt
\end{align}
Integrating this over $V$ yields
\begin{align}
\int_{V} \left|\frac{ u(x+he_1) - u(x)}{h}\right|^p dx &\leq \int_{V} \int_{0}^{1} \left| \nabla u(x+the_1)\right|^p dt \;dx \\
&=\int_{0}^{1} \int_{V} \left| \nabla u(x+the_1)\right|^p dx \;dt \\
&\leq \int_{0}^{1} \int_{U} \left| \nabla u(y)\right|^p dy \;dt \\
&= \|Du\|_{L^p (U)}^p
\end{align}
where the last inequality holds because we have chosen $h$ small enough such that $x+the_1 \in U$ for $0 < t < 1$ and $x \in V$.
EDIT: For the density argument, let $u_n \in C_{c}^{\infty}(\mathbb{R})$ converge against $u$ in $W^{1,p}(U)$. From what we've shown so far, we know that
$$\int_{V}\left|\frac{u_n(x+he_{1})-u_n(x)}{h}\right|^{p}dx\leq \|Du_n\|_{L^{p}(U)} ^p $$
holds for any $n \in \mathbb{N}$. Due to the continuity of the $W^{1,p}$-Norm, the right hand side clearly converges against $\|Du\|_{L^{p}(U)}^{p}$, so it suffices to show that the left hand side converges against $\left\|\frac{u(\cdot+he_{1})-u(\cdot)}{h}\right\|_{L^{p}(V)}^{p}$. A simple change of variable shows that $u_n (\cdot + he_1) \to u(\cdot + he_1)$ in $L^{p}(V)$:
$$\int_{V} \left|u_n(x+he_1) - u(x+he_1)\right|^p dx = \int_{V+he_1} \left|u_n(y) - u(y)\right|^p dy \leq \|u_n - u\|_{L^{p}(U)} \to 0 $$
where the last inequality follows again because $V + he_1 \subseteq U$. Therefore, we may conclude that $$ \frac{u_n(x+he_{1})-u_n(x)}{h} \to \frac{u(x+he_{1})-u(x)}{h} \quad \text{in}\quad L^{p}(V)$$
holds. This implies convergence of the respective $L^{p}(V)$-norms, which proves
$$\int_{V}\left|\frac{u(x+he_{1})-u(x)}{h}\right|^{p}dx\leq \|Du\|_{L^{p}(U)} ^p $$
for all $u \in W^{1,p}(U)$ and $h$ satisfying $0 < |h| < \text{dist}(V,\partial U)$. Therefore, we may take the supremum over all such $h$ on the left hand side and the inequality will remain true.
Comment: Oh Thanks! Perfect. Then how can I show this for the original sobolev space? Right hand side is approximated by the smooth functions but how about left hand side?
Comment: @HeonjinHa I've added the details for the density argument.


rewrite rule for case sensitive directory

Question: I'm looking into setting up a re-write to ignore the case of the directory name of the URL.
For example, I have
example.com/TestDirectory

I want to ignore the case so the URL will still direct to
example.com/testdirectory

Here is what I have, but it doesn't seem to be working:
# rewrite rules for example.com/TestDirectory
RewriteCond %{http_host} ^example\.com [NC,OR]
RewriteCond %{http_host} ^www\.example\.com\TestDirectory [NC]
RewriteRule $ http://www.example.ccom/testdirectory/

Am I missing a step?
Comment: http_host does not contain directories.  It's a hostname, not a full URL.
Answer: In order to implement a canonical redirect to the correctly cased directory (in this case, all lowercase) you could do something like the following:
RewriteCond %{REQUEST_URI} !^/testdirectory
RewriteRule ^testdirectory /testdirectory/ [NC,R,L]

The NC (nocase) flag on the RewriteRule ensures that it would match TestDirectory or TESTDIRECTORY etc. and the RewriteCond directive prevents a redirect loop by checking that we are not already at testdirectory via a case-sensitive match.
However, this only redirects to the directory. Any file after the directory name is lost. In order to redirect /TestDirectory/<whatever> to /testdirectory/<whatever> then try something like the following instead:
RewriteCond %{REQUEST_URI} !^/testdirectory
RewriteRule ^testdirectory/?(.*) /testdirectory/$1 [NC,R,L]

Note that this is a temporary (302) redirect. Change the R flag to R=301 if this is intended to be permanent, but only after you have checked that it is working OK.

RewriteCond %{http_host} ^www\.example\.com\TestDirectory [NC]

Note that the HTTP_HOST server variable contains just the requested hostname. There is no URL-path information. If you need to check the host as well (if you have multiple domains) then include an additional condition:
RewriteCond %{HTTP_HOST} ^www\.example\.com [NC]

(This assumes the domain has already been canonicalised to include the www subdomain.)


ComboBox com PHP mudança a de status no banco de dados

Question: Como posso mudar o Campo Status no banco de dados através do ComboBox no PHP? Eu consegui
montar uma mudança de status com onclick, mas agora preciso mudar com o ComboBox.
//PERMISSÃO Nº31 = BLOQUEAR/DESBLOQUEAR OS
        if((array_key_exists(31, $sessao->getMenuPermissao())) && $qtOsIniciada == 0 ){

            if($os->getStatus() == 'BLQ'){
                $bloquearOrdemServico = "getIdOrdemServico().", true )' id='cancelarOrdemServico'
                                            title='Desbloquear OS'>

                                        ";
            }
            else{

                $bloquearOrdemServico = "getIdOrdemServico().", false )' id='cancelarOrdemServico'
                                            title='Bloquear OS'>

                                        ";
            }
        }
        else{

            $bloquearOrdemServico = '';
        }

Comment: Você vai precisar dar mais dicas do que você quer... Você quer mudar o que, para que, qual o motivo, o que você quer fazer?
Comment: bom queria entender como faço pra que  getStatus() == 'BLQ') em vez de ficar BLQ  ele passe a ficar null  por uma comboBox. quando selecionar no campo bloqueado ou desbloqueado respectivamente ele mude o status.
Comment: Sim até ai eu entendi, mas eu estou tentando entender a aplicação prática, me explique um pouco mais sobre sua aplicação para eu poder entender o que ela tem que fazer e te ajudar nisso.
Comment: KhaosDoctor, desculpa brow estava cheio dos problemas e nem tive tempo de entrar para ver as respostas, então se puder me ajudar ainda agradeço. Te explicar melhor eu tenho algumas class.php e o oque eu estou precisando fazer e atualizar vários campos de uma vez através de php e javascript, seria um campo de bloqueio e desbloquio de varias informações ao mesmo, no caso essa informação vem do banco de dados e me é apresentado num site cara você poderia me passar o seu e-mail porque ai eu te mandaria o print da tela e te explicaria com mais detalhes.
Comment: Você consegue recuperar o valor do status selecionado?
Comment: consigo sim! esse codigo ai de cima ele funciona numa boa ele
bloqueia e desbloqueia numa boa, oque eu queria era em vez de bloquear/desbloquear clicando em cima do icone eu queria bloquear/ desbloquear  todas as os de uma unica vez
Comment: Deixa eu entender, você quer um unico combo no topo que bloqueie todos os inputs abaixo? Coloque uma foto por favor.
Comment: isso mesmo!!segue a foto!
Comment: Ah sim, mas essas Ordens estão no banco de dados correto? Você teria que executar uma query no banco para bloqueá-las?
Comment: isso mesmo.....
Answer: Como as ordens de serviço estão em um banco de dados, ao invés de realizar uma query com uma restrição para o ID da ordem, você terá de realizar uma outra query sem restrição, ou então com restrições que apliquem-se ao modo de visualização do usuário. Ex:
Ao invés de usar
UPDATE TBL_ORDEM SET STATUS = 'BLOQUEADO' WHERE ID = 123

Você terá de usar
UPDATE TBL_ORDEM SET STATUS = 'BLOQUEADO'

Isto vai variar do seu sistema, ou seja, você terá que (provavelmente) criar uma outra função para enviar o comando para o programa e recarregar a tela da mesma maneira como você faz hoje, porém sem o código da ordem.
Comment: obrigado KhaosDoctor!


Power BI - Gerar tabela com DAX filtrando linhas

Question: Olá, preciso criar uma tabela usando DAX que filtre as linhas duplicadas pegando somente uma, aquela que contenha o maior valor da coluna [Valor]. Exemplo:
Quando utilizo o código:
Tabela =

SUMMARIZECOLUMNS(
   'Cliente'[Cod_cliente],
   'Cliente'[Valor],
    FILTER(
        'Cliente',
        NOT '[Cod_cliente] == BLANK()
      // Como devo calcular esse filtro de duplicatas???
    )
)

Ele gera uma tabela assim:

Cod_cliente
Valor

01
22

02
12

01
23

02
14

02
30

04
10

03
12

04
6

Gostaria que ele gerasse a tabela contendo somente um valor por código do cliente e que esse valor fosse o maior. A tabela que desejo retornar:

Cod_cliente
Valor

01
23

02
30

03
12

04
10

Esse é só um exemplo do que estou tentando fazer, a tabela real na qual estou trabalhando retorna milhares de linhas. Estou completamente perdido.
Comment: Por favor, edite a pergunta para limitá-la a um problema específico com detalhes suficientes para identificar uma resposta adequada.
Answer: Para pegar o maior valor de uma coluna você pode utilizar a função MAX. O seu código ficaria da seguinte forma:
Tabela =
SUMMARIZECOLUMNS(
   Cliente[Cod_cliente],
   "Valor", MAX(Cliente[Valor]),
    FILTER(
        Cliente,
        NOT [Cod_cliente] == BLANK()
    )
)