PHP escrevendo javascript encriptado

Question: Estou com uma duvida em relação a um ofuscador de código javascript feito em php.. https://damidev.000webhostapp.com
alguém pode me ajudar a entender como esse cara fez pra encriptar? toda vez que é gerado o código ofuscado ele gera diferente do anterior mesmo o código sendo o mesmo
meu site esta sofrendo com crawlers, estão acessando o meu site e roubando informações pelo html.. com o método packer (packed) é fácil reconhecer um padrão e capturar oque quiser: pastebin.com/BZEsmxNm.. porem com o método desse site damidev.000webhostapp.com deixa tudo escondido: pastebin.com/tw90KYSi, assim dificultando a vida desses crawlers entendeu ? pois se você reparar ele sempre gera um código diferente mesmo com a mesma entrada de js .. tava estudando e percebi que é um método em XOR ou algo assim..
Answer: Geralmente estes sistemas tem uma chave de encriptação que é usada de forma unica, justamente para não ter como desfazer e o objetivo é realmente fazer ele diferente a cada ciclo.
Dei uma olhada e ele muda as chaves a cada geração, não deve ser dificil de reproduzir isso em php caso você queira gerar sua própria rotina.
Comment: pois, eu só quero entender que método ele usa pra encriptar, tentei estudar o código porem não consigo entender muito bem e fazer a engenharia reversa ..

PHP escrevendo javascript encriptado


Make script that fills and format cells

Question: Have to do some Apps Script for uni I cant do it, I have attached an image of what we have to make via the code

<code>function myFunction() {

  var mysheet = SpreadsheetApp.getActiveSheet();

mysheet.getRange('a1').setValue('I Hate Programming')
mysheet.getRange('a2').setValue('I Hate Programming')
mysheet.getRange('a3').setValue('I Hate Programming')
mysheet.getRange('a4').setValue('It Works')
mysheet.getRange('a5').setValue('I Love Programming')
mysheet.getRange('a1:a5').setFontColor('#ff000')
mysheet.getRange('a1:a5').setBackgroundRGB(0,0,0)

mysheet.autoResizeColumn(1)
mysheet.setFrozenRows(5)
}
</code>
that is my current code, how ever I just get a black box with no text,
Comment: Please check out [How do I ask and answer homework questions?](https://meta.stackoverflow.com/q/334822/1595451)
Answer: Try this:
mysheet.getRange('a1:a5').setFontColor('#ff0000')

Make script that fills and format cells


ASP.NET C# DropDownList dúvida

Question: Tenho um módulo que gera relatórios em excel, sendo um desses relatórios,o módulo chamado de Ocorrências. Onde através de DropDownList ele me informa todos os registros da tabela OcorrTipoEntr, que tem as colunas OctCodigo e OctDesc porém nesse ddl ele apenas me trás a descrição da ocorrência:

Destinatário Ausente

Na classe que informa essa consulta TipoOcorrencia.cs ele apenas faz uma consulta simples SELECT * FROM OcorrTipoEntr pois como disse, preciso de toda carga de dados que existe nessa tabela.
Porém preciso que nesse ddl informe o código da ocorrência, seguido da descrição.Exemplo:

46 - Destinatário Ausente

Minha dúvida é, onde eu posso aplicar essa alteração?
No jQuery, no code-behind, na classe? Seria apenas uma concatenação?
Comment: É AspNETMVC ??? Se tem o código que faz o Envio dessa informação para tela ??? Seu banco é SQL Server?
Answer: Essa é uma saída para quem usa WebForms...
HTML do Formulário
<form id="form1" runat="server">

    <asp:DropDownList ID="ddlOcorrencias" runat="server" OnDataBound="ddlOcorrencias_DataBound"></asp:DropDownList>

</form>

Classe de Ocorrencias
public class Ocorrencias
{
    public Ocorrencias()
    {

    }

    public String Ocorrencia { get; set; }

    public string CodigoOcorrencia { get; set; }
}

Page_Load do DropDownList para populá-lo
    protected void Page_Load(object sender, EventArgs e)
    {
        List<Ocorrencias> Ocorr = new List<Ocorrencias>();

        Ocorrencias Oc1 = new Ocorrencias();
        Oc1.CodigoOcorrencia = "45";
        Oc1.Ocorrencia = "Alguma Ocorrencia Ocorreu !";

        Ocorrencias Oc2 = new Ocorrencias();
        Oc2.CodigoOcorrencia = "46";
        Oc2.Ocorrencia = "Destinatário Ausente";

        Ocorr.Add(Oc1);
        Ocorr.Add(Oc2);

        ddlOcorrencias.DataValueField = "CodigoOcorrencia";
        ddlOcorrencias.DataTextField = "Ocorrencia";
        ddlOcorrencias.DataSource = Ocorr;
        ddlOcorrencias.DataBind();
    }

Concatenação no DataBound do DropDownList
    protected void ddlOcorrencias_DataBound(object sender, EventArgs e)
    {
        foreach (ListItem li in ddlOcorrencias.Items)
        {
            li.Text = li.Value + " - " + li.Text;
        }
    }

ASP.NET C# DropDownList dúvida


Need help with inverse laplace transform problem

Question: I'm really stuck this problem.
This actually resulted because of equations for a circuit analysis problem, so in case it would help I'll list the equations here too. Although, feel free to ignore them. We are solving for currents $i_1$ and $i_2$,
$$(i_1 - i_2)s - 2s^{-1} + i_1 = 0 \\ (i_2 - i_1)s + i_2 + (s^{-1} + i_2)2s^{-1} = 0 \tag{1}.$$
I get that $i_2$ is given by,
$$i_2 = {2(-s^3 + s + 1)\over s((s^2 - s - 1)s^2 - s(s + 1) - 2(s + 1))} \tag{2}$$
I am supposed to calculate the inverse transform of,
$$\displaystyle V(s) = (s^{-1} + i_2)2s^{-1} \\ \ \ \ \ \ \ \ \ \ \ = \  {2(s^3 - 3s^2 - 2s - 1) \over s(s^4 - s^3 - 2s^2 - 3s - 2)} \tag{3}$$
The expression for $V$ was obtained with sage. I can't see any easy way to decompose $V$, and this is where I am stuck.
All help is greatly appreciated! Thanks!
Comment: First, are you sure you wrote the systems equations properly and then solved them properly? I get different values for $i_1$ and $i_2$?
Comment: @Amzoti Yeah, that could be it. I got two different expressions for $i_2$ by solving the system differently. I guess I'll just have to try another approach.
Comment: Glad it all worked out and you are very welcome! Regards
Answer: I get the following results (you can plug these into $(1)$ and see if they satisfy each of the system's equations):
$$i_1 = \frac{2(s^2 + 2)}{s(2s^2 + 3s + 2)}$$
and
$$i_2 = \frac{2(s^2 - s - 1)}{s(2s^2 + 3s + 2)}$$
You gave:
$$\displaystyle V(s) = (s^{-1} + i_2)2s^{-1} = \left(\frac{1}{s} + \frac{2(s^2 - s - 1)}{s(2s^2 + 3s + 2)}\right)\frac{2}{s} = \frac{8s + 2}{s(2s^2 + 3s + 2)}$$
The Inverse Laplace Transform is given by:
$$ \displaystyle \mathcal{L}^{-1} (V(s)) = V(t) = 1-\frac{e^{-3 t/4} \left(\sqrt 7 \cos\left(\sqrt 7 t/4\right)-13 \sin(\sqrt 7 t/4)\right)}{\sqrt 7}$$
However, like I said, you had better validate my $i_1$ and $i_2$ since they do match yours.
Update
Note: I substitute $a = i_1$ and $b = i_2$ to get rid of any potential issues. Find a Wolfram Alpha solution to the simultaneous equation for $i_1$ and $i_2$.
Here is a WA solution to the simultaneous equations.
Comment: Thanks for solving the system! Your solution seems to be on mark, also because of the type of circuit at hand; so I'll check and get back.
Comment: @ThisIsNotAnId: Please see the Wolfram Alpha link and solution to compare against what you are using. SAGE should certainly work! Regards
Comment: Ok, I double checked and I finally have the proper expressions for $i_2 \text{ and } V(s).$ Thank you so much for all the help!
Comment: Can you let us know if Ron was correct or if the above was correct or if it turned out to be another answer? Thanks
Comment: Well, Ron's was correct under the assumption that the expression for $V(s)$ in my op was correct, which it turns out it wasn't. You provided the correct expression for $i_2, V(s), \text{ and } \mathcal{L}^{-1}[V(s)].$
Comment: Great feedback to a very helpful answer! ;-)
Comment: @Amzoti I was looking at this problem again and realized that I have the incorrect inverse transform. I get that $v(t) = 1 - cos({\sqrt{7}t\over4})e^{{-3t\over4}} + {10\over \sqrt{7}}sin({\sqrt{7}t\over4})e^{{-3t\over4}}$. I decomposed $V(s)$ as $s^{-1} - {2s \over \alpha} + {5 \over \alpha} \ (\alpha = 2s^2 + 3s + 2)$, and went from there. Also, I factored $\alpha$ as $2\left(\left(s + {3 \over 4}\right)^2 + {7 \over 16}\right).$ What was your approach?
Comment: The expression I get is almost identical to yours; the only difference is that in my expression, the coefficient of the sine term is ${10 \over \sqrt{7}}$ rather than ${13 \over \sqrt{7}}$ as in yours. Also, using WA for the expression for $V(s)$ in my comment above gives me the same inverse as the one you have. But the problem is that I don't get the same expression doing the inverse manually.
Comment: I'll take it from $V(s) = s^{-1} - {2s \over \alpha} + {5 \over \alpha} = {1 \over s} - {s \over {\left(s + {3 \over 4}\right)^2 + {7 \over 16}}} + {4\over \sqrt{7}}{5 \over 2}{\sqrt{7}/4 \over {\left(s + {3 \over 4}\right)^2 + {7 \over 16}}}$. The expression has standard inverse transfroms; the inverse is $1$ for the first term, $-\cos\left({\sqrt{7} \over 4}t \right)e^{{-3 \over 4}t}$ for the second, and ${10 \over \sqrt{7}}\sin\left({\sqrt{7} \over 4}t \right)e^{{-3 \over 4}t}$ for the third.
Comment: You lost the 2 product in the middle term. When you fix that, you should get an inverse of -(e^(-3 t/4) (sqrt(7) cos((sqrt(7) t)/4)-3 sin((sqrt(7) t)/4)))/sqrt(7). When you add the sin term to the correct last term you got, you will get my result. Regards
Comment: Oh, I see! Much thanks!
Answer: If your expression for $V(s)$ is correct, there really isn't much you can do about the roots: the expression is not factorable over the rationals, or even square roots.  Rather, a plot reveals two real roots and a pair of complex roots; these you can find in terms of the horrifying quartic solution, or just numerically as I did.
Let the roots of the quartic be as follows:
$$s_1 \approx 2.45111 \quad s_2 \approx -0.788821 \quad s_{\pm} \approx -0.331144 \pm 0.931636$$
These are all simple roots, as is the root at $s_0=0$.  We may determine the ILT from the sum of the residues of the poles of the function $V(s) e^{s t}$.  The residue at $s_1$ is, for example:
$$2 \frac{2 s_1^3-3 s_1^2-2 s_1-1}{5 s_1^4-4 s_1^3-6 s_1^2-6 s_1-2} e^{s_1 t} \approx -0.26737 e^{2.45111 t}$$
where I used the fact that, for a simple pole $s_0$ of a function $p(s)/q(s)$ is $p(s_0)/q'(s_0)$  Repeat for all roots, and add; I get
$$f(t) = 1-0.26737 e^{2.45111 t}-1.22806 e^{-0.788821 t} + e^{-0.331144 t} [0.247714 \cos{0.961636 t} + 0.962263 \sin{0.961636 t} + i (-0.962263 \cos{0.961636 t} +0.247714 \sin{0.961636 t})] $$
Comment: First, thank you for going through the trouble of finding the roots and the expression for $f$. Although, it now seems that I really did obtain an incorrect expression for $i_2$, because $f$ is supposed to be capacitor voltage which, here, will eventually go to negative infinity. Uhhhh, back to the drawing board for me.


Local / session storage - pause video and playback from where it has stoped - JavaScript

Question: I know this question is possible duplicate. SO has suggested lot links me when typing my question side by side.
my situation is,
example: i've 3 videos as course for each user which are visible only after logged in. the thing is i just want play the video where it has paused.
example Video_001 has length 4 mins. but user has watched till 2.30 mins and did the same for Video_002 and then logged out. if user logged in again. the videos has to start from where it has stopped.
pls see this
<code>`https://codepen.io/theNoobsCode/pen/omgGZx`
</code>
could someone tell me where and how to use local/session storage here and what needs to be change?
kindly share your thoughts and examples if possible
helps much appreciated.
Comment: Split your problem in multiple smaller tasks. You need 1. get an event when user logs out. 2. get video's current time when this event fires. 3. store this time info in Storage. 4. retrieve this info from Storage at next login. 5. set the video's current time to a fixed value (the one that has been stored). All these 5 questions have been asked many time in here, and should not be too hard to figure out.
Answer:
You can save the fragment end time from where it is paused in local storage.

When user comes back you can get the fragment end time from local storage of that video and pass to following code
e.g. user has watched video for 40 seconds and if you want start video again after 40 seconds you can use following

<code><source src="video.mp4#t=40,100" type="video/mp4"/>
</code>

For more details you can see following link


MongoDB find query maxTimeMS

Question: I want to terminate my find query if that query cross time limit so I using a query like this :
db.collection.find({description: /August [0-9]+, 1969/}).maxTimeMS(50).toArray()

According to this, if my find query takes more than 50 milliseconds, then I want to terminate this query. but I need to understand what happens at the DB level if the query crosses the 5 milliseconds then my application giving me the error but on the DB level the query still running or it also terminates or it will complete and then terminate?
Kindly help me here to understand this and if possible how we can check this?
Answer: Yes, MongoDB will kill the operation.

MongoDB targets operations for termination if the associated cursor exceeds its allotted time limit. MongoDB terminates operations that exceed their allotted time limit using the same mechanism as db.killOp(). MongoDB only terminates an operation at one of its designated interrupt points.

MongoDB does not count network latency between the client and the server towards a cursor's time limit. For a sharded cluster, however, MongoDB does include the latency between the mongos and mongod instances towards this time limit.

Queries that generate multiple batches of results continue to return batches until the cursor exceeds its allotted time limit.

Read maxTimeMS

From - https://github.com/Automattic/mongoose/issues/4066#issuecomment-502260563
https://mongoosejs.com/docs/api/mongoose.html#mongoose_Mongoose-set
mongoose.set('maxTimeMS', 3000);

Or:
https://mongoosejs.com/docs/api/connection.html#connection_Connection-set
const db = mongoose.createConnection(uri);

db.set('maxTimeMS', 3000);

Comment: Thanks For the quick reply any option to set DB level time out for all queries like maxTimeMS?
Comment: is any tool or any command to check locale MongoDB CPU usage?

MongoDB find query maxTimeMS


How to list all managed files?

Question: I need to get Drupal to list all its files and their management status for debugging purposes. It seems like there must be a simple way to print the list of managed files, right? How is this done?
Answer: There is at least 1 issue queue item looking to add "reporting" to the Media module, such as show me where this file is used on the site.
If you're using Drush. Look at drush sql-cli and a query such as select fid, filename from file_managed where status = 1
Comment: http://api.drupal.org/api/drupal/includes%21file.inc/function/file_usage_list/7
Comment: see this issue regarding tracking asset usage on a site. http://drupal.org/node/1599460
Comment: This is correct. It turns out I asked the wrong question, because I wanted to look at the file *usage* table instead, but this is still helpful because I didn't know about drush sql-cli before this.
Comment: So, this is great, but is there really no API call that returns a list of files?
Comment: There we go, that's what I was looking for. Thank you!

How to list all managed files?


cannot do any operation on the ssrs manager

Question: I have installed a named instance of sql server with reporting services (2016) on my local machine. But in the reporting service manager (the web portal) I cannot perform any operation*. My guess is that there is a problem in connection between reporting service and database, or some permission issues. I have tried for three days and still no success, cause apparently I'm looking at the wrong place. Any help is highly appreciated.
*for example: when I want to uplad an rdl I face this error:

Could not connect to the server. Please check your network settings and try again later.

I just add some scree shots which give the overview of my settings, but, please tell me if you think adding some more info helps.
Comment: Could you provide an anonymous screen shot of your permission settings (site permissions and root permissions)?
Answer: It is really strange and I don't know how to explain the reason this solution works, but I state it here because I found this solution after three days! and it may help someone else.
I was accessing the SSRS portal on Google Chrome (as I did before the installation of SQL Server and Reporting Services) but it wasn't working -- It just kept giving me strange pop up messages.
Solution: Use IE! Yes, use IE (finally there is something that IE is good at).
Edit: At the moment that I posted this answer I said that I don't know why this trick does the job but after some researches for another problem I concluded that this behaviour of Chrome is because it saves/buffers many settings to serve the pages faster and that's sometimes problematic. Therefore, clearing the hole settings (cookies, ...) should solve this problem.


How to force HAProxy load balancer to redirect specific URLs always to the same server?

Question: My domain is using HAProxy as a load balancer, there are 3 servers balanced, but I want to execute some particular urls always on the same server.
Is this possible?
or maybe this is an XY problem and there is a better solution:
In some urls I'm creating files, I want to create the files always in one of my fron servers because that one has an rsync to the others.
EDIT: Is similar to https://stackoverflow.com/questions/33041131/can-haproxy-direct-a-request-to-a-particular-server
But the problem is my HAProxy is not managing the SSL, so I cannot create the ACL rule based on the path (or at least I don't know how).
Comment: Sounds like a bit of an XY problem, but hard to tell. What have you tried?
Answer: So, you want traffic switched based on the URL? That's pretty easy, normally. You'd configure haproxy to read the URL or a header or even something deeper in the body of the request.
But if the http is encrypted as it passes through, haproxy can't read any of that. In fact, to haproxy, that would probably just look like a TCP connection - it wouldn't know it was HTTP.
Comment: OK, I think you mean something like this: https://stackoverflow.com/questions/33041131/can-haproxy-direct-a-request-to-a-particular-server
Comment: The problem is my HAProxy is not managing the SSL, so I cannot create an ACL rule based on the URI because is not accessible, do you know some workaround?


Tamanho de uma String

Question: Um char na linguagem C ocupa 1 byte na memória.Ex:
char ch;//a variável ch esta ocupando 1 byte na memória

E um vetor de char mais conhecido por string, o seu tamanho em bytes será contado de acordo com o numero do vetor. Ex:
char ch[4];

Essa variável estará ocupando 4 bytes na memoria, ou a contagem é outra?
Answer: Vamos conceituar corretamente. Variáveis são espaços reservados para armazenar algo. Só isso, nada mais que reservados de alguma forma.
Esta variável reservará 4 bytes na memória. Se a intenção é ter uma string padrão do C, então ela poderá ter até 3 caracteres e terá no final um terminador, que é o caractere 0, também chamado de nulo e comumente representado por '\0'.
Nesse caso sabemos o tamanho dela durante o desenvolvimento. E note que nada garante que a string estará formada corretamente. Nada garante que ela terá só esses 3 caracteres. O que determina efetivamente o tamanho da string é o terminador. Portanto se criar 10 caracteres e depois colocar o nulo final vai funcionar e funções que tratam de strings vão considerar que tem 10 caracteres.
Aí pode perguntar como ele coloca 10 caracteres onde estava reservado para 3. Isso é um enorme erro. Mas a linguagem deixa. É problema do programador se virar em fazer certo. Nesse caso o conteúdo irá invadir o espaço de outra variável se produzirá resultado no mínimo estranhos, possivelmente desastrosos e inseguros.
A função normalmente usada para determinar o efetivo tamanho de uma string em C, e esse é um dos maiores defeitos da linguagem, é a função strlen() que conta todos caracteres até achar o terminador nulo.
Isso pode ser observado em:
#include <stdio.h>
#include <string.h>

int main() {
    char ch[4];
    strcpy(ch, "abc");
    printf("ch tem %d bytes\n", sizeof(ch));
    printf("ch conta com %d caracteres\n", strlen(ch));
    strcpy(ch, "texto longo");
    printf("ch conta com %d caracteres\n", strlen(ch));
}

Veja funcionando no ideone. E no repl.it. Também coloquei no GitHub para referência futura.
Note que em C++ geralmente é mais adequado usar o tipo string. Tem algumas desvantagens e várias vantagens. Outra forma só deveria ser usada se houver boa justificativa.
Answer: Complementando a resposta.

Você consegue saber quantos bytes cada variável ocupa em memória. Existem duas maneiras de fazer isso, a primeira é simplesmente colocando as palavras reservadas dentro do operador sizeof(). A segunda maneira é declarando variáveis e colando ela dentro do operador sizeof().
Primeira:
#include <stdio.h>

int main(void)
{
    printf("Char: %d bytes\n", sizeof(char));
    printf("Int: %d bytes\n", sizeof(int));
    printf("Float: %d bytes\n", sizeof(float));
    printf("Double: %d bytes\n", sizeof(double));

    return 0;
}

Agora, além de mostrar quantos bytes cada variável ocupa, mostre o endereço dela. Segunda:
#include <stdio.h>

int main(void)
{
    char caractere;
    int inteiro;
    float Float;
    double Double;

    printf("Caractere: %d bytes \t em %d\n", sizeof(caractere), &caractere);
    printf("Inteiro: %d bytes \t em %d\n", sizeof(inteiro), &inteiro);
    printf("Float: %d bytes \t em %d\n", sizeof(Float), &Float);
    printf("Double: %d bytes \t em %d\n", sizeof(Double), &Double);

    return 0;
}

Veja funcionando no Ideone:

Primeira
Segunda
Comment: "Sizeof" é um operador, não uma função. Assumindo uma variável "x", "sizeof x" compila normalmente. Quando é aplicado a um tipo ("sizeof(int)") os parênteses são necessários, provavelmente por razões sintáticas, não por sizeof ser uma função.
http://en.cppreference.com/w/cpp/language/sizeof
Comment: @JoséX., editei a resposta. Obrigada pela observação =)
Answer:
Um array de caracteres ("vetor de char") não é conhecido por "string". É um array de caracteres...
Este array de caracteres (char ch[4]) ocupa 4 bytes ou 4 posições de memória nos computadores de hoje (eventualmente podem existir ou terem existido computadores onde isso não é verdade, mas hoje em dia isso é mera curiosidade histórica).

Tamanho de uma String


Is nested dictionary in design ok?

Question: My data is structured in a way that I ended up creating a nested dictionary in my design like:
my_dict = {"a": {"b": {"c":"I am c"}}}
my_dict["a"]["b"]["c"]

Is it usual! or we have some other better alternatives (using objects!)?
Comment: The code you posted isn't indicative of a nested dict.
Comment: I think he means a[b][c]
Comment: I though people will understand so just accessed my nested dictionary!
Answer: There is nothing inherently wrong with nested dicts. Anything can be a dict value, and it can make sense for a dict to be one.
A lot of the time when people make nested dicts, their problems could be solved slightly more easily by using a dict with tuples for keys. Instead of accessing a value as d[a][b][c], then, the value would be accessed as d[a, b, c]. This is often easier to set up and work with.
Comment: Tuples also have significantly less overhead than dictionaries.
Comment: @Vishal, You would simply access an element like `d[a, b, c]` or assign to it like `d[a, b, c] = 4`. This is after initializing it as an empty dict `{}` or with some values like `{(1,2,3): 4, (5,6,7): 8}`.
Comment: @Max S., When indexing, the parens there are optional and would usually be omitted.
Comment: @Mike Graham, yeah, after all it's always the commas that make a tuple, not the parens, but I think it was clearer to show the tuple involvement that way.
Comment: @Mike: What's the difference if I am using string "a-b-c" as a key instead of (a, b, c)?
Comment: @Vishal, In one case you are using a string like `"a-b-c"` and in the other you are using the tuple `(a, b, c)`. The latter case is often useful when you have three Python objects, the combination of which in that order defines what you want to look up. This makes it a somewhat suitable replacement for d[a][b][c].
Answer: You could use a tuple to store your values in a flat dictionary:
d = {}
d[a, b, c] = e

It all depends on what you are doing, but remember that The Zen of Python says that flat is better than nested :)
Answer: At first they may seem like a good idea, but usually you'll find yourself needing more information/functionality from them. If that happens, your first reaction may be "I need more hashes", but all this can be avoided by using a simpler hierarchy ... it would be easier too.
Answer: I would not build complex data structures like that in the code itself. There is too great a risk of making a mistake with punctuation, and anyone reading the code will tend to get confused by this. Far better to put your constant data in some simple form, with no nesting of data structures. Then if you need to have a nested dictionary in the app, build it with code.
a = {"a":"I am a"}
b = {"b":"I am b"}
c = {"c":"I am c"}
mydict = {}
mydict["a"] = a
mydict["b"] = b
mydict["c"] = c
print mydict

{'a': {'a': 'I am a'}, 'c': {'c': 'I am c'}, 'b': {'b': 'I am b'}}

Answer: Maybe one nested dictionary is okay... but even then you're asking to get confused later and there's a pretty good chance that if you're already doing nested stuff you're gonna want more information in it later.
In general I'd say take a step back and see if all that information in the dictionaries is needed. Try to simplify it first. If it really is all needed, I'd try to make a simple class for it. Might be a little overkill but like I said, if you're going down that road already, you're probably gonna end up adding more information later. It's easier to modify a class than it is to try and figure out all that nested information and make your code work with it later.
Answer: You can also use a struct type. Like Dictionary<string, Custom> dict. The struct type is like a dict I guess, but its more rigid.
Comment: Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer).

Is nested dictionary in design ok?


Correlated constrasting dependent variables (X positive Y1, X negative Y2, but Y1 positive Y2)?

Question: everyone, not sure if I do this appropriately. I wish to raise a related question: If I got
X positively related to Y1, and
X1 negatively related to Y2 (both in GLM), however
the correlation coefficient between Y1 and Y2 is positive and significant (using SPSS).
How can I interpret such result? Shouldn't Y1 and Y2 also negatively correlated? Thanks!
Comment: Why do you think they have to be negatively correlated? They don't necessarily have to be, as long as the [covariance matrix](http://en.wikipedia.org/wiki/Covariance_matrix) of the triplet is [positive definite](http://en.wikipedia.org/wiki/Positive-semidefinite_matrix#Negative-definite.2C_semidefinite_and_indefinite_matrices). For example, if ${\rm cor}(X,Y_1) = .5, {\rm cor}(X,Y_2) = -.5$ and then ${\rm cor}(Y_1, Y_2)$ could be anywhere in the open interval $(-1,.5)$ to still produce a valid covariance matrix. Some information about the magnitude of these correlations would be helpful.
Answer: I assume that you mean "correlated" when you say "related".
It is certainly possible depending on the level of correlation between your variables.
As an example
<code>x = rnorm(100)
eps = rnorm(100)
y = x + 2 * eps
z = x - 2 * eps

cor(x, y) # 0.4684695
cor(x, z) # 0.4726246
cor(y, z) # -0.5571685
</code>


What does it mean if $P^n$ is irreducible for every $n\in\mathbb{N}$?

Question: If $P$ is the transition matrix belonging to a markov chain, then what does it mean that $P^n$ is irreducible for every $n\in\mathbb{N}$?
For $n=1$ it means that all states communicate with each other, i.e. for all states $i,j$ it is
$$
\mathbb{P}(\exists m\in\mathbb{N}: X_m=j|X_0=i)>0.
$$
But what does it mean for $n\geq 2$?
Edit
Does it maybe mean that for any states $i,j\in E$ it is
$$
\mathbb{P}(\exists m\in\mathbb{N}: X_{n\cdot m}=j|X_0=i)>0?
$$
Comment: From wikipedia: A matrix is irreducible if it is not similar via a permutation to a block upper triangular matrix (that has more than one block of positive size).
Comment: Sorry but that does not help me at all.
Comment: Means that P is irreducible and aperiodic.
Comment: @Did I have to follow from this that $P$ is irreducible and aperiodic. So cannot use it.
Comment: Did not say to use it, just to prove it. By the way, your question is "what does it mean?" and my comment says what it means.
Answer: It means that all states make up a single subclass. In other words, it means that matrix $P$ is primitive (as also noted in comments by @Did it's aperiodic which I believe is another term for that).
This can easily be seen from the following theorem:
Theorem. (Gantmacher F.R. The Theory of Matrices, 1960, Vol. 2, P. 81, Theorem 9.)
If $A \geqslant 0$ is an irreducible matrix and some power $A^q$ of $A$ is reducible, then $A^q$ is completely reducible, i.e., $A^q$ can be represented by means of a permutation in the form $A^q = \operatorname{diag} \{ A_1, \dots, A_d \}$, where $A_1, \dots, A_d$ are irreducible matrices having one and the same maximal characteristic value. Here $d$ is the greatest common divisor of $q$ and $h$, where $h$ is the index of imprimitivity of $A$.
Since $d$ is $1$ for any $q$, $h = 1$. QED.


How to use euler's formula for edges and faces?

Question:
Let (G, φ) be a connected 4-regular plane simple graph in which every vertex lies on
  two (opposite) faces of length 5 and on two (opposite) faces of length 3. Use Euler's formula
  to find the number of edges and the number of faces of (G, φ)

So euler's formula says that e - v + f = 2. And with the question it seems to give 4 faces (2 opposing pairs). How do I figure out the number of vertices to be able to find the number of edges?
Answer: Denote the number of faces of size $k$ by $f_k$. Then we find the following equations to hold
$$\begin{align*}
 v-e+f &=2&(\text{Euler})\\
f_3+f_5&=f&(\text{Def})\\
4v&=2e\\
3f_3+5f_5&=2e\\
3f_3&=2v\\
5f_5&=2v
\end{align*}$$
Solving the corresponding matrix equation we obtain $v=30, e=60, f=32$.


How to click on an image to show images with a function

Question: Trying to click the magic8, but the happy, sad and surprised pictures won't show below the line. What did I do wrong? I have saved the images in random.js in the same folder.

 Magic 8-ball (Mattel, Inc.)

 Enter a question below, then click on the Magic 8-Ball to recieve its wisdom.

            <input type="text" id="questionBox" size=90 value="">

                <input type="image" src="http://balance3e.com/Images/8ball.gif" id="button" onclick="magicEight();">

Comment: what is `random.js`? Does the console log any errors?
Comment: and what is `RandomOneOf`?
Comment: Please post ALL of your code. It will help us answer your question. Thank you. Welcome to Stackoverflow  :)
Answer: If you want to show and image you need to add the value of the randomoneof on a img tag not on a div tag. Change that and I think it will work
Comment: how? so i shouldn't use outputDiv?
Comment: No, you should use:

And on javascript you should change the src value:
    document.getElementById('rand-image').src = "path-to-the-image";
Answer: Setting .value on outputDiv will not display images. You have to set the src attribute of an  tag.
Assuming all of the random images live in /Images, you could use the below as your new magicEight function.
function magicEight() {
     var imgName;
     imgName = RandomOneOf(["happy.gif", "sad.gif", "surprised.gif"]);
     var imageTag = "";
     document.getElementById('outputDiv').innerHTML= imageTag;
}

Comment: it doesn't work. I have to use RandomOneOf and each time when I click on the ball, it should shows up only one emotion.
Comment: @WinnieChan I've edited my answer. But if HienHuynh already answered your queation, accept his answer. (There should be a check mark somewhere to the left of his answer)
Answer: Demo: https://codepen.io/hienhuynhtm/pen/dpLgNr

 Magic 8-ball (Mattel, Inc.)

 Enter a question below, then click on the Magic 8-Ball to recieve its wisdom.

    <input type="text" id="questionBox" size=90 value="">

<input type="image" src="http://balance3e.com/Images/8ball.gif" id="button" onclick="magicEight();">

Comment: Nice. Just make it clear what/where `randomImg` is for completeness.
Comment: @Terminus: I've just updated full code + Demo link. Thanks for your suggestion.
Comment: @WinnieChan: my pleasure :)


Australian payment gateway adapter for Pay API

Question: Is anyone aware of a working code for the Pay (7.x) module that will process payments over eWay or NAB Transact?
I am considering writing adapters for these gateways, but though I would put out a call for any existing code to start from.
Answer: There are a few modules floating around for commerce, CiviCRM and Ubercart that use eWay, they would be good basis.
Comment: Thanks Chris. I'll dig through these models for inspiration.


How to show $\{a^n \bmod \alpha\}_{n \in \mathbb{N}}$ is dense in $[0,\alpha]$ if $a > 1$ is trancendental over ${\mathbb Q}[\alpha]$

Question: How to show $\{a^n \bmod \alpha\}_{n \in \mathbb{N}}$ is dense in $[0,\alpha]$ if $a > 1$ is trancendental over ${\mathbb Q}[\alpha]$? If $a$ is transcendental over ${\mathbb Q}[\alpha]$ then the integer multiples $\{na \bmod \alpha\}_{n \in \mathbb{N}}$ are dense in $[0,\alpha]$. But what about the positive integer powers of $a$ when $a > 1$? It seems like $\{a^n \bmod \alpha\}_{n \in \mathbb{N}}$ should be dense if $a > 1$ is transcendental over ${\mathbb Q}[\alpha]$. But how to prove it?
Answer: This isn't true. According to the second paragraph of this paper, Vijayaraghavan has shown (in particular) the following:

There are uncountably many numbers $a>1$ such that $\{a^n\}$ is not dense in $[0,1]$.

In particular, there must be such a transcendental $a$. Hence the claim is false for $\alpha=1$.


How to interpret the coefficient when both Y and X are expressed in %?

Question: I have an issue: my dependent variable is expressed in % (it's the % of people that think they will lose their job) , my regressor is expressed in % (it's the share of foreign residents on total population). The coefficient of my regression (FE estimator) is -1,44.
What is the correct interpretation?
A 1% increase in x reduced my y by 144%? OR a 1% increase in x reduced my y by 1,44%?
Thank you very much in advance
Answer: When talking about changes of the quantities that are measured in percents, one should use percentage points. Percentage point is nothing else than just the arithmetic difference between two percentages. So here the correct interpretation would be (in case of an additive model such a linear regression):
A 1 percentage point increase in X corresponds to 1.44 percentage points decrease in Y.
In other words, if we raise X from 50% to 51% (for example), then Y would decrease from 50% to 48.56%.
Comment: This is the correct answer...assuming an additive model, such as a linear regression. I do believe that is the case here, however.
Comment: Yes, I implicitly assumed that. Mostly because of the example of the interpretation that was already given there... Should have included this in my answer anyway. Thanks!


I have placed OJDBC jar in library of both maven and benerator still I am getting error as Class not found: 'oracle.jdbc.OracleDriver'

Question: I am generating test data from db by using benerator tool with maven.
I have placed ojdbc jars in lib of both the installable still I am getting error as :

Failed to execute goal org.databene:maven-benerator-plugin:0.7.7:generate (default-cli) on project AA: Execution default-cli of goal org.databene:maven-benerator-plugin:0.7.7:generate failed: Connecting the database failed. URL: jdbc:oracle:thin:@localhost:1521:xe: Connecting jdbc:oracle:thin:@localhost:1521:xe failed: Class not found: 'oracle.jdbc.OracleDriver'
Comment: Try to put it in the lib of jdk if nothing else works
Comment: Please [edit] your question and include your maven `pom.xml` ([**formatted text**](http://stackoverflow.com/help/formatting) please, [no screen shots](http://meta.stackoverflow.com/questions/285551/why-may-i-not-upload-images-of-code-on-so-when-asking-a-question/285557#285557))
Answer: Please check the  section under  in your plugin configuration
Comment: " " section
Comment: Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer).


Como converter uma String para Date em Swift

Question: eu recebo a data da seguinte forma 2016-08-14T20:38:27.031-03:00 como string, gostaria de passar para data no padrão dd/MM/yyyy, já procurei na net algumas soluções porém não foram úteis
Answer: Para este formato de data 2016-08-14T20:38:27.031-03:00 iso8601, voce precisa usar o seguinte formato com milésimo de segundos SSS e XXX  para time zone (-03:00 ou Z):
"yyyy-MM-dd'T'HH:mm:ss.SSSXXX"
Xcode 8 Beta 6 • Swift 3
extension Date {
    struct Formatter {
        static let iso8601: DateFormatter = {
            let formatter = DateFormatter()
            formatter.calendar = Calendar(identifier: .iso8601)
            formatter.locale = Locale(identifier: "en_US_POSIX")
            formatter.timeZone = TimeZone(secondsFromGMT: 0)
            formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSXXX"
            return formatter
        }()
    }
    var iso8601: String { return Formatter.iso8601.string(from: self) }
}

extension String {
    var dateFromISO8601: Date? {
        return Date.Formatter.iso8601.date(from: self)
    }
}

Date() // "Aug 18, 2016, 8:09 PM"
let dateString = Date().iso8601  // "2016-08-18T23:09:59.830Z"
print(dateString) //  "2016-08-18T23:09:59.830Z\n"

if let dateFromString = dateString.dateFromISO8601 {
    print(dateFromString)   // "2016-08-18 23:09:59 +0000\n"
    print(dateFromString.iso8601)  // "2016-08-18T23:09:59.830Z"
}

Xcode 7.3.1 • Swift 2.2.1
extension NSDate {
    struct Formatter {
        static let iso8601: NSDateFormatter = {
            let formatter = NSDateFormatter()
            formatter.calendar = NSCalendar(calendarIdentifier: NSCalendarIdentifierISO8601)
            formatter.locale = NSLocale(localeIdentifier: "en_US_POSIX")
            formatter.timeZone = NSTimeZone(forSecondsFromGMT: 0)
            formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSXXX"
            return formatter
        }()
    }
    var iso8601: String { return Formatter.iso8601.stringFromDate(self) }
}

extension String {
    var dateFromISO8601: NSDate? {
        return NSDate.Formatter.iso8601.dateFromString(self)
    }
}

NSDate() // "Aug 19, 2016, 1:49 AM"
let dateString = NSDate().iso8601  // "2016-08-19T04:49:35.792Z"
print(dateString) //  "2016-08-19T04:49:35.792Z\n"

if let dateFromString = dateString.dateFromISO8601 {
    print(dateFromString)   // "2016-08-19 04:49:35 +0000\n"
    print(dateFromString.iso8601)  // "2016-08-19T04:49:35.792Z\n"
}

Uma vez que voce tem a sua data no formato NSDate voce deve usar o NSDateFormatter para formatar a data para o usuário. Voce nao deve especificar o formato e sim o estilo da data dateStyle (short, medium, long ou full). Desta forma a data sera formatada de acordo com as preferencias de região do usuário. Segue o link da resposta do site em Ingles:
https://stackoverflow.com/a/28347285/2303865
Se precisar de uma tabela pra referencia:
Answer: Você pode usar a classe NSDateFormatter para fazer esta conversão.
Exemplo:
let dateString = "2016-08-14T20:38:27.031-03:00"
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SZZZZZ"
let date = dateFormatter.dateFromString(dateString)
dateFormatter.dateFormat = "dd/MM/yyyy"
print(dateFormatter.stringFromDate(date!)) // Saída: 14/08/2016

Answer: De forma simplificada, você deve fazer exatamente isso:
let dateString = "2016-09-16T21:09:22.031-03:00" // Data de entrada
let dateFormatter = NSDateFormatter() //Instância do date Formatter
//Aqui você DEVE indicar qual formato é sua data de entrada.
//Se caso não for do formato que você colocou, ocorrerá uma exception!
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SZZZZZ"
//Aqui você está Convertendo sua date String para uma data válida
let date = dateFormatter.dateFromString(dateString)
//Aqui você está mudando o formato que você quer retornar
dateFormatter.dateFormat = "dd/MM/yyyy"
//Aqui você está convertendo a data que você transformou para date em String no formato "novo" que você modificou acima.
print(dateFormatter.stringFromDate(date!)) // Saída: 16/09/2016


Can I have HTTPS and HTTP for a single instance of an application?

Question: I'm planning a web application that will have its own server behind the corporate firewall.
There will be two sets of users, internal and external to the organisation.  Internal users will be located inside of the firewall as same as the application server and the external users are outside over the internet.  All users will be authenticated via a login by the web application.
I would like a setup where the external users will be required to access whole of the application using SSL and the internal users via standard http connection.
I would like to know, if it is possible to setup a single instance the application so that it can be accessed via SSL for external (over the internet) users AND over http for internal users?
The server OS will be Windows 2008R2 and using IIS 7.5.  The application will be using .NET
Framework 3.5.
Thanks
Comment: Could you please specify your server OS/software? (you can edit your question)
Comment: Why not just enable SSL for both internal and external?
Answer: I would suggest that your best bet is to setup your web server to listen for both HTTP and HTTPS traffic, and then only allow external HTTPS traffic to go to your server. Either by restricting it at your firewall, or by having your web server only listed on port 443 on the External IP address.
To give you more specific details we will need to know what web server you are using.
Comment: +1 Definitely the simplest approach, regardless of OS or web server.
Answer: Yep sure its possible. Using Apache with VirtualHosts you can have different VHosts defined and they can have different authentication rules.
If you are allowing access to something from the big bad internet, best to place it in a DMZ in case someone does break into it, so they can't then break into the rest of your network.
I would further question what is the reasoning behind doing this? It would be better to have everyone using SSL all the time if they are passing around credentials. Again if the webserver is in a DMZ then the firewall between the internal users and the DMZ can transparently NAT their requests to the webserver - that is if you are worried about how to route internal users to the server.
Comment: I was just about to ask why the OP is bothering to use HTTP internally and HTTPS externally instead of just requiring HTTPS for everyone...simpler, plus protects from internal snooping of credentials.
Comment: Primary concern for using both http and https was performance degradation when using large amount of data.  Do you not think this is an issue?

Given that I'm using Win 2008 R2 with IIS 7.5 is than possible?
Comment: Performance degradation for clients using a large amount of *data* is not an issue, and here is why. The SSL public-key handshake is the expensive step (hurting the server more than the client) but after that is complete an asymmetric key is established which is super-fast to process. Performance is only a problem when you have lots of clients. Lots means lots - we have small 2VCPU 2GB ram Xen guests running up to 512 simultaneous SSL connections without a problem.

nginx is a high performance web server: http://nginx.net/
Comment: Brilliant, Thanks.  I will enable SSL on all sides.
Answer: Generally, yes. Details depend on the software you use.


After power loss, my RAID config changed, some drives marked as foreign, but all data still there

Question: I have a Perc 5/i in a Dell Precision 590. The controller DOES have a battery backup, and the controller reports that its status is healthy. There are five 1TB SATA drives connected to the controller. My original config looked like this:

VD0: RAID5

PD0
PD1
PD2

VD1: RAID1

PD5
PD7

Fairly simple setup. Last week we had a power failure and I was notified that both VDs were degraded. So I investigated. The configuration has changed. Here is the new configuration:

VD0: RAID5

PD0
PD1
PD5

VD1: RAID5

PD0
PD1
PD5

This makes no sense. How is this even possible!?
Note: The PD Mgmt screen says that Discs 0, 1, and 5 are online and 2 and 7 are "foreign" (what does that even mean???).
Ever weirder, much to my surprise: The VDs both seem to be completely functional and all of my data is intact and my system runs fine. I'm at a loss for words.
I have the data backed up, so it won't be The Worst Day Ever if I lose it and have to restore. But I'd really rather not have that happen. If this had been a normal drive failure, I'd know what to do. But this state is so fubarred I'm afraid to even touch it. Help?
Here are some "screenshots" (for lack of a better word) that hopefully will add some context / additional information if needed.
Comment: **Edit:** Not that it really matters in this case, but it's actually a Precision 490, not a Precision 590.
Answer: Although the config shown in the PERC BIOS looks all wrong, it's clearly still able to properly use the right configuration because you have access to data. The odd data displayed from the BIOS is likely just due to a firmware bug caused by some damage that happened to the configuration data on some of the disks.
You should never import foreign config on a PERC controller if you can see all data from the OS (no missing/offline VDs), no matter how strange things look from the PERC BIOS.
Foreign config is usually seen in two scenarios:

The configuration data was somehow damaged on one or more drives, and the controller recognizes a mismatch with the copy of config data that it keeps cached.
The controller booted and found that its cached configuration was completely missing or damaged, and had to refer to the disks to detect the config (this usually results in all drives showing as foreign)

An import essentially takes the config data on a "foreign" drive and uses that to replace the config data on the other drives it claims to be part of a VD with. In some scenarios, this can leave you with an offline VD instead of just a degraded one.
I would recommend that you ensure your PERC's firmware is up to date. There are no steps you can take to resolve this which have zero risk of causing you to have to restore from backup at this point though, so you might also consider getting those backups up-to-date...
Answer: Foreign basically means that the RAID system doesn't recognize the item (be it a physical disk or virtual disk or whatever).  This can happen if you remove the disks from one server and put them into another with a similar RAID controller.  The new RAID controller will see those disks as "foreign", but you can import the foreign config and it will work just fine.
Based on what you've shown, it looks like VD0 is working because disks 0 and 1 are present, and VD1 is working because disk 5 is present.  The thing that confuses me is how the controller thinks that VD1 is a RAID-5.
My recommendation is to remove the whole RAID configuration and rebuild it based on the original implementation.  RAIDs are surprisingly resilient when importing foreign configs in that manner (I've done similar operations before.  It's scary because it feels like you're wiping out the drives, but you're not).
Importing a foreign config is like getting the RAID to just shrug and trust you about how it should be configured.  If you're sure about how it was configured originally then it'll work fine.


How to add any plugin to ckeditor manually?

Question: I'm trying to add a new plugin ckwebspeech in ckeditor module. Here is the plugin which I want to add.

So, that the final editor will look like mentioned in screenshot. Is there any way to add this manually?
Comment: Does this [link](https://www.drupal.org/node/1793710) help?
Comment: But you your question is not saying what problem you are getting.
Comment: I was trying adding manually first, as there is one an option available to build your custom editor. above link will be the last option.
Comment: CodeNext, I mentioned in the last line " Is there any way to add ckwebspeech plugin manually in ckeditor drupal module? Plugin is attached above, if you click on link.
Comment: @SugandhKhanna I found another good tutorial on that http://margotskapacs.com/2014/05/adding-ckeditor-plugins-manually-in-drupal/. If you can state what you have tried or what method you supposed to have, it is easier for others answer the question :)
Comment: Every plugin to be added to the CKeditor are **Manual method** only..:( let me write the answer!!
Answer: The manual process is described on that plugin page itself, as you can see on the instruction page in first image(red circle.)
If you click that link which you have provided in your question, you can see the Download option on that page. If you click it will download and it will open up a new pop-up window.

1. As you can see in the image. Copy that file and paste to that path.
So, I did copy and paste at at module/ckeditor/plugins/ckwebspeech
2. Now second step says, put this code config.extraPlugins = 'ckwebspeech'; So, I went to admin/modules/ckeditor/config. I did choose either Full or advanced, whichever my site is using. Clicked edit, went to Advanced options And paste the second step as shown in the step-2. Saved it ans clear the cache.

3. Now again went to same place at described in step-2. Instead of Advanced option went to Editor appearance and move the webSpeechSetting and webSpeechEnabled button to the custom toolbar as shown in following image.

4. Now if I scroll down further on the same page, I will have all option of the plugins then I enabled that plugin as shown in following image.(see second option which i checked). Saved cleared cache.

5. Now went to any page where I can see my editor, and, it showed up in editor.
Comment: Lot's of screenprints ... but ... interesting!


Cloud Pub/Sub missing ack/nack in callback not causing redelivery

Question: I'm trying to make sure that Cloud Pub/Sub will redeliver my message if there is no ack/nack sent. It doesn't seem to do this even though I wait for more than 10 minutes, which should be the maximum time for the Acknowledgement Deadline.
I'm using the example here as a starting point:
https://cloud.google.com/pubsub/docs/quickstart-py-mac
Essentially, I commented the line in the callback function that ack's the message. I used two terminals, one for publishing the message and one for receiving it as a subscriber. Since no ack's are being sent, I expected Cloud Pub/Sub to attempt to redeliver the message to the subscriber sometime within the ack deadline, but it doesn't.
The docs here
https://godoc.org/cloud.google.com/go/pubsub#hdr-Deadlines
say the the "ACK deadlines are extended periodically by the client... up to 10 minutes", so I waited 10 minutes in case the ack deadline was extended to that maximum but I still didn't receive the redelivered message.
Here is the edited callback method that I used. This was the only change I made to the example code.
def callback(message):
        print('Received message {} of message ID {}'.format(
            message, message.message_id))
        # Acknowledge the message. Unack'ed messages will be redelivered.
        # message.ack()
        print('Acknowledged message of message ID {}\n'.format(
            message.message_id))

If I kill the subscriber (sub.py) and restart it, the message is redelivered. Am I doing something wrong? Also, when I send a Nack instead of not sending anything at all, the message is quickly redelivered.
EDIT:
It seems like similar questions have been asked on
https://github.com/googleapis/google-cloud-python/issues/5005
https://github.com/googleapis/google-cloud-python/issues/5044
Things I wanted to confirm:

The Ack Deadline set in the subscription is not always the value used. It's extended as Pub/Sub deems necessary.
The 10 minute max Ack Deadline is not actually the maximum time that can elapse before a message is redelivered
This maximum time is determined by the flow_control.max_lease_duration variable (default is 2 hours)
Comment: Add this to the bottom of your code `return abort(500)`. Is the message redelivered?
Comment: @JohnHanley Adding `return abort(500)` to the end of my callback method causes this error: 'No handlers could be found for logger "google.cloud.pubsub_v1.subscriber._protocol.streaming_pull_manager"', then immediate, continuous redelivery of the message roughly every half second. The issue I'm concerned about is if for some reason the callback halts or errors and the ack/nack is never sent (or in this case, the abort)
Comment: I'm not sure if this helps, but I ran the subscriber for a couple hours and after reaching this error, "RetryError: Deadline of 600.0s exceeded while calling , last exception: 503 failed to connect to all addresses", the messages started being redelivered every 10-12 seconds. Maybe that caused the ack deadline to be reset to the default?
Answer: The ackDeadline is the maximum amount of time a message can be outstanding to a subscriber without ack, nack, or modAckDeadline. Once this time passes, the message becomes a candidate to be redelivered, though redelivery may not be immediate. The maximum value for this field is ten minutes.
The Cloud Pub/Sub client libraries, upon receiving a message, automatically sends modAckDeadline requests for the message until it is acked, nacked, or the flow_control.max_lease_duration period passes. Essentially, it extends the ack deadline. The goal is for the client library to keep track of ack deadlines and extend messages as necessary itself so the user doesn't have to do it.
This is why you see the discrepancy between the client library behavior and the ackDeadline configured on the subscription. When using the client libraries, you should set the max_lease_duration to the maximum amount of time you want a message to be outstanding to a subscriber.
Comment: None of these values is a _guarantee_ that messages will not be redelivered in that time frame. It is possible that messages will get redelivered before `max_lease_duration` due to network or server blips.
Comment: Thanks for the answer! One thing I'm still confused about is why the `max_lease_duration` isn't always hit when I run the subscriber that never ack's or nack's. The redelivery interval seems to be random, any duration between 10 seconds and 2 hours


Redirecting to the IP of an amazon EC2 instance

Question: As you know amazon EC2 instances get an address like:
ec2-72-44-40-153.z-2.compute-1.amazonaws.com
If I have the domain example.com, is there any way that I can make bob.example.com or preferably example.com/bob redirect to the IP of
ec2-72-44-40-153.z-2.compute-1.amazonaws.com
??
Thanks!!
Comment: Robert, it would be nice if you waited a bit longer than 30 minutes after asking to select an answer. The first answer may not be the best one, and an open question can be an incentive to others who may otherwise ignore your question.
Comment: ec2-72-44-40-153.z-2.compute-1.amazonaws.com does not look like an IP address at all.
Answer: If you just want to redirect a domain, you can create a CNAME record in DNS:
bob.example.com IN CNAME ec2-72-44-40-153.z-2.compute-1.amazonaws.com

Which will redirect everyone trying to connect to bob.example.com to your EC3 site.
If you want example.com/bob to redirect, you will need to configure some URL rewrite rules on the webserver running on example.com.
Comment: Will the domain redirection also work if the domain is not accessed from a web browser>
Comment: Yes - domain redirection will work with anything that attempts to resolve using DNS. URL redirection will (I believe) only work with HTTP requests.
Answer: Amazon has provided a solution that is perfect for your requirements, and more flexible than  a CNAME record. You can request a so-called Elastic IP address from EC2.
This IP address is static, so you can create an A record in your DNS that points to it, but it points to an EC2 instance of your choosing. A regular A record like the following would be fine:
bob.example.com    A    220.127.116.11

If your server goes down and you boot another instance (which gets a different hostname), simply reallocate the Elastic IP to the new instance. In a minute or two, the new instance is available behind the IP. This means there will be far less delay than you would experience from a DNS change.
Elastic IPs are free, as long as they are in use. You get charged a small hourly amount when you're not using the IP. This is done to discourage bad usage of limited resources.
You can request and assign the Elastic IP's via the API tools, or a GUI such as ElasticFox. Reading Amazon's howto will make things clearer.


Django: object not iterable

Question: I want to fill my model form with initial data. However, I always receive an 'Attendee' object is not iterable. Full traceback: http://dpaste.com/0BH9MAM
When I comment this out: initial=self.object, the error disappears. However, my from is not pre-filled with any data. As I add more forms I can't work with FormMixin or UpdateForm
class AssignAttendee(SuccessMessageMixin, SingleObjectMixin, TemplateView):
        template_name = 'attendees/front/assign_attendee.html'
        success_message = _("Attendee has been successfully updated.")

        def get_object(self):
            return get_object_or_404(
                Attendee,
            ticket_reference=self.kwargs['ticket_reference'],
            ticket_code=self.kwargs['ticket_code'],
        )

    def get(self, request, *args, **kwargs):
        self.object = self.get_object()
        return super().get(request, *args, **kwargs)

    # def post(self, request, *args, **kwargs):
    #     self.object = self.get_object()
    #     return super().post(request, *args, **kwargs)

    @cached_property
    def attendee_form(self):
        return AssignAttendeeForm(
            prefix='attendee',
            data=self.request.POST or None,
            initial=self.object,
        )

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context = {
            'attendee': self.object,
            'attendee_form': self.attendee_form,
        }
        return context

forms.py
class AssignAttendeeForm(forms.ModelForm):

    class Meta:
        model = Attendee
        fields = (
            'ticket_reference',
            'first_name',
            'last_name',
            'company_name',
            'email',
        )

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.fields['ticket_reference'].widget = forms.HiddenInput()
        self.fields['ticket_reference'].disabled = True
        for visible_field in self.visible_fields():
            visible_field.field.widget.attrs['class'] = 'form-control'

Answer: You should pass a dict to Form.initial, not an object.
You are probably looking for the ModelForm.instance keyword argument, which allows updating an existing instance of a model.

Django: object not iterable


in ableton live 10 where did the crossfade controls on two adjacent clips go?

Question: In Ableton if you have two clips butted up against each other on the same track, you used t be able to edit the crossfade between them by pulling down the menu on the track controls on the right and choosing Fades.
That seems to have disappeared and though their website sys the default 4ms fade can be edited like a manually created fade, i can't find where it defines exactly how to do that.
So where can I adjust the crossfade between adjacent clips on the same track?
Comment: does this answer your question: https://help.ableton.com/hc/en-us/articles/360000036890-Editing-Fades-in-Live-10  Make sure to turn off Automation Mode in Live 10 in order to view and edit Fades. Fades are not visible when Automation Mode is active.
Comment: That worked though I'd add a quick note that you turn off automation but then hover the cursor over the ends of the clip to reveal the fade handles
Answer: As mentioned in the comment, turning off automation will let you hover your cursor over the clip's boundaries and that reveals the fade handles.


Two vertices of a triangle being fixed, find the locus of the third vertex such that the triangle has its circumcenter inside the incircle

Question: Recently I played a little bit around with GeoGebra and I constructed the in- and circumcircle of a $\triangle ABC$ with $A=(0,0)$ and $B=(1,0)$ and I asked myself if it is possible to construct the area where all the points are for which the center of the circumcircle is still inside the incircle. With the trace option I figured that it almost looks like a circle but I don't think it is one so how could one approach a construction of it? I came to no real approach or start.

I baptize this curve with the name ,,Rocklage-curve". It is probably possible to create similar surfaces in other cases.
Comment: Connected : https://dan-reznik.github.io/ellipse-mounted-triangles/
Comment: nice question ...+1
Comment: Instead of the former title, "Area where the centre of circumcircle is inside the incircle", I have taken the liberty to write a more adapted one.
Answer: I will first find a condition the side lengths $a,b,c$ must satisfy for the circumcentre to lie within the incircle. In trilinear coordinates $x:y:z$ the incircle has equation
$$ayz+xbz+xyc-(ax+by+cz)\left(\frac{x(b+c-a)^2}{4bc}+\frac{y(c+a-b)^2}{4ca}+\frac{z(a+b-c)^2}{4ab}\right)=0$$
Now substitute the circumcentre's coordinates $a(b^2+c^2-a^2):b(c^2+a^2-b^2):c(a^2+b^2-c^2)$ into this equation and factor over $\mathbb Q(\sqrt2)$. The factor that matters is
$$a^3+b^3+c^3-(a^2(b+c)+b^2(c+a)+c^2(a+b))+2\sqrt2abc$$
Since the circumcenter lies in the incircle when $a=b=c=1$, our desired condition is when the above expression is nonpositive:
$$a^3+b^3+c^3-(a^2(b+c)+b^2(c+a)+c^2(a+b))+2\sqrt2abc\le0$$
$$\iff\frac1{2abc}(a+b-c)(b+c-a)(c+a-b)\ge\sqrt2-1$$
You want the region for $C=(p,q)$ where the condition holds for $\triangle ABC$. In this triangle $c=1$, $a=\sqrt{p^2+q^2}$ and $b=\sqrt{(1-p)^2+q^2}$. Substituting these into the condition and plotting in the $pq$ plane reveals a very decidedly non-circular shape:

Numerical integration based on the cylindrical algebraic decomposition in Mathematica reveals the area and perimeter of this shape as
$$A=0.9271379517\dots$$
$$L=3.4431978101\dots$$
Comment: Can you give a geogebra construction? I would like to measure length and area
Comment: @calculatormathematical (1) I don't use GeoGebra (anymore), I use Mathematica. (2) The numerical area and perimeter have been added – don't bother trying to find exact expressions for these!
Comment: great answer .....+1
Comment: @Shiva Venkata Please have a look at my solution.
Answer: Here is a solution based on ratio $\frac{r}{R}$, where $r$ is the inradius and $R$ the circumradius.
See Geogebra animation here. A static view is available at the bottom of this answer.

Let us recall a relationship called "Euler formula":

$$d^2=R^2-2Rr$$
connecting $r$ and $R$ with $d$ defined as the distance between the incenter $I$ and the circumcenter $O$ of a triangle.
As your inclusion condition is:
$$d \le r,\tag{1}$$
your issue is equivalent to condition :
$$R^2-2Rr \le r^2 \ \iff \ (R-r)^2-r^2 \le r^2$$
Otherwise said, equivalent to :
$$\frac{r}{R} \ge \sqrt{2}-1\tag{2}$$

Besides, there exists another formula involving ratio $\frac{r}{R}$, which is

$$\frac{r}{R}= \cos(\hat{A})+\cos(\hat{B})+\cos(\hat{C})-1 \tag{3}$$
where $\hat{A},\hat{B},\hat{C}$ are resp. the angles in vertices $A,B,C$ ; see here at paragraph "further conditional identities".
Connecting $(2)$ and $(3)$, the inequality implicitly describing the locus of point $C$ is
$$\cos(\hat{A})+\cos(\hat{B})+\cos(\hat{C}) \ge \sqrt{2}\tag{4}$$
It remains to express (4) in terms of the coordinates $(x,y)$ of $C$.
Intermediate expressions are the sidelengths $a=BC$ and $b=AC$ of triangle $ABC$ given by :
$$\begin{cases}a&=&\sqrt{(x-1)^2+y^2},\\  b&=&\sqrt{x^2+y^2}\end{cases}\tag{5}$$
Relationships (5) are useful in the following expressions of the 3 terms in the LHS of (4) :
$$\begin{cases}\cos(\hat{A})&=&\frac{x}{b}\\
\cos(\hat{B})&=&\frac{(1-x)}{a}\\ \cos(\hat{C})&=&\frac{a^2+b^2-1}{2ab}\end{cases}\tag{6}$$
(the last formula comes from cosine rule : $1=a^2+b^2-2ab \cos \hat{C}$)
It remains to "plug" formulas (5) and (6) into (4) to get the implicit equation of the frontier of the locus. Using a CAS like Geogebra we obtain the following shapes which coincides with the locus given in the answers of Parcly Taxel and Robjohn (with $a=f(x,y)$ and $b=g(x,y)$) ; [the locus itself is the two interior parts of these curves].
Comment: @user148298 I am tempted to say that the equation of the boundary being rather complicate, it's doubtful that it is a "registered curve", with a name.
Comment: Is there a name for the plotted shape? It has a pleasant form.
Comment: I like your solution as well as it uses geometrically elementary arguments rather than trilinear coordinates. Thanks for your contribution.
Comment: I wonder how large the area and circumfence are...
Comment: @calculatormathematical About area and perimeter, I have seen that, meanwhile, Parcly Taxel has provided numerical values. I approve his comment : no exact value can be reasonably awaited...
Comment: When I started writing my answer, only Parcly Taxel's answer was showing. After posting my answer, I see that your answer uses the same idea: $d^2=R(R-2r)$. I hope my answer is dissimilar enough. If not, I can remove mine.
Comment: @robjohn Don't erase it : it is sufficiently different !
Comment: @JeanMarie Interesting, I'm not a math person, but can this equation be generalized to graphically render leaves of different sizes length etc. Might be a cool generative algorithm in simulations.
Comment: @user148298 In order ro render leaves, more generally plants, there are more effective ways.
One of the most interesting way is by using L-systems
 https://en.wikipedia.org/wiki/L-system or by using polar plots https://en.wikipedia.org/wiki/L-system
Comment: @JeanMarie Thanks. I was thinking of individual leaves and flowers.
Comment: +1 for this nice answer
Answer: In this answer, it is shown that the distance $d$ between the incenter and circumcenter is
$$
d^2=R(R-2r)\tag1
$$
where $R$ is the circumradius and $r$ is the inradius.
For the circumcenter to be within the incircle, we would need $d\lt r$, that is
$$
R(R-2r)\lt r^2\tag2
$$
Therefore,
$$
\left(\frac Rr\right)^2-2\frac Rr-1\lt0\tag3
$$
which is satisfied if $1-\sqrt2\lt\frac Rr\lt1+\sqrt2$. Since $r,R\gt0$, we need
$$
\frac Rr\lt1+\sqrt2\tag4
$$
From $(3)$ and $(4)$ in the same answer, we get
$$
\begin{align}
\frac Rr
&=\frac{\frac{abc}{4A}}{\frac{2A}{a+b+c}}\tag{5a}\\
&=\frac{abc(a+b+c)}{8A^2}\tag{5b}\\
&=\frac{abc(a+b+c)}{8s(s-a)(s-b)(s-c)}\tag{5c}\\
&=\frac{2abc}{(b+c-a)(a-b+c)(a+b-c)}\tag{5d}
\end{align}
$$
Explanation:
$\text{(5a):}$ $(3)$ and $(4)$ from this answer
$\text{(5b):}$ simplify
$\text{(5c):}$ Heron's Formula (proven in this answer)
$\text{(5d):}$ $2s=a+b+c$
Fix the endpoints of $c$ and plot locus of the remaining vertex of the triangles with sides $a$ and $b$ where
$$
\frac{2abc}{(b+c-a)(a-b+c)(a+b-c)}\lt1+\sqrt2\tag6
$$


How to do this: example.com/users/user1

Question: How to make a url to look like example.com/users/user?
I do not use a framework and I write procedural PHP code.
Comment: Keyword: mod_rewrite. And now go do some research please.
Comment: I haven't tried anything because I have no experience with Apache rules
Answer: You need somthing like this? Not clear what is your requirement. Check this blog for more

Rewriting example.com/user.php?username=xyz to example.com/xyz

RewriteEngine On
RewriteRule ^([a-zA-Z0-9_-]+)$ user.php?username=$1
RewriteRule ^([a-zA-Z0-9_-]+)/$ user.php?username=$1

Refer htaccess2 tricks

How to do this: example.com/users/user1


Android Java Multitasking operations on listview

Question: How to create dynamic threads for dynamic data? i have spinner item and depending on the spinner item selected, the listview shows whats in a database related to the spinner item. Here is what i want to do...
 _________________
|_________________|  <-spinner item     select an item
 _________________
|_________________|  <-listview         A thread for the spinner
|_________________|                     item that runs through the
|_________________|                     list items
      _______
     |_______|       <-toggle button    thread started by button

 _________________
|_________________|  <-spinner item     select a second item
 _________________
|_________________|  <-listview         First thread still running BTW.
|_________________|                     if button clicked, a new thread
|_________________|                     for this spinner item created
      _______
     |_______|       <-toggle button    thread started by button

 _________________
|_________________|  <-spinner item   Going back to the first spinner item,
 _________________                    the toggle button is on because its
|_________________|  <-listview       thread is still doing repetitive tasks
|_________________|
|_________________|
      _______
     |_______|       <-toggle button    stop thread by toggling off.

Here is my code
public class Sequencer extends play_Activity implements Runnable{
private String Task;

public Sequencer(String taskName){
    this.Task = taskName;
}

@Override
public void run() {
    int switcher = 0;
    int limit = Tasks.size();//each listview item is a task in a list called Tasks

    while(switcher <= limit){
        //my repetitive tasks
    }
}

public void setTask(String taskName){
    this.Task = taskName;
}

public String getTask(){
    return Task;
}

}

public void ThreadMaster(){
    DB_Handler db = new DB_Handler(getContext());
    List<String> TaskList = db.getSpinnerSelectionsPossible();//returns a list
    int jobsize = TaskList.size();
    for(String job: TaskList) {
        Thread thread = new Thread(new Sequencer(job));
        for(int i=0; i<jobsize; i++){
            thread.setName(TaskList.get(i).toString());
            continue;
        }
        //thread.start();
    }
    Set<Thread> threadSet = Thread.getAllStackTraces().keySet();
    for (int i=0; i<=threadSet.size(); i++){
        Log.e(LOG, String.valueOf(threadSet.toArray()));
    }
}

Answer: Use AsyncTask instead of Thread. Execute each AsyncTask in ListView's adapter.getView() & define a boolean: 'finished' for each task, then set it true on AsyncTask.onPostExecute() method to find out this task is finished or not.
When viewing the same list for the second time, check if tasks are finished before executing those tasks again and update the toggle button state based on finished state.


Diagnosing Logon Audit Failure event log entries

Question: I help a client manage a website that is run on a dedicated web server at a hosting company. Recently, we noticed that over the last two weeks there have been tens of thousands of Audit Failure entries in the Security Event Log with Task Category of Logon - these have been coming in about every two seconds, but interesting stopped altogether as of two days ago.
In general, the event description looks like the following:
<code>An account failed to log on.

Subject:
    Security ID:        SYSTEM
    Account Name:       ...The Hosting Account...
    Account Domain:     ...The Domain...
    Logon ID:       0x3e7

Logon Type:         10

Account For Which Logon Failed:
    Security ID:        NULL SID
    Account Name:       david
    Account Domain:     ...The Domain...

Failure Information:
    Failure Reason:     Unknown user name or bad password.
    Status:         0xc000006d
    Sub Status:     0xc0000064

Process Information:
    Caller Process ID:  0x154c
    Caller Process Name:    C:\Windows\System32\winlogon.exe

Network Information:
    Workstation Name:   ...The Domain...
    Source Network Address: 22.214.171.124
    Source Port:        1605
</code>
The value in the Account Name field differs. Above you see "david" but there are ones with "john", "console", "sys", and even ones like "support83423" and whatnot.
The Logon Type field indicates that the logon attempt was a remote interactive attempt via Terminal Services or Remote Desktop. My presumption is that these are some brute force attacks attempting to guess username/password combinations in order to log into our dedicated server. Are these presumptions correct?
Are these types of attacks pretty common? Is there a way to help stop these types of attacks? We need to be able to access the desktop via Remote Desktop so simply turning off that service is not feasible.
Thanks
Answer: The March 2012 Security Bulletins included MS12-020, which is for a Critical vulnerability in Remote Desktop Services.  On March 19, it was reported that there is proof of concept code in the wild.
http://www.pcworld.com/businesscenter/article/252092/patch_now_microsoft_rdp_exploit_code_is_in_the_wild.html
https://secunia.com/advisories/48395
https://technet.microsoft.com/en-us/security/bulletin/ms12-020
I would not expose Remote Desktop without a smart card or VPN solution.  There are inexpensive VPN solutions available for evaluation and testing (such as Hamachi).  There are even free versions if you don't need all the features or only have a small number of remote client computers.
Comment: FWIW, the Microsoft security patch was applied on 3/17.
Answer: Are they common? Yes.
Can you stop them? No.
You can't stop someone from attempting the attack, but you can reduce their chance of success by keeping the system up to date with patches, by using some type of IDS/IPS, and auditing your logs regularly to stay aware of the frequency and volume of the attempts.
Answer: As Joe mentioned these are common and your best bet is to secure the surface area (updates, etc). I'm assuming since this is a dedicated server it should be behind a shared/dedicated firewall. Call up your hosting provider and have them white list your source IP's for 3389 and drop all other traffic not originating from your sources.


Automapper and null dictionaries

Question: I am using Automapper to patch an object onto itself.
I want to ignore null values from the source object when doing the mapping. This works for collections by using AllowNullCollections = true;. When I have a destination object that contains a dictionary with some elements and I try to map a source object that contains a null dictionary, I expect the null dictionary to be ignored because I am ignoring null collections.
But on my destination object, the Dictionary wind up empty.
Is this the expected behavior for Dictionaries?
This is my profile
AllowNullCollections = true;

CreateMap<T, T>()
.ForAllOtherMembers(o => o.Condition((s, d, value) => value != null));

And my mapping call
var context = PatcherProfileContext.Create();

var originalEntity = new TestEntity
{
    Dictionary = new Dictionary<string, object> { { "key", "value" } }
};

var patchEntity = new TestEntity
{
    Dictionary = null
};

context.Mapper.Map(patchEntity, originalEntity);

originalEntity.Dictionary.ShouldHaveSingleItem();

But It winds up being empty.
Comment: Per the [automapper documentation](http://docs.automapper.org/en/stable/Lists-and-arrays.html#handling-null-collections), I do not think this is the expected behavior.  Which version of Automapper are you using?
Comment: I am using Automapper  8.1.1
Comment: It's my opinion that this is a bug in Automapper 8.1.1, but I am not positive.  That version is only a few months old, and only one version has been released since.  I seached Automapper's [issue tracker](https://github.com/AutoMapper/AutoMapper/issues?utf8=%E2%9C%93&q=is%3Aissue+AllowNullCollections+dictionary) but don't see anything like this reported.  (I wouldn't report it as a bug until you have a second opinion here on SO.)
Comment: When mapping to an existing collection, the destination collection is cleared first. If this is not what you want, take a look at AutoMapper.Collection.
Answer: I have realized, with help from Lucian, that the default behavior of mapping to an existing collection is to clear that collection out, regardless of if AllowNullCollections = true. I found an old stackoverflow post detailing that I should use precondition instead of regular condition in this case. I think this will work for me: Automapper does not map properly null List member, when the condition != null is specified

Automapper and null dictionaries


Apache Sorl Add Custom Term Indexing with Hierarchy

Question: My project was have 3 content types with taxonomy, i need to combine all the content types term field values and display with hierarchy.
My fields are :
field_peoples_rits_term,
field_publcation_rits_dev,
field_research_rits_term
I Need combine all these fields as a new field. Thanks in advance
Comment: that's not a code ! that's just mumbo jumbo right there!
Answer: You don't need custom code to achieve this, quoting from here:

There's a wonderful little checkbox in the Search API workflow tab
  which enables it.
Head to:
admin/config/search/search_api/index/your solr server/workflow
(You'll need to have created a server to get to this.)
And then tick the box "Index Hierarchy".
In callback options select the taxonomy field where you would like
  searching for the parent to include the child.
Comment: My project was have 3 content types  with taxonomy, i need to combine all the content types term field values and display with hierarchy.

My fields are : field_peoples_rits_term,field_publcation_rits_dev,field_research_rits_term

I Need combine all these fields as a new field.

Thanks in advance


Como desativar o CTRL+C em batch?

Question: É possível desativar o comando CTRL+C em batch?
Answer: Outra opção seria um script como o abaixo, adapte-o para suas necessidades:
Esse arquivo de lote não pode ser cancelado por Ctrl-C e, se for cancelado por Ctrl-Break, a janela cmd.exe será fechada.
<code>@echo off
setlocal

if "%~1" equ "NonCancelable" goto NonCancelable
start "" /B cmd /C "%~F0" NonCancelable
exit

:NonCancelable
echo You can NOT cancel me!
echo/
set "var="
set /P "var=Enter password (enter Exit to end): "
if /I "%var%" neq "exit" goto :NonCancelable
echo Terminating non cancelable...
pause
exit
</code>
Original: https://stackoverflow.com/a/36953316/935330
Comment: Obrigado pelo seu comentário!
Answer:
Sim e Não !
por padrão, no Batch não há como barrar o Ctrl+C porém é possível
  desativar essas teclas com algum "utilitário" externo, escrito em uma
  linguagem de programação, porém eu não conheço nenhum, mas é possível caso exista algum.
Comment: Obrigado pelo seu comentário!
Answer: No windows 10 é possível alterando as propriedades, primeiro abra o prompt em modo Administrador, depois clique com o direito no titulo do prompt e vá em propriedades e desabilite a opção para ctrl:

(fonte: merabheja.com)
Comment: mas aí não vai funcionar mais nenhum atalho de Ctrl, correto?
a não ser que essa máquina seja um servidor e não seja necessário usar atalhos, essa opção e boa.
Comment: Obrigado pelo seu comentário!

Como desativar o CTRL+C em batch?


Identification of the holomorphic tangent space with the real tangent space

Question: I'm reading Griffiths and Harris and just want to check I'm interpreting a passage correctly.
Let $M$ be a $n$ dimensional complex manifold.
We define $T_p^\mathbb{R}M$ as the tangent space of the underlying smooth manifold, and define $T_pM:=T_p^\mathbb{R}M\otimes \mathbb{C}$. We then define $T_p'M=\langle\frac{\partial}{\partial z_i} \rangle_{i=1}^n$ where $\frac{\partial}{\partial z_i} =\frac{1}{2}\left(\frac{\partial}{\partial x_i} -i\frac{\partial}{\partial y_i}\right) $. When then have $T_pM=T_p'M\oplus\overline{T_p'M}$.
Now we have a natural isomorphism of real vector spaces $T_p^\mathbb{R}M\to T_p'M$ defined by the composition
$$T_p^\mathbb{R}M\hookrightarrow T_pM\stackrel{\pi}{\to}T_p'M$$
I see that one could define this, but it seems a bit strange to consider this map when we consider what it does to our elements:
$$\frac{\partial}{\partial x_i}\mapsto \frac{\partial}{\partial x_i}\otimes 1=\frac{\partial}{\partial z_i}+\frac{\partial}{\partial\bar{z_i}}\stackrel{\pi}{\to}\frac{\partial}{\partial z_i}$$
$$\frac{\partial}{\partial y_i}\mapsto \frac{\partial}{\partial y_i}\otimes 1=i\frac{\partial}{\partial z_i}-i\frac{\partial}{\partial \bar{z_i}}\stackrel{\pi}{\to}i\frac{\partial}{\partial z_i}$$
So under this $\mathbb{R}$ linear isomorphism we map $\frac{\partial}{\partial x_i}$ to $\frac{\partial}{\partial z_i}$ and $\frac{\partial}{\partial y_i}$ to $i\frac{\partial}{\partial z_i}$. Of course we can do this, but why is this natural? I get that is it natural in the sense that we get this map essentially from the definition of complexification of a vector space.
But I mean moreso why it is natural from a more analytic point of view when we think about our tangent vectors as derivations. Or for example when we have a Hermitian inner product $g$ on $T_p'M$, we define the inner product on $T_p^\mathbb{R}M$ as $Re(g)$, where we also use the identification above, so for example
$$Re(g)(\frac{\partial}{\partial x_i},\frac{\partial}{\partial y_j})=g(\frac{\partial }{\partial z_i},i\frac{\partial }{\partial z_j})+\overline{g(\frac{\partial }{\partial z_i},i\frac{\partial }{\partial z_j})}$$
I can see how this definition is correct in the sense of giving us an inner product on $T_p^\mathbb{R}M$, but I feel that I'm missing some understanding as to why this is a definition that makes sense, which in turn makes me suspect that there's something I'm not getting.
So my question is whether what I've written above is correct in the sense that this is what Griffiths and Harris meant. And then if it is, if someone could maybe motivate some of this.
Answer: Reviving an old post here.
As I am sure Griffiths and Harris mention in the book, the bundle $T'M$ (or $T^{1,0}M$ in other books) is supposed to be the holomorphic tangent bundle. One way to specify what that is to say that it should act on holomorphic functions, in other words it should consist of derivations mapping holomorphic functions back to holomorphic functions.
Now note that given a holomorphic function $f$ on an open subset of $\mathbb{C}^n$, we have $$ \frac{\partial{f}}{\partial{x_j}}=\frac{\partial{f}}{\partial{z_j}}, \quad \frac{\partial{f}}{\partial{y_j}}=i\frac{\partial{f}}{\partial{z_j}}$$where $\frac{\partial{}}{\partial z_j}$ can either be given by the formula you mention in your post, or simply as the partial differentiation symbol in the $j$-th direction (which makes sence, because the limit in the partial derivative exists by the virtue of $f$ being holomorphic). In this sense it is a pretty natural identification.
Comment: A derivation don't really maps holomorphic functions to functions: at maps functions to real numbers.
Comment: @Arctic Char, there are two types of derivations, one of local rings where the target is the field of numbers, the other one the derivation of the ring (sheaf) of functions to itself. Check out the Wikipedia page about that
Comment: Which page are you referring to? I am looking at [this](https://en.wikipedia.org/wiki/Tangent_space#Definition_via_derivations) and can't find that.
Comment: @ArcticChar, here is a general discussion of derivations: https://en.wikipedia.org/wiki/Derivation_(differential_algebra) , vector fields as derivations of the sheaf of functions: http://virtualmath1.stanford.edu/~conrad/diffgeomPage/handouts/dervector.pdf


Finding a toric variety of a cone

Question: I'm trying to find the toric variety associated to the cone $\sigma_0$ which is the region in the real plane with $x\geq 0$ and $y-x\geq 0.$ I found that it's dual cone is $\check{\sigma_0}$ the region in the real plane with $y+x\geq 0$ and $y\geq 0.$ So we have a commutative semi group $S_{\sigma_0} = \check{\sigma_0} \cap \mathbb{Z}^2$, with generators $(-1,1) $ and $(0,1).$ But there doesn't seem to be any $\mathbb{N}$ linear relations between these generators. The variety associated to the cone is $\operatorname{Spec} (\mathbb{C}[S_{\sigma_0}])$ and in Fulton's Toric Varieties book on page 6, it states that
$$ \operatorname{Spec} (\mathbb{C}[S_{\sigma_0}]) = \operatorname{Spec}( \mathbb{C}[X,X^{-1}Y] ) = \mathbb{C}^2. $$
How does he obtain both of these inequalities? I can't even see the second one. I find the notation $\mathbb{C}[X,X^{-1}Y]$ to be confusing, for example I would prefer that instead of $\mathbb{C}[X,X^{-1}]$ we write instead $\mathbb{C}[X,Y]/(XY-1)$ because it makes it clearer to make that its Spec is the set of points $(x,y)\in\mathbb{C}^2$ such that $xy=1.$ So how do we do the same thing for $\mathbb{C}[X,X^{-1}Y]$?
Answer: First, you've made a small mistake with your second generator for $S_{\sigma_0};$ it should be $(1,0)$ rather than $(0,1).$ Thus the monoid algebra generated by this monoid is $\mathbb C[\chi^{(1,0)},\chi^{(-1,1)}] =\mathbb C[X,X^{-1}Y].$
We can think of the ring $\mathbb C[X,X^{-1}Y]$ as the subring of the Laurent polynomials $\mathbb C[X,X^{-1},Y,Y^{-1}]$ generated by $X$ and $X^{-1}Y,$ and show that $\mathbb C[X,X^{-1}Y]$ is isomorphic to the polynomial ring $\mathbb C[U,V]$ by the obvious map $U\mapsto X,V\mapsto X^{-1}Y.$
(In general, we begin with a cone contained in a lattice $\mathbb Z^n,$ so we always think of these monoid algebras as subrings of some $\mathbb C[X_1,X_1^{-1},\ldots,X_n,X_n^{-1}].$ It is not always trivial to see what the relations amongst generators will be!)
Once you are comfortable with this isomorphism (which interestingly describes one chart of the blowup of $\mathbb A^2$ at the origin), the equality $\mathbb A^2 = \operatorname{Spec}(\mathbb C[X,X^{-1}Y])$ is trivial.
Comment: Thanks for your answer and spotting my mistake, but I'm still confused. I haven't learned about monoid algebras yet (I'm still near the start of Fulton's Toric varieties). As an example of what I've seen, if some cone has a dual cone with 3 generators that satisfy the $\mathbb{N}$-linear relation $x_1+x_3=2x_2$ then I would write it multiplicatively as $x_1x_3=x_2^2$ and then say the variety associated to the cone is $\operatorname{Spec} (\mathbb{C}[X,Y,Z]/(XZ-Y^2))$. Would that be correct? There still doesn't seem to be such a relation here.
Comment: That's correct, generators of the monoid determine generators of the monoid algebra $X,XY,XY^2$, and the relations carry through, in this case $X(XY^2)=(XY)^2$. Since you know the monoid algebra is generated by $3$ elements, it is some quotient of $\mathbb C[U,V,W],$ in this case by the aforementioned relation. It's really rather simple. (Though, in Fulton's book the monoids are as nice as possible -- finitely generated and saturated.)
Comment: (BTW, I'm assuming the generators here are $(1,0),(1,1),(1,2)$.)

Finding a toric variety of a cone


Sorteio de posiçoes de uma matriz

Question: Preciso criar uma funçao para sortear dentro de uma matriz cheia de 0 com tamanho n x n, quatro posições para modificar o valor somente dessas posições sorteadas.
Comment: O que já tem desta função pronta? Podemos ajudar a montar sua função com base no que já fez
Answer: Usa a class java.util.Random e depois algo deste género:
<code>void fillRandomPositions(int[][] arr, int n, int positions) {
    Random rnd = new Random();
    for(int i=0; i<positions; i++)
        arr[rnd.nextInt(n)][rnd.nextInt(n)] = 1; // Inserir os valores aqui
}
</code>

Sorteio de posiçoes de uma matriz


Why some browser can not display ★ star sign?

Question: Why some browser can not display ★ star sign ?
I test my code on chrome, ie8 but this browser cannot dispaly ★ star sign.
And on header i put this code
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
how can i do that ?
Comment: [Duplicate](http://stackoverflow.com/questions/9353043/is-there-a-way-to-get-ie-to-display-the-black-star-character-html-entity-starf) try this albert
Comment: user3801433 , but in firefox it's display ok
Answer: specifying the charset doesn't always it is always set. Use your developer tool to ensure that the page is encoded using utf-8. Also, try to use the ascii code for the star to see if it would work ★
Comment: The browser knows how to handle it. Just replace the star with the code. You can put it within any tag or in the middle of a paragraph. It doesn't matter really.
Comment: Aman could you polease give me some demo about how to place `★`
Comment: Sure, feel free to experiment in this page:
http://jsfiddle.net/#&togetherjs=VTl31tAhDA
Comment: OK, i try, but in chrome not display too
Comment: @albertnertuwe It looks like a font issue


How can I distribute end users certificates in an Enterprise

Question: We us our own mechanism to create a signed certificate for each and every end user of an Enterprise. However, we'd like to use the Enterprise mechanisms (like AD) to distribute each user its designated certificate.
How can we do it ?
(AD answer would be great :-))
Answer: Providing you use a the MSWindows CA, you can use the certificates autoenrollment feature to deploy User and Computer certificates through GPO.
Edit: Here's a link to one relevent Technet article.
Hope this helps.
Comment: My certificates are not created by the AD CA.
Can it still be done ?
Comment: Maybe... You would need to issue with your existing CA the certificate for the Root AD CA (or subordonate/issuing CA), then the already issued certificates will continue to work as the cert chain include your existing ca. Maybe others have come across this.
Comment: Let me make it clear: My certificates CA and the AD CA are not related. Can the AD auto-enrollment feature, or GPO still do the trick.


Mock objects being created inside a method while Unit Testing

Question: I have a following scenario:
public void DoSomething(...)
{
   ...
   ClassA obj1 = new ClassA();
   ClassB obj2 = new ClassB();
   ClassC obj3 = new ClassC();
   ...
}

I understand that if I was using Dependency Inversion Principle, I could Mock the interface and it will work. The issue is that these instances are needed Only in this method, so it doesn't make sense to create them at class level. On top of that, some methods have 5-6 object declarations, so passing these as parameters will bloat up the parameter list.
Is there anyway I can use Moq, NMock etc to Mock these classes (which are based off of a common interface)?
Answer: If you only need to instantiate those types in that method, you're right in that they shouldn't be injected into the class.
Instead, the typical solution is to inject a factory that will allow your method to resolve an interface.
Here's the usual approach:
interface IMessageFactory
{
    IMessage CreateMessage(string text);
}

class ConcreteMessageFactory : IMessageFactory
{
    IMessage CreateMessage(string text) { return new Message(text); }
}

class MockMessageFactory : IMessageFactory
{
    public IMessage CreateMessage(string text) { return new MockMessage(text); }
}

class MyClient
{
    private readonly IMessageFactory _msgFactory;

    public MyClient(IMessageFactory msgFactory)
    {
        _msgFactory = msgFactory;
    }

    public void SendMessage(string text)
    {
        IMessage msg = _msgFactory.CreateMessage(text);
        msg.Send();
    }
}

//Usage:
new MyClient(new ConcreteMessageFactory());
//Mocking
new MyClient(new MockMessageFactory());

Depending on which DI framework you're using, the framework can make this way easier for you. Castle Windsor, for example, lets you inject a delegate-based factory, as opposed to the interface-based factory above:
class MyClient
{
    private readonly Func<string, IMessage> _msgFactory;

    public MyClient(Func<string, IMessage> msgFactory)
    {
        _msgFactory = msgFactory;
    }

    public void SendMessage(string text)
    {
        IMessage msg = _msgFactory(text);
        msg.Send();
    }
}

//Usage:
new MyClient(() => new Message());
//Mocking
new MyClient(() => new MockMessage());

Answer: You can use something like StructureMap to do the work for you, your method would become something like.
public void DoSomething(...)
{
   ...
   IClassA obj1 = ObjectFactory.GetInstance<IClassA>();
   IClassB obj2 = ObjectFactory.GetInstance<IClassB>();
   IClassC obj3 = ObjectFactory.GetInstance<IClassC>();
   ...
}

Then normally you'd map them like this in global.asax or similar
        ObjectFactory.Initialize(x =>
        {
            x.ForRequestedType<IClassA>().TheDefaultIsConcreteType<ClassA>();
            ...etc
        });

But for your unit tests
        ObjectFactory.Initialize(x =>
        {
            x.ForRequestedType<IClassA>().TheDefaultIsConcreteType<UnitTestClassA>();
            ...etc
        });