Why is the last stage of Le Tour de France "friendly"?

Question: It hasn't always be like this, but these last years, the last stage is not decisive for the victory. The general rankings stay basically the same as the day before.
While officially racing in Paris, riders take pictures, drink champagne so this stage is more like a celebration and the stage victory is left to the final sprinters.
Is there a reason for this? Are there some implied rules to let the rankings stable on this day and not try to attack the yellow jersey?
Answer: Simply, because there's no point It's a flat stage, so they can't gain time.
If you look at the different stages, time differences between General Classification contenders tend to be achieved on mountain stages, time-trials or occasionally on flat/rolling stages with severe cross-winds (too much of the stage in in the city for this to be a problem).
On flat stages it's too easy for teams and individual riders to "mark" each other. ie. if the second placed rider in GC attacks, then the GC leader can just cycle along behind him and finish on the same time.
Realistically, the GC leader can only lose if there's a severe crash.
The only people who will actually be "racing" are people who are trying to win the stage, or possibly people trying to win the points classification if that's close.
So...when there's no chance of winning, why not drink champagne and have fun?
Comment: In 2005 Alexandre Vinokurov was only 2 seconds off fifth place, so he attacked a few kilometres from the finish, won the stage and collected the 20 bonus seconds that put him into fifth place. The peloton was on his heels, so didn't actually gain time on them. So if less than 20 seconds separate riders, it might make sense to attack - it's unrealistic to gain much more time, but "only" highly unlikely to gain this much.
Answer: In addition to Niall's good answer, I'd say:

A specific rule of this step says that, because of the slippery pavement of the Champs-Elysées, when the weather is wet, race commissaries can decide that time will stay still at the first time riders go through the finish line.
This rule can also be applied at the n-th lap if the wet weather occurs later in the race.
The specifics of this step create conditions much in favour of the peloton than isolated breakaway riders. At some point, a peloton can reach a speed close to 70 km/h (in the slightly descending part of the avenue). On the other part, the speed is still high, around 50 km/h, which is still hard to maintain for a lonely rider for a long time.


A tough integral

Question: As a physicist of living matter, I've come across this integral in my work : $\int_1^x\frac{\tanh(u)}{u^4} du$. Does anyone have an idea how to compute it ? Mathematica returns nothing of value, and I need more than asymptotics...
Thanks a lot !
Comment: The indefinite integral $\int \frac{\tanh u}{u^4}$ is presumably non-elementary. Otherwise, Mathematica would have found a closed-form expression.
Comment: I tried Mathematica, ahah. I don't have much knowledge in computing hard primitives. My first integral was something far uglier but I got it down to this by changing variables. It first was something like $\int^x \sqrt{u} \tanh(\sqrt{y/u}) du$ where $y$ is fixed and positive.
Comment: @John_dydx Isn't _u_ just a dummy variable?
Comment: what have you tried so far?
Comment: @Célestin I guess so... But I heard of cases where Mathematica would do worse than clever approaches to some integrals, so I tried my luck
Comment: Whats the relationship between $u$ and $x$?
Comment: @John_dydx Yes, u is a dummy variable, and $x \geq 1$.
Comment: You could get good results from people on this site with a large improper integral, but you cannot expect anything better than a series solution to a nonelementary general integral such as this
Answer: I hope this estimation is good enough for you.
Remarking that $\tanh(u)=\sinh(u)/\cosh(u)$, and $\cosh'(u)=\sinh(u)$, one can integrate by parts obtaining
\begin{align}\int_1^x u^{-4}\tanh(u)du&=\left[u^{-4}\ln\cosh(u)\right]_{1}^{x}+\frac{1}{5}\int_{1}^x u^{-5}\ln\cosh(u)du=\\
&=\frac{\ln\cosh(x)}{x^4}-\ln\cosh(1)+\frac{1}{5}\int_{1}^x u^{-5}\ln\cosh(u)du.\end{align}
$1\le\cosh(u)=\frac{e^u+e^{-u}}{2}\le e^u$ for $u\ge1$, that is $0\le\ln\cosh(u)\le u$ for $u\ge1$.
It follows that
\begin{align}
\frac{1}{20}(1-x^{-4})\le\int_1^x u^{-4}\tanh(u)du-\frac{\ln\cosh(x)}{x^4}+\ln\cosh(1)\le\frac{1}{15}(1-x^{-3}).
\end{align}
Again, if you don't like having $\ln\cosh(x)$, you can use the same estimation as above and obtain
\begin{align}
-\ln\cosh(1)+\frac{1}{20}(1-x^{-4})\le\int_1^x u^{-4}\tanh(u)du\le x^{-3}-\ln\cosh(1)+\frac{1}{15}(1-x^{-3}).
\end{align}
EDIT: I remarked my estimation have been really sloppy, since I could have use this estimation instead
\begin{align}
\frac{e^{u}}{2}\le\cosh(u)=\frac{e^u+e^{-u}}{2}\le e^u \Rightarrow u-\ln2\le\ln\cosh(u)\le u,\ \text{for}\ u\ge1.
\end{align}
It follows
\begin{align}
F(x)-\frac{\ln(2)}{20}(1-x^{-4})\le\int_1^x u^{-4}\tanh(u)du\le F(x).
\end{align}
where $F(x)=\frac{\ln\cosh(x)}{x^4}-\ln\cosh(1)+\frac{1}{15}(1-x^{-3}).$
Comment: Thanks ! Sadly it won't help much for my problem. Excuse me if I'm mistaken but I think you've forgotten the $x=1$ boundary term after integrating by parts, but no biggie.
Comment: No, simply $\ln\cosh(1)=\ln(1)=0$. In any case, you can try integrate by parts in the opposite direction, by using the property of hyperbolic functions and by estimating the logarithm which appears at the end.

It is not difficult, but there are too much counts for me to write them down on latex.
Comment: Well but $\cosh(1) \neq 1$ right ?
Comment: you are right, my bad, i'll correct

A tough integral


Filter view with multiple displays

Question: Using Drupal 7. I have a view with several page displays, 2 of them being /review and /mentions. I have some exposed filters on these pages visible on a side block of the page.
When clicking the apply button to filter the content, I get redirected to /review?filter=....
whether I am on the /review page or /mentions page.
How can I make the filter work so that
- when filtering the /review page, I land on /review?filter=...
- when filtering the /mentions page, I land on /mentions?filter=...
Thanks for your help,
Jerome
Comment: Your question not understandable - explain it clearly
Comment: More specifically, the action of the filter form is 'review' on both pages. It should be 'review' on the /review page and 'mentions' on the /mentions page.
Answer: I found what I was doing wrong.
I assumed that the exposed filter block for the view was the same for all displays of that view, When it actually creates 1 block per display.
I disabled the block "Exposed form: filter_view-page" for the /mention path and added the another block "Exposed form: filter_view-page_2" for it.
Works fine now.

Filter view with multiple displays


Problema com $_POST e IF

Question: Estou tentando fazer q se caso a pessoa digite 12 em qualquer parte do texto ele entre no if mas ele n esta entrando
if ($_POST['mensagem'] !="%12%"){
        echo"vc digitou 12";
    }

Comment: Esta sintaxe que utilizou não existe. Pesquise por `strpos`.
Comment: Além do citado acima, como eu digitei 12 se a comparação é de diferença??
Comment: coloquei errado essa parte era vc n digitou 12 kkkk
Comment: obg @AndersonCarlosWoss vou procurar
Answer: Para saber se um texto está contido em outro se usa strpos.
if ( strpos( $_POST['mensagem'] , '12' ) !== false ){
    echo 'vc digitou 12';
}

Importante: note o uso de !== false, pois se a string estiver no começo, usar apenas != vai dar errado, pois o resultado do strpos será zero, indicando que há um 12, mas no começo da string, pois a contagem se inicia na posição zero.
Se quiser o comportamento inverso:
if ( strpos( $_POST['mensagem'] , '12' ) === false ){
    echo 'vc NAO digitou 12';
}

Use === pela mesma razão explicada anteriormente.
Perceba que há outras funçoes para encontrar substrings, mas o próprio manual recomenda a strpos para estes casos, pela diferença significativa de performance.
Mais detalhes no manual:

https://secure.php.net/manual/pt_BR/function.strpos.php

Leitura recomendada sobre a diferença de === e !== para == e !=:

O que é uma comparação frouxa?
Comment: Não entendi o voto negativo

Problema com $_POST e IF


How to deserialize object with different serialVersionUID

Question: I'm aware that serialVersionUID is used for versioning a serializable class, so, how can I load a old serialized object with the new class?
The only related question I found is:
how to discover serialVersionUID of serialized objects
But still, how I would be able to deserialize the old object as an instance of the new updated class?
Comment: By making sure the new class has the same serialVersionUID as the old one, and only has compatible changes. Read http://docs.oracle.com/javase/7/docs/platform/serialization/spec/version.html#6519
Comment: Well, this is a solution, post as an answer please so we can add relevant information
Answer: You can set the serialVersionUID to any value needed (the expected vs actual values are normally seen in the error messages). Put the field like
<code>   private static final long serialVersionUID = 1L;
</code>
(replace 1 by the old value) and you will be able to read your old data.
If you need to read both new and old format at the same time and they are actually somewhat different, best seems to give the new version of the class a new name use resolveObject to convert the old format into new if the leagacy class appears in the stream.


Convert csv.DictReader to CSV File

Question: I've got a csv.DictReader called reader:
reader = csv.DictReader(csvfile())
for row in reader:
    print(row)

gives me the following output:
{'field1': '23.10', 'field2': '48.70', 'entry_id': '18', 'created_at': '2017-09-10 09:21:43 UTC'}
{'field1': '23.10', 'field2': '48.30', 'entry_id': '19', 'created_at': '2017-09-10 10:20:35 UTC'}
{'field1': '23.00', 'field2': '48.50', 'entry_id': '20', 'created_at': '2017-09-10 11:19:29 UTC'}

I am trying to write this DictReader element into a csv file. The delimiter should be a \tand the output should look like this:
created_at    entry_id   field1    field2
2017-09-10 09:21:43 UTC    18   23.10   48.70
2017-09-10 10:20:35 UTC    19   23.10   48.70

I tried the following:
with open(Write_File, 'w') as csv_file:
    writer = csv.writer(csv_file,delimiter="\t", dialect="excel-tav")
    for row in reader:
        writer.writerow(row)

with no result and I tried to understand the DictWriter module but I'm not getting the desired output.
Comment: Are you trying to iterate over the reader after you printed it? Check that there's anything actually happening in your write loop - if you iterated over the reader once, there's nothing left to iterate over. And next time write a [MCVE] so it's easier for others to verify what your code does.
Comment: I actually tried to iterate of the reader after I printed it which I now know dos not work :-) This added to my confusion
Answer: Try to use a csv.DictWriter.
with open('output_file.csv', 'w', newline='') as csv_file:
    fieldnames = ['created_at', 'entry_id', 'field1', 'field2']
    writer = csv.DictWriter(csv_file, fieldnames, delimiter='\t')
    writer.writeheader()
    for row in reader:
        writer.writerow(row)

Comment: I got close to what you proposed but got the `writer=csv.DictWriter(csv_file...`part wrong... thanks

Convert csv.DictReader to CSV File


Obter informação guardada em um "attribute"

Question: No ORM que utilizo, as classes são mapeadas usando Attributes. Eu preciso recuperar o valor armazenado nos mesmos. Ex.:
[Table("CADASTRO_CLIENTE")]
public class Cliente
{
    [Property("Id")]
    public int Id { get; set; }
}

Exemplo de uso (fictício - é isso que eu preciso saber)
var nomeTabela = Cliente.GetTableName();
//nomeTabela seria "CADASTRO_CLIENTE"

Estou usando NHibernate com ActiveRecord.
Answer: Pode fazer o seguinte:
public static string GetTableName()
{
    TableAttribute myAttribute = (TableAttribute)Attribute.GetCustomAttribute(typeof(Cliente), typeof(TableAttribute));

    // versao pre C#6
    return myAttribute == null ? string.Empty: myAttribute.MyTableName;
    // ou entao
    // return myAttribute?.MyTableName ?? string.Empty;
}

(Veja aqui um exemplo no MSDN e veja aqui uma demonstração no dotNetFiddle).
Answer: Você pode usar o método GetCustomAttributes:
TableAttribute.GetCustomAttributes(typeof(Cliente), false).OfType<TableAttribute>().FirstOrDefault().Name;

Lembre-se de tratar as possíveis exceções.
Referência: Attribute.GetCustomAttributes Método
Comment: Boa! Muito obrigado.


can we show UIPopOver over UIWindow

Question: I'm working on application where I want show popover in
- (void)applicationWillEnterForeground:(UIApplication *)application

app delegate function but application throwing exception
"'NSInvalidArgumentException', reason: 'Popovers cannot be presented from a view which does not have a window.'".

I'm calling popOver like
[popOver presentPopoverFromRect:self.rootViewController.view.frame inView:self.rootViewController.view  permittedArrowDirections:0 animated:YES];

If I change code like
[popOver presentPopoverFromRect:self.rootViewController.view.frame inView:self.window  permittedArrowDirections:0 animated:YES];

the code work fine.
So is it right to show popOver in appdelegates window?
Answer: The view isn't presented yet.  That is why it doesn't have a window.  Try adding that code to the root view controller's viewDidAppear method.
Comment: Thanx peter actually there are many views in my app. I m not sure which view will be present at that time so is there any other solution to this problme.
Comment: yes peter it is working but i am not sure is it valid to show popOver like this.

can we show UIPopOver over UIWindow


Which external frameworks does Drupal use, if any?

Question: I'm looking for ways to prepare and ease a transition to Drupal.
My department is planning on completely rebuilding our custom CMS in Drupal. There are 4 members on the team, two programmers. I've been researching ways to ease the learning process, as only our manager is familiar with it and he's not a developer.
My question is this: Is it possible to integrate any of the specific technologies or practices that Drupal uses in generic PHP-based websites? For instance, Drupal 8 will use Twig.
Are there other technologies or plugin components that we can learn and use before we start the process of moving to Drupal?
Comment: Is it possible to integrate any of the specific technologies or practices that Drupal uses in generic PHP-based websites? It depends from what part of Drupal and from the web site. Are there other components that we can learn and use before we start the process of moving to Drupal? Drupal is peculiar in many parts; you need to learn them all, to master Drupal.
Comment: Welcome to Drupal Answers! The question is too broad for a Stack Exchange Q&A site. There are many details that are missing to make the question useful to future users too.
Comment: The following url will also be helpful for drupal 8 beginners.
https://www.drupal.org/getting-started-d8-bkg-prereq . It covers drupal 8 module development.
Comment: Some more research into the subject indicates that Drupal's components are largely unique to Drupal, so this question may not be able to receive the specific answers I was looking for.
Answer: Theme-wise there are a couple of very good base themes that make use of SASS/Compass (and therefore Ruby) such as

Omega, and
Zen

(I prefer Omega, having just discovered its power).
There are some good integration modules such as LDAP for single sign on, and loads of third party service integrations from paid services such as MailChimp.
But, when it comes to handling the database and rendering pages, the core system really shines.  I'd really recommend learning Drupal's database API because it does an excellent job of defusing potentially unsafe queries and is quite easy to use once you get the hang of it.
[edit] Another resource I keep going back to time and again is the form API.
Comment: If I've completely missed the mark, let me know.
Comment: The OP is interested in Drupal parts to use in a site created with PHP. ("Is it possible to integrate any of the specific technologies or practices that Drupal uses in generic PHP-based websites?") I guess the OP is planning to make a gradual transition to Drupal by starting with using parts of Drupal in the existing site.
Comment: @kiamlaluno. This is basically true. Mentioning things like SASS/Compass, Twig, etc. is what I'm looking for.


Insert into ... values ( FROM SELECT ... FROM ... )

Question: insert into tab3(a,b,c,d,e)
values ( 1,
         ( select  a
           from tab2
           left join tab1 ON tab1.a = tab2.a
           where tab2.b="x" ),
         'somting1',
         'somting2',
         'somting3');

the probelm is if the select return more then 1 row this function not working and i get error  "the result is more then 1 row"
i want if have more then 1 row in result of the select to insert all the row whit the select rutrun but also whit the cost varibel same my code
Comment: `left join` will have null for non matching results and you may expect to get more than one row. Provide some more info ex: table structures with data and expected result.
Answer: Besides from the fact that your join seems to have no use you can do
insert into tab3 (a,b,c,d,e)
select 1, tab2.a, 'somting1', 'somting2', 'somting3'
from tab2
left join tab1 ON tab1.a = tab2.a
where tab2.b = 'x'


How to get the searched text in v-client-table?

Question: I am trying to create a custom column filter in v-client-table.
https://codepen.io/pydev/pen/BaZKgpR
    options: {
      dateColumns: ['birth_date'],
      filterable: ['name','manufacturer', 'birth_date'],
      headings: {
        name: 'Name',
        birth_date: 'Birth Date',
        age: 'Age',
      },

I am trying to make some tweaks to the 'Name' column filter.

I tried to get the text entered in the 'Name' search field so that I can mimic a customFilter, but unable to find a way to get the searched text.

I am strictly looking to keep the search box in the column filter.

Thanks in advance.
Answer: The vue-tables component does not expose API to read the filter value. It dispatches vue-tables.filtered event but with just resulting items matching the query as the parameter. Query itself is not reachable. Here are the details
It is worth raising an issue to the author maybe, to extend this event with the query as well.
You can still hack the component, and use this event to know when the value of the input is changed like this (ready method). But it's obviously very hacky.
  ready: function() {
    // ... other things
    this.$on('vue-tables.filtered', function(event) {
      console.log(this.$el.querySelector('.VueTables__name-filter-wrapper input').value);
    });

  },


ARIMA with increasing variance

Question: my time series data looks like that:
I would like to use ARIMA model to forecast next steps in time series. Unfortunately because of increasing variance data is non-stationary.
Is there any way to transform my data to get rid of this variance?
In addition before training I normalised data. Is normalisation required by ARIMA model?
Comment: Try a variance stabilizing transform, like the log.
Comment: What  demetri said is fine. You could also try to model the process directly by saying possibly $y_t = \mu + \epsilon_t$ where the variance of  $\epsilon$ is say  (arch or garch ) or stochastic ( so SV model ). Just another possibility.
Answer: As Demetrios says, you could try transforming your data to stabilize the variance. The classical approach is to use a Box-Cox transformation. One special case of this is the log transform. Some software will estimate a Box-Cox transformation parameter $\lambda$ for you.
Alternatively, as mlofton says, you could consider modeling your variance directly using an ARCH or a GARCH model. Your data does look somewhat like a financial returns series to me, with an essentially constant mean. In finance, we are often most interested in modeling variances, not so much means, and ARCH/GARCH is custom-made for this.
Comment: in fact this is financial data. Thanks for great tip!

ARIMA with increasing variance


transform-origin doesnt apply in safari

Question: Why doesn't transform-origin doesn't work in Safari?
Here, how it should look (Chrome): https://i.stack.imgur.com/CDkNF.png
Here, how it looks in Safari: https://i.stack.imgur.com/3Zh1O.png
I already tried some stuff with percents but it my content divs are having different sizes, so it looks awkward.
Here's the JSFiddle. http://jsfiddle.net/2f4pferq/
text-align: right;
    -ms-transform: rotate(-90deg);
    -ms-transform-origin: right top;
    -webkit-transform: rotate(-90deg);
    -webkit-transform-origin: right top;
    transform: rotate(-90deg);
    transform-origin: right top;
Here's the code:

.verticaltext {
    position: absolute;
    top: 10px;
    left: 25px;
    transform: translateX(-100%);
    text-transform: uppercase;
}

.verticaltext_content {
    text-align: right;
    -ms-transform: rotate(-90deg);
    -ms-transform-origin: right top;
    -webkit-transform: rotate(-90deg);
    -webkit-transform-origin: right top;
    transform: rotate(-90deg);
    transform-origin: right top;
}

.content {
    background-color: #000;
    color: #FFF;
    margin-bottom: 25px;
    padding: 25px;
    width: 100%;
    min-height: 200px;
}

.content p {
    margin: 0px 0px 0px 30px;
}

.content ul {
    list-style-type: none;
    margin: 0;
    padding: 0;
}

.content a,
.content a:link,
.content a:visited {
    color: #FFF;
    -webkit-transition: all 0.2s ease-in-out;
    -moz-transition: all 0.2s ease-in-out;
    -o-transition: all 0.2s ease-in-out;
    transition: all 0.2s ease-in-out;
}

.content a:hover {
    color: #FFA500;
    -webkit-transition: all 0.2s ease-in-out;
    -moz-transition: all 0.2s ease-in-out;
    -o-transition: all 0.2s ease-in-out;
    transition: all 0.2s ease-in-out;
    text-decoration: none;
}

.content i.fa {
    color: #FFF;
    width: 15%;
}

.content i.fa:hover {
    color: #FFA500;
}

Diskografie

 Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet.

Comment: Instead of pasting your code make a jsfiddle please.
Comment: http://jsfiddle.net/2f4pferq/ @Ace
Answer: Your not vendor prefixing for the .verticaltext on your transform
.verticaltext {
  position: absolute;
  top: 10px;
  left: 25px;
  transform: translateX(-100%);
  text-transform: uppercase;
}

Should be
.verticaltext {
  position: absolute;
  top: 10px;
  left: 25px;
  -webkit-transform: translateX(-100%);
  -ms-transform: translateX(-100%);
  transform: translateX(-100%);
  text-transform: uppercase;
}

transform-origin doesnt apply in safari


Good architecture/approach for encoding text

Question: I want to create a model that efficiently encodes text for retrieving images that match the description given in the text.
I have extracted features of images through VGG19 model(4096 features for each image). I want to create a text encoder that extracts the features of text (4096 features) and then I want to use a metric like cosine similarity so that I retrieve images that match textual description given.
For training the text encoder I have created a loss function that penalizes it for creating encoding that is different from vgg19 encoding using mean squared error.
1.Is my approach alright?
2.flickr8k is the dataset. Should I have an even bigger dataset. Although i do not have much computation power.
3.Is there a pre-trained model that I should use or should I go with a new text encoder?
Answer:
1.Is my approach alright?

The more usual approach would be to train some kind of text-to-image model, though the idea of using pre-trained image embeddings and text embeddings is interesting and a very practical approach.
The part that I find troublesome is that you want to train a text encoder to produce the same embeddings as the ones created by an image encoder. If you think about it, the representation of an image and the representation of a sentence are likely completely different things. Images have colors, spatial features, edges, etc, while sentences have parts of speech, words, and their relations. Even the human brain has different regions for processing language and visual stimuli. This may be hard to achieve. Maybe it would be easier if you had a single model that tries encoding images and text at the same time with the constraint that the learned representations need to be the same, in such a case you would be forcing both representations (for text and images) to be alike, rather than forcing one of them to pretend to be the another.
Alternatively, you could use two pre-trained models to create representations of images and text and train a model that would make a decision if the two representations are alike or not. It sounds like a simpler problem. You could use something like triplet loss to train it. Such a model could be simpler to train since instead of predicting 4096 targets, it would need to return just a single similarity score, e.g. probability that the representations are the same. Moreover, with such models, there is no need for the dimensions of both representations to be the same.
Finally, you could go through the literature on GAN models that have the generator and discriminator components, since they seem to be trying to solve a similar problem.

2.flickr8k is the dataset. Should I have an even bigger dataset. Although i do not have much computation power.

If I understand correctly, flickr8k dataset has 8000 samples. You want to train a model with 4096 features, so two samples per target. This sounds way too little. My guess is that you would need at least something like 100x more samples. All the deep learning models are very data-hungry, that's certainly the case for the image and text models.

3.Is there a pre-trained model that I should use or should I go with a new text encoder?

If you stick to the idea of using pre-trained models for representing both images and text, you can use any NLP model. TensorFlow, Pytorch, HuggingFace, and lots of other software enable you to use such models.


Historical Development of PDEs

Question: I would be really thankful if someone could tell me good references giving development of techniques of Solving PDEs why such equations are important.
Regards,
Harish
Answer: Here is a pretty detailed history of PDEs in the 20th century. The first few chapters give a nice early history and early applications of the subject without going into much mathematical detail and the subsequent chapters will give a fairly thorough history of its development.
http://www.math.ualberta.ca/~fazly/files/HistoryPDE.pdf
Edit: it seems that the previous link is now dead. Here is different excellent survey article on the modern development of PDEs: https://math.berkeley.edu/~evans/evans_pcam.pdf

Historical Development of PDEs


BayesA, BayesB, etc

Question: I would like to get a plain English explanation of BayesA, BayesB.  I found that a lot in bioinformatic literature but found nothing in Wikipedia, etc.
Comment: Are you referring to these definitions for BayesA and BayesB, from Meuwissen, Hayes, and Goddard (2001):  http://www.genetics.org/content/157/4/1819.long
Comment: Yes that's the context.  I just got lost in those math notations/semantic.  If there's a "hello world" example, it would be super helpful.
Answer: Long story short, BayesA is a mixed model that assumes that each marker is a random effect, whereas snpBLUP assumes that all markers make a single random effect. They call it BayesA because it is solved via MCMC because REML takes too long.
Then, BayesB is the same thing but it has a variable selection - which means that the model can assign zero effect to a markers. Since it runs through MCMC, it will never be a true zero but something very close to it.
You can check this to get the ABC of how these models are solved http://rd.springer.com/article/10.1007/s00122-016-2750-y

BayesA, BayesB, etc


Why DID estimator is ATT?

Question: A generalized DID has the equation as below
$Y_{it}$ = $\alpha$ + $\beta$ $(Leniency Law)_{kt}$ + $\delta$$X_{ikt}$ + $\theta$$_t$ + $\gamma$$_i$ +$\epsilon$$_{it}$
where i,k, and t index firms, countries, and years respectively. $X_{ikt}$ is a vector of the different firm, country, and industry control, while $\gamma$ and $\theta$ are firm and year fixed effects.
From this answer of Ariel,

$\beta$ is the average difference between pre- and post for the
treated population. Because the ATT is the effect on the treated
population of the intervention. Remember, DID is using the common
trends assumption to try to tell us what would have happened to the
treated population had they not been treated. It then compares the
realized treated outcomes to the predicted untreated counterfactual

I am wondering if $\beta$ is ATT, meaning that we did not mention control group in our explanation, so if we did not mention, why we include the control group into our regression?
Answer: The two-period DID is typically taken to estimate the ATT. This can easily be seen by doing out the expectations. Consider the specification at the unit $i$ level,
$$Y_i = \alpha + \gamma G_i + \theta T_i + \beta D_i + \epsilon_i$$
Here we use $G_i\in\{0,1\}$ to denote the group and $T_i \in \{0,1\}$ to denote the period. And $D_i = G_iT_i$ denotes treatment status.
Then to extract the treatment effect $\beta$ (and determine what it is) we will look at the potential outcomes when the group and period indicators are switched on. We have the potential outcome for the control as,
$$\mathbb{E}[Y_i(0)|G_i=1,T_i=1]=\alpha + \gamma + \theta$$
And for treated,
$$\mathbb{E}[Y_i(1)|G_i=1,T_i=1]=\mathbb{E}[Y_i(0)|G_i=1,T_i=1]+\beta$$
So we have,
$$\beta = \mathbb{E}[Y_i(1)-Y_i(0)|G_i=1,T_i=1]=\mathbb{E}[Y_i(1)-Y_i(0)|D_i=1]=ATT$$
In the case of a generalized DID estimator where there are multiple periods and multiple groups whose treatment status can be switched on at different times the answer is more complicated. As I wrote in this answer the generalized DID can always be broken down into a weighted average of two-period DIDs. Each of these will exhibit an ATT. But overall, you will have estimated an average of ATTs. The exact interpretation of this is a little bit uncertain. Under a constant treatment assumption (which is very strong) this will indeed be the ATT. However, usually, that is not the case.
Goodman-Bacon (2018) provides a little more study of how to interpret this. See section 2 of the attached paper.

Why DID estimator is ATT?


Random effects model for meta-analysis of rare events

Question: The Cochrane Handbook states that

incorporation of heterogeneity into an estimate of a treatment effect
should be a secondary consideration when attempting to produce
estimates of effects from sparse data

This has for example motivated authors of this meta-analysis to use a fixed effects model for their analysis, because their events of interest were rare.
In general, to what extent should this recommendation be followed? If I have data from studies that I have very good reasons to think that they are heterogeneous, but that report very rare events, what type of model should I use?
Answer: There is an updated version of 'the Handbook' with a more detailed explanation (https://training.cochrane.org/handbook/current/chapter-10#section-10-4-4-3). What they're saying that the RE models in Revman can be biased and therefore to use a Peto-OR (FE model) for rare events (<1%). Others (https://pubmed.ncbi.nlm.nih.gov/18562399/) have shown that approximate/ asymptotic methods in general are biased and exact methods are more precise for dealing with meta-analysis of rare events.
Regarding FE vs. RE in general, this Q & A might provide some additional insight (Reporting results of fixed effect MA alongside results of random effects MA). In summary, the choice of FE or RE should be an a priori decision (when both are valid options - not particularly in this case).


There are 39 students in our class. We form groups of 2, with one left out. How many ways can the students be paired up?

Question: I know that the answer is $\frac{39!}{(2!)^{19}\cdot19!}$, where each pair can be organized $2!$ ways and the pairs can be arranged in $19!$ ways. We can also extrapolate the case for $5$ students, where I see that there are $15$ possible subsets ($\frac{5!}{2!^2\cdot2!}$).
What I don't understand is why we don't account for where the single student can be placed in our solution. There are $19!$ ways to organize the pairs, but aren't there $20!$ ways to arrange the pairs and the one extra student?
Comment: Once you have picked all the pairs, the left out person is determined, there is no more arranging to do.
Comment: Or else you can decide the lonesome student can be chosen in $39$ ways. For each of these ways we need to divide the remaining $38$ into pairs. You may know this can be done in $\frac{38!}{2^{19}(19!)}$ ways.
Answer: Consider this alternate process:
First, arrange the students in some arbitrary order:  age, weight, IQ, whatever...
Now take a set of 39 cards.  Two are labelled "Group #1", two are labelled "Group #2", and so on, up to "Group #19".  The last, 39th card is labelled "On Your Own".  (Note we're now accounting for the lone student).  You are going to shuffle the cards, and then distribute them one by one, off the top, to the students in their arbitrary order.
How many distinct ways can you arrange 39 items, when there are 19 identical pairs and one item distinct from all the others?


Proper Weighted Average

Question: If I have a 3x3 matrix of information where the row totals describe the total goods produced by a particular company and the column totals provide the total for a particular type of good for all companies how would I create a weighted average that tells me the average percentage Good A takes up, out of all production, for all companies?  Is it necessary to weigh by company if the total number of products produced is, say, 10, 50, and 20?  I imagine the variation makes it necessary, right?
Answer: Yes, you will need to weight by total production. The reason being consistency: Imagine you are only told that the total production of each company. Then the total amount of A produced must equal the average fraction of A produced times the total production, which is equivalent to the average fraction of a per company.

Proper Weighted Average


How can I run a Python File in a Django Environment using Crontab?

Question: I'm trying to make a Crontab job that will run a Python script once everyday at 4AM.
Here is my crontab line
0 4 * * * cron_scripts/scripttorun.py

The file is being linked correctly, and it's attempting to execute it. However, when it tries to execute the file it gives me some errors based on my imports.
Here is the part of my python file that causes the crash, it crashes on the first line because it's not importing the file correctly for some reason...
from history.models import Model1
from users.models import User

I am trying to run the Python File with some other code from my web server, that uses Django.
Do I have to do something extra in order to be able to import my models?
I get the same result when I run python scripttorun.py.
Comment: What's the specific error you're getting?
Answer: In Django you can write custom django-admin commands. Just check this: https://docs.djangoproject.com/en/dev/howto/custom-management-commands/
Then you include in the crontab file: 0 4 * * * python /path/to/myapp/manage.py scriptorun.py
Comment: Definitely this. Just make a management command and run that instead of your own script. Take it from someone who spent a lot of time bashing his head against this very wall - this works and it's quick.
Answer: My personal suggestion here is to create a new command in app/management/commands/yourcommand.py
from django.core.management.base import BaseCommand, CommandError

class Command(BaseCommand):
    help = "Might wanna add a help text"
    args = '<arg>' # need args?

    def handle(self, *args, **options):
        # Do whatever you want to do

Then run that from your crontab.
/path/to/python /path/to/manage.py name_of_command

Answer: You can also do it like this:
do_something.py
#! /usr/bin/python
#coding:utf-8
from __future__ import unicode_literals

import os
os.environ["DJANGO_SETTINGS_MODULE"] = "prj.settings"

from app.models import YourModel

# do something

put the file the same place with manage.py
How to use, you can write a .sh script
cd pjc-directory
python do_something.py

then run this script with crontab
Answer: You should take a loot at the runscript command from Django-extensions
It let you create easy Django management command, with all the django environnement in it.
Then you can set a cron to execute the task periodically.

Django Extensions provide other useful tools for your Django project, take a look at it.


How to test that your missing data is completely at random (MCAR)

Question: I am doing a secondary analysis of data from a local trial (N=450, mean follow-up longer than 10 years). I am specifically looking at a secondary outcome (diagnosis of hypertension) after 10 years from the start of the trial.
My problem is that the trial itself only lasted 2 years and, for my analysis (which is using a 10-year follow-up time), I have complete data only on approximately 50% of the sample (i.e. there are no clinical records for 50% of the original sample due to various reasons such as drop-off, death, etc). Considering the high proportion of missing data (without even testing the MAR assumption), I am not considering the multiple imputation as an option. Therefore, the two possibilities that seem worth exploring are i) still run the analysis using complete-case analysis ii) applying the inverse probability weighting.
Because I suspect that the lost at follow-up has no systematic reason (the trial was about the use of a coenzyme which hardly might be associated to the likelihood of dropping off) I would be inclined to analyse the data with complete-case analysis.
What I initially did was to test differences in the distribution of study covariates between the population with data at follow-up and the population with missing data. I found no difference between the two populations.
I came across this approach in old papers but I am not sure this is robust enough (also, I remember I have read these papers but cannot find them now for a closer look at the issue). Also, I am not sure whether the comparison should have been conducted the way I did (population with complete data vs population with missing data) or should have been between the initial population and the population with complete data - under the assumption that the population with complete data is still representative. Can you help me clarifying this?
However, I suspect this approach is not sufficient. I read about the Little test (which doesn't seem to be used much anyway as it is not a gold standard), but I also read that you can test this assumption by creating dummy variables for missing data and employing probit/logistic regression models using each covariate at time as independent variable. However, I am not sure I understood it correctly as I could not find a practical example.
Any help would be appreciated. Also, references would be very welcome.
Thanks
Comment: What do you mean "you have complete data on 50% of the population" (you mean sample not population). Do you mean only 50% were actually diagnosed with hypertension or...?
Comment: Hi. Thank you for your answer. I edited the question accordingly.
What I meant is that because it is a secondary analysis using a much longer follow-up than the one defined by design with the original trial, I don't have data on approximately 50% of the sample. This is because time from the beginning of the study is more than 10 years.
Answer: The approach you outline towards the end of your question is often done in practice. You create an indicator variable for missing (yes/no) and then do logistic regression to see whether anything predicts missingness. You then include any variables which do predict missingness in your final model even if they are not otherwise of scientific or clinical interest. Doing comparisons the way you did will probably lead to the same conclusion but a multiple logistic regression is preferable as it allows for the covariates together rather than one by one.


Problems calling child constructor using C# in XNA

Question: I have a two classes, and one inherits from the other.

Partition
class Partition
{
    protected Vector3 midpoint
    protected float radius

    public Partition(Vector3 midpoint, float radius)
    {
        this.midpoint = midpoint;
        this.radius = radius;
    }
}

PartitionSegment
class PartitionSegment : Partition
{
    protected Vector3 midpoint
    protected float radius

    public PartitionSegment(Vector3 midpoint, float radius)
    {
        this.midpoint = midpoint;
        this.radius = radius;
    }
}

I am being flagged for an error in PartitionSegment, for its constructor.

PartitionJunction.PartitionJunction(Vector3 midPoint, float radius)
There is no argument given that corresponds to the required parameter 'midPoint' of 'Partition.Partition(Vector3, float)'

What am I doing wrong?
Comment: You aren't calling the base class constructor.
Comment: Why does the child class duplicate the fields of the parent?
Comment: Either could be directly called to set up an element, and coordinates are required to determine position in the game world, for sorting.
Comment: _PartitionSegment_ is already inheriting _midpoint_ and _radius_ from _Partition_. You should have warnings telling you that those members are being hidden.
Answer: Remembering my old days developing C#, don't you have to write ? :
public PartitionSegment(Vector3 midpoint, float radius) : base(midpoint, radius)
{ }

Comment: A simple solution. It appears my issue is an unfamiliarity with the base() function, but I think that's another question for another time.
Answer: You can use the base constructor.
public PartitionSegment(Vector3 midpoint, float radius) : base(midpoint, radius)
{
    //additional relevant code
}

Answer: giving your partition base class a parameter less default constructor would also get rid of your error message.
Comment: It certainly would, but in this application, both need to handle the parameters.


Tabela com Quebra de página sobrescrevendo elemento fixo

Question: Tenho um script de um sistema legado que cria uma tabela com os dados vindo do banco em php. O  script foi desenvolvido pra armazenar tudo numa tag $html e no final dar um echo.
Ao final desse script existe um elemento rodapé com lugar para o funcionário assinar. Cliente pediu pra que esse rodapé ficasse no final de toda página que for impressa.
Até aí tudo bem. Coloquei a div com o css abaixo:
div.footer {
    position: fixed;
    bottom: 0;
}

e a tabela com a seguinte configuração pra quebra de página se a "linha" ultrapassar o final da página:
table { page-break-inside:auto; margin-bottom: 10px; }
tr    { page-break-inside:avoid; page-break-after:auto; }
thead { display:table-header-group }
tfoot { display:table-footer-group }

Tudo funciona de forma bacana a não ser pelo fato de o elemento rodapé sobrescrever a última linha da tabela em certas páginas onde a tabela pega toda a altura da página.
Teria alguma forma evitar isso? Tentei algumas formas com javascript e css mas como o número de elementos rodapé é um só, mesmo ele sendo impresso em 3, 4, 5 páginas, ainda não consegui.

        ...

        Assinatura: _______________________________________________
Por ser verdade, assino e dou fé ao presente documento

Comment: Cara acho que posso ter uma solução para vc, mas edite sua pergunta coloque codígo suficiente para que possa pelo menos simular o problema que vc está tendo ai, sem isso não da para te ajudar muito
Comment: @hugocsl ok. Basicamente é isso que editei. A tabela é criada dinamicamente no looping dos dados do banco. Fora desse looping tá o rodapé que coloquei fixo na hora de imprimir pra sair em todas as folhas.
Comment: Publiquei uma solução ao que vc pode ajustar os valores para ficar mais perto do que vc precisa
Answer: Cara tenho uma solução para vc, não é uma solução totalmente perfeita, mas vai resolver o problema. vc precisa que a altura da TD seja maior que a altura da div Footer, apenas isso.
Eu tb fiz essa regra CSS para mostra o footer só quando for impressão, mas vc pode tratar isso depois, conforme achar melhor.
div.footer {
    display: none;
}

@media print {
    div.footer {
        display: block;
        position: fixed;
        bottom: 0px;
        height: 45px;
    }
}

Então vc precisa declarar na mão um height para as TD, tipo 60px, e a div footer que que ter no máximo uns 45px, dessa forma, a última TD da página sempre vai "quebrar" para próxima página quando não tiver espaço para ela, deixando assim um espaço de aproximadamente 59px, justamente o espaço suficiente para caber o footer que tem 45px de altura entende :)

table {
    page-break-inside: auto;
}

tr {
    page-break-inside: avoid;
    page-break-after: auto;
}

thead {
    display: table-header-group
}

th,
td,
div {
    border: 1px solid #000;
}

th,
td {
    height: 60px;
}

div.footer {
display: none;
}

@media print {
div.footer {
    display: block;
    position: fixed;
    bottom: 0px;
    height: 45px;
}
}

                th

                td

                td

                td

                td

                td

                td

                td

                td

                td

                td

                td

                td

                td

                td

                td

                td

                td

                td

                td

                td

                td

                td

                td

                td

                td

                td

                td

                td

                td

                td

                td

                td

                td

                td

                td

                td

                td

                td

                td

                td

                td

                td

                td

                td

                td

                td

                td

    Assinatura: _______________________________________________
Por ser verdade, assino e dou fé ao presente documento

Comment: Não deu muito certo cara. Os `td` tem alturas variáveis conforme o número de dados. Até apliquei a altura fixa somente nos `td` de dentro, abaixo do cabeçalho pra não mexer com o resto. O `@media` eu especifiquei na abertura do `
Comment: @A52 cara nesse caso não vou conseguir te ajudar muito


$\sum_{k=0}^{n} a_{k}=\sum_{k=0}^{\lfloor n/2 \rfloor} a_{2k} +\sum_{k=0}^{\lfloor (n-1)/2 \rfloor}a_{2k+1}$

Question:
I would like to show that
  \begin{align}
\sum_{k=0}^{n} a_{k}&=\sum_{k=0}^{\lfloor n/2 \rfloor} a_{2k} +
  \sum_{k=0}^{\lfloor (n-1)/2 \rfloor}a_{2k+1}\\
\end{align}

I'm interested in more ways of prove it

My proof.
\begin{align}
\sum_{k=0}^{n} a_{k}&=\sum_{\substack{k=0 \\ k \text{ is even }}}^{n} a_{k}+\sum_{\substack{k=0 \\ k \text{ is odd }}}^{n} a_{k}\\
&=\sum_{\substack{k=0 \\ k=2k' \text{ with } k'\in\mathbb{Z}}}^{n} a_{k}+\sum_{\substack{k=0 \\ k=2k'+1 \text{ with } k'\in\mathbb{Z}}}^{n} a_{k}\\
&=\sum_{\substack{k=0 \\ k'=\frac{k}{2} }}^{n} a_{2k'}+\sum_{\substack{k=0 \\ k'=\frac{k-1}{2} }}^{n} a_{2k'+1}\\
&=\sum_{\substack{k=0 \\ k'=\frac{k}{2}\\ k=0 \implies k'=0 \\ k=n \implies k'=\frac{n}{2}}}^{n} a_{2k'}+\sum_{\substack{k=0 \\ k'=\frac{k-1}{2}\\ \text{since k is odd can start with 1 and not 0 } k=1 \implies k'=0 \\ k=n \implies k'=\dfrac{n-1}{2}  }}^{n} a_{2k'+1}\\
&=\sum_{k'=0}^{ n/2 } a_{2k'} +
  \sum_{k'=0}^{ (n-1)/2 }a_{2k'+1}\\
&\text{If $n$ is even, then $\frac{(n−1)}{2}$ is not an integer, which is why we  need the floor.}\\
&\text{Similarly, if $n$ is odd, then $\frac{n}{2}$ is not an integer}\\
\sum_{k=0}^{n} a_{k}&=\sum_{k=0}^{\lfloor n/2 \rfloor} a_{2k} +
  \sum_{k=0}^{\lfloor (n-1)/2 \rfloor}a_{2k+1}
\end{align}

Is my proof correct
I'm interested in more ways of prove it
Comment: If $n$ is even, then $(n-1)/2$ is not an integer, which is why you need the floor. Similarly, if $n$ is odd, then $n/2$ is not an integer.
Comment: well, shoot.  Yes, your idea is correct and what you are trying to express is clear.  I'm not sure your notation of indexing is  technically legitimate however.  Normally one really shouldn't get bogged do in details like that.  However in this case what you are trying to prove is simply "The sum of all terms is the sum of the even terms plus the sum of the odd terms" (which is obvious) and your proof is verifying that the reindexing is valid.
Comment: so that you don't have to worry that: even number may take odd value and vice versa
Comment: also, a small typo in the first line of your proof: in the second summation, $k$ should start from 1 instead of 0.
Comment: @HowDoIMath yes i see that's why i have to add floor thanks. what about my proof
Comment: Okay, where you say "with k' $\in$ Z", I, personally would say "for some k' $\in$ Z".  It's a *minor* point, but "with k" implies (to me at least) that you are trying to us *all* integers rather than just the ones were 2k' (or 2k' + 1) are between 0 and n.
Comment: @fleablood  would please post version of solution with notation of indexing is technically legitimate.
Answer: $\sum_{k=0}^{\lfloor n/2 \rfloor} a_{2k}= \sum_{i=0; i\ is\  even}^{2\lfloor n/2 \rfloor} a_{i} = \sum_{i=0; i\ is\  even}^{n} a_{i} = \sum_{k=0; k\ is\  even}^{n} a_{k}$
$\sum_{k=0}^{\lfloor (n-1)/2 \rfloor} a_{2k + 1}= \sum_{i=0; i\ is\  odd}^{2\lfloor (n-1)/2 \rfloor + 1} a_{i} = \sum_{i=0; i\ is\  odd}^{n} a_{i}= \sum_{k=0; k\ is\  odd}^{n} a_{k}$
$\sum_{k=0}^n a_n = \sum_{k=0; k\ is\  even}^{n} a_{k} + \sum_{k=0; k\ is\  odd}^{n} a_{k} = \sum_{k=0}^{\lfloor n/2 \rfloor} a_{2k} + \sum_{k=0}^{\lfloor (n-1)/2 \rfloor} a_{2k + 1}$
Comment: i think in the second line $i=1$ not $0$ since $i=2k+1$
Answer: If $n$ is odd, i.e. $n=2m+1$,
then $k=0, 1, 2, 3, ..., 2m+1=\underbrace{(0, 2, 4, 6, .., \color{blue}{2m})}_{\underset{k=0, 1, ..., \lfloor n/2\rfloor}{2k}},(\underbrace{1, 3, 5, ..., 2m-1, \color{red}{2m+1}}_{\underset{k=0, 1, ..., \lfloor (n-1)/2\rfloor}{ 2k+1}})$
as
$$\begin{align}
&2\bigg\lfloor \frac n2 \bigg\rfloor&&=2\bigg\lfloor \frac {2m+1}2\bigg\rfloor&&=2\bigg\lfloor m+\frac 12 \bigg\rfloor&&=\color{blue}{2m}\\
&2\bigg\lfloor \frac {n-1}2 \bigg\rfloor+1&&=2\bigg\lfloor\frac{2m}2\bigg\rfloor+1&&&&=\color{red}{2m+1}\end{align}$$
If $n$ is even, i.e. $n=2m$,
then
$k=0, 1, 2, 3, ..., 2m=\underbrace{(0, 2, 4, 6, .., \color{green}{2m})}_{\underset{k=0, 1, ..., \lfloor n/2\rfloor}{2k}},(\underbrace{1, 3, 5, ..., \color{orange}{2m-1}}_{\underset{k=0, 1, ..., \lfloor (n-1)/2\rfloor}{ 2k+1}})$
as
$$\begin{align}
&2\bigg\lfloor \frac n2 \bigg\rfloor&&=2\bigg\lfloor \frac {2m}2\bigg\rfloor&&=\color{green}{2m}\\
&2\bigg\lfloor \frac {n-1}2 \bigg\rfloor+1&&=2\bigg\lfloor\frac{2m-1}2\bigg\rfloor+1=2\underbrace{\bigg\lfloor m-\frac12\bigg\rfloor}_{m-1}+1=2(m-1)+1&&=\color{orange}{2m-1}\end{align}$$
Hence the formula
$$\sum_{k=0}^{n} a_{k}=\sum_{k=0}^{\lfloor n/2 \rfloor} a_{2k} +
  \sum_{k=0}^{\lfloor (n-1)/2 \rfloor}a_{2k+1}\\$$
holds irrespective of whether $n$ is odd or even.


Having issue in adding values to django/python dictionary

Question: officials = {}
name = ['My Name','You Name']
job_title = ('Director','Programmer',)

for i in range(len(job_title)):
officilas[job_title[i]] = name[i]
or officials.update({job_title[i]:name[i]})

Results u'{'Director': ['M','y','N','a','m','e'],'Programmer':   ['Y','o','u','r','N','a','m','e']}'
Desired Result u'{'Director':'My Name','Programmer':'Your Name'}'
What am I doing wrong?
Models
class SuffixName(models.Model):
suffix_name_desc = models.CharField('Suffix Name', max_length=20,unique=True)
active = models.BooleanField('Active',default=True)

class Person(models.Model):
GENDER = (
('M','Male'),
('F','Female'),
)
first_name = models.CharField("First Name", max_length=100)
last_name = models.CharField("Last Name",max_length=100)
middle_name = models.CharField("Middle Name", max_length=100, blank=True)
salutation = models.ForeignKey(Salutation, verbose_name="Salutation", null=True, blank=True) #
suffix_name = models.ManyToManyField(SuffixName, verbose_name="Suffix Name",null=True, blank=True) #
job_title = models.ManyToManyField(JobTitle, verbose_name="Job Title",null=True, blank=True) #
gender = models.CharField(max_length=1, choices=GENDER)

Code:
officials = {}
job_title = (
'Director',
'Programmer',
)
per = Person.objects
lst =[]
con = []
fullname =[]
complete_lst = []
con.append(per.values_list())
ctr = 0
for i in range(len(job_title)):
    spec = per.filter(job_title__job_title_desc=job_title[i]).values_list('suffix_name__suffix_name_desc', flat=True)
    if len(spec) != 0:
        ctr += 1
        temp_fullname = con[0][i][2] + ' ' + con[0][i][3] + ' ' + con[0][i][1]
        fullname.append(temp_fullname))
        lst.append(spec)

for ii in range(0,ctr):
    temp_spec = [', '.join(x for x in lst[ii])]
    temp_spec1 = temp_spec[0]
    temp_name = str(fullname[ii])
    temp_complete_lst =  temp_name + ', ' + temp_spec1
    officials[job_title[ii]] = temp_complete_lst

Answer: You can do this:
name = ['My Name','You Name']
job_title = ('Director','Programmer',)
officials = dict(zip(job_title, name))
print officials
>>> {'Programmer': 'You Name', 'Director': 'My Name'}


Survival estimation with left-truncated data

Question: I have some difficulties understanding the effect of the truncated data on my estimation of survival function.
I am studying the survival for some "dependent" people (policyholder with Long Term Care contracts). I want to study how long they survive based on their age at entry (because the survival function is different by age at entry into dependency state).
I have a database of 15 years where I can observe entries and exit from dependency (for death or other type of event). I also have some people that are already dependent at the start of the study.
I've set this start of study to 01/01/2000 because data before are not reliable and where death event and censorship are melted. However, I want to keep the information provided by already dependent policyholder at 01/01/2000 especially that I have their real entry date into dependency state.
I choose to look at their survival starting from 0. It's easy to understand what happen with all new dependent within our observation period. Starting from 0, we can observe them until they left the study (death or other).
However, I'm wondering how the already dependent people at begining will influence my risk set (or exposure). Do I have to consider these people at the begining (starting time spent of 0) or as entering the risk set with a time spent in the dependency state corresponding to their real time spent (as I know the entry date even before 01/01/2000).
In the first case, I would include them in the exposure at the begining of the study, while in the latter case, the exposure will be the sum of all new dependent people entering within the observation period, and then having the exposure variating when we reach time spent by the policyholder (calculated at the begining of the study).
Let me know if it's not clear and sorry if english is approximate
thank you for your help
Actaman
Answer: Your population is 'policy holders in our database from 01/01/2000 or after' but that is not a start date for your study.  You are looking at survival after a determination of a dependent condition. This is the known start of duration for each study subject.  So since you know this date of determination for subjects prior to 01/01/2000, I would keep them in the study. Since survival analysis permits rolling entry, there is no left censoring.
However, because death data from before 01/01/2000 is excluded, people with policies on 01/01/2000 might be biased to live longer in a dependent condition.  For example someone that bought a policy on 01/01/1990 and becomes dependent on 01/01/1998 and dies on 01/01/1999 will be excluded from the study.  I would create a dummy variable called 'pre-2000' and enter that in the model along with age.
Comment: Thanks for your answer. It's exactly my problem, as I exclude some of the policies but keep others, I think that it creates an overestimation of survival as I keep only persons who survived after 01/01/2000 (my database start in reality at 01/01/1995).
I'm wondering if there is any solution to avoid bias whithout the "easy" solution of excluding all these policyholders
Comment: If I understand well, you propose to add the variable pre-2000 to identify such policies. To do that, I have to use a Cox regression for example to estimate the survival function ?
What if, I want to use a non parametric estimation as of Kaplan-Meier, how these policies influences my risk set and at what moment ?
Comment: Is it what we call delayed entries ?
If so, and if we consider time spent as our variable of interest (studying the duration between time already spent at entry and exit time, using age at entry and age at leaving), can it be done by including these policyholder wihtin the risk set at time T only when their time already spent at entry is greater than the time T while other complete observation enter at time spent = 0.
Comment: Since you have one continuous covariate, you need to use proportional hazards or some other type of regression. I would be more concerned about external changes over the 15 years such as new medications and definition changes in dependency status than biases from the earlier subjects.  I don't understand your definition of delayed entry.


What's the time signature for "Son of Flynn" and "Recognizer" in the TRON: Legacy Soundtrack by Daft Punk?

Question: What's the time signature for "Son of Flynn" and "Recognizer" in the TRON: Legacy Soundtrack by Daft Punk?
It seems to me that "Son of Flynn" is clearly in a mixed meter: 3/8 and 5/8 -- but I'm not sure. "Recognizer" has a common theme and meter with the strings as in "Son of Flynn" that suggests 3/8 and 5/8 mixed meter, but the emphasis on these beats is less than in "Son of Flynn". At 1:48 in "Recognizer", the pace/rhythm changes. The brass and woodwinds seems to go with a 4/4 time signature.
What's going on here with these two tracks in terms of the time signature?
Answer: Recognizer seems to be 4/4 throughout.
The fast notes in Son of Flynn are in groups of 6+6+4=16 so they can be viewed as 16th notes in a 4/4 bar; this isn't the only way to think about it though.


A pair of dice is rolled repeatedly until it turns up doubles for the 9th time.

Question:
A pair of dice is rolled repeatedly until it turns up doubles for the 9th time.
a) Write the probability mass function for the number of rolls until this happens.
b) What is the probability it will take exactly 50 rolls (rounded to the nearest percent)?

I have tried: <code>(nC9)(5/6)^n-9(1/6)^9</code>
$$^n\mathsf C_9{(\tfrac 56)}^{n-9}{(\tfrac 16)}^9$$
Comment: (nC9)(5/6)^n-9(1/6)^9
Comment: Edit the original post, @AKhan (As I have done for you)
Comment: appreciate it thanks
Answer: Probability of a success (double) is ${6\over 36} = {1\over 6}$
Number of trials until 9 successes is a Negative Binomial random variable with parameters $r=9$ and $p=\frac{1}{6}$
$P(X=n)={n-1\choose r-1}p^r(1-p)^{n-r}$ for $n=r,r+1...$
So for this case:
$P(X=n)={n-1\choose 8}\left(\frac{1}{6}\right)^9\left(\frac{5}{6}\right)^{n-9}$ for $n=9,10,11...$
$P(X=50)={49\choose 8}\left(\frac{1}{6}\right)^9\left(\frac{5}{6}\right)^{41}\approx 3\%$
Comment: very helpful thank you!


Visual Studio 2022: 'Add property' refactoring stopped working

Question: in the past I've gotten a lot of mileage out of writing a property as if it exists, and then using the refactoring option to add the property automatically. This has recently stopped working for me in VS2022:

Placing the caret on any of missing properties and pressing Ctrl+. used to give the option to generate the property from name and context, but now it doesn't work.
How can I restore this option? I've already tried resetting all options to default.
Answer: I had this issue and had to turn off all my extensions until I found the one that broke this.


If A ⊥ B | C and A ⊥ C | B, is A ⊥ B and A ⊥ C?

Question: I'm doing some homework for self-study in probalistic graphical models, and this question has me stumped.
I'm pretty sure the answer is no. But I don't know how to prove it.
So far, I have:
<code>(1) A ⊥ B | C ==> P(A, B | C) = P(A | C) P(B | C)
(2) A ⊥ C | B ==> P(A, C | B) = P(A | B) P(C | B)
(3) P(A, B, C) = P(A, B | C) P(C)
(4) P(A, B, C) = P(A, C | B) P(B)
(5) combining (1) and (3), P(A, B, C) = P(A | C) P(B | C) P(C) = P(A | C) P(B , C)
(6) combining (2) and (4), P(A, B, C) = P(A | B) P(C | B) P(B) = P(A | B) P(B , C)
(7) from (5) and (6), P(A | C) = P(A | B)
</code>
Given the last statement, it seems that in order for A ⊥ B and A ⊥ C, it must be true that either (a) everything is independent or (b) B = C. I'm having a hard time coming up with a proof, though. Not sure what kind of counterexample I could use.
Answer:
A ⊥ B | C and A ⊥ C | B, is A ⊥ B and A ⊥ C?

No, for example, let $B=C$. Conditional statements hold, but $A$ and $B$ doesn't have to be independent in the first place.

it seems that in order for A ⊥ B and A ⊥ C, it must be true that
  either (a) everything is independent or (b) B = C

No, for example, B and C can be different events, every pair of events can be pairwise independent but $A,B,C$ not mutually independent (which is what I understood from your 'everything is independent' idea).
Answer: We have probabilities for 8 different situations
$$\begin{array}{rrrr}
    P(& A,& B,& C) \\
    P(&!A,& B,& C) \\
    P(& A,&!B,& C) \\
    P(&!A,&!B,& C) \\
    P(& A,& B,&!C) \\
    P(&!A,& B,&!C) \\
    P(& A,&!B,&!C) \\
    P(&!A,&!B,&!C) \\
\end{array}$$
Given the information there are several equations that allow to restrict the values.
With the conditional independence there are four equations that restrict these values
$$A \perp B | C \\
\begin{array}{rcl}
\frac{P(A,!B,!C)}{P(!A,!B,!C)} = \frac{P(A,B,!C)}{P(!A,B,!C)}\\
\frac{P(A,!B,C)}{P(!A,!B,C)} = \frac{P(A,B,C)}{P(!A,B,C)}\\
\end{array} \\
A \perp C | B \\
\begin{array}{rcl}
\frac{P(A,B,C)}{P(!A,B,C)} = \frac{P(A,B,!C)}{P(!A,B,!C)}\\
\frac{P(A,!B,C)}{P(!A,!B,C)} = \frac{P(A,!B,!C)}{P(!A,!B,!C)}\\
\end{array} \\
$$
And because of some repetitions we can combine them
$$\frac{P(A,B,C)}{P(!A,B,C)} = \frac{P(A,!B,C)}{P(!A,!B,C)} = \frac{P(A,B,!C)}{P(!A,B,!C)} = \frac{P(A,!B,!C)}{P(!A,!B,!C)}$$
Which means that there are effectively 3 equations for the dependence but it straps all odds ratios for the events $A$ and $!A$, which are the same independent of all four possible conditions of $B$ and $C$ and therefore $A$ is independent of $B$ and independent of $C$.
Thus, A ⊥ B | C and A ⊥ C | B implies A ⊥ B and A ⊥ C.
More strictly we have
Thus, A ⊥ B | C and A ⊥ C | B if and only if A ⊥ B and A ⊥ C.

Given the condition "A ⊥ B | C and A ⊥ C | B" we can express all 8 values in terms of only 4 values.
We use $P(B)$, $P(C)$, $P(B,C)$ and $P(A)$ to express all values.
With the additional derived values $$\begin{array}{}
P(!B,!C) &=& 1-P(B)-P(C)+P(B,C)\\
P(B,!C) &=& P(B) - P(B,C)\\
P(!B,C) &=& P(C) - P(B,C)\\
P(!A) &=& 1 - P(A)\end{array}$$
you get the following
$$\begin{array}{rrrrl}
    P(& A,& B,& C) & = &P(A) \cdot P(B,C)\\
    P(&!A,& B,& C) & =& P(!A) \cdot P(B,C)\\
    P(& A,&!B,& C) & = &P(A) \cdot P(!B,C)\\
    P(&!A,&!B,& C) & =& P(!A) \cdot P(!B,C)\\\
    P(& A,& B,&!C) & =& P(A) \cdot P(B,!C)\\
    P(&!A,& B,&!C) & =& P(!A) \cdot P(B,!C)\\
    P(& A,&!B,&!C) & =& P(A) \cdot P(!B,!C)\\
    P(&!A,&!B,&!C) & =& P(!A) \cdot P(!B,!C)\\
\end{array}$$

it seems that in order for A ⊥ B and A ⊥ C, it must be true that either (a) everything is independent or (b) B = C.

No, based on the above, we only need 'A ⊥ B and A ⊥ C'; the variables B and C can be independent and do not need to be B = C.


As variáveis são alocadas aleatoriamente na memória?

Question: Em um livro sobre C, no qual comecei a estudar sobre variáveis, dizia que as variáveis eram colocadas na memória aleatoriamente, por exemplo:
int a;
int b;

printf("a = %d\n", &a); --> 5000 (endereço) (%d ao invés de %p para simplificar)
printf("b = %d\n", &b); --> 7634 (endereço) (%d ao invés de %p para simplificar)

Porém, pelo que eu pesquisei, as variáveis locais (ou seja, dentro de uma função), elas ficam na stack, ou seja, sequencialmente. E as variáveis globais ficam aleatoriamente, ou seja, na heap. Se eu colocar um printf() nas variáveis locais, elas estão em endereços sequenciais, como nesse caso (compilado pelo GCC no Linux):
char a;
int n;
float b;

printf("a = %p\n", &a); --> a = 0x7ffeb85afd5f
printf("n = %p\n", &n); --> n = 0x7ffeb85afd60
printf("b = %p\n", &b); --> b = 0x7ffeb85afd64

Então, isso contradiz com o que eu aprendi no livro. Como entender isso?
Comment: [O que são e onde estão o "stack" e "heap"?](https://pt.stackoverflow.com/q/3797/66203)
Comment: Lembre-se que nem todas as arquiteturas/plataformas possuem o mesmo tipo de gerenciamento de memória. Um bom exemplo seria o gerenciamento de memória virtual, que nem todos os sistemas/plataformas possuem um! Quando o autor diz que *as variáveis são colocadas aleatóriamente na memória*, significa que **quem controla esses endereços é o sistema/plataforma no qual o código está sendo executado. Esses endereços de memória são retornados pelo sistema e não podem ser determinados de forma "portável".** A propósito, qual é a data de publicação do livro que você mencionou ?
Comment: Livro de 2007, chamado Linguagem C, do Luis Damas.
Answer: Aleatoriamente nunca é o termo, sempre tem um certo determinismo, só não tem como antecipar onde exatamente quando escreve código, só em tempo de execução.
E vou falar aqui de memória virtual, a memória física certamente é organizada de outra forma e as coisas nem serão sequenciais fisicamente, mas não é aleatório, e isto não afeta o seu código. Vamos só no que interessa.
Antes tenha certeza que entende sobre stack e heap.
A linguagem C não determina que seja assim, vou falar como funciona de fato.
Não use variáveis globais. Elas ficam em uma área estática, que não é o heap, é reservada pelo compilador antecipadamente.
Stack é uma pilha, então é algo sequencial por definição. Você não tem controle onde exatamente estará ela (pode consultar isso em tempo de execução, como fez no código da pergunta), mas está longe de ser aleatória.
No heap também não é aleatório, tem critérios, mas é um pouco mais bagunçado. Ele é um monte, então a organização deixa a desejar, o objetivo é outro. Mas também não fica espalhado por toda a memória sem um sentido. E algumas variáveis estarão em sequência sim, especialmente em arrays. A organização apenas pode não ser tão óbvia.
O livro pode ter feito uma simplificação. Ou você pode ter interpretado errado o que estava escrito. Ou o livro é ruim mesmo.
Eu fiz simplificações, é muito mais complicado que isso, mas assim já é compreensível.
Comment: Eu acho que foi pra simplificar, pois o livro é ótimo. No segundo capítulo já entra o conceito de variáveis, então, não tinha como entrar nesse conceito de memoria stack e heap.
Comment: Mais uma dúvida: as funções também sao colocadas na memoria stack?
Comment: Não, fica na área estática.
Comment: Entendi, mas de acordo com esse site: https://blog.pantuza.com/artigos/heap-vs-stack , as funções ficam na pilha
Comment: Em nenhum lugar deste texto está escrito que as funções ficam na pilha.
Comment: Ah Sim, consegui esclarecer minha dúvida, muito obrigado.


pub/sub in google cloud platform

Question: How can i view the messages in the queue of pub/sub in google cloud platform?
I have searched for it a lot but, i did not get the related content Click Here I have gone through this link but it did not solve my problem
Answer: Officially, there are no dashboards to view the message content inside the queue however we can see the number of undelivered messages and the number of published messages which resides into the queue using StackDriver Monitoring Dashboard.
However if want to see the message content of the messages present in the queue you can use gcloud pubsub subscriptions pull --auto-ack MySub.The message you sent appears in the DATA field of the command output.This command acknowledges the message and hence the message will be deleted form the queue.
The hack to prevent the deletion of the messages is to write a script which reads the content of the messages without sending the acknowledgment.

pub/sub in google cloud platform


How does the log(p(x,y)) normalize the point-wise mutual information?

Question: I'm trying to understand the normalized form of pointwise mutual information.
$npmi = \frac{pmi(x,y)}{log(p(x,y))}$
Why does the log joint probability normalize the pointwise mutual information to be between [-1, 1]?
The point-wise mutual information is:
$pmi = log(\frac{p(x,y)}{p(x)p(y)})$
p(x,y) is bounded by [0, 1] so log(p(x,y)) is bounded by (,0]. It seems like the log(p(x,y)) should somehow balance changes in the numerator, but I don't understand exactly how. It also reminds me of entropy $h=-log(p(x))$, but again I don't understand the exact relationship.
Comment: For starter, [pointwise mutual information](http://en.wikipedia.org/wiki/Pointwise_mutual_information) uses logarithm (I am not sure whether its typo or you are using [another quantity](http://stats.stackexchange.com/questions/6047/does-this-quantity-related-to-independence-have-a-name)).
Answer: From Wikipedia entry on pointwise mutual information:

Pointwise mutual information can be normalized between [-1,+1] resulting in -1 (in the limit) for never occurring together, 0 for independence, and +1 for complete co-occurrence.

Why does it happen? Well, the definition for pointwise mutual information is
$$
pmi \equiv \log \left[ \frac{p(x,y)}{p(x)p(y)} \right] = \log p(x,y) - \log p(x) - \log p(y),
$$
whereas for normalized pointwise mutual information is:
$$
npmi \equiv \frac{pmi}{-\log p(x,y)} = \frac{\log[ p(x) p(y)]}{\log p(x,y)} - 1.
$$
The when there are:

no co-occurrences, $\log p(x,y)\to -\infty$, so nmpi is -1,
co-occurrences at random, $\log p(x,y)= \log[p(x) p(y)]$, so nmpi is 0,
complete co-occurrences, $\log p(x,y)= \log p(x) = \log p(y)$, so  nmpi is 1.
Comment: It would be a more complete answer to show why npmi is on the interval $[-1,1]$. See my proof in the other answer.
Answer: While Piotr Migdal's answer is informative in giving the examples where nmpi achieves three extreme values, it does not prove it is on the interval $[-1,1]$. Here is the inequality and its derivation.
\begin{align}
&\log\,p(x,y) \\
\le&\log\,p(x,y)-\log\,p(x)-\log\,p(y) \\
=&\log  \frac{p(x,y)}{p(x)p(y)}=:\text{pmi}(x;y) \\
=& \log \left[ \frac{p(x,y)}{p(x)} \cdot \frac{p(x,y)}{p(y)} \cdot \frac{1}{p(x,y)} \right] \\
=& \log \left[ p(x|y) \cdot p(y|x) \cdot \frac{1}{p(x,y)} \right] \\
=&\log\, p(x|y)+\log\, p(y|x)-\log\,p(x,y) \\
=& -\log\,p(x,y) \;\; [\because -\log\,p(A)\ge0 \text{ for any event } A]
\end{align}

\begin{equation}
\therefore \log\,p(x,y) \leq \text{pmi}(x;y) \le-\log\,p(x,y)
\end{equation}
Dividing both side by the non-negative $h(x,y):=-\log\,p(x,y)$, we have
$$ -1\le\text{npmi}(x;y):=\frac{\text{pmi(x;y)}}{h(x,y)}\le1.$$


SQLite Ionic 3 - Problema ao salvar respostas do SELECT em um array

Question: Eu estou em um projeto usando Ionic 3 e preciso manipular dados em sqlite. O problema atual é o seguinte, eu executo um SELECT em uma tabela e armazeno o retorno em um array (this.list_off) criado na class. Quando uso o console.log pra mostrar o valor deste array DENTRO da função de busca no banco, ele me mostra os dados que preciso, mas quando tento usar esse array fora (após o SELECT que armazena os dados nele) o array está vazio, como se numca tivesse sido preenchido.
Há alguma forma diferente de retornar e armazenar os dados de um SELECT em sqlite?
 getKeyList(){
   this.sqlite.create({
    name: 'rfleet.bd',
    location: 'default'
  }).then((db: SQLiteObject) => {
  db.executeSql('SELECT * FROM app_teclado WHERE list_id= 1', [])
    .then(res => {
      for(var i=0; i<res.rows.length; i++) {
        this.list_off.push({tec_id:res.rows.item(i).tec_id, tec_codigo:res.rows.item(i).tec_codigo,
          tec_data:res.rows.item(i).tec_data, tec_status:res.rows.item(i).tec_status,
          inst_id:res.rows.item(i).inst_id, list_id:res.rows.item(i).list_id, tipo:res.rows.item(i).tipo})
      }

    }).catch(e => console.log("SELECT TECLADO ERROR", e) );
}).catch(e => console.log(e));

}
Answer: Encotrei uma solução, só nao tenho certeza se é a melhor forma. Fiz com que a função trabalhe com respostas em "promessa", onde o retorno da função é um RESULT, tipo chamada com ajax.
getListId(){
return new Promise((resolve, reject)=>{
  this.sqlite.create({
    name: 'rfleet.bd',
    location: 'default'
  }).then((db: SQLiteObject) => {
    db.executeSql('SELECT * FROM app_listaoff WHERE list_status = 0', [])
      .then(res => {
          let id
          if(res.rows.length > 0){
            id = res.rows.item(0).list_id;
          }
          console.log("LAST list_id inserted", id);
          resolve(id)

      }).catch(e => console.log("SELECT app_listoff ERROR", e));
    }).catch(e => console.log(e));
})

Aqui é a chamada e o modo como recebo a resposta da função.
this.getListId().then(res =>{
  this.list_id = res
})


Como diminuir o tamanho dessa navigation bar?

Question: Estou fazendo essa aplicação e precisei remover a seta de voltar, e após fazer essa remoção a barra continuou a existir, deixando a mesma muito grande e deselegante para a minha aplicação... Alguém sabe me dizer como fazer para diminui-la? Abaixo a imagem de como está:
Aqui a parte do código do mainpage:
[XamlCompilation(XamlCompilationOptions.Compile)]
    public partial class MainPageRoot : MasterDetailPage
    {
        private ListView menu;
        private ObservableCollection<MasterPageItem> _menuLista;

        public MainPageRoot ()
        {
            InitializeComponent ();
            //menu = Master.navigationDrawerList;
            _menuLista = ItemService.GetMenuItens();
            navigationDrawerList.ItemsSource = _menuLista;
            Detail = new NavigationPage((Page)Activator.CreateInstance(typeof(MainPage)));
           NavigationPage.SetHasBackButton(this, false);

        }

        private void OnMenuItemSelected(object sender, SelectedItemChangedEventArgs e)
        {
            var item = (MasterPageItem)e.SelectedItem;
            Type pagina = item.TargetType;

            Detail = new NavigationPage((Page)Activator.CreateInstance(pagina));
            IsPresented = false;
        }
    }
}

Aqui o meu arquivo App.xaml.cs:
public partial class App : Application
{
    public App ()
    {
        InitializeComponent();

        MainPage = new NavigationPage(new LoginPage());
    }

    protected override void OnStart ()
    {
        // Handle when your app starts
    }

    protected override void OnSleep ()
    {
        // Handle when your app sleeps
    }

    protected override void OnResume ()
    {
        // Handle when your app resumes
    }
}

Comment: Na verdade, provavelmente o que está acontecendo aí é que você tem uma MasterDetailPage dentro de uma NavigationPage. Compartilhe o código de criação da página e onde você define a MainPage do App para podermos ajudar.
Comment: Vou editar a pergunta inserindo o código!!
Comment: Nesse arquivo só tenho isso aqui
Comment: @DiegoRafaelSouza desculpe, foi sonseira minha... mas, editei dê uma olhada!
Answer: Basta tirar a NavigationPage que está encapsulando a sua MasterDetailPage.
Em algum lugar depois do login você deve estar fazendo algo parecido com isso:
// Dentro da página do login ou da view model de login você deve estar empilhando uma nova página na navigation do login.
this.Navigation.PushAsync(new MainPageRoot());

Altere esse código para algo assim:
App.Current.MainPage = new MainPageRoot();

Espero que funcione.
Comment: cara perfeito, isso mesmo... muito obrigado pela ajuda!


Exclusão de registro no BD MySql

Question: Boa tarde.
Preciso de uma ajuda em relação a exclusão de um registro do BD MySql.
Tenho um BD que tem uma tabela chamada CHAVES.

Tenho uma página chamada listagem.php, essa página recebe os valores da tabela
CHAVES. Nessa página tem um link chamado EXCLUIR que ao clicar nesse link leva para uma página chamada exclusão.php.
Essa página exclusão uso $_GET para pegar o código correspondente no BD e preencher dinamicamente á pagina Exclusão.php

O problema:
Quando clicasse no botão confirmar a exclusão era para excluir o registro no BD e voltar para pagina Listagem.php com a página alteração atualizada sem a linha de registro.
Não estou conseguindo excluir o registro quando clico no botão está dando (erro na exclusão do registro).
Verifiquei o código várias vezes e não estou achando o erro que está impedindo a exclusão no BD e a atualização.
Ufa! é isso desculpem pelo longo texto, mas só assim acho que estou explicando meu problema.
Esse é o código: tive de colocar print do HTML do código porque está dando bug quando estou colando o código. Agradeço muito quem poder ajudar.

php
//confirmar se à página foi chamada a partir do formulário de exclusão
if(isset($_POST["nomecolaborador"])){
    $chID = $_POST["IDchaves"];

    $exclusao = "DELETE * FROM chaves ";
    $exclusao .= "WHERE IDchaves = {$chID} ";

    $con_exclusao = mysqli_query($conexao,$exclusao);
    if(!$con_exclusao){
        die("Erro na exclusão do registro");
    }else{
        header("location:listagem.php");
    }
}

?php
  //consulta a tabela chaves
  $cha = "SELECT * FROM chaves ";
  if(isset($_GET["codigo"]) ){
    $id = $_GET["codigo"];
    $cha .="WHERE IDchaves = {$id} ";
 }

  $cons_chaves = mysqli_query($conexao,$cha);
  if(!$cons_chaves){
      die("Erro na consulta");
  }
  $info_chaves = mysqli_fetch_assoc($cons_chaves);
Answer: Retira o asterisco.
<code>$exclusao = "DELETE FROM chaves ";
$exclusao .= "WHERE IDchaves = {$chID} ";
</code>
Vai dar certo!
Comment: Olá Júlio, cara o obrigado mesmo pela ajuda, ficamos tão cego olhando pra outro problema que a solução pode estar na nossa frente. Valeu mesmo!!
Comment: Há funcionou sua sugestão.
Comment: Infelizmente acontece isso, ficamos horas e horas procurando um problema complexo e depois descobrimos que é simples. :)
Comment: Super verdade, as vezes procuramos pelo em ovo. Forte abraço! :)

Exclusão de registro no BD MySql


Managing multiple databases with NHibernate and Autofac

Question: I thought I'd get this question out there while I noodled on a solution on my own.
After having built out the bulk of an application, I have a last minute requirement to support reading/writing to an additional database (2 total, no known others).  I built the application using NHibernate, with Autofac supplying the DI/IoC components.  FWIW, this resides in an ASP.NET MVC 2 app.
I have a generic repository class that takes an NHibernate session.  Theoretically, I can continue to use this generic repository (IRepository<>) for the second database so long as the session that gets passed to it is spawned from an appropriate SessionFactory, right?
Well, when the app starts, Autofac does it's thing.  With regards to the Session and SessionFactory, I have a module that states:
builder.Register(c => c.Resolve<ISessionFactory>().OpenSession())
    .InstancePerMatchingLifetimeScope(WebLifetime.Request)
    .OnActivated(e =>
    {
        e.Context.Resolve<TransactionManager>().CurrentTransaction = ((ISession)e.Instance).BeginTransaction();
    });

 builder.Register(c => ConfigureNHibernate())
    .SingleInstance();

where ConfigureNHibernate(), which returns the base SessionFactory, looks like:
private ISessionFactory ConfigureNHibernate()
{
    Configuration cfg = new Configuration().Configure();
    cfg.AddAssembly(typeof(Entity).Assembly);
    return cfg.Configure().BuildSessionFactory();
}

Currently, this is limited to just the one database.  In any other NHib scenario, I'd likely shove instances of the separate SessionFactories into a hash, and retrieve them as needed.  I don't want to have to re-architect the whole thing as we're fairly close to a major release.  So, I'm guessing I need to modify at least the methods above so that I can independently configure two SessionFactories.  My gray area is how I'll go about specifying the correct Factory be used with a specific repository (or at least for entities specific to that second database).
Anyone have experience with this scenario while using an IoC container and NHibernate in this manner?
EDIT
I've stubbed out a GetSessionFactory method that takes a configuration file path, checks for the existance of a matching SessionFactory in the HttpRuntime.Cache, creates a new instance if one doesn't already exist, and returns that SessionFactory.  Now I still need to hammer out how to tell Autofac how and when to specify an appropriate config path.  The new method looks like (borrowed heavily from Billy's 2006 post here):
private ISessionFactory GetSessionFactory(string sessionFactoryConfigPath)
    {
        Configuration cfg = null;
        var sessionFactory = (ISessionFactory)HttpRuntime.Cache.Get(sessionFactoryConfigPath);

        if (sessionFactory == null)
        {
            if (!File.Exists(sessionFactoryConfigPath))
                throw new FileNotFoundException("The nhibernate configuration file at '" + sessionFactoryConfigPath + "' could not be found.");

            cfg = new Configuration().Configure(sessionFactoryConfigPath);
            sessionFactory = cfg.BuildSessionFactory();

            if (sessionFactory == null)
            {
                throw new Exception("cfg.BuildSessionFactory() returned null.");
            }

            HttpRuntime.Cache.Add(sessionFactoryConfigPath, sessionFactory, null, DateTime.Now.AddDays(7), TimeSpan.Zero, System.Web.Caching.CacheItemPriority.High, null);
        }

        return sessionFactory;
    }

Comment: Storing the session factory in cache is a bad idea. It's not something that can just vanish and be recreated.
Comment: I know.  In reality, I'm going to have to manage the lifetime of that cached object.  Billy's example actually takes this a step further and created a singleton scoped SessionManager class that takes care of the caching concerns.  I was trying to dumb it down so I could eventually let Autofac manage it via it's own (very elegant) scoping mechanisms.
Answer: I'm assuming that you want different types of entities to go into each database; if you want to keep the same kinds of entities in each database, check out AutofacContrib.Multitenant.
The two ingredients that can help with this scenario are:

Named services http://code.google.com/p/autofac/wiki/TypedNamedAndKeyedServices
Resolved parameter http://code.google.com/p/autofac/wiki/ResolveParameters (minimal docs on this one - the coming Autofac 2.4 release has some syntax sweeteners around this...)

First, use named services to refer to the two different databases. I'll call them "db1" and "db2". All of the components relating to the database, all the way up to the session, get registered with a name:
builder.Register(c => ConfigureDb1())
    .Named<ISessionFactory>("db1")
    .SingleInstance();

builder.Register(c => c.ResolveNamed<ISessionFactory>("db1").OpenSession())
    .Named<ISession>("db1")
    .InstancePerLifetimeScope();

// Same for "db2" and so-on.

Now, assuming you have a type NHibernateRepository<T> that accepts an ISession as its constructor parameter, and that you can write a function WhichDatabase(Type entityType) that returns either "db1" or "db2" when given the type of an entity.
We use a ResolvedParameter to dynamically choose the session based on the entity type.
builder.RegisterGeneric(typeof(NHibernateRepository<>))
    .As(typeof(IRepository<>))
    .WithParameter(new ResolvedParameter(
        (pi, c) => pi.ParameterType == typeof(ISession),
        (pi, c) => c.ResolveNamed<ISession>(
            WhichDatabase(pi.Member.DeclaringType.GetGenericArguments()[0])));

(Warning - compiled and tested in Google Chrome ;))
Now, resolving IRepository<MyEntity> will select the appropriate session, and sessions will continue to be lazily initialised and correctly disposed by Autofac.
You will have to think carefully about transaction management of course.
Hope this does the trick!
NB
Comment: Dude, that was it.  So awesome!  I had some tweaking to do for my scenario, and dug in a little more into the updated Autofac source so I understood what was going on, but hell yes, this is why I love SO!  Thanks Nicholas!


Safely Stopping MySQL Server on Windows Server

Question: Is stopping MySQL Process with net stop MySQL57 safe? We are running MySQL Server on Windows Server and would like to backup whole server with file-system approach. If we would use net stop MySQL57 would it not cause any database corruption?
Answer: Using net stop and then net start is equivalent to using the services applet in the Windows control panel.
net stop also causes the service's dependent services (if any) to stop and restart.  For example, IIS Admin depends on World Wide Web, NNTP, FTP and SMTP if you have those installed and running.
net stop causes the services to shutdown "properly" and re-read the Windows registry before starting again.  It's the same as restarting safely.  Use the service names and not the display names (which won't work anyway).
You can also use the service controller app sc as well as net start/net stop.
You can see (or should see, if it installed properly) the MySQL service in the registry along with all others under HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\.
Hope that helps a bit.
Comment: In other words, yes it's safe to use net stop. :)
Comment: This question is more about MySQL which is a very complex thing rather than stopping processes.
Comment: Yes that's right.  MySQL is careful to start, stop, pause and restart in the Windows environment, digging down to its Nt Service class.  It's aware of whether mysqld was spawned by a Windows service or not, and includes an extensive test suite.  If the software malfunctioned in this environment I am sure it would be fixed quickly.  I think you can be confident that MySQL starts up and shuts down safely in the Windows environment, GUI or command line controlled.  Or as confident as you reasonably can be.  Running your own test cases is one way to be sure.
Comment: This seems like a better solution https://www.percona.com/blog/2020/05/07/prepare-mysql-for-a-safe-shutdown/


Create a View that redirects to node content based on contextual filter?

Question: I've created a view with a contextual filter for 'field_object_id' -> this is a field that the content type has which is unique but it's not the Node ID, these field_object_id's are brought in from a JSON feed.
So I can go to my view page like this:
drupal-site.com/my-view
Which would display a page not found. Then going to:
drupal-site.com/my-view/230
Would load up the content node that has '230' set for 'field_object_id' -> however that content node ID is not 230, I have no idea what it is. It could be 8509.
What I need to do, is set my view to automatically redirect the page to the node that it finds (I would set it to redirect to the first result it finds).
I have Panels installed too, would this be easier to do with Panels or should I look to creating a module?
Comment: I don't think redirecting was ever built into Views. But it seems to me that you do not want real redirect (http 302 found), just to load and display one node. Could you clarify?
Comment: Yeah, I'm not too concerned about the real redirect (302), just to load and display one node but to "redirect" to that nodes' URL. Someone in IRC told me to use Location(node/[nid]) in the View -> Footer -> Text area (PHP), which seems to work well.
Answer: One way I think of is to to this in a custom menu callback. So you could have an URL /mycallback/[OBJECT_ID] which would redirect to the first node that has the given [OBJECT_ID].
Something like this:
/**
 * Implements hook_menu().
 */
function MYMODULE_menu() {
  $items['mycallback/%'] = array(
    'page callback' => 'fieldvalue_redirect_callback',
    'page arguments' => array(1),
    'access arguments' => array('access content'),
    'type' => MENU_CALLBACK,
  );
  return $items;
}

/**
 * Custom callback given a object id.
 */
function fieldvalue_redirect_callback($id) {
  $query = new EntityFieldQuery();
  $query->entityCondition('entity_type', 'node')
  ->fieldCondition('field_object_id', 'value', $id, '=')
  ->addMetaData('account', user_load(1));
  $result = $query->execute();

  if (isset($result['node'])) {
    drupal_goto(url('node/' . key($result['node'])));
  } else {
    drupal_set_message(t('Page not found'), 'error');
    drupal_goto('<front>');
  }
}

First comes the definition of the menu callback, MYMODULE_menu().
The argument after mycallback/ is being passed on the the page callback function by defining it here 'page arguments' => array(1),.
fieldvalue_redirect_callback() will get the id entered by the user after /mycallback as argument. In the function we use EntityFieldQuery to fetch the node that matches the given ID.
And last we redirect if we get a result, otherwise we show an error message and the front page.
Hope this can help you or someone else.
Answer: So I was able to get this working (although maybe not the best way) by doing:
Setting show fields instead of content.
Selecting node ID in the fields (and set it to be excluded from display, although not necessary)
Then in the Views' FOOTER, add Text Area and set the filter to PHP.
Then I put:
<?php
  global $base_url;
  header("Location: $base_url/node/[nid]");
?>

And this seems to do what I want. Now going to the view page with an ID, it automatically redirects to the Node which redirects to the nodes' URL Alias.


Does the von Neumann-Morgenstern utility theorem work for infinitely many outcomes?

Question: The von Neumann-Morgenstern utility theorem is easy to prove for a finite number of outcomes. Is it still true for an infinite number of outcomes?
With infinite outcomes, a lottery can now be any probability distribution on the set of outcomes.
The problem seems to be that to prove the theorem one would need to use the independence axiom an infinite number of times, which of course is not possible.
If the theorem is false in the infinite case, can we generalize the axioms to make the theorem true?

Here is a (sketch of a) proof of the theorem for infinite outcomes if we only consider lotteries with finite support.
Let $A$ be the set of outcomes.
If $X \sim Y$ for every $X, Y \in A$, we define $u$ as $u(Z) = 0$ for all $Z \in A$.
Otherwise, $X \prec Y$ for some $X, Y \in A$. We will define $u(X) = 0$ and $u(Y) = 1$.
For every outcome $Z \in A$, we define $u_Z$ as the von Neumann-Morgenstern utility function for the relation $\prec$ restricted to lotteries over the set $\{X, Y, Z\}$. Since this set is finite, the theorem guarantees $u_Z$ will exist. We also require that $u_Z(X) = 0$ and $u_Z(Y) = 1$, which ensures uniqueness.
We now define $$u(Z) := u_Z(Z)$$ for all $Z \in A$.
Now for any events $L, M$ with finite support, we define the utility function $u_{L,M}$ as the von Neumann-Morgenstern utility function for $\prec$ restricted to the set $\{X, Y\} \cup \operatorname{supp}(L) \cup \operatorname{supp}(M)$. We again require that $u_{L,M}(X) = 0$ and $u_{L,M}(Y) = 1$. Now for every $Z$ in $u_{L,M}$'s domain, $u_Z$ is just a restriction of $u_{L,M}$. Therefore $u_{L,M}(Z) = u_Z(Z) = u(Z)$.
$L \preceq M$ iff $E[u_{L,M}(L)] \le E[u_{L,M}(M)]$ iff $E[u(L)] \le E[u(M)]$
Q.E.D.
Answer: It is not fully clear to me what the question is, but there is a huge literature on versions of the von Neumann and Morgenstern utility representation on infinite sets. The most common approach is to impose a continuity axiom. (Formally, there are different alternatives, f.i.\ assuming an archimedean property.)
Among many possible references, I recommend J.-M. Grandmont, "Continuity properties of a von Neumann-Morgenstern utility", Journal of Economic Theory 4, 45-57. Theorem 2 provide simple conditions for existence that elucidate the role of the independence (or linearity) axiom. And Theorem clarifies the difference between assuming a continuous representation or a continuous NM-utility function.
Comment: How does my answer look? https://math.stackexchange.com/a/3070682/49592
Answer: No, it does not hold in the infinite case (as stated). To see this, we will define a VNM-rational $\prec$ that does not have a utility function.
Let $A$ be any infinite set of outcomes. Then for lotteries $L$ and $M$, $L \prec M$ iff the support of $L$ is finite and of $M$ is infinite.
Completeness: We define $L \preceq M$ as $M \nprec L$. It is clear that $M \nprec L$ or $L \nprec M$, since otherwise $L \prec M$ and $M \prec L$, implying $L$ has both finite and infinite support, a contradiction.
Transitivity: If $L \prec M$ and $M \prec N$, $L$ has finite support and $N$ has infinite support. Ergo, $L \prec N$.
Continuity: Given $L \preceq M \preceq N$, then we have two cases:

The support of $M$ is finite. Then $M \sim 1L + 0N$.
The support of $M$ is infinite. Then $M \sim 0L + 1N$.

Independence: If $L \preceq M$ and $p \in [0,1]$, there are four cases:

$p = 0$: $0L + 1N \sim 0M + 1 N$
$0 < p < 1$ and the support of $N$ is finite: $pL + (1-p)N \sim L \preceq M \sim pM + (1-p)N$
$0 < p < 1$ and the support of $N$ is infinite: $pL + (1-p)N \sim pM + (1-p)N$
$p = 1$: $1L + 0N \preceq 1M + 0N$

So $\prec$ satisfies the VNM-axioms. However, there is no utility function $u$ such that $L \prec M \iff u(L) < u(M)$. To see this, note that $u$ must assign every outcome to some value $f$, since if $L=1x$ and $M=1y$ then
$$L \sim M$$
$$E[u(L)] = E[u(M)]$$
$$u(x) = u(y)$$
For any lottery $N$ with infinite support (which exists since $A$ is infinite), $E[u(N)]$ also equals $f$, since $u$ assigns each outcome in $L$'s support to $f$. So $E[u(L)] = E[u(N)]$. This implies $L \sim N$, which is false since $L$'s support is finite and $N$'s support is infinite.
$\Box$
Comment: In the Wikipedia version of the theorem, independence is a biconditional: $L\preceq M$ iff $pL+(1-p)N\preceq pM+(1-p)N$. The right-to-left direction fails in your example: let $L$ and $N$ have disjoint infinite supports and let $M$ have finite support.
Comment: Don't we need a biconditional in the finite case, too? Suppose there are three points $A,B,C$, and say $L\prec M$ iff $L$'s support doesn't intersect $\{B,C\}$ but $M$'s does.


What was the purpose of Jean Adam Guilain's Organ Suites?

Question: I'm looking for context for these pieces, as I am about to play the Suite of the Second Tone in recital. Guilain wrote these Suites, and whenever I hear recordings of them, each movement begins with a chant which is not in the score. For example: https://play.spotify.com/track/4zQ4UvAQAYbyxD7FqIuSD3
What is the exact chant they use in the recording, and does anyone have a link to an online version? Can anyone explain why chant is used here?
Answer: In the Catholic church liturgy of the time, alternating verses of the texts were sung unaccompanied by the choir, and replaced by a organ solo, either pre-composed or improvised. The congregation did not take any part in the music.
This procedure was the prescribed method in France from the 15th century until the start of the 20th century. Since printed music could only be published in France with Royal permission, most of the organ repertoire was improvised.
The notion that half of the text should be omitted from the religious service seems strange by modern standards, but official documents from the 17th century onwards indicate that the text could be spoken while the organ sections were being played, or if the organ music was based on a plainsong cantus firmus, a soloist could sing the text in unison with that part of the counterpoint.
Most likely, the recording is following some specific (and documented) contemporary performance instructions as to the chants being used, but unless the recording information identifies it, it would be hard to discover exactly what instructions were being followed.


Apertar 'infinitamente' botão do teclado

Question: Estou fazendo um teste em python3.5 utilizando a biblioteca pyautogui. Meu objetivo é que o algoritmo aperte botões para mim.
import pyautogui

while True:
 pyautogui.press('f1')

Nesse caso, ele está apertando f1. Fiz vários testes e ele realmente funciona no meu pc. Mas, gostaria de testa-lo em um game, Lineage II, mas nao pega :S. Ja testei com letras a,b,c... (no meu pc funciona, no server nao :S). Teriam dicas de como colocar para funcionar no servidor?
Comment: Como assim não funciona no servidor? Eu não conheço esse jogo.
Comment: Para fazer isso você tem que abrir a linha de comando interativa do Unreal Engine e escrever o equivalente desse código em Unreal C++.
Answer: A função "press()" não é mais do que a utilização das funções "keyDown()" e "keyUp()" em sequência.
Poderá ser que as duas funções sejam evocadas com um intervalo demasiado curto entre elas para serem reconhecidas pelo jogo.
Experimenta fazer o seguinte:
import pyautogui, time

while True:
    pyautogui.keyDown('f1')
    time.sleep(1)
    pyautogui.keyUp('f1')

Porém, a maioria dos jogos bloqueiam a execução de script de terceiros justamente para evitar burlar a interface com o jogador.
Comment: Andei pesquisando um pouco e tem que burlar uma proteção do server deles. :S