On the proof of limsup is the largest cluster point

Question: I'm studing the following proof:

the proof for the case $x^* \in \mathbb{R}$ is as follows. Define $y_n = \sup_{n \geq k} x_n$ so $x^* = \inf_{n} y_n$:

My problem is at the last paragraph: "the interval $(x^* - \epsilon, x^* + \epsilon)$ must contain infinitely many terms of the sequence $(x_n)$". I know that for each $n$ we can find $x_k$ such that $x_k > x^* - \epsilon$, but why is it true that $x_k < x^* + \epsilon$ ?
Comment: Because $x^{*}$ is the infimum $\inf_{n} y_n$, so for each $\varepsilon > 0$ there exists an $n$ such that $y_n < x^{*} + \varepsilon$, as $y_n$ is itself the supremum of $x_k$ we have that for any $k \geq n$; $x_k \leq y_n < x^{*} + \varepsilon$.
Comment: That is perfect :)
Comment: I'll post it as an answer if you don't mind.
Answer: As pointed out in my previous comment, you can justify $x_k < x^{*} + \varepsilon$ by noting that $x^{*}$ is by definition the infimum $\inf_n y_n$, so for each $\varepsilon > 0$ there exists an $n$, such that $y_n < x^{*} + \varepsilon$. $y_n$ is itself a supremum over $x_k$, so we have for any $k \geq n$ the desired inequality: $x_k \leq y_n < x^{*} + \varepsilon$.
Comment: The trick is to turn the statements around: first pick $\varepsilon > 0$ then we have (some) $n'$ such that $y_{n'} x^* - \varepsilon$, as $k \geq n'$ and we kept the value of $\varepsilon$, we can safely say  $x_{k} < x^{*}+\epsilon$, therefore $x_{k} \in (x^{*} - \varepsilon, x^{*} + \varepsilon)$
Comment: sorry for my stupidity but one little question: I can understand "for each $\epsilon>0$ there exists an $n$, such that $y_n 0$, for all $n$ there exists $k \geq n$ such that $x_k > x^* - \epsilon$; what we have here is that for *some* $n'$ such that $y_{n'}<x^∗+\epsilon$, and it is not shown that $n = n'$.
Comment: That solves it, thanks!


Un-readable core dump after segmentation fault

Question: I have the following problem on my LAMP(hp) stack, from time to time I get Segmentation fault. So I made core dump in my Debian Squeeze and I hoped that it will tell me something, but it tells me nothing:
Reading symbols from /usr/sbin/apache2...Reading symbols from /usr/lib/debug/usr/sbin/apache2-mpm-prefork...done.
(no debugging symbols found)...done.
Core was generated by `/usr/sbin/apache2 -k start'.
Program terminated with signal 11, Segmentation fault.
#0  0x00007f479782ca9d in ?? ()
(gdb) bt full
#0  0x00007f479782ca9d in ?? ()
No symbol table info available.
#1  0x00007f4700000002 in ?? ()
No symbol table info available.
#2  0x00007f479d2df648 in ?? ()
No symbol table info available.
#3  0x0000000000000001 in ?? ()
No symbol table info available.
#4  0x00007f479788d11c in ?? ()
No symbol table info available.
#5  0x00007f478aebbcf8 in ?? ()
No symbol table info available.
#6  0x00007f479b593488 in ?? ()
No symbol table info available.
#7  0x00007f479b593488 in ?? ()
No symbol table info available.
#8  0x00007f4797f450c0 in ?? ()
No symbol table info available.
#9  0x00007f479d2df648 in ?? ()
No symbol table info available.
#10 x00007f479786f81c in ?? ()
No symbol table info available.
#11 0x00007f479b593488 in ?? ()
No symbol table info available.
#12 0x00007f479786f5b0 in ?? ()
No symbol table info available.
#13 0xfffffffffffffff9 in ?? ()
No symbol table info available.
#14 0x7400737574617473 in ?? ()
No symbol table info available.
#15 0x0000000000007375 in ?? ()
No symbol table info available.
#16 0x0000000000000009 in ?? ()
No symbol table info available.
#17 0x00007f479cfedd10 in ?? ()
No symbol table info available.
#18 0x00007f478c6ee020 in ?? ()
No symbol table info available.
#19 0x00007f479d2df648 in ?? ()
No symbol table info available.
#20 0x0000000000000000 in ?? ()
No symbol table info available.

What approach should I try to find the problem?
Answer: You should compile apache yourself with the -g option in CFLAGS set. If you use any third-party apache modules then you should also compile them with -g option. Check this link for more info


Programa que abre Bloco de Notas em segundo plano

Question: Preciso fazer um programa que, ao usuário apertar um botão, o programa abra o bloco de notas e insira uma mensagem previamente programada por mim no código. Como eu poderia fazer a parte do programa inserir o texto da mensagem no Bloco de Notas?
Comment: Então coloque o que você já fez e qual problema está enfrentando.
Answer: O seguinte código abre o Bloco de Notas e insere um texto dentro:
<code>[DllImport("user32.dll")]
public static extern IntPtr FindWindowEx(IntPtr hwndParent, IntPtr hwndChildAfter, string lpszClass, string lpszWindow);

[DllImport("User32.dll")]
public static extern int SendMessage(IntPtr hWnd, int uMsg, int wParam, string lParam);

static void AbrirBlocoDeNotasComTexto(string texto)
{
    ProcessStartInfo startInfo = new ProcessStartInfo("notepad");
    startInfo.UseShellExecute = false;

    Process notepad = Process.Start(startInfo);
    notepad.WaitForInputIdle();

    IntPtr child = FindWindowEx(notepad.MainWindowHandle, new IntPtr(0), null, null);
    SendMessage(child, 0x000c, 0, texto);
}
</code>
Tirei daqui.


How can one analyze the chord progression from "Your Affection (from Persona 4 soundtrack)" by Shoji Meguro?

Question: I've been listening to Persona 4 soundtrack by Shoji Meguro recently, and soon got hooked on a song called "Your Affection". It's a J-pop song whose catchy chorus intrigued me with a seemingly uncommon chord progression. (But given that I'm pretty much an amateur music lover who mostly listens to pop songs with a single I-IV-vi-V progression throughout, this might be biased haha).
According to this website (https://www.hooktheory.com/theorytab/view/shoji-meguro/persona-4---your-affection), the song is in B major, and the chord progression is:
iim7 - I6 - vim7 - V43/IV
iim7 - viim7b5-V7/vi - vim7 - V43/IV
iim7 - I6 - IVmaj7 - iii
iim7 - V7 - I - I
I googled the progression in each phrase without much finding. In general, I'm interested in if this is some variation of a popular progression (it gives me a lot of VI-I and II-V-I cadence vibe though), how the chords work together, and how they fit into the melodies.
In my limited understanding, The only thing obvious are the II-V-I cadences (viim7b5 - V7/vi - vim7 and iim7 - V7 - I) that make perfect sense, especially in the closing phrase. I also find it interesting that progressions like vim7 - V43/IV - iim7, with the G# - A (off the scale) - G# note playing, create nice tension/dissonance (and given the similarity between iim7 and IV, the resolution feels nice too), and that the comparison of the endings of each phrase, from V43/IV to iii to I, with the  A - A# - B note chromatically ascending, gives a smooth resolution when we look at the bigger picture. Howver, I don't study music professionally, so I wonder if there are any underlying theories (that I miss) that summarize the techniques used here and explain why the progression sounds so amazing.
Thanks! ^_^
Comment: You should consider that most pop music doesn't have an "actual" key (at least, considering the aspects regarding the major/minor modes and their tonal center). They often "circle around" a tonal mode, and sometimes they don't even use its fundamental, if not for a very small amount of time. We are also often bound to the concepts of "chorus", which has a *major* (pun intended) role in the overall harmony, and from what I can hear this is clearly an example: in the "chorus" we're clearly in B+, but if there were no bass there (or no chorus), we could even consider being in Eb-.
Comment: «They often "circle around" a tonal mode [...] if not for a very small amount of time» -> this is actually true for most of tonal music: the tonic harmony is actually used much less than others. The point is that a lot of pop music focuses on few harmonic functions (usually alternating between the same chords that are part of subdominant and dominant harmonic roles), which makes "statistically" different the actual role of the fundamental scale in the overall music piece. In the given example, we assume that it's in B+ because: 1. it's in the chorus; 2. the bass potentially changes the harmony
Answer: Listening to the recording, I think the analysis on the hook theory site is automated, which means it is good as a guide but it's not the only way to view this progression.
What you're hearing is probably the strong ascending bass movement against the static melody note. The melody sits on the root note (B, in B major here) and the bass moves scalewise from C# to D# to E. This is a cool sound and is widely used. Not quite the same, but the best example I can think of at the moment is "Here There and Everywhere" - anyway it's a strong bass movement.
The underlying theory for this specific part - a strong, moving bass against a relatively static melody is a good effect. The ii moving to I6 also creates a nice counterpoint as the melody stays the same, the bass rises and the middle voices drop. This is called voice leading and is something you can study in texts on counterpoint.
The other interesting progression is bars 5 and 6. IIm, IIm with the seventh in the bass, then a minor ii-V-I into chord VI. This is common in many jazz progressions too (e.g. The Days of Wine and Roses).
To me it seems to be all functional harmony in terms of chords - my advice would be to treat automated analysis tools like hook theory as a good starting point, but then try to perform your own analysis too to see what makes the most logical sense. The chords progressions used here are common in jazz standards, so learning a few of those would also be a good idea. I recommend John Elliot's "Insights in Jazz" for this.


Error: Cannot find module 'ejs' even though it's listed in package.json

Question: My application is not loading the 'EJS' module when I try and invoke routing in my app.js file and I'd like to know why.
My question is very similar in scope to this one, but it has some additional wrinkles to it that were not addressed in the answers there so I thought I'd turn this into a new question entirely.
If I start a very basic app.js file like this that calls ejs it works as expected and raises no errors.
APP.JS:
var express = require('express');
var app = express();

app.set('view engine', 'ejs');

app.get('/', function(req, res){
    res.send("Hello World");
    }).listen(3000, function(){
    console.log("The port is now listening at 3000");
  });

However, once I modify app.js to use routes to render a view I get the error message in the title.
The following script provides the error:
APP.JS:
var express = require('express');
var app = express();
var root = require('./routes/index');

app.set('view engine', 'ejs');
app.set('views', __dirname + '/views');
app.use(express.static(__dirname + '/public'));

app.use(root);

app.listen(3000, function(){
console.log("The port is now listening at 3000");
});

module.exports = app;

My index.js file that I use to establish the route looks like this:
INDEX.JS:
var express = require('express');
var router = express.Router();

/* GET home page. */
router.get('/', function(req, res) {
res.render('index', {
  pageTitle: 'The Formula Generator',
  pageDescription: 'Easily manage and store your supplement formulas',
  pageID: 'home' });
});

module.exports = router;

EJS is correctly loaded in my package.json like so:
PACKAGE.JSON:
"dependencies": {
"body-parser": "~1.15.2",
"cookie-parser": "~1.4.3",
"debug": "~2.2.0",
"ejs": "^2.5.5",
"express": "~4.14.0",
"mongodb": "^2.2.16",
"monk": "^3.1.3",
"morgan": "~1.7.0",
"serve-favicon": "~2.3.0"
 },

It's also installed in my node_modules folder as well.
My file structure currently looks like this:
Answer: app.js
var express = require('express');
var app = express();
var root = require('./routes/index');

app.set('view engine', 'ejs');
app.set('views', __dirname + '/views');
app.use(express.static(__dirname + '/public'));

root(app); // pass app to index

app.listen(3000, function(){
console.log("The port is now listening at 3000");
});

module.exports = app;

index.js
var controller = function(app){
    app.get('/', function(req, res) {
    res.render('index', {
      pageTitle: 'The Formula Generator',
      pageDescription: 'Easily manage and store your supplement formulas',
      pageID: 'home' });
    });
};
module.exports = controller;

package.json
{
  "name": "test",
  "version": "0.0.1",
  "private": true,
  "scripts": {
    "start": "node app.js"
  },
  "dependencies": {
    "express": "3.2.6",
    "ejs": "*"
  }
}

Comment: Hi Sumeet, thank you for the answer.  However, I'm still getting the same error message.  I'm beginning to think the issue is with a system variable on my computer that isn't set correctly, since this really seems to be a simple program that ought to work.  Any ideas what it might be?
Comment: npm install ejs  did it install ejs for you?@JonathanBechtel
Comment: can you show us error stack trace what you are getting @JonathanBechtel
Comment: I just did an npm install express in my root directory and that did the trick for me.  I'm not sure why this was the cause of the issue, since I ran express with "Hello World" and that did the trick, but that solved the problem.
Comment: Great @JonathanBechtel
Answer: Install express on root of the project .
npm install express --save


SEM and latent variables

Question: I have been reading about SEM and latent variables. Now it seems usually that a latent variable is a function of observed manifest variables. But is there a SEM where a latent variable is a predctor of an outcome? So in my example, we have outcomes (y1, y2), observed independent variables (x1, x2), one latent l1, and two errors (e1, e2), over the same indviduals.
y1 = x1 + l1 + e1
y2 = x2 + l1 + e2
Would that work in lavaan?
Comment: Indicators of a latent variable *are* the outcomes.  The causal theory behind a common-factor model is that there is a common (set of) cause(s) of the "manifest" indicators.  So your 2-equation system is in fact a 2-indicator factor model.
Answer: The outcome variable in SEM most definitely can be a latent variable. A latent variable is just a bunch of observed variables together to represent a construct (usually a theory). I would familiarize with factor analysis first, before you dive into SEM. SEM is used when you want to use a latent variable (a factor) in a path analysis, usually (said with caution here) to attempt to show causality.
Yes, it can be a predictor. A latent variable can used anywhere in a SEM model.
Comment: The post asked whether the latent variable can be a predictor, so this response doesn't really answer the question.
Comment: Thanks for clarifying. Added answer to response.

SEM and latent variables


Non parametric Wilcoxon Signed Rank test

Question: I have the following data vector(in fact its 2392 data points long):
> (dput(head(data, 35)))
c(0.009917216, 0.158975732, -0.008065753, -0.018648987, 0, 0.283519647,
-0.108234184, 0, -0.151124958, -0.049062385, -0.12970766, 0,
-0.281741056, -0.04834985, -0.025923954, 0.167527783, 0.080834965,
0.457401398, -0.007328027, -0.026647639, 0, 0.146048389, 0.059651004,
-0.115781325, -0.022670935, -0.025330951, -0.011990763, 0, -0.051658383,
-0.054335988, -0.190313988, -0.031937749, -0.000498226, -0.064351546,
0.108053675)

Now I want to do a non parametric wilcoxon signed rank test for this data frame:
> (wilcox.test(data))

    Wilcoxon signed rank test with continuity correction

data:  data
V = 1100747, p-value = 8.992e-12
alternative hypothesis: true location is not equal to 0

As you can see V is extremely high and I think its therefore probably wrong. Any recommendations what I am doing wrong? What I personally think is, that my R input could be wrong. Any recommendations how to specify it "much more" for a Non parametric Wilcoxon Signed Rank test. I really appreciate your answer!
Answer: I see no reason whatever to suspect it's wrong.
You have a huge sample. Why couldn't the statistic be large?
In fact, your statistic is actually on the low side ...
It looks like it's using the "sum of the positive ranks" for the test statistic. It's possible to work out the expected value for n=2392 (assuming no ties/zeroes) -- it's  2392*2393/4 = 1431748
[edit: Under the null hypothesis each rank has a 50-50 chance of getting a + or - sign. The sum of $n$ ranks, $1+2+...+n$ is $n(n+1)/2$.  The expected sum of the positive ranks is therefore half that, or $n(n+1)/4$.]
Let's generate some samples to check:
a <- replicate(1000,wilcox.test(rnorm(2392))$statistic)
hist(a,n=50)

Which is consistent with my calculation. Testing with small samples confirms that the statistic being used is the sum of the positive ranks (one of two common forms of the statistic).
Your statistic is quite some way down the low end. If I generate a normal sample with mean -0.2 and standard deviation 1, I get a test statistic roughly the size of yours.
It may be that you're expecting it to be using a different form of the statistic from the one it's actually using.
Comment: Included in an edit to the answer just after the place where I said that.
Comment: Thx a lot for your answer! However, I do not understand: How do you come up with this `2392*2393/4` equation?


Gerar um número inteiro a partir da sequencia existente em outro numero inteiro, com Python

Question: Para chegar nesse resultado, eu pensei em começar transformando a str em int, criando uma lista com os elementos sequenciais. No entanto, não sei como fazer nos casos em que o número de entrada possua mais de uma sequência.
Por exemplo, uma entrada 123687 irá retornar (1, 2, 3), ok.
Mas, no caso de uma entrada 123965678, ele irá retornar (1, 2, 3, 5, 6, 7,8), sendo que eu gostaria de gerar listas separadas para cada sequência.
Logo, uma lista (1, 2, 3) e outra (5, 6, 7, 8).
Por fim, irei transformar isso numa função que retorne apenas o inteiro com a maior sequência.
numero = input('Digite um número inteiro: ')
lista = [int(i) for i in numero]
for i in range(len(lista) - 1):
    if lista[i] == lista[i + 1] - 1:

        sequencia.append(lista[i])
        sequencia.append(lista[i + 1])

print(list(set(sequencia)))

Comment: 1. Porque ```set``` no print() final?
2. Qual deve ser o resultado de ```2567```?
Comment: O set é para excluir os repetidos. O resultado de 2567 seria `[5, 6, 7]`
Answer: Uma solução é iterar pelos dígitos do número inserido pelo usuário e utilizar uma lista auxiliar para fazer a análise da entrada e assim identificar sequencias de números naturais consecutivos menores que dez segundo o seguinte algoritmo:
Dada uma string como entrada cujo os caracteres sejam dígitos decimais

Armazene a entrada do usuário como uma string na variável numero.
Defina uma lista auxiliar chamada lista.
Defina uma lista chamada sequencias contendo os resultados a serem retornados ao fim do processo iterativo.
Do primeiro digito a esquerda da entrada até o último digito a direita faça:

Verifique se a entrada foi esgotada:

Se sim verifique se há mais de um elemento na lista auxiliar lista:

Se sim adicione uma cópia da lista auxiliar a lista sequencias contendo os resultados.

Retorne o lista sequencias como resultado.

Retire um dígito a esquerda da entrada.
Verifique se a lista auxiliar não está vazia e verifique se o dígito extraído não seja o digito consecutivo ao último digito da lista auxiliar.

Caso as duas afirmações anteriores sejam verdadeiras

Verifique se há mais de um elemento na lista auxiliar.

Se sim adicione uma cópia da lista auxiliar a lista sequencias contendo os resultados.

Esvazie a lista auxiliar.

Adicione o dígito extraído a lista auxiliar.
Reitere o processo.

O algoritmo pode ser implementado usando um laço de iteração ou função recursiva, no caso preferi o implementar por meio de uma função recursiva e a implementação não faz nenhuma validação da entrada do usuário:
numero = "12396567899456789345"#input('Digite um número inteiro: ')

def verificador(numero, lista=[], sequencias=[]):
    if len(numero) == 0:
        if len(lista) > 1:
            sequencias.append(lista.copy())
        return(sequencias)
    digito = int(numero[0])
    numero = numero[1:]
    lista = lista
    if len(lista) != 0 and lista[-1] != digito - 1:
        if len(lista) > 1:
            sequencias.append(lista.copy())
        lista.clear()
    lista.append(digito)
    return verificador(numero, lista, sequencias)

print(verificador(numero))
#[[1, 2, 3], [5, 6, 7, 8, 9], [4, 5, 6, 7, 8, 9], [3, 4, 5]]

Teste o exemplo no Repl.it
Comment: Obrigado pelo ensinamento, Augusto. Funciona perfeitamente!


Single header for multiple web pages

Question: I want to use one header for all pages in my project directory for website. But I am little bit confused. If I kept single header and import it in all web pages then will it affect SEO? can crawler crawl those header for each page? I want the way which does not affect SEO of my website.
Comment: if you're dynamically replacing the content of the description and title per page you should be good to go
Comment: Please share the code what you tried.
Answer: Using a single header for your entire website will not hurt the SEO of your website - upwards of 90% of websites do it.
Comment: Yes its right as mentioned by @Brendan. It will not affect SEO at all. I myself have used it in almost every site I have developed so far.
Comment: but how to do that? I mean using single header for all pages. I need a proper way
Comment: Make a template file and use it by including it every were.
Comment: Please share your code what you have done so far. So that suggestion can be made in right direction.
Comment: @Vickrant How to include?
Comment: @GauravDeshpande a fundamental element of PHP development: [include](http://php.net/manual/en/function.include.php)
Answer: Try like this :

<title></title>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />
<meta name="description" content="">
<?php include 'header.php'; ?>

in header.php use static content such as css,javascript etc.
header.php
<link rel="icon" href="../../favicon.ico">
<link href="css/bootstrap.min.css" rel="stylesheet">
<link rel="stylesheet" type="text/css" href="css/style.css">
<link rel="stylesheet" type="text/css" href="css/responsive.css">
<link href='http://fonts.googleapis.com/css?family=Open+Sans:400,300,300italic,400italic,600,600italic,700,800,800italic,700italic' rel='stylesheet' type='text/css'>

I think, your problem is solved by doing this

Single header for multiple web pages


Event study / DiD with panel data and repeated treatment in different years for each country

Question: I have an unbalanced panel dataset with approximately 30 countries from 1980-2000. I would like to study how political uncertainty measured by close elections affects a certain continuous variable $Y$, say countries' investments. The independent variable is thus close elections where 1 indicates a very even election outcome and 0 indicates either a non-close election year or a non-election year. So, the treatment variable is a close election which may have occurred several times within a country during the period 1980-2000. Now I want to do an event study with two-way fixed effects including one lag and one lead variable to study the effect before and after the treatment. The specification I have in my mind would then look like the following:
$$
Y_{ct} = beta_0 + \beta_1 \times Treat_{ct} + \beta_2 \times Lag1_{ct} + \beta_3 \times Lead1_{ct} + \beta_4 \times Treat_{ct} \times Lag1_{ct} + \beta_5 \times Treat_{ct} \times Lead1_{ct} + Country_{FE} + Year_{FE} + u_{ct}
$$
where $Treat$ is close election.
My questions are:
(1) Whether this counts as a diff-in-diff or event study if the treatment occurs repeatedly and in different periods for each country?
(2) If this is a form of diff-in-diff, can one argue that the parallel assumption is valid by stating that the countries that are not treated at same time serve as the control group and that the fixed effects ensure that the groups aren't behaving differently?
(3) If not, what would be the right model to use in order to estimate this effect?
Thanks in advance!

Country
Year
TREAT
Lag 1
Lead 1

1
1980
0
1
0

1
1981
1
0
0

1
1982
0
0
1

1
1983
0
0
0

1
1984
0
0
0

1
1985
0
0
0

1
1986
0
0
0

1
1987
0
1
0

1
1989
1
0
0

1
1990
0
0
1

1
...
...
...
...

30
1980
0
0
0

30
1981
0
0
0

30
1982
0
1
0

30
1983
1
0
0

30
1984
0
0
1

30
1985
0
1
0

30
1986
1
0
0

30
1987
0
0
1

30
1989
0
1
0

30
1990
1
0
0

30
...
...
...
...
Comment: So a close (even) election is the "treatment" in your setting. By design, the treatment is only in effect for one period at a time, correct?
Comment: @ThomasBilach Yes, exactly.
Answer:
Whether this counts as a diff-in-diff or event study if the treatment occurs repeatedly and in different periods for each country?

The difference-in-differences (DiD) equation you're considering has been adapted to assess how investments vary with time since exposure to treatment. In most DiD applications, the equation is modified to satisfy the conditions of a typical "event study" framework, though I'm not so comfortable arguing that all "event study" applications qualify as DiD methodologies. In my opinion, the term "event study" is a rather broad methodological framework for the study of "events" in general, and it has traditionally been used to study a market's reaction to financial events/shocks. Peruse the accepted answer here for more detail.
As for your other concern, the treatment variable in this more general setting can take on almost any pattern, including one where the event starts at different times in different countries, and/or where countries experience multiple events over time. In fact, the generalized DiD equation is commonly used in settings with nonuniform exposure patterns. Upon review of the abridged data frame included in your post, it appears you've coded the relevant period indicators appropriately. Even though the treatment 'turns on' and 'turns off' multiple times over time, it still retains the basic structure of a DiD equation. The leads and lags of treatment assess the evolution of investments around close election years.

If this is a form of diff-in-diff, can one argue that the parallel assumption is valid by stating that the countries that are not treated the same time serve as the control group and that the fixed effects ensure that the groups aren't behaving differently?

The "fixed effects" do not ensure a parallel trajectory of the trends over time. That is for you to demonstrate to your audience. By including the lag in your specification, you've already given this some thought. The "effect" of a close election on say, direct investments, shouldn't emerge before the actual referendum. But is one lag enough? Perhaps not, especially if you suspect investments vary in anticipation of the actual election.
Investigating more than one lead and/or lag is also complicated by the fact that political uncertainty sunrises and sunsets with a more or less predictable cadence every few years. Do you suspect political uncertainty will 'carry over' into the next election cycle? Because it appears a subset of countries have many sequential treatments in close temporal sequence, I would only include a finite number of leads and/or lags. Note how "event time" doesn't always correspond with actual calendar time. Estimating a long-run effect by including a second and third lead may seem appropriate, but by the third lead a country may already be moving into a second wave of treatment, as is the case with 'Country 30' in your data frame.
On a tangential note, 'Country 30' is a unique case. The events suggest triennial election cycles, but the third election in 1990 suggests otherwise. If you're considering a mixture of local and regional elections, then it's prudent to match treated countries with counterfactuals that have a similar treatment history up until the next election. There are computationally efficient ways of doing this, and I believe my answer here should help. That answer also recommends a couple of useful R packages.

Lastly, I want to address some concerns with respect to notation.
Note, the interactions between $Treat_{ct}$ and the lead/lag variables are redundant. The interaction term is implicit in the coding of the treatment variable. To be specific, $Treat_{ct}$ equals 1 if country $c$ is treated in year $t$, 0 otherwise. Simply include the relevant periods indicators as is. I reproduced your model below:
$$
Y_{ct} = \beta_0 + \beta_1Lag^{1}_{ct} + \beta_2Treat_{ct} + \beta_3Lead^{1}_{ct} + Country_{FE} + Year_{FE} + u_{ct}
$$
where $Lag^{1}_{ct}$ and $Lead^{1}_{ct}$ assess effects in the periods before and after a close election year, respectively. I often see the terms reversed, where the lag denotes the delayed onset of treatment. As long as you keep the notation consistent and explain what the relevant variables mean, it shouldn't really matter.
Technically, the lead/lag variable is a clone of the treatment variable.  The only difference is they represent different time configurations of $Treat_{ct}$. To make the equation more compact, let's define $T_{ct}$ as the immediate effect of treatment. Political uncertainty is transient, by definition, so $T_{ct}$ is the same as the treatment variable from earlier. Here is a different way to specify your equation:
$$
Y_{ct} = \gamma_c + \lambda_t + \beta_{-1} T_{c,t-1} + \beta T_{ct} + \beta_{+1} T_{c,t+1} + u_{ct}
$$
where $\gamma_c$ and $\lambda_t$ represent fixed effects for countries and years, respectively. The variable $T_{c,t-1}$ is testing for a specific consequence of treatment in the period before the actual election year. Assuming consequences do not precede causes, you shouldn't be observing a strong non-zero effect pre-event. On the other hand, $T_{c,t+1}$ investigates whether the effect of a close election on investments lingers beyond that election year, or kicks in with some delay. Your post-treatment epoch is limited to one year, so you should expect countries' investments to mostly concentrate around a "close" election—not just any election. I recommend plotting the $\hat{\beta}$'s to get a sense of how investments evolve around uncertain elections.


Estou tentando resolver um exercíco com arrays em java minha dificuldade é imprimir a média de indice par e impar do array

Question:
Fazer um  programa java fazer o  seguinte:

a)  Preencher o  array  com as alturas de 30  individuos;
b)  Visualizar o array;
c)  Recorrendo  ao  array,  calcular  e imprimir a média de todas as alturas em  indeces pares do array;
d)  Recorrendo  ao  array,  calcular  e imprimir a média de todas as alturas em  indeces impares do array.
e) encontrar  e imprimir o individuo mais alto  e mais baixo.
Tentei fazer assim:
import java.util.Scanner;
public class Array02 {

    public static void main(String[] args) {
        Scanner s = new Scanner(System.in);
        int nrIndividuos = 6;

        int[] alturas = new int[nrIndividuos];

        for (int i = 0; i < nrIndividuos; i++) {
             System.out.println("Introduza a altura do " + (i + 1) + " individuo");
            alturas[i] = s.nextInt();
        }

        int soma = 0;
        double mediaPar = 0;
        for(int j = 0; j < nrIndividuos; j++){
            if(alturas[j]%2==0){

                soma = soma + alturas[j];

                mediaPar = soma/nrIndividuos;
            }
        }
        System.out.println(mediaPar);

    }

}

Comment: Qual é a sua dúvida?
Answer: Para a média dos indices par, é preferível fazeres um ciclo que comece em 0 e ande de 2 em 2. O mesmo é válido para os ímpares ( a começar em 1).
int cont = 0;
for(j=0; j < nrIndividuos; j=j+2){
    soma += alturas[j];
    cont++;
}
media = soma / cont

O que estás a fazer no teu programa é a média das alturas pares. Ou seja:
Num array [200,150,195], o teu programa soma 200 + 150 e divide por 3, uma vez que estás a avaliar a paridade de array[j] e não de j. No entanto, o objetivo é somar 200 + 195 e dividir por 2
Obs: é possível retirar a variável cont e utilizar divisões inteiras / restos de divisão por 2, mas para simplificar e ficar válido para par e ímpar, achei por bem utilizar.
Comment: Percebido muito obrigado!
Answer: Scanner s = new Scanner(System.in);
int nrIndividuos = 6;

ArrayList<Integer> alturas = new ArrayList<>();

while (nrIndividuos != alturas.size()) {
    System.out.printf("Introduza a altura do %d individuo: ", alturas.size() + 1);
    alturas.add(s.nextInt());
}
s.close();

List<Integer> pares = alturas.stream().filter(value -> value % 2 == 0).collect(Collectors.toList());
List<Integer> impares = alturas.stream().filter(value -> value % 2 == 1).collect(Collectors.toList());

System.out.printf("Pares: %s \n", Arrays.toString(pares.toArray()));
System.out.printf("Impares: %s \n", Arrays.toString(impares.toArray()));

Integer totalPares = pares.stream().reduce(0, Integer::sum);
Integer totalImpares = impares.stream().reduce(0, Integer::sum);

System.out.printf("Media Par: %f \n", (double) totalPares / nrIndividuos);
System.out.printf("Media Impar: %f \n", (double) totalImpares / nrIndividuos);

System.out.printf("Menor individuo: %s \n", alturas.stream().min(Comparator.naturalOrder()).get());
System.out.printf("Maior individuo: %s \n", alturas.stream().max(Comparator.naturalOrder()).get());

Um macete legal é usar Streams, elas reduzem o código bastante. Por exemplo criei uma lista dinâmica "ArrayList".
Também substitui o for por um while, ambos tem o mesmo efeito nesse caso, mas o while deixa o código mais agradável.
Agora vamos aos macetes, primeiro usando a lista que contem todas as alturas vamos aplicar uma stream de filter, separando todos os pares e impares criando uma lista nova para cada um deles.
Usando a lista de pares e impares vamos aplicar uma stream de reduce, o objetivo da reduce é reduzir a lista em apenas um valor, nesse caso vamos reduzir a lista somando todos os elementos, por isso o Integer::sum.
Sem muito segredo, o cálculo de média.
Agora vem um outro macete legal das stream, vamos pegar o maior e o menor indivíduo usando as funções min e max, essas funções elas precisam de um comparador nesse caso vamos usar a ordem crescente "ordem natural"
As Streams são funções que trabalham sobre as Arrays / Listas, elas podem ser usadas em cadeia, por exemplo vamos filtrar todos os pares e soma-los:
int totalPares = alturas.stream()
                        .filter(value -> value % 2 == 0)
                        .reduce(0, Integer::sum);

Espero ter ajudado :-)
Obs: Não esqueça de fechar o scanner quando não estiver mais usando :-)
Comment: Muito obrigado, me ajudou bastante


AVAssetExportSession exportAsynchronouslyWithCompletionHandle : export audio error

Question: I'm using AVAssetExportSession exportAsynchronouslyWithCompletionHandler to export an audio, but error.
(In many audios, just one audio will occur this problem.)
<code>+ (void)exportAudioWithAsset:(AVAsset *)asset exportPath:(nonnull NSString *)exportPath completion:(nonnull void (^)(BOOL, NSError * _Nullable, NSURL * _Nullable))completion {
    if (!asset || !exportPath) {
        if (completion) {
            completion(NO, nil, nil);
        }
        return;
    }
    AVAssetExportSession *session = [[AVAssetExportSession alloc] initWithAsset:asset presetName:AVAssetExportPresetAppleM4A];
    session.outputURL = [NSURL fileURLWithPath:exportPath];
    session.outputFileType = AVFileTypeAppleM4A;
    session.shouldOptimizeForNetworkUse = YES;
    [session exportAsynchronouslyWithCompletionHandler:^{
        if (session.status == AVAssetExportSessionStatusCompleted) {
            NSData *data = [NSData dataWithContentsOfFile:exportPath];
            if ([data length] > 0) {
                if (completion) {
                    completion(YES, nil, [NSURL fileURLWithPath:exportPath]);
                }
            } else {
                if ([[NSFileManager defaultManager] fileExistsAtPath:exportPath]) {
                    [[NSFileManager defaultManager] removeItemAtPath:exportPath error:nil];
                }
                if (completion) {
                    completion(NO, session.error, nil);
                }
            }
        } else {
            if ([[NSFileManager defaultManager] fileExistsAtPath:exportPath]) {
                [[NSFileManager defaultManager] removeItemAtPath:exportPath error:nil];
            }
            if (completion) {
                completion(NO, session.error, nil);
            }
        }
    }];
}
</code>
Session's error : Error Domain=AVFoundationErrorDomain Code=-11800 "这项操作无法完成" UserInfo={NSLocalizedFailureReason=发生未知错误(-12769), NSLocalizedDescription=这项操作无法完成, NSUnderlyingError=0x283a97630 {Error Domain=NSOSStatusErrorDomain Code=-12769 "(null)"}}
(这项操作无法完成 means couldn't complete)
Answer: To solve this problem, I replace AVAssetExportSession  with AVAssetReader And AVAssertWriter to export.


Probability of event occurring first given alternating group of people?

Question: I'm having a difficult time wrapping my head around this problem:
There are two groups A and B. There is a p0 chance that a person in group A will fail and a p1 chance that a person in group B will fail. People are assigned to the two groups alternating and outcomes are independent. What is the probability that the first failure happens in group A?
This is what I have: $p_0^np_1^{n-1}$. Where n is the number of rounds done of selection. I am unsure if I even need to use n or if this is correct.
Thank you
Comment: If the first failure happens in group A, either a person in group A fails, or a person in group A succeeds and a person in group B succeeds and a person in group A fails, or ...
Answer: Your description is a little unclear, so I will be making assumptions.  Assignment starts with group A.  Failure occurs at the time of assignment. There is no limit to the total of people assigned.  In that case if the first failure is in group A after 2k assignments, the probability is $(1-p_0)^k(1-p_1)^kp_0$.   The total probability is $p_0\sum_{k=0}^\infty ((1-p_0)(1-p_1))^k =\frac{p_0}{1-(1-p_0)(1-p_1)}=\frac{p_0}{p_0+p_1-p_0p_1}$.


How do repeated roots of the discriminant correspond to the order of repeated roots in the original polynomial?

Question: Background/context:
If $S \subset \mathbb{CP}^1 \times \mathbb{CP}^1$ is a smooth curve with bidegree $(d_1, d_2)$, we know that its genus is $(d_1 - 1)(d_2 - 1)$ for example by the adjunction formula.
Alternatively, we can attempt to compute the genus via the Riemann-Hurwitz formula as follows:

Write $S = \{P(z,w) = 0\}$ where $z, w$ are in $\mathbb{CP}^1$.

The projection map $p$ onto the first factor is a $d_2$-sheeted branched cover. The branch points $z_i$ occur exactly when the polynomial $P(z_i, w)$ has repeated roots (when considered as a polynomial in $w$, treating $z_i$ as coefficients).

These repeated roots are detected by the discriminant of $P(z_i, w)$, which has degree $2d_2 - 2$ in the "coefficients". But the coefficients are homogeneous of degree $d_1$ in $z$, so the discriminant is a degree $d_1(2d_2-2)$ polynomial in $z$.

Computing $\chi(S) = 2d_2 - d_1(2d_2 - 2)$, we actually get exactly the correct genus for $S$! This means $d_1(2d_2 - 2)$ precisely counts the ramification $\sum (e_p - 1)$ of the branched cover.

Question:
Given the above context, it must be the case that the degree of the discriminant counts exactly the number of roots of $P(z,w)$ which are lost due to branching of $(z,w) \mapsto z$. Why is this the case? There are basically two opposing forces which must somehow cancel out:

If the discriminant has a repeated root, then downstairs it corresponds to losing a branch point.
If a branch point has ramification index greater than two, then upstairs it corresponds to "the vanishing of the discriminant" not accounting for all of the repeated roots which are lost at this branch point.

I have no idea why these two phenomena should cancel out, and would love some insight. Thank you!
Answer: After getting no engagement here, I cross-posted the question to Math Overflow. I received some answers there, and will accordingly close this post.
See https://mathoverflow.net/questions/466758/what-relationship-is-there-between-repeated-roots-of-discriminants-and-orders-of


Home directories created with wrong Selinux context

Question: [root@tst-01 home]# ls -Z
drwxr-xr-x. ujjain   users          system_u:object_r:home_root_t:s0 ujjain
drwxr-xr-x. johndoe   users          system_u:object_r:home_root_t:s0 johndoe

The selinux context should be object_r:user_home_dir_t.
[root@tst-01 ~]# sesearch -T -t home_root_t
Found 10 semantic te rules:
   type_transition oddjob_mkhomedir_t home_root_t : dir user_home_dir_t;
   type_transition automount_t home_root_t : dir automount_tmp_t;
   type_transition lsassd_t home_root_t : dir user_home_dir_t;
   type_transition useradd_t home_root_t : dir user_home_dir_t;
   type_transition firstboot_t home_root_t : dir user_home_dir_t;
   type_transition smbd_t home_root_t : dir user_home_dir_t;
   type_transition quota_t home_root_t : file quota_db_t;
   type_transition sysadm_t home_root_t : dir user_home_dir_t;
   type_transition cups_pdf_t home_root_t : dir user_home_dir_t;
   type_transition postfix_virtual_t home_root_t : dir user_home_dir_t;

[root@tst-01 ~]#

New home-directories are created with the wrong Selinux context. I can fix the selinux context with chcon, but this creates problems on multiple servers.
What can be the reason the context was set wrong in the first place?
Comment: What does `sesearch -T -t home_root_t` say?
Comment: I added the output as a comment!
Answer: Adding to this question for future people who may come across it. If you are putting home directories on an NFS share, you will need to set the correct SELinux context. Assuming your nfs home directory is /nfshome, do the following:

[root@host /]# semanage fcontext -a -e /home /nfshome
[root@host /]# restorecon -vR /nfshome
Comment: Thank you, this is exactly what I needed. This should be a FAQ for *any* home directory not in /home/ (e.g. mine were in /data/).
Comment: This worked for me -- the first `semanage ...` line marks the /nfshome directory as having the same selinux context as the standard /home directory, and the second line verbosely and Recursively restores the security contexts of the /nfshome directory.   I used it on a non-nfs /local/home dir.  What I liked about it was not having to determine and explicitly set the contexts, but I just matched the contexts of a working, existing dir.
Answer: In the case of user's $HOME directories, usually in /home/$USER, you don't need to use chcon, which changes the security context of files and directories, in the sense of diverting them from the policy, and, for what is worth, won't survive a system relabel. Rather, you need to find out what is the expected security context of the directories:
# matchpathcon /home/ujjain
# matchpathcon /home/johndoe

And if the context doesn't match the output of ls -lrtZ, restore the context:
# restorecon -v /home/ujjain
# restorecon -v /home/johndoe

Note that restorecon can be used recursively -R.
Regarding your question, the reason why this directories have a wrong label depends on the procedure used to create them (which you didn't specify) and the location of the /home directory (local filesystem vs. NFS, for example)
Answer: The issue appears to be here:
[root@tst-01 ~]# grep homedir /etc/pam.d/system-auth
session     optional      pam_mkhomedir.so skel=/etc/skel

Since the pam stack should not be making homedirs, the odd job module should be used to do the heavy lifting instead with the pam_oddjob_mkhomedir module since it requires fewer permissions and works well with SELinux.
Comment: Looks like a bug. Be sure to report it in BZ.
Comment: Yes, pam_mkhomedir does not make home directories with the correct SELinux contexts. This is confirmed by Red Hat and their recommendation is using pam_oddjob_mkhomedir.


Comments filter by Last in Twig

Question: I try to render the last comment  from a list of comments.
I try {{ comments|last }} ---> no result.
Then {{ comments|reverse }} ---> this render them
Then {{ comments|reverse|first }} ---> no result
The above part is  solved.See anser 1. Pls if annyone have a solution for rendering the last comment in views.
I like to achieve the same in a view. There is a relation filter that output the last comment. But I think I do something wrong.
Comment: You don't provide details in which template you are exactly, but what you have here might be the product of viewMultiple(), where the childrens are not ready for rendering yet and you need to provide a prerender callback, see https://drupal.stackexchange.com/questions/263158/cycle-comments-on-field-comment-html-twig/263198#263198
Comment: I use the field--comment.html.twig file from Stable in core, if I debug, this template is resposable to render the commenst
Answer: The last item in comments is the pager, which you have to remove first to get to the last comment. Then you can build a new render array with the single comment and the pre-render callback:
{% set last_comment = comments|without('pager')|last %}
{% set pre_render = comments['#pre_render'] %}
{% set last_comment_build = { '#pre_render': pre_render, '0': last_comment } %}
{{ last_comment_build }}

Comment: This indeed works. However I dont understand the entire code. Wy the '0' . I also dont understand how you see that this last item is the pager. The view mode still render all the comments. Thanks.
Comment: The '0' is arbitrary, could be anything not starting with a `#`. You can look into `comments`, if there is no pager then you don't need `|without()`,but it doesn't harm either.

Comments filter by Last in Twig


"Escopo do programa não foi fechado corretamente." em pseudocódigo

Question: Escrevi o seguinte pseudocódigo só que estou recebendo o seguinte erro: O escopo do programa não foi fechado corretamente. insira o caracter '}' para corrigir o problema. Já tentei fechar com o '}' só que acaba gerando mais erros, alguém poderia me ajudar?
programa
{ Var cont, somatoria: inteiro
    funcao inicio()
    { cont ← 0
        para cont ← 1 Ate 100 Faca
            soma ← soma + cont
            cont ← cont + 1
        fim para
        escreva "A somatoria é: ", soma
    }
}

Comment: Em que ferramenta isto está sendo escrito?
Comment: estou usando o Portugol Studio.
Answer: Você tem um fim para sobrando, apague ele
programa
{
    Var cont, somatoria: inteiro
    funcao inicio()
    {
        cont ← 0
        para cont ← 1 Ate 100 Faca
           soma ← soma + cont
           cont ← cont + 1
        fim para
        escreva "A somatoria é: ", soma
    }
    fim para //apague essa linha
    escreva "A somatoria é: ", soma //essa linha está repetida, seria isso proposital?
}

É sempre importante identar corretamente seu código, assim você evita esse tipo de erro bobo. Perceba o espaço que eu pus antes de cada linha tornando o código muito mais legível.
EDIÇÃO
Você escreveu seu programa em pseudo-código, entretanto o Portugol possui uma sintaxe bem definida de programação, um exemplo correto de laço de repetição for seria:
para(inteiro i=0; i<qtd; i++) {
    escreva("i vale", i)
}

Dentre vários outros detalhes que você passou batido, como por exemplo a declaração de variáveis deveria ser:
inteiro cont, somatoria

Comment: @matheusferreira você tem certeza disso? se sim, poderia então atualizar seu código e seu erro?
Comment: @matheusferreira por favor, veja minha **EDIÇÃO**
Comment: eu tinha testado novamente e acabei esquecendo esta parte mais o erro não tem nada a ver com esta linha.
Comment: o erro esta na linha 2 . o mesmo erro que esta na edição.
Comment: não, eu já apaguei oque estava repetindo o erro esta em uma parte usando o { e esta falando que não esta fechando corretamente para fechar usar o } mais já tentei.
Comment: @matheusferreira estou baixando essa ferramenta
Comment: @matheusferreira a sitaxe dos comandos é completamente diferente do que você escreveu
Comment: poderia ser mais claro? meio que testei esse programa e estou pensando em testar em outro poderia me indicar um de confiança para escrever este código sem nem um tipo de erro?
Comment: @matheusferreira dá uma olhada nesse vídeo [aqui](https://www.youtube.com/watch?v=AKK8NPeeROM&index=7&list=PLb9yvNDCid3jQAEbNoPHtPR0SWwmRSM-t)
Answer: Existe um fim para antes do ultimo escreva
Answer: Acredito que a sintaxe não corresponde ao portugol tradicional
programa
{
    funcao inicio()
    {
        inteiro cont
        inteiro somatoria
        inteiro soma

        cont = 0
        somatoria = 0
        soma = 0

        para (cont = 1; cont < 10; cont++)
        {
               soma = soma + cont
               cont = cont + 1
        }
        escreva ("A somatoria é: ", soma)
    }
}

Site: PortugolStudio
Comment: ate o momento esta certo mais preciso fazer com que ele some no intervalo de 1 até 10 e tem que ser números inteiros.
Comment: Só lembrando que a soma já foi feita no exemplo!


Can you set css image-rendering on an image cursor?

Question: Heres an example: https://minecraft.fandom.com/wiki/Minecraft_Wiki
The cursor is blurry, it would be nicer to set image-rendering: pixelated, crisp etc on it.
Can you do it?
Here is a js fiddle
.test {
    background: gray;
    width: 200px;
    height: 200px;
    image-rendering: -moz-crisp-edges;
 cursor: url(https://vignette.wikia.nocookie.net/minecraft/images/e/e1/WikiSwordCursor.png), auto;
}

img {
image-rendering: -moz-crisp-edges;
}

Comment: first you can read the image in java script canvas. then after enhancing the image you can set it back to cursor.
Answer:

img {
  cursor: url('https://vignette.wikia.nocookie.net/minecraft/images/e/e1/WikiSwordCursor.png'),auto;
}

Comment: Are your two answers supposed to be parts of the same solution? If so, you should merge them into one by editing one and pasting the content of the other one into it.


Java, what to use instead of PrintStream to get exceptions?

Question: I am creating a file on a network drive and then adding data to it. Time to time writing to that file fails. Is there a good way of checking if the file is accessible before every time i save data to it or maybe is tehre a way checking afther to see if the data was saved?
EDIT:
Right now i am using try-catch block with PrintStream in my code:
<code>        try
        {
            logfile = new File(new File(isic_log), "log_" + production);
            //nasty workaround - we'll have a file the moment we assign an output stream to it
            if (!logfile.exists())
            {
                    prodrow = production;
            }

            out = new FileOutputStream(logfile.getPath(), logfile.exists());
            p = new PrintStream(out);
            if (prodrow != "")
            {
                p.println (prodrow);
            }
            p.println (chip_code + ":" + isic_number);
            p.close();
        }
        catch (Exception e)
        {
                logger.info("Got exception while writing to isic production log: " + e.getMessage());
        }
</code>
So might be the PrintStream the problem? (PrintWriter and PrintStream never throw IOExceptions)
Comment: doesn't it throw an exception when it fails? checking first wouldn't help all that much because it could become unavailable at any point during the write.
Comment: Checking whether a file is accessible before opening it leads to race conditions, esp. in the case of a networked filesystem.
Answer: I would use plain BufferedWriter and add the newlines myself as required.

Normal FileOutputStream operations should throw an IOException if there is an error.
AFAIK, The only exception is PrintWriter which does not throw an exception. Instead you need to call checkError() but it gives you no indication of what the error was or when it occurred.
I suggest you not use PrintWriter in this situation.
Comment: FYI: Im using PrintStream in there right now. Found this thread: http://stackoverflow.com/questions/297303/printwriter-and-printstream-never-throw-ioexceptions
Answer: The only reasonable way to address this is to try to write to the file, and handle any resulting exception in an appropriate manner. It's pretty much impossible to know beforehand whether an I/O operation is going to succeed, due to the unreliable nature of networks.


Cannot close socket pressing Ctrl+C

Question: I am trying to close a socket when the user presses ctrl-c. This works fine if the socket is still doing something. But when the socket is done with it's job and is doing nothing and I press ctrl-c nothing happens. By the way I am using windows 8.1.
Here is my code:
# close socket ctrl-c
from signal import signal, SIGINT
def sigint_received(signum, frame):
    s.close()
    exit(0)

# register SIGINT callback
signal(SIGINT, sigint_received)

When I try this code I have the same issue :
OriginalExceptHook = sys.excepthook
def NewExceptHook(type, value, traceback):
    if type == KeyboardInterrupt:
        exit("\nExiting.")
    else:
        OriginalExceptHook(type, value, traceback)
    sys.excepthook = NewExceptHook

Anyone knows what's wrong?
Comment: can you show the code where your socket is doing `something` or `nothing`? is that in a loop?
Comment: yes it's a while(1){waiting for data} loop.
Comment: have you tried `raise KeyboardInterrupt`?
Comment: What do you mean by that?
Comment: see
my answer for your info
Answer: Re the comment, to use except for any unexpected KeyboardInterrupt will catch the "Ctrl+C" alike, what I meant is like:
while 1:
    try:
        ... your stuff here ...
        ... you should also break the while loop if no data is received ...
    # and except it when Ctrl + C like happens
    except KeyboardInterrupt:
        print "Ctrl C or alike is pressed..."

Cannot close socket pressing Ctrl+C


Freshly installed redis not responding?

Question: I had to install a very old redis-server on a very old Ubuntu server and used the package manager for it. However, after installing and starting the server, I do not get any response but timeouts.
redis-cli ping: Timeout
The log only shows this:
[27714] 25 Jul 13:27:59 * Server started, Redis version 2.2.11
[27714] 25 Jul 13:27:59 # WARNING overcommit_memory is set to 0! Background save may fail under low memory condition. To fix this issue add 'vm.overcommit_memory = 1' to /etc/sysctl.conf and then reboot or run the command 'sysctl vm.overcommit_memory=1' for this to take effect.
[27714] 25 Jul 13:27:59 * The server is now ready to accept connections on port 6379

Does anyone know what could be wrong here?
Comment: Somebody forgot to upgrade the server from 12.04 to a newer version?
Comment: Almost :) See my answer.
Answer: It turned out to be lo not getting up after a dist-upgrade and restart. All I had to do is ifconfig lo up

Freshly installed redis not responding?


$\sum {a_n}$ be a convergent series of complex numbers but let $\sum |{a_n}|$ be divergent..

Question: I am stuck on the following problem that says:

Let $\sum {a_n}$  be a convergent series of complex numbers but let $\sum |{a_n}|$
be divergent.
Then it follows that
a. $a_n \to 0$ but $|{a_n}|$  does not converge to $0$.
b. the sequence $\{a_n\}$ does not converge to $0$.
c. only finitely many $a_n$'s are $0$.
d. infinitely many $a_n$'s are positive and infinitely many are negative.
e. none of the above.

I am not sure which of the aforementioned options is correct . I think option (a) is the right choice but am unable to prove it. Wiki has been of little help.
Can someone explain? Thanks and regards.
Comment: Actually, NO sequence is such that (a) holds.
Comment: @learner Rational numbers *are* complex numbers! $\mathbb{Q} \subseteq \mathbb{C}$
Comment: $a_n = (-1)^n/n$ is a counterexample to (a).
Comment: @SpamIAm yes.That is true but can you give a counter example by taking $a_n$ to be a complex number.
Comment: @SpamIAm yes ,I know that $\Bbb R \subset \Bbb C$ but I was just curious.
Answer: The correct option is (e): The proof that if $\sum a_n$ converges, then $a_n \to 0$ is essentially the same in both the real and complex cases (so (b) is not correct). If $a_n \to 0$, then $|a_n| \to 0$ as well, so it's not (a). Easy counterexamples can be found for (c) and (d) using purely imaginary sequences..
Answer: Let $a_n=u_n+iv_n$ then the series
$$\sum_n a_n$$
is convergent if and only if the two series
$$\sum_n u_n\quad\text{and}\quad\sum_n v_n$$
are also convergent and the series
$$\sum_n a_n$$
is absolutely convergent if and only if the series
$$\sum_n (u_n^2+v_n^2)^{1/2}$$
is convergent.
Now from the above definitions and the fact that if the series
$$\sum_n a_n$$
is convergent then the sequence $(a_n)$ is convergent to $0$ we see that none of the above statements is correct. The following series is a good counterexample:
$$\sum_n \frac{(-1)^n}{n}(1+i)$$
Answer: 1) Is not true. For example, take $a_n = \dfrac{(-1)^n}{n}$, $n > 0$.
2) Also not true. Take the same sequence.
3) Not true. Take $a_n = \dfrac{(-1)^n}{n}$ if $n$ is odd, and $0$ if $n$ is even. Then, $a_n$ converges and $|a_n|$ does not, but there are not finitely many $a_n$'s that are $0$.
4) True. If finitely many $a_n$'s are negative or positive, we can take them out and the series would be convergent, and since all of the would be positive or negative, the absolute value of the sequence would converge too.
For the fourth one, you could prove it more rigorously, but I let that for you.
Comment: Thanks a lot for your time and effort..


Show workflow transition bar in all states

Question: I've created a custom workflow using the workflow module with the transitions listed below and I've noticed that when going to the view page of a node the workflow 'bar' that lets you transition a node between states only appears when it's set for review.
From what I can gather this is because only when it's in the review state is it considered moderated content which is also why it appears on the "Moderated Content" view. What I'd like is to have that appear no matter the moderation state it is in. How could I accomplish this?
States

Draft
Review
Published

Transitions

Draft || Review || Published > Draft
Review > Published
Draft > Review
Answer: I worked out what the issue is, you can only see that bar when you're looking at the Latest Version of a node (using the "Latest Version" tab) not when viewing the latest published version of the node (using the "View" tab).
So this is now resolved by checking if they have access to the "Latest Version" tab of a node (basically checking that exists) and sending them to that if it does, otherwise sending them to the "View" tab. The code below does it and is called from hook_node_insert & hook_node_update in my custom module .module file.
function send_user_to_view_page_after_save(NodeInterface $node) {
  $nid = (string) $node->id();

  if (!is_null($nid)) {
    $alias = Drupal::service('path.alias_manager')->getAliasByPath("/node/{$nid}");
    $url_service = new Url("entity.node.latest_version", ["node" => $nid], []);

    if ($url_service->access() === TRUE) {
      $response = new RedirectResponse("/node/{$nid}/latest");
      $response->send();
    }

    $response = new RedirectResponse($alias);
    $response->send();
  }
}


Jasper Studio com Hibernate Session

Question: Estou tentando adicionar uma conexão no Jasper Studio via a opção "Hibernate Session" Adicionei os .jars do Hibernate, o Driver do MySQL e setei o arquivo hibernate.cfg.xml, mas mesmo assim, sempre tenho a acessão:
Caused by: java.sql.SQLException: No suitable driver found for jdbc:mysql://localhost:3306/dbteste

Tentei também a conexão via "EJBQL". Adicionei os .jars das bibliotecas e um .jar com o persistence.xml e minhas entidades, mas sempre recebo a exceção:
Caused by: javax.persistence.PersistenceException: No Persistence provider for EntityManager named JPAUnit

Alguém tem alguma dica de como realizar essas conexões. Eu quero realiza-las para testar os relatórios com consultas HQL ou JPQL ao invés de usar o SQL.
Comment: Qual é a versão do driver do mysql que está usando?
Comment: A versão é a 5.1.35, mas já tentei com a 5.1.6 também.
Answer: Finalmente consegui resolver. O que acontece é o seguinte, bug no Jasper Studio. Eu estava usando a versão 6.2.2 e com ela não teve jeito de fazer funcionar.
Então, instalei a versão 6.3.0 do Jasper Studio e deu certo.
Mas tem alguns poréns, só consegui a conexão via "EJPQL", para JPA utilizando bibliotecas do EclipseLink:
<dependency>
    <groupId>org.eclipse.persistence</groupId>
    <artifactId>org.eclipse.persistence.jpa</artifactId>
    <version>2.6.3</version>
</dependency>

Já com o Hibernate, tentando usar JPA, cada vez que eu mudava a versão das bibliotecas, gerava uma exceção diferente na tentativa de conexão. Então, acabou que não consegui com as libs do Hibernate.
Mas, se usar a versão 6.0.1 do Jasper Studio, com as bibliotecas do Hibernate 3.3.2-GA funciona com "EJPQL" para JPA. Porém, tem que compilar o jar com as entidades na versão 1.6 do Java, na versão 1.8 e 1.7 não deu certo.
Por fim, não foi possivel de forma alguma, tanto trocando as versões das bibliotecas do Hibernate ou mesmo do Jasper Studio conseguir uma conexão via "Hibernate Session". Sempre rola o mesmo erro:
Caused by: java.sql.SQLException: No suitable driver found for jdbc:mysql://localhost:3306/dbteste

;D

Jasper Studio com Hibernate Session


how to calculate $\int_{C}(2x^2+1)e^{x^2+y^2}dx+(2xy)e^{x^2+y^2}dy$ using Green theorem

Question:
Compute $\int_{C}(2x^2+1)e^{x^2+y^2}dx+(2xy)e^{x^2+y^2}dy$ where $C$ connects $(1,0)$ to $(0,1)$ by a straight line segment.

I tried to use green theorem since $Q_x = P_y$ so $\int \vec F_\dot{}\vec dr=0$
i need to close $C$ so i build a triangle with vertices
$(0,0)$ , $(1,0)$ ,$(0,1)$ now i got a complicated integral in the line parametrization :
$y = 0 ~~~ dy=0$
$x = t ~~~ dx=dt$
$0\leq t \leq 1$

$\int_0^1 (2t^2 + 1)e^{t^2}dt$  , since $dy=0$ only the left side stays

any hints how i can build an easy enclosier ?
Answer: Since $e^{x^2+y^2}$ is a radial function, it is better to choose $D:(\cos t,\sin t), 0\le t\le \frac{\pi}{2}$ and use the fact
$$\begin{eqnarray}
\int_{C}(2x^2+1)e^{x^2+y^2}dx+(2xy)e^{x^2+y^2}dy&=&\int_{D}(2x^2+1)e^{x^2+y^2}dx+(2xy)e^{x^2+y^2}dy\\
&=&e\int_D (2x^2+1)dx + 2xydy\\
&=&e\left[\left(\frac{2}{3}x^3+x\right)\Big|^0_1+\frac{2}{3}\right]\\
&=&-e.
\end{eqnarray}$$
Comment: yes i got it now alone thaaaaanks ! i am glad to notice that
Answer: Seeing $x^2+y^2$ in the expression hints at circles and polar coordinates. I would suggest connecting the two given points with the quarter of the circle $x^2+y^2=1$ in the first quadrant. Then you can parametrize it as $x=\cos t$, $y=\sin t$, for $0\le t\le\dfrac{\pi}{2}$.
Comment: thank you i noticed that right after asking the question !
Comment: i have question though can i use implicit function theorem ?
Comment: $ x^2 + y^2 = 1$ $2x + 2yy' = 0$ $dy = \frac{-x}{y} dx$
Comment: @Mather: Use it for what? Here you need to find both $dx$ and $dy$ with respect to $t$ from the chosen parametrization, not with respect to each other. For example, $x=\cos t$, so $dx=-\sin t\,dt$.
Answer: Since $\int x e^{x^2 + y^2} d(y^2) = x e^{x^2 + y^2} + C(x)$, we can see that $\phi(x, y) = x e^{x^2 + y^2}$ is a potential for $\mathbf F$. Then, by the gradient theorem,
$$I = \int_C (\nabla \phi) \cdot d\mathbf r = \phi(0, 1) - \phi(1, 0) = -e.$$


Application is not installed error, when launched from home screen shortcut

Question: FYI: I have gone through these links already
'App not Installed' Error on Android
Application not installed when i try to autoupdate
My question is little different.

I released app with default/main activity as XActiivity.java in version 1.0
I released update with changing default/main activity as YActivity.java
I find that app opens fine from application meanu, but when I try to launch from home screen shortcut, it throws an error saying "Application is not installed"

I know that its due to shortcut referencing to old XActivity.java, by removing would solve this issue, but if I release app to thousands as an update  who already have this app would get annoyed at the first instance of this error message. I would loose on good reviews I got
Comment: Try removing the icon and creating a new shortcut.
Answer: Please check if you have the property android:exported="false" on an activity that should have been a "android.intent.category.LAUNCHER". This disables the specific activity from being launched on the launcher.
Comment: Android 12 requires activities [explicitly set this value](https://developer.android.com/about/versions/12/behavior-changes-12#security). I set it to false originally, but changed it because of your answer. Thanks!
Comment: No it didn't, the doc applied it on a service. Just discern what is used as a launcher activity vs what is on a service so you would know where to apply the export attribute.
Comment: I linked the documented changes for Android 12 (API 31) above.

"If your app targets Android 12 and contains **activities**, services, or broadcast receivers that use intent filters, you must explicitly declare the android:exported attribute for these app components."
Comment: I looked more closely, it specifies that activities which use intent filters need the attribute. Since the Main/Launcher activity uses an intent filter, the attribute is required.
Comment: android:exported="true"  <= this fixed my issue.
Comment: This should be the accepted answer; so simple! Thanks @PierBetos!
Comment: This requirement (of course) also exists when debugging from Android Studio. I discovered this when upgrading an application that had been built in an older set of tools and then only to support up to Android 10.  The debugger messages in the IDE were a little different, about not finding the app. [Adding this comment essentially to inject "debugger" and "debugging" into the search results on the subject]
Answer: in 2021,
just add
android:exported="true"

in the manifest, and it will be fixed
Answer: That is because homescreen shortcuts work slightly differently from the launcher icons in some launchers.
Your old shortcut still contains a reference to XActiivity as the main Activity, when you have updated it to be YActiivity. This causes Android to think the app isn't installed, as it cannot find an XActiivity in your app marked as the MAIN Activity.
Simply removing the home screen icon and adding it back will solve this.
Comment: Thank you, Yes I agree with /know your solution, but however if I release my update to thousands, its going to effect every one, so they might face same issue.
Comment: @Shri Unfortunately, there's not much you can do to get around it short of not changing your launcher class' name. Some launchers don't even have this problem, but a fair bit do. Its just one of those things you can't control.
Comment: Can anyone identify which launchers have this problem. I would like to be able to reproduce this.
Comment: omg I was thinking about an Android issue but it was just an Activity name update, such a stupid typo;)
Answer: Putting
  <intent-filter>
    <action android:name="android.intent.action.MAIN"/>
    </intent-filter>

inside specific activity inside Manifest.XML did the job for me.
Comment: This is not connected to this problem. Documentation says Activity for shortcuts must be LAUNCHER and action MAIN. ( doc https://developer.android.com/guide/topics/ui/shortcuts)
Answer: This question is old, but still relevant today.
This occurred because I changed the starting activity. I had this originally (truncated):
<manifest>
    <application>
        <activity android:name=".activities.StartActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity
            android:name=".activities.OtherActivity"
            android:exported="false" />
    </application>
</manifest>

I removed StartActivity but I forgot to remove android:exported="false", after adding the intent filter. It looked like this:
<manifest>
    <application>
        <activity
            android:name=".activities.OtherActivity"
            android:exported="false">
            <intent-filter>
                <action android:name="android.intent.action.MAIN"/>
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
</manifest>

In short, make sure your starting activity is exported.
Answer: What if you implement both XActivity and YActivity as entry points in your app?  XActivity could remove its launcher shortcut, install the YActivity shortcut, and launch YActivity.
Answer: first ensure if current installed apps can be moved to sd card
if they cant be that is it you have got the reason
on my htc desire 300 while rooting i flashed wrong rom bricked my phone in bootloop
got it repaired from a shop
now running custom rom i dont know which one
but it doesnt support moving app to sd card
so i copied app to phone memory
unmounted or removed sd card
then i try to install from phone memory and my fs2014 1.35 is now installed
horrray
hope it help you
this will only work if you have custom rom because original rom does nt have errors like that
or you call that a bug
Comment: yeah but that works only if app not installed during app package installation
Answer: Possible Solutions of "Application not Installed" error

Reboot the phone: In times like this, first thing to do is to reboot
your device. Or just shut down, remove and reinsert your battery.
Make sure to uninstall any apps you don't use to free up space, also
uninstall previous versions of the same app currently installed on
your device.
Double check the apk files you download and be sure they were
completely copied or downloaded.
Try resetting app permissions by going to Settings >Apps>All>Menu key

Reset application permissions or Reset app preferences.

Change app installation location to Automatic or Let system decide.
Make sure your SD card is not mounted or connected to a PC or
elsewhere.
For worst case scenarios, format your SD card – copy it's contents
somewhere else for backup and format.
The last solution would be to totally wipe your device. Either by
doing a factory reset under Settings or by doing a full wipe in
recovery mode.

Reference
Answer: I've had the same problem, just a minute ago.
I'm not expert so all I could get from all answers is problem is in shortcut created on home screen by launcher.
I'm using classic minimalist launcher which doesn't have app drawer so all apps are on home screen, so I can't just delete shortcut without uninstalling it.
So I cleared cache of my launcher and it created new shortcut for that app on its own and it started working.
Answer: Might be a case, check your code for "App shortcut creation" where the Intent.EXTRA_SHORTCUT_INTENT is mapped to the LAUNCHER activity. (Might be SplashScreenActivity)
Answer: The solution I wrote is.
AndroidManfest.xml

I retained intent filter  android.intent.action.MAIN for my previous XActivity.java.
I also retained intent filter android.intent.action.MAIN and also category as LAUNCHER to YActivity.java

In the onCreate() method of XActivity.java I added these lines, and it seems to have solved issue
Intent thisIntent = getIntent();
if(thisIntent.getAction() == "android.intent.action.MAIN"){

        Intent intent = new Intent(this,YActivity.class);
        startActivity(intent);
        finish();
}

Comment: Hi - I am trying out your solution, but unfortunately this is really hard to test. Can you please explain how this fixes it, because if the problem is with the shortcut having a mismatched launcher activity embedded in its details then I'm not sure how this should resolve it. Please elaborate. Thanks!
Comment: This didn't fix it for me, but setting `android:exported="true"` did, as per this answer: https://stackoverflow.com/a/39957428/1346778


How do I fix jQuery attr ID change not working?

Question: Using jQuery 3.5.1 I try to change the ID on a button when another button is clicked, using $('#convertBtn').attr('id', 'convertBtnDownload'); but this is not working .. does anyone have an idea on why and how to fix this?
Working example:

$(document).ready(function() {

  $("#convertBtn").click(function() {

    console.log("Clicked")

    $("#convertBtnSpinner").show();
    $("#convertBtn").attr("disabled", true);
    $("#convertBtnText").html("Genererer ...");
    document.documentElement.style.cursor = 'wait'

  });

  $("#convertBtnDone").click(function() {

    console.log("Done")

    $("#convertBtnSpinner").hide();
    $("#convertBtn").attr("disabled", false);
    $("#convertBtn").removeClass("btn-primary");
    $("#convertBtn").addClass("btn-success");
    $("#convertBtnText").html("Download PDF ");
    $('#convertBtn').attr('id', 'convertBtnDownload');
    document.documentElement.style.cursor = 'default'

  });

  $('.convertBtnDownload').click(function() {
    $('#resultLink').click();
  });

});
.dot1 {
  animation: visibility 1.5s linear infinite;
}

@keyframes visibility {
  0% {
    opacity: 1;
  }
  65% {
    opacity: 1;
  }
  66% {
    opacity: 0;
  }
  100% {
    opacity: 0;
  }
}

.dot2 {
  animation: visibility2 1.5s linear infinite;
}

@keyframes visibility2 {
  0% {
    opacity: 0;
  }
  21% {
    opacity: 0;
  }
  22% {
    opacity: 1;
  }
  65% {
    opacity: 1;
  }
  66% {
    opacity: 0;
  }
  100% {
    opacity: 0;
  }
}

.dot3 {
  animation: visibility3 1.5s linear infinite;
}

@keyframes visibility3 {
  0% {
    opacity: 0;
  }
  43% {
    opacity: 0;
  }
  44% {
    opacity: 1;
  }
  65% {
    opacity: 1;
  }
  66% {
    opacity: 0;
  }
  100% {
    opacity: 0;
  }
}

<link href="https://email@example.com/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-+0n0xVW2eSR5OomGNYDnhzAbDsOXxcvSN1TPprVMTNDbiYZCxYbOOl7+AMvyTG2x" crossorigin="anonymous">

<button id="convertBtn" class="btn btn-primary" style="width: 220px;" type="button">

Generate PDF
</button>

<button id="convertBtnDone" class="btn btn-primary" type="button">Swap ID</button>
Comment: Is `.convertBtnDownload` supposed to be `#convertBtnDownload`?  Also note you are targeting dynamically added elements.  Event handlers only bind to elements that exist at page load.  If you come along later and add (or update) a button with an ID that did not exist at page load, your event handler for that ID will not work.  You need to delegate your handlers, see eg https://stackoverflow.com/questions/203198/event-binding-on-dynamically-created-elements.
Comment: (Though in this case I'd suggest rethinking your flow/functionality so that you don't need to go changing elements might be a better approach?)
Comment: Hi @Don'tPanic .. you might be right regarding rethinking the functionality .. in the end the "Swap ID" button offcause will not be there, the jQuery part that this button at the moment does will be triggered by a jSON response so that instead of posting (this part is in a other script not posted here) I need the button to execute `$('#resultLink').click();` .. but at the moment I cannot see how I can do that without changing the ID on the button .. maybe I do not think right here :-)
Comment: I have as you suggested @Don'tPanic rethought my solution and have found a better way to do it .. I will post my solution shortly .. Thanks :-)
Answer: I have as @Don'tPanic suggested rethought my solution and have come up with a better and working solution:
Instead of the using the same button, I am hiding/showing different buttons depending on the state they need to be in:
<button id="convertBtn" class="btn btn-primary" style="width: 220px;" type="button">

  Generate PDF
</button>

  Download PDF

The jQuery used :
$( "#convertBtn" ).hide();
$( "#result" ).show();
$( "#resultLink" ).attr("href", "<PATH_TO_PDF>.pdf");
document.documentElement.style.cursor = 'hand'


Delegação de evento apenas uma vez, em um cenário 'dinâmico'

Question: Eu tenho uma função hello() cujo argumento é o retorno de uma chamada de ajax:
function hello(msg) {
    alert(msg);
}

$.ajax({
    url: 'example.com',
    data: data
  }).done(function(resp) {
     // abre_modal
     // apenas no fecho (click close) da modal é que eu quero que a função abaixo seja executada
     $('#myModal').on('hide.bs.modal', function() { hello(resp); });
  });

Mas o cenário acima provoca um problema, o evento é delegado várias vezes, e como consequência a função hello() é executada o mesmo número de vezes.
Como faço, tendo em conta que apenas quero delegar o evento uma vez, mas a resp é dinâmica, para que a função seja executada apenas uma vez, assim como a delegação do evento click close da modal?
Answer: Não deste muito contexto ao resto do código, mas podias fazer algo assim:

var resposta = '';
$('#myModal').on('hide.bs.modal', function() {
  hello(resposta);
});

$.ajax({
  url: 'example.com',
  data: data
}).done(function(resp) {
  resposta = resp;
});

Assim tens a variável acessível globalmente (não é o ideal mas é uma maneira de fazer). Isso só irá funcionar depois do ajax ter corrido uma vez.
Provavelmente podes também usar o .one( que é a maneira do jQuery correr um event handler só 1 vez.
Seria assim:

function hello(msg) {
  alert(msg);
}

$.ajax({
  url: 'example.com',
  data: data
}).done(function(resp) {
  // abre_modal
  // apenas no fecho (click close) da modal é que eu quero que a função abaixo seja executada
  $('#myModal').one('hide.bs.modal', function() {
    hello(resp);
  });
});
Comment: Isso não tem problema porque a modal só abre quando ajax é `done()`. Entretanto consegui resolver assim: `$('#myModal').off('hide.bs.modal').on('hide.bs.modal', function() {...});`. Mas vou aceitar a tua com certeza. Obrigado.
Comment: @HulaHula testa também com `.one(`, que o jQuery tem para correr event handlers só uma vez
Comment: Ha boa, não sabia disso não


Get binary representation of variables in C

Question: I would like to get a binary representation for all types of variables in C: int, unsigned int, long, unsigned long, short, unsigned short, float, double and char.
It is the best solution, when I getting the size of a variable (by sizeof()) and converting it to the binary system?
How to quickly and easily carry out such a conversion?
Comment: https://stackoverflow.com/questions/111928/is-there-a-printf-converter-to-print-in-binary-format
Comment: They are already in binary.
Comment: Use `sizeof` to determine the size of the type, point an `unsigned char *` to the variable in question, loop through each byte, then use bit shifting to print each bit.
Comment: In a **binary** digital computer, there is no other representation of data than binary.
Comment: @GradyPlayer I was just thinking how to reply to Olaf, but he is right, BCD is still binary coded, and endianess is not a binary issue.
Comment: Are you wanting a binary conversion function for all these types? Or sizeof() those types? Please clarify a little more of what you need
Comment: @olaf... BCD... little endian, big endian... not to mention different encoding schemes...
Comment: ...even floating point encoding schemes are in binary, with various fields within the whole. But I like the dup.
Comment: @GradyPlayer: And which one of them is **not** binary? If you look up what "BCD" means, you will find: **Binary** **C**oded **D**ecimal. Representation != encoding!
Comment: @Olaf some times I forget why I come here...
Answer: Get binary representation of any type:
I wrote the following code to provide two functions that do what you asked for. The first function getBinaryHostMemoryRepresentation() will fill your provided buffer with the bits how they are saved in your hosts memory: That could be little-endian, big-endian or something else (unlikely). For example the integer 0xABCD is saved on a little-endian as 0xCDAB.
The getBinaryRepresentation() function will check on what machine you are running and will fill your buffer with the bit representation you would expect as human readable which is big-endian so you would get 0xABCD. To check on what kind of machine the program is running it uses the isLittleEndian() function, see how it works here on SO.
Both functions need the following arguments: char * const buffer, size_t bufSize, const void * var, size_t varSize. The first two are the buffer and the size of the buffer. The last two are the variable you want to convert (it's a void pointer, it can be any data) and the size in bytes of the variable which can get by sizeof(). Further the functions check if the buffer is big enough, if not they're returning a null pointer. If it is big enough they return the pointer to the buffer you provided. The usage could be observed in main() function.
The main() function uses two inputs for teh functions above:

The integer: 2882400235 which is 0xABCDEFEB or 0b10101011110011011110111111101011
The float: 42.0 which is 0x42280000 or 0b01000010001010000000000000000000.

To check integers you could use the Windows calculator, to check floats you can use this site online.
Output of the program:
integer 2882400235:
Host memory binary representation:    "11101011111011111100110110101011"
Human readable binary representation: "10101011110011011110111111101011"

single floating point 42.0:
Host memory binary representation:    "00000000000000000010100001000010"
Human readable binary representation: "01000010001010000000000000000000"

The code in C as you tagged the question with C:
#include <stdio.h>
#include <stddef.h>
#include <limits.h>

#if CHAR_BIT != 8
#error "unsupported char size"
#endif

int isLittleEndian ()
{
   static const int num = 1;
   if (1 == *((char *) &num))
   {
      return 1;
   }
   else
   {
      return 0;
   }
}

char * getBinaryHostMemoryRepresentation (char * const buffer, size_t bufSize, const void * var, size_t varSize)
{
   size_t byteIdx;
   size_t bitIdx;

   if (bufSize < varSize * CHAR_BIT + 1)
   {
      return NULL;
   }
   const unsigned char * curByte = (const unsigned char *) var;
   for (byteIdx = 0; byteIdx < varSize; ++byteIdx, ++curByte)
   {
      for (bitIdx = 0; bitIdx < CHAR_BIT; ++bitIdx)
      {
         unsigned char curBit = (*curByte & (1 << ((CHAR_BIT - 1) - bitIdx))) >> ((CHAR_BIT - 1) - bitIdx);
         buffer[byteIdx * CHAR_BIT + bitIdx] = curBit + '0';
      }
   }
   buffer[varSize * CHAR_BIT] = '\0';
   return buffer;
}

char * getBinaryRepresentation (char * const buffer, size_t bufSize, const void * var, size_t varSize)
{
   size_t byteIdx;
   size_t bitIdx;

   if (bufSize < varSize * CHAR_BIT + 1)
   {
      return NULL;
   }

   const unsigned char * curByte;;
   int incByte;
   if (isLittleEndian ())
   {
      curByte = (const unsigned char *) var + (varSize - 1);
      incByte = -1;
   }
   else
   {
      curByte = (const unsigned char *) var;
      incByte = 1;
   }
   for (byteIdx = 0; byteIdx < varSize; ++byteIdx, curByte += incByte)
   {
      for (bitIdx = 0; bitIdx < CHAR_BIT; ++bitIdx)
      {
         unsigned char curBit = (*curByte & (1 << ((CHAR_BIT - 1) - bitIdx))) >> ((CHAR_BIT - 1) - bitIdx);
         buffer[byteIdx * CHAR_BIT + bitIdx] = curBit + '0';
      }
   }
   buffer[varSize * CHAR_BIT] = '\0';
   return buffer;
}

int main ()
{
   int integer = 2882400235; /* 10101011110011011110111111101011 */
   char bufferMemInt[sizeof (integer) * CHAR_BIT + 1];
   char bufferBinInt[sizeof (integer) * CHAR_BIT + 1];

   printf ("integer 2882400235:\n");
   if (getBinaryHostMemoryRepresentation (bufferMemInt,
                                          sizeof (bufferMemInt),
                                          (void *) &integer,
                                          sizeof (integer)))
   {
      printf ("Host memory binary representation:    \"%s\"",
              bufferMemInt);
      printf ("\n");
   }

   if (getBinaryRepresentation (bufferBinInt,
                                sizeof (bufferBinInt),
                                (void *) &integer,
                                sizeof (integer)))
   {
      printf ("Human readable binary representation: \"%s\"",
              bufferBinInt);
      printf ("\n");
   }

   float floating = 42.0; /* 01000010001010000000000000000000 */
   char bufferMemFloat[sizeof (floating) * CHAR_BIT + 1];
   char bufferBinFloat[sizeof (floating) * CHAR_BIT + 1];

   printf ("\n");
   printf ("single floating point 42.0:\n");
   if (getBinaryHostMemoryRepresentation (bufferMemFloat,
                                          sizeof (bufferMemFloat),
                                          (void *) &floating,
                                          sizeof (floating)))
   {
      printf ("Host memory binary representation:    \"%s\"",
              bufferMemFloat);
      printf ("\n");
   }

   if (getBinaryRepresentation (bufferBinFloat,
                                sizeof (bufferBinFloat),
                                (void *) &floating,
                                sizeof (floating)))
   {
      printf ("Human readable binary representation: \"%s\"",
              bufferBinFloat);
      printf ("\n");
   }

   return 0;
}

Comment: Hi @geekcode if this answer has solved your question please consider [accepting it](https://meta.stackexchange.com/q/5234/179419) by clicking the check-mark. This indicates to the wider community that you've found a solution and gives some reputation to both the answerer and yourself. There is no obligation to do this.


Date picker não aparece

Question: É o seguinte eu estou a tentar mostrar um date picker num formulario mas ele nao aparece a minha pergunta é a seguinte e possivel por o date picker num modal de bootstrap? é que eu fora do modal consigo usar o date picker dentro e que nao consigo
Deixo imagem do modal!!
Answer: Bom eu não sei como está o seu modal, mas você pode fazer assim.

Launch demo modal

    <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>

Modal header

      <input data-format="dd/MM/yyyy hh:mm:ss" type="text"></input>

    <button class="btn" data-dismiss="modal" aria-hidden="true">Close</button>

E coloque no final da pagin, antes do fechamento da tag body:

Comment: Voce testou e funcionou?
Comment: sim, veja funcionando https://codepen.io/Sinetheta/pen/Ftjwi
Comment: pois estoua  ver mas ent nao sei o que estou a fazer mal
Comment: você está usando o datepicker próprio para o bootstrap certo?
Comment: Provavelmente o problema é do meu date picker
Comment: Qual é o date picker que devo usar entao pode me indicar?
Comment: @Shider tente usar essa versão aqui: https://github.com/uxsolutions/bootstrap-datepicker

Date picker não aparece


Monitor Wait for caching,... it this a good practice?

Question: i just wrote a code, and then i found out that there are some issue with the monitor.wait, forcing me to do the operation within the locks, i wanted to now if this is a good way to keep a thread waiting,....
i'm not sure if the thread.join would do the job, as there are lots of threads running within my application, and each do specific job, that they may terminate within the time...
here is my code:
public static class TaskManager
{
    private static readonly object UpdateLock = new object();
    private static readonly object WaitLock = new object();

    private static readonly LiaisonDb _db = new LiaisonDb();
    private static List<liaQueue> _liaQueueList = new List<liaQueue>();
    private static DateTime _lastUpdate = new DateTime();

    public static liaQueue GetTask(string sessionType)
    {
        liaQueue task;
        lock (UpdateLock)
        {
            if (_lastUpdate < DateTime.Now.AddSeconds(-5))
            {
                Thread t = new Thread(UpdateCache) {IsBackground = true};
                t.Start();
                lock (WaitLock)
                {
                    Monitor.Wait(WaitLock);
                }

                _lastUpdate = DateTime.Now;
            }
            task = _liaQueueList
                .FirstOrDefault(w => w.Stat == 0
                                     && w.Type != null
                                     || string.Equals(w.Type, sessionType));
        }
        return task;
    }

    private static void UpdateCache()
    {
        try
        {
            _liaQueueList = _db.liaQueue.Where(w => w.Stat == 0).ToList();
        }
        finally
        {
            lock (WaitLock)
            {
                Monitor.Pulse(WaitLock);
            }
        }
    }
}

As you see i put two lock, and one of them is only for monitor.wait, keep the thread waiting for the answer...
i think i also have to returns null while the cache is getting refreshed?...
Comment: If your code IS working - you do not have a technical problem but ask for a code review.
Comment: Questions seeking debugging help ("why isn't this code working?") must include the desired behavior, a specific problem or error and the shortest code necessary to reproduce it in the question itself. Questions without a clear problem statement are not useful to other readers. See: How to create a Minimal, Complete, and Verifiable example. 1
Comment: @TomTom my code is working, but the question is would this continoue working? (my first time with monitor.wait / palse), is the way i implement it the good way? and something like this. i want to know if what i did is good, and if it doesn't cause troubles, as it will become part of complex application. &&  how to ask for code review?
Answer: From MSDN

If two threads are using Pulse and Wait to interact, this could result in a deadlock.

So, no. Your implementation would not be best practice.
It seems to me that GetTask is supposed to update the cache on a background thread, then block the calling thread until the cache was updated, and then return the first task according to a select criteria.
Since the calling thread will block (wait) for the cache to be updated, I don't quite understand the point of using a background thread in the first place.
If the purpose is to prevent multiple calling threads to update the cache in parallel, use just the lock(UpdateLock) statement.
If you do want to run the cache on a background thread anyway (and wait for it), consider using the Task library instead. But I don't really se the point of it.
lock (UpdateLock)
{
  if (_lastUpdate < DateTime.Now.AddSeconds(-5)) {
    Task.Run(() => {
      _liaQueueList = _db.liaQueue.Where(w => w.Stat == 0).ToList();
    }).Wait();

    _lastUpdate = DateTime.Now;
  }
}

return _liaQueueList.FirstOrDefault(w => w.Stat == 0 && w.Type != null || string.Equals(w.Type, sessionType));

Comment: Any way i look at it, and want to put your though under question, i found answer in it. BTW, using another lock i managed to stop other thread from using wait pulse together, and the other lock, is just for the sake of "synchronous block code" requirement of the Monitor.wait/pulse, since the wait pulse also release the lock, i had to use multiple lock so my first lock won't get released when i call the wait(), but the fake one. So in this case, is this acceptable for some other circumstances when there are need for multiple thread? BTW, thanks a lot.
Comment: Your question ends with "is this good practice?" (title). And the answer to that is no, because you may end up with a deadlock. Especially if you use more than one synchronization object. Thread 1 may hold lock A, but waiting for lock B. Thread 2 may hold lock B and is waiting for lock A.
In summary, your solution sounds complex, and complexity adds risk. By simplifying the solution you reduce risk.
Comment: You are right, but, lock 'A' surround whole stuff even lock 'B' itself, so Thread with lock 'B', either have lock 'A', or the 'B' is not locked at all and waiting for 'A' then 'B' to be achieved... Next thing, i can test it using task, but i have to remove the task latter, since some of our client run under .net 3.5 and less. server 2003, BTW i put the code directly in the body due to your right previous opinion. if someone has a thread, then with this code at least, there is no need to run another thread.
Comment: Yes, that may be true in your specific case. But as I said in my answer; I do not understand why you need the background thread. The point of a background thread is usually to add capability to do something asynchronously. Your locking mechanism and signalling seems to attempt to achieve synchronization for a async job. Why do you even need a background thread then?
Comment: yes you are right, at that point i failed to see that


Why am I forced to log in?

Question: I'm a long-time Drupal 7developer, and tried a Drupal 8 install yesterday for evaluation. I installed a bunch of contrib modules. All seems ok, but when I go to the home page, I'm presented with a login screen. I want anonymous users to be able to see the site, how can I allow this? I don't see any settings to force login, and am not using the shield module.
Comment: What is the front page set to at Admin -> Configuration -> System -> Basic Site Settings? Set it to `/node` if it's empty.
Comment: This is not standard behavior of a default install. Something within "I installed a bunch of contrib modules" is likely the culprit.
Comment: Simply restart with a fresh standard installation. Check if everything's fine. Then add modules one by one. Until the error occurs. But most likely you simply have left the default front page to be empty at /admin/config/system/site-information.
Comment: I think the login block is often on the page by default. My guess is the front page is empty and all you're seeing is the login block.
Answer: D8 default front page is a view page admin/structure/views/view/frontpage/edit/page_1. Views in 7 and 8/9 is quite similar from a end user perspective meaning you should feel right at home. D7 and 8 default front page is /node as you see and normal access permission.
Comment: Thanks for the good explanation. Figured it out.

Why am I forced to log in?


Incremental Compilation in Eclipse. ASTNode-s and SVN versioning

Question: I am building up some statistics after analyzing the source code in eclipse. But the overall process is too slow because i rebuild my model every time from scratch after each compilation.
I am looking for a way to get only the changed parts of the code (as ASTNodes) and to rebuild just that part of my model. I suppose that even the changed compilation units and not the exact code elements would be enough after the user compiles and still would be a nice optimization.
I am sure eclipse is capable of knowing what code elements are changed (and even to know their semantics), because when I use the subclipse plugin my changes are ordered by a code element (an import, a method, a variable declaration, etc). Well.. at least that plugin is capable of knowing that info.
Thanks in advance
Answer: The Eclipse builder infrastructure is created for exactly this reason. For a start I suggest the following article and FAQ entry.


Como colocar a scrollbar dentro do body?

Question: Estilizei a scrollbar do meu site para webkit, e coloquei o background da track como transparent, porém eu gostaria que a thumb se sobreposse ao conteúdo do body, simulando um efeito de position absolute, e o body 100% sem deixar o padding para a track, como posso fazer isso?
Exemplo de como está:

Gostaria que o body ocupasse toda a extensão da janela, ocupando o inclusive o espaço da track para ficar assim:

Apesar do código que o Marcos Henzel ter funcionado bem aqui, por algum motivo não funcionou no site, então fiz um "hackzinho" pra poder conseguir o efeito que eu queria e o código ficou da seguinte forma:
body{
    width:100%;
    height:100%;
    position:absolute;
    overflow-y:scroll;
    background-color:#312d28;
    font-family:'Ebrima';
    margin:10px;
    top:-10px;
    left:-10px;
    padding-right:14px;
}
body::-webkit-scrollbar {
     width: 14px;
}
body::-webkit-scrollbar-thumb {
    height: 6px;
    border: 4px solid rgba(0, 0, 0, 0);
    background-clip: padding-box;
    -webkit-border-radius: 7px;
    background-color: rgba(255, 255, 255, 0.7);
}
body::-webkit-scrollbar-button {
    width: 0;
    height: 0;
    display: none;
}
body::-webkit-scrollbar-corner {
    background-color: transparent;
}

Dessa forma consigo com que o efeito fiquei exatamente igual ao da imagem de exemplo. Aplicando um margin ao body e depois puxando-o de volta com as propriedades left e top e então coloco um padding-right para puxar o body no espaço que a scrollbar ocupa. Imagem abaixo:
Comment: Não altere a pergunta com solução, você pode postar sua versão finalizada como resposta, e manter a que resolveu como aceita.
Comment: Acho que só colocar a cor de fundo da barra transparent, não parece que está. Tem o site no ar ou um fiddle ?
Comment: a track já está com o background transparente
Comment: Posta o código...
Comment: O site ta assim atualmente: http://www.bluanime.com/v2/navegar
Comment: Coloque seu código...
Comment: @MagicHat coloquei o css na pergunta
Comment: você não quer que sua barra de rolagem encoste na margem é isso?
Comment: quero que a barra de rolagem fiquei por cima do body, de forma que o body ocupe 100% do espaço da tela, os reais 100% inclusive o espaço que a scrollbar deveria usar
Answer: Para navegadores webkit (Chrome, Safari, Opera 15+):
    ::-webkit-scrollbar              { /* 1 */ }
    ::-webkit-scrollbar-button       { /* 2 */ }
    ::-webkit-scrollbar-track        { /* 3 */ }
    ::-webkit-scrollbar-track-piece  { /* 4 */ }
    ::-webkit-scrollbar-thumb        { /* 5 */ }
    ::-webkit-scrollbar-corner       { /* 6 */ }
    ::-webkit-resizer                { /* 7 */ }

Para criar um scrollbar exatamente como da tua pergunta seria algo deste genero:
    ::-webkit-scrollbar-track {
        background-color: transparent;
    }

   ::-webkit-scrollbar {
        width: 10px;
    }

    ::webkit-scrollbar-thumb {
        background: #dad7d7;
     }

Conforme o snippet, abra no Navegador Chrome ...

.container {
    height:200px;
    overflow: auto;
    width: 200px;
    border-bottom: 1px solid #D4D4D4;
    background-color: blue;
}

.container::-webkit-scrollbar-track {
    background-color: transparent;
}
.container::-webkit-scrollbar {
    width: 10px;
}
.container::-webkit-scrollbar-thumb {
    background: #dad7d7;
}

fdsf