Dúvida com EntityFramework (Migration)

Question: Estou tentando fazer meu código rodar, mas não estou conseguindo por causa deste Error

Severity  Code    Description Project File    Line
  Error   CS0311  The type 'ControleInterno.Migrations.ControleInterno.ControleIntContexto' cannot be used as type parameter 'TContext' in the generic type or method 'DbMigrationsConfiguration'. There is no implicit reference conversion from 'ControleInterno.Migrations.ControleInterno.ControleIntContexto' to 'System.Data.Entity.DbContext'.   ControleInterno F:\Documentos\Visual Studio 2015\Projects\Controle Interno\ControleInterno\Migrations\Configuration.cs  6

using ControleInterno.Model;
using System.Data.Entity;

namespace ControleInterno
{
    class ControleIntContexto : DbContext
    {
        public ControleIntContexto()
        {
            Configuration.LazyLoadingEnabled = false;
        }

        public DbSet<Produto> Produtos { get; set; }
    }
}

Segue o código do arquivo Configuration.cs
namespace ControleInterno.Migrations
{
    using System;
    using System.Data.Entity;
    using System.Data.Entity.Migrations;
    using System.Linq;

    internal sealed class Configuration : DbMigrationsConfiguration<ControleInterno.ControleIntContexto>
    {
        public Configuration()
        {
            AutomaticMigrationsEnabled = false;
        }

        protected override void Seed(ControleInterno.ControleIntContexto context)
        {
            //  This method will be called after migrating to the latest version.

            //  You can use the DbSet<T>.AddOrUpdate() helper extension method
            //  to avoid creating duplicate seed data. E.g.
            //
            //    context.People.AddOrUpdate(
            //      p => p.FullName,
            //      new Person { FullName = "Andrew Peters" },
            //      new Person { FullName = "Brice Lambson" },
            //      new Person { FullName = "Rowan Miller" }
            //    );
            //
        }
    }
}

Comment: Coloque também o código da classe de configuração que você excluiu. A explicação está nela.
Comment: Não entendo pq ele não reconhece minha classe de contexto...
Comment: Coloque o código da sua classe de contexto
Comment: Eu usei esta dica [http://stackoverflow.com/questions/11918401/enable-migrations-error-project-failed-to-build] e deu certo. Queria saber quais os efeitos disso?
Answer: Isto aqui estava gerando ambiguidade de nomes:
namespace ControleInterno
{
    class ControleIntContexto : DbContext
    { ... }
}

Como você retirou o contexto do namespace correto dele (ControleInterno.Models), observe que o compilador resolveu o nome do contexto da seguinte forma:
ControleInterno.Migrations.ControleInterno.ControleIntContexto

E que obviamente está errado.
Bastava trocar o namespace do contexto e corrigir as referências que volta a funcionar.
Comment: Deu certo @CiganoMorrisonMendez . Por incrível que pareça, eu não modificado nada. Quando dei o Enable-Migrations ele já gerou assim.
Comment: Esse problema não é realmente simples. Percebi ele pela sua mensagem de erro.

Dúvida com EntityFramework (Migration)


What does $\int(x^2-4)d \lfloor x \rfloor$ mean?

Question: What does $\int(x^2-4)d \lfloor x \rfloor$ mean? How do I integrate wrt $\lfloor x\rfloor$? This has to be a typo.
Comment: It means a Riemann-Stieltjes integral.
Comment: Possible duplicate of [Integration of a function with respect to another function.](https://math.stackexchange.com/questions/295383/integration-of-a-function-with-respect-to-another-function)
Comment: @rhaldryn it's on the wiki. $f(x) = x^2-4$, $g(x) = \lfloor x \rfloor$, $\int_0^4 f(x) dg(x)$
Comment: @Jakobian Could you link me to a definition of RS Integrals that uses that notation? The wiki article doesn't seem to.
Comment: Where are these questions from?
Comment: @Ovi It's an M.Sc. math entrance exam of a university in India. However Riemann-Stieltjes integrals were not in the syllabus.
Comment: @rhaldryn Ah thanks. For what it's worth, the only time I have seen the notation $\int f(x) d$(something other than $x$) is in Riemann-Stieltjes integral, so I'm not sure, maybe the syllabus was mistaken. I was actually asking about the problems because they look interesting and would be good practice for me. Would you happen to have a link to the problems, or know where I could get more such problems? Thanks.
Comment: You can go to any state university or institute (in India at least eg, IIT, IMSC, CMI, ISI, TIFR etc.) website and search for the previous year question papers. Most of them take MCQ tests like these. If you want proof based subjective questions then there are tons of problem books recommendations on MSE.
Answer: Working with Riemann-Stieltjes integrals,$$\int_0^4(x^2-4)d\lfloor x\rfloor=\left[(x^2-4)\lfloor x\rfloor\right]_0^4-\int_0^4\lfloor x\rfloor 2xdx\\=48-\int_1^22xdx-2\int_2^32xdx-3\int_3^42xdx\\=48-(2^2-1^2)-2(3^2-2^2)-3(4^2-3^2)=48-3-10-21=14.$$ More generally,$$\int_{0}^{n}f\left(x\right)d\left\lfloor x\right\rfloor =nf\left(n\right)-\sum_{k=1}^{n-1}k\left(f\left(k+1\right)-f\left(k\right)\right)=\sum_{k=1}^{n}f\left(k\right)$$for $n\in\mathbb{N}$.
Answer: You can use integration by parts as follows.
$$\int_0^4 (x^2-4)d\lfloor x\rfloor = (x^2-4)\lfloor x\rfloor |_{x=0}^{x=4} - \int_0^4 \lfloor x\rfloor d(x^2-4) = \\ 48-\int_0^4 2x\lfloor x\rfloor dx = 48-(4-1)-2(9-4)-3(16-9) = 14 $$


VGG19 vs Resnet18. When does VGG win?

Question: I have always been under the impression that resnet is more technologically advanced than vgg and so you will always get better performance on resnet. I trained and tested my model on a sample data and got 93.7% accuracy on vgg19 and 93.3% accuracy on resnet18 (balanced classes). Given sufficiently large dataset, what could be the possible reasons to get better performance on pretrained vgg19 than pretrained resnet18 (both pretrained on imagenet)
Answer: Being "more technologically advanced" does not make a machine learning model better. There are cases where much simpler models outperform complicated ones. There's no free lunch theorem stating that there can't be single best model that works for all problems. Moreover, most of deep learning models are based on a number of clever hacks that appear to work for particular classes of problems. There's no theoretical arguments why one of those models should perform better. ResNet tried to solve some of the problems observed in earlier models (vanishing gradients), but this does not mean it will always outperform the earlier ones.
Answer: ResNet18 is quite a shallow network, while VGG19 is a deep network. It is better to compare ResNet50/ResNet101 with VGG19 or ResNet18 with VGG11 because otherwise your comparison makes no sense.
Based on your accuracy, deep networks work better for this dataset. A good choice would be EfficientNetB7 or DenseNet161.
I have never seen VGG19 being superior to more modern architectures, but there can be exceptions when you have special datasets (as was noted in the other answer). So I would estimate that in about 90% of cases, VGG will not defeat a modern architecture.
Looking beyond VGG, the situation is more difficult. For example, EfficientNet uses "mobile inverted bottlenecks" (see MobileNetV2) and not all datasets can deal with it (at least my impression). Then an older architecture like SEResNeXt101 that also uses squeeze-and-excitation blocks (SE) can work much better than EfficientNet.
Another thing you should consider is the receptive field of your CNN. When you have big objects, then you might not need deep networks like VGG19, ResNet50, etc.

VGG19 vs Resnet18. When does VGG win?


2 Macros 1 Module

Question: Hello I have these two macros in one module but when I run it only runs the first part where it deletes the rows but I would like it to also send the emails... I had some excellent help from @Simoco on the send part earlier but cant seem to figure out the combine part...
I tried to add the Call Sub... but no luck
Sorry about the length of the code...
Sub DeleteDuplicateRows()

Dim R As Long
Dim N As Long
Dim V As Variant
Dim rng As Range

Range("D2").Select
    ActiveCell.FormulaR1C1 = "1"
    Range("D2").Select
    Selection.Copy
    Range("A5").Select
    Range(Selection, Selection.End(xlDown)).Select
    Selection.PasteSpecial Paste:=xlPasteAll, Operation:=xlMultiply, _
        SkipBlanks:=False, Transpose:=False
    Rows("1:3").Select
    Application.CutCopyMode = False
    Selection.Delete Shift:=xlUp
    Columns("A:A").Select
    Columns("A:A").EntireColumn.AutoFit

On Error GoTo EndMacro
Application.ScreenUpdating = False
Application.Calculation = xlCalculationManual
Set rng = Application.Intersect(ActiveSheet.UsedRange, _
                    ActiveSheet.Columns(ActiveCell.Column))
Application.StatusBar = "Processing Row: " & Format(rng.Row, "#,##0")
N = 0
For R = rng.Rows.Count To 2 Step -1
If R Mod 500 = 0 Then
    Application.StatusBar = "Processing Row: " & Format(R, "#,##0")
End If
V = rng.Cells(R, 1).Value
If V = vbNullString Then
    If Application.WorksheetFunction.CountIf(rng.Columns(1), vbNullString) > 1 Then
        rng.Rows(R).EntireRow.Delete
        N = N + 1
    End If
Else
    If Application.WorksheetFunction.CountIf(rng.Columns(1), V) > 1 Then
        rng.Rows(R).EntireRow.Delete
        N = N + 1
    End If
End If
Next R
EndMacro:
Application.StatusBar = False
Application.ScreenUpdating = True
Application.Calculation = xlCalculationAutomatic
MsgBox "Duplicate Rows Deleted: " & CStr(N)

End Sub

Sub Send_Email()

Dim OutApp As Object
Dim OutMail As Object
Dim strbody As String
Dim cel As Range
Dim SigString As String
Dim Signature As String
Dim lastrow As Long
Set OutApp = CreateObject("Outlook.Application")

SigString = Environ("appdata") & _
"\Microsoft\Signatures\GBS.txt"

If Dir(SigString) <> "" Then
Signature = GetBoiler(SigString)
Else
Signature = ""
End If

lastrow = Cells(Rows.Count, 3).End(xlUp).Row

For Each cel In Range("C2:C" & lastrow)
strbody = "Hi there" & cel.Offset(, -1) & vbNewLine & vbNewLine & _
"My name Is William, Please choose the following option ..." & vbNewLine & _
cel.Offset(, 3) & _
"I work at Fair" & vbNewLine & _
"Bye" & vbNewLine & _
"WH"

On Error Resume Next
With OutApp.CreateItem(0)
If cel.Value <> "" Then
.To = cel.Value
.CC = cel.Offset(0, 10).Value
.Body = strbody & vbNewLine & vbNewLine & Signature
Else
.To = cel.Offset(0, 10).Value
.Body = "Hello " & cel.Offset(, 9) & "! " & cel.Offset(, -1) & "  is having this event" & vbNewLine & Signature
'.HTMLBody = strbody & vbNewLine & RangetoHTML(cel.Offset(, -2).Resize(, 4)) & vbNewLine & Signature
End If
'.BCC = ""
.Subject = "Choose your plan"
.Display
'.Attachments.Add ("C:\test.txt")
'.Send
End With
On Error GoTo 0
Next cel

Set OutApp = Nothing
End Sub
Function RangetoHTML(rng As Range)
' Changed by Ron de Bruin 28-Oct-2006
' Working in Office 2000-2013
Dim fso As Object
Dim ts As Object
Dim TempFile As String
Dim TempWB As Workbook

TempFile = Environ$("temp") & "\" & Format(Now, "dd-mm-yy h-mm-ss") & ".htm"

'Copy the range and create a new workbook to past the data in
rng.Copy
Set TempWB = Workbooks.Add(1)
With TempWB.Sheets(1)
.Cells(1).PasteSpecial Paste:=8
.Cells(1).PasteSpecial xlPasteValues, , False, False
.Cells(1).PasteSpecial xlPasteFormats, , False, False
.Cells(1).Select
Application.CutCopyMode = False
On Error Resume Next
.DrawingObjects.Visible = True
.DrawingObjects.Delete
On Error GoTo 0
End With

'Publish the sheet to a htm file
With TempWB.PublishObjects.Add( _
SourceType:=xlSourceRange, _
Filename:=TempFile, _
Sheet:=TempWB.Sheets(1).Name, _
Source:=TempWB.Sheets(1).UsedRange.Address, _
HtmlType:=xlHtmlStatic)
.Publish (True)
End With

'Read all data from the htm file into RangetoHTML
Set fso = CreateObject("Scripting.FileSystemObject")
Set ts = fso.GetFile(TempFile).OpenAsTextStream(1, -2)
RangetoHTML = ts.readall
ts.Close
RangetoHTML = Replace(RangetoHTML, "align=center x:publishsource=", _
"align=left x:publishsource=")

'Close TempWB
TempWB.Close savechanges:=False

'Delete the htm file we used in this function
Kill TempFile

Set ts = Nothing
Set fso = Nothing
Set TempWB = Nothing
End Function

Function GetBoiler(ByVal sFile As String) As String
'**** Kusleika
    Dim fso As Object
    Dim ts As Object
    Set fso = CreateObject("Scripting.FileSystemObject")
    Set ts = fso.GetFile(sFile).OpenAsTextStream(1, -2)
    GetBoiler = ts.readall
    ts.Close
End Function

Comment: what about adding `Call Send_Email` just before `MsgBox "Duplicate Rows Deleted: " & CStr(N)` ?
Comment: @simco Worked fine...
Comment: Well formatted code and clearly visible separated functions and procedures makes it easier to help. Reducing the lines of code by removing not needed bits helps as well.
Comment: @William, see answer threeFourOneSixOneThree
Answer: If you execute a macro you call one procedure or one function. I assume you want to call Delete_Duplicate_Rows and Send_Email. To execute two procedures you can create one procedure that calls the other procedures
Sub Delete_And_Send()
    Call Delete_Duplicate_Rows()
    Call Send_Email()
End Sub

Comment: It worked this way also... I couldn't try it yesterday, but thanks for the insight here.

2 Macros 1 Module


How to call ajax from a javascript function on button click?

Question: I have written this function for calling a php script but its not working
function finalfun(id) {
    $.ajax({
        data: {
            'id': id
        },
        url: '/delete.php',
        method: 'POST', // or GET
        success: function (msg) {
            alert(msg);
        }
    });

This my php script delete.php
    <?php
    if(isset($_POST['id']))
    {
     echo ($_POST['id']);
     }
    else
    {
     echo "Id not found";
     }
     ?>

I have wriiten the finalfun() in .php file so is this a problem
Comment: Explain the term ***Not Working***
Comment: `data: {'id':id},` is enough
Comment: `data: {id: id},` do it like this
Comment: Change the url from `url: '/delete.php',` to `url: 'delete.php',`
Comment: The php script is not getting called
Comment: have tried changing the url but the script is not getting called
Comment: If delete.php in root folder then use   `./delete.php`  and if some another folder named   test then write   `./test/delete.php`  then try..
Answer: Probably the issue is with your id, you doing id=, just do
function finalfun(id) {

  $.ajax({
    data: {
      'id': id
    },
    url: '/delete.php',
    method: 'POST', // or GET
    success: function (msg) {
      alert(msg);
    }
  });

Comment: Try changing the `URL` from `/delete.php` to just `delete.php`
Answer: Try this: and also add jquery library file in your page.
function finalfun(id) {
    $.ajax({
        type: 'POST', // use here type instead of method
        url: 'delete.php',
        data: JSON.stringify({ id: id }),
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (msg) {
            alert(msg);
        }
    });
}

Answer:

call the function using onclick
Answer: test.html:

delete.php:
<?php
echo $_POST['id'];
?>

Comment: there were two errors 1:function not properly closed 2:delete.php having '/'


What would this scale be? Is it something Eastern?

Question:
Its kind of like a pentatonic scale, but some parts are chromatic. The note between the fourth and fifth is played. Moth minor and major seven are played. PLEASE HELP! thank you
Answer: This is just the A minor blues scale with an added major seventh.


Alternate (?) definition of sample variance

Question: The variance of a sample can be defined as
$$s^2 = \frac{1}{2}\frac{1}{n(n-1)}\sum_{i}\sum_{j\ne i}\left(x_i - x_j\right)^2$$
Apart from the factor of $1/2$, this can be paraphrased verbally as

The variance is the average of the squared distances between pairs of distinct data points

Mathematically, this is equivalent to the "usual" definition of variance, $s^2 = \frac{1}{n-1}\sum \left(x_i -\bar{x} \right)^2$.  Conceptually, however, it seems (to me) quite different, in two respects:

This definition makes no reference to the mean value $\bar{x}$; we are not measuring how far apart points are from the mean, but rather how far away points are from one another.
The factor of $n-1$ in the denominator -- which is well-known to be a source of confusion for students (see, e.g., Intuitive explanation for dividing by $n-1$ when calculating standard deviation?) -- appears naturally because there are $n(n-1)$ ordered pairs of distinct data points $(x_i, x_j), i\ne j$.  No need for either hand-waving justifications about "cushioning" the sample variance, or for complicated calculations of estimator bias.

Again, just to be clear, I understand why the standard definition of $s^2$ includes a denominator of $n-1$, and I understand that the double-sum definition above is mathematically equivalent to the standard definition.  What I would like to know:
Are there contexts (pedagogical or otherwise) in which the alternate definition of variance (as a double-sum over pairs of data points) is more commonly referred to?  Are there any textbooks, for example, that take this as the primary definition?
Comment: The double sum definition is (of course) prominently used when discussing U statistics. It is also interesting to see the sample variance as a measure of typical (squared) distance between two randomly picked points, not unlike gini impurity for a categorical variable.
Comment: That emphasis doesn't come through very clearly, so I recommend you reformulate your question to give that issue prominence.  Since the two formulas are algebraically equivalent, as *definitions* they are equally good.  For further insight you might consider the complexities of the two algorithms: one is $O(n)$ and the other is $O(n^2).$
Comment: Please see https://stats.stackexchange.com/questions/3931 for answers to (2) and (3) and https://stats.stackexchange.com/questions/18058 for a visual explanation of (1).
Comment: I have read your question through--in its various versions--some three or four times over already.  I apologize, but I see no reason to keep rereading it.  All along it repeatedly emphasizes the $n-1$ term and there still is nothing in the explicit list of questions that attempts to focus the reader's attention on whether or not one first removes the mean from the data.  So far, everything I have seen looks like it is answered elsewhere on this site (apart from that observation about algorithmic complexity, but there's nothing much to it after all).
Comment: I have edited the question to try to clarify what I am asking (and in particular to emphasize that I am *not* asking why the variance has a factor of $n-1$ in the denominator).  I hope this helps?
Comment: @whuber  Thank you for those links - in particular the answer https://stats.stackexchange.com/a/3966/48466 seems to be most relevant for my question, but I don't really see how any of those answer my questions (2) or (3). My question was *not* "Why do we use $n-1$ instead of $n$?", but rather "Why do we define variance in terms of difference from the mean, rather than in terms of pairwise differences?"
Comment: @whuber  Maybe you stopped reading after the first paragraph?  In any case I appreciate your comment on computational complexities, as it definitely answers why people would not use my alternative algorithm in practice.
Comment: @Xi'an  I included a link to that question in my own question.  I am asking about something else.
Comment: Are you asking specifically about use of the alternative _definition_ or of statistical use of the equivalence of two "definitions"?
Comment: @MichaelM Could you elaborate on those examples in an answer? I think it's exactly the kind of thing I'm looking for (and reassures me that my question is not vacuous).
Comment: @ttnphns  I'm asking partly about *pedagogical* use (are there textbooks or other treatments of introductory stats where the double-sum definition is used?) but also about other use-cases (are there situations in which the double-sum definition is more useful or otherwise preferred for some reason)?
Answer: Using symmetry, your double sum can be written as
$$
  s^2 = \text{ave}_{i < j} f(x_i, x_j)
$$
with $f(x, y) := \frac{1}{2} (x - y)^2$ and as such is a U-statistic of degree 2 with kernel $f$ for the estimation of the parameter $\theta = E(f(X, Y)) = \ldots = \text{Var}(X)$, $X$, $Y$ iid. It is actually one of the most prominent, non-trivial examples of a U-statistic and shines accordingly in theoretical math stats classes.
Being a U-statistic is nice because e.g.

a U-statistic is automatically "optimal" in the sense of being U-nbiased with minimum variance (bye-bye Rao-Blackwell theorem) and
there is a (more or less explicit) formula for its variance and thus its standard error.

Nevertheless, this alternative representation of the sample variance $s^2$ is rarely used in practice although, as you mentioned, it seems to highlight a different aspect of variation ("typical squared difference between two random picks" instead of "typical squared difference between random pick and mean").
The U-statistics representation of $s^2$ always reminds me of Gini impurity used in decision tree learning where that often plays the role of variance for categorical responses. For a discrete random variable $Z$ with levels $z_1, \dots, z_m$ and $\text{Pr}(Z = z_j) = p_j$, it is defined as
$$
 I(Z) = 1 - \sum_{j = 1}^m p_i^2 = \sum_{i}\sum_{j \ne i} p_i p_j,
$$
and as such is the probability of two random picks not being equal (again something like a typical difference between two random picks).


Como encontrar coordenadas no maps da Apple?

Question: Preciso mostrar diversos lugares diferentes no mapa, um para cada local, gostaria de saber como posso apontar para cada coordenada através do código?
No caso o app é para iOS, usando Objective-C.
Answer: Utilizando o MapKit são necessárias poucas linhas de código. Depois de adicionado o framework no projeto e o mapa em si na tela, você pode inserir um ponto em determinada coordenada desta maneira:
// Alloca um novo MKPointAnnotation que pode ser usado como pin no mapa
MKPointAnnotation *point = [[MKPointAnnotation alloc] init];

// Ajusta para a coornedada desejada
point.coordinate = CLLocationCoordinate2DMake(-21.805149, -49.089977);

// Pode customizar o título e subtitulo
point.title = @"Título";
point.subtitle = @"Subtitulo do pin";

// Adiciona o pin no mapa
[self.mapView addAnnotation:point];

Comment: Cara sua resposta é fenomenal!!! Me adiantou 90% do trab. Mas sao mais de 20 localizacoes e o cliente é de outro estado e ele não sabe como fazer isso. Eu pensei em ver as coordenadas no Goole Maps e converter para o mapa da Apple, vou dar mais uma pesquisda! Mas sua resposta é realmente util! Obrigado novamente!!!
Comment: Eu fiz um teste aqui tbm, parece que as coordenadas do Google Maps tbm serve para o MapKit, mas não é 100% preciso :/


Is this c the same as that c?

Question: Are the highlighted $c$'s the same or should it be $c_1$ and $c_2$.
Comment: The two yellow $c$'s are the same.
Comment: Full proof of part a) has been given
Comment: The propositions are supposed to be true for all positive finite $c$ so they can be the same or different in the two propositions. They just have to be constant in each proposition at any one time.
Answer: I am not very good at analysis, but the answer to your question is clearly "the $c$'s are the same", by plain elementary logic. I'll try to explain it to you:
call $\varphi(\alpha)$ the "sentence"
$$\forall x \ \left[ \overline{\lim}_{r \to 0} \mu(B(x,r)/r^s < \alpha \right]$$
and call $\psi(\beta)$ the "sentence"
$$\mathcal H^s(F) \geq \mu(F)/\beta.$$
Then your theorem can be written as
$$\varphi(c) \implies \psi(c).$$
If you think about it, you can see that it would make no sense to write something like
$$\varphi(c_1) \implies \psi(c_2).$$

I'll use an easier example for you to understand better:
suppose $\alpha,\beta \in \mathbb N$ and call $\varphi(\alpha)$ the "sentence"
$$x \leq \alpha.$$
Now call $\psi(\beta)$ the "sentence"
$$x \leq 2\beta.$$
Then it is of course true that
$$\varphi(n) \implies \psi(n),$$
since this can be written in natural language as

If $x \leq n$, then $x \leq 2n$.

But which sense would it make to say $\varphi(n_1) \implies \psi(n_2)$? That is, which sense would it make to state

If $x \leq n_1$, then $x \leq 2n_2$.

?

Is this c the same as that c?


transformar string em array javascript

Question: Boa tarde,
tenho a seguinte string
[{"programa":"teste"},{"programa":"Aprender"},{"programa":"outro teste","indice":"0;1;0"}][{"programa":"Programando 1","indice":"1;2;3"},{"programa":"hostórico","indice":"1;2;2"},{"programa":"análise","indice":"1;2;1"}]

como faço para obter array através dessa string?
Comment: Era pra ter 2 arrays nesse JSON ? `...{"programa":"outro teste","indice":"0;1;0"}][{"programa":"Programando 1","indice":"1;2;3"},...`
Comment: na verdade usei o concat para unir
Comment: Essa string vem de onde ? O formato era suposto ser JSON ?
Comment: sim, seria mas como ela é a junção acabou ficando com esse formato. mas irei ajustar a formatação. OBg
Answer: Sua string JSON parece estar mal formatada, tem dois arrays mal definidos (isso dá erro: ][).
Fiz uma pequena alteração para que seja um array válido e converti para objeto usando JSON.parse:

var x = '{"1":[{"programa":"teste"},{"programa":"Aprender"},{"programa":"outro teste","indice":"0;1;0"}],"2":[{"programa":"Programando 1","indice":"1;2;3"},{"programa":"hostórico","indice":"1;2;2"},{"programa":"análise","indice":"1;2;1"}]}';

var o = JSON.parse(x);
console.log(o);
Comment: Se você utilizar `eval` ao invés de `JSON.parse`, daí o javascript da pergunta é válido! Mas o resultado é `undefined`.
Comment: Nem tinha pensado nisso, pensei num array com array dentro. Testei aqui e realmente fica `undefined` bem observado

transformar string em array javascript


Restore files from a recycle bin, that is located on a server store of a roaming profile

Question: An organization has a domain and all users have a roaming profiles.
A user deletes files from My Documents, and they appear to be in the recycle bin on the server's user profile store.
How can admin access and restore those files?
A particular computer, from where the files were put to the recycle bin is no longer available. If an admin logs in with this user profile on a different PC, the recycle bin in the profile is empty.
Answer: If there's a file in the profile on a server that you want access to as an administrator you can take ownership of the profile and all the files under it, give yourself the rights to access that profile and navigate the filesystem as you would any other directory. When done you change the owner of that profile folder and all sub-folders and files back to the original user.
I'm not sure if the files in the recycle bin are typically stored in the profile. The best solution if it's something important is to restore it from your backups so you don't need to mess with the ownership and permissions on the profile. I've had times where things got screwy after changing this, plus you have to make sure the user isn't accessing those files anywhere else on the network at the time.
Another method to check is to have them log in somewhere and access their profile path from their login. They have permission to access it on the server, and if you think it's in a recycle folder within the profile on the server it should get synced to another machine at login. If it's not on the workstation at login, it's not part of the profile...so emptied recycle bin means it's not in the profile. You wouldn't be able to get it back anyway.


Find position of a term in ClueWeb09 corpora

Question: I want to read term from clueweb09 corpora and find its position to check that term is an entity or not based on dataset that was created here. They claim they calculate the position based on:
**" The zero (0) location used for calculating the annotation offsets is the beginning of the HTTP headers*. This is the first byte after the WARC document header."* .
I calculate the length of each term by calling term.getBytes().length function and sum all positions to find the position of the entity. Unfortunately my position is about 400 byte less than the reported position. I calculate position by reading each warcfile file based on following code.
ArrayList<Integer> pos = new ArrayList<Integer>();
    int position=-1;
    String text;
    try{
    FileReader fileReader = new FileReader("05");
    BufferedReader bufferedReader = new BufferedReader(fileReader);

    while(true){
        String line= bufferedReader.readLine();
        if(line==null)
            break;
        else
        {
            int index=line.indexOf(word);
            if(index==-1)
                position=position+line.getBytes().length;
            else{
                  int poss= position +index;
                  pos.add(poss);
                  position=position+line.getBytes().length;
            }
        }
    }
    bufferedReader.close();
    }
    catch(Exception e)
    {
        e.printStackTrace();
    }

Could you please tell me what is the problem(s)?
Answer: To Find a position of the Clueweb dataset terms in byte I used this code which implement the annotation version of this data set here. The lemur.cw.ann.DetectEncoding class returns the annotation which are not match with clueweb dataset based on their positions. I change that class and lemur.cw.ann.Matcher class to calculate the postion of the Clueweb terms based on byte offset.


Reinforcement learning in non stationary environment

Question: Q1: Are there common or accepted methods for dealing with non stationary environment in Reinforcement learning in general?
Q2: In my gridworld, I have the reward function changing when a state is visited. Every episode the rewards reset to the initial state. All I want my agent to learn is "Don't go back unless you really need to", however this makes the environment non-stationary. Can/Should this very simple rule be incorporated in the MDP model, and how? Is Q-learning the best solution for dealing with this problem? Any suggestions or available examples?
Q3: I have been looking into Q-learning with experience replay as a solution to dealing with non stationary environments, as it decorrelates successive updates. Is this the correct use of the method or it is more to deal with making learning more data efficient? And I have only seen it used with value approximation. I am not sure if it is an overkill to use it for a simple discretised state space, like gridworld, or there is a different reason for this.
Please feel free to answer or comment even if you can't address all questions.
Answer:
Q1: Are there common or accepted methods for dealing with non stationary environment in Reinforcement learning in general?

Most basic RL agents are online, and online learning can usually deal with non-stationary problems. In addition, update rules for state value and action value estimators in control problems are usually written for non-stationary targets, because the targets already change as the policy improves. This is nothing complicated, simply use of a learning rate $\alpha$ in updates when estimating values, effectively a rolling geometric mean as opposed to averaging over all history in an unweighted fashion.
However, this addresses longer-term non-stationarity, such as the problem changing between episodes, or over an even longer time scale. Your description looks more like you wish to change the reward structure based on actions the agent has taken, within a short timescale. That dynamic response to actions is better framed as a different more complex MDP, not as "non-stationarity" within a simpler MDP.
An agent cannot learn changes to the environment that it has not yet sampled, so changing reward structure will not prevent the agent from returning to previously-visited states. Unless you are using something like a RNN in the agent, the agent will not have a "memory" of what happened before in the episode other than whatever is represented in the current state (arguably using a RNN makes the hidden layer of the RNN part of the state). Across multiple episodes, if you use a tabular Q-learning agent, then the agent will simply learn that certain states have low value, it will not be able to learn that second or third visits to the state cause that effect, because it has no way to represent that knowledge. It will not be able to adjust to the change fast enough to learn online and mid-episode.

Q2: In my gridworld, I have the reward function changing when a state is visited. All I want my agent to learn is "Don't go back unless you really need to", however this makes the environment non-stationary.

If that's all you need the agent to learn, perhaps this can be encouraged by a suitable reward structure. Before you can do that, you need to understand yourself what "really need to" implies, and how tight that has to be logically. You may be OK though just by assigning some penalty for visiting any location that the agent has already or recently visited.

Can/Should this very simple rule be incorporated in the MDP model, and how?

Yes, you should add the information about visited locations into the state. This immediately will make your state model more complex than a simple grid world, increasing the dimensionality of the problem, but it is unavoidable. Most real-world problems very quickly outgrow the toy examples provided to teach RL concepts.
One alternative is to frame the problem as a Partially Observable Markov Decision Process (POMDP). In that case the "true" state would still include all the necessary history in order to calculate the rewards (and as this is a toy problem on a computer you would still have to represent it somehow), but the agent can attempt learn from restricted knowledge of the state, just whatever you let it observe. In general this is a much harder approach than expanding the state representation, and I would not recommend it here. However, if you find the idea interesting, you could use your problem to explore POMDPs. Here is a recent paper (from Google's Deep Mind team, 2015) that looks at two RL algorithms combined with RNNs to solve POMDPs.

Q3: I have been looking into Q-learning with experience replay as a solution to dealing with non stationary environments, as it decorrelates successive updates. Is this the correct use of the method or it is more to deal with making learning more data efficient?

Experience replay will not help with non-stationary environments. In fact it could make performance worse in them. However, as already stated, your problem is not really about a non-stationary environment, but about handling more complex state dynamics.
What you may need to do is look into function approximation, if the number of states increases to a large enough number. For instance, if you want to handle any back-tracking and have a complex reward-modifying rule that tracks each visited location, then your state might change from a single location number to a map showing visited locations. So for example it might go from $64$ states for an $8 \times 8$ grid world to a $2^{64}$ state map showing visited squares. This is far too high to track in a value table, so you will typically use a neural network (or a convolutional neural network) to estimate state values instead.
With a function estimator, experience replay is very useful, as without it, the learning process is likely to be unstable. The recent DQN approach for playing Atari games uses experience replay for this reason.
Comment: @Voltronika I expanded the answer adding a paragraph about POMDPs. Note that framing your problem as a POMDP makes it much harder to work on and solve than extending the state to include suitable memory of visited locations. So I suggest you only look into that if studying POMDPs is a goal.
Comment: If the environment is non-stationary then how do you deal with the fact that, in the grid world example, being in the state at time t=1 is not the same as being in that state at t=2? If you treat them as separate states then surely the dimensionality of your state space will just explode?
Comment: @tryingtolearn: The whole point of a Markov state is that it captures all the important details of how the MDP will progress from that point. Typically being in state at t=1 is **not** different from being in the same state at t=2, in terms of expected future reward and state transitions. If you wind up with rules that are based on the value of t, then you put t into the state. This might happen if you can get reward at any time step, but the number of time steps is limited - the episode always ends at t=10 for example. In that case knowing your remaining time could be important
Comment: @NeilSlater can you expand on the POMDP and RNN ideas in your answer? They sound interesting. And if possible, give relevent sources because sometimes it is hard to navigate the literature. I really don't like the idea of keeping the sequence of visited states, although this is the only thing I could think of so far as well, so I am looking for other options. The model becomes overcomplicated that way, given that I need to introduce a very simple rule. I am not sure if I am missing something very obvious or I am just not using the correct model and formulation.
Comment: @NeilSlater Can't this be helped by using things like policy-gradient methods? In practice, do you happen to know what the *standard* for solving these kind of problems is?
Comment: @tryingtolearn: No, policy gradients still need a correct state representation, they work nicely when there are lots of actions to choose, or in continuous action spaces. Having a correct and valid state representation is "the standard". You have some free choices, based on domain knowledge, on what counts as "correct and valid". If you want to know what the "standard" is for a grid-based movement with dynamic restrictions to movement, then I very much doubt there is some published reference on how to do it "correctly". It will depend too much on the nature of the restrictions.
Answer: Q1: Q learning is an online reinforcementn learning algorithm that work well with the stationary environment. It may also be used with a non-stationary model with the condition that the model (reward function and transition probabilities) does not change fast.


MongoDB regex matching trouble

Question: Here is my MongoDB shell session;
> db.foo.save({path: 'a:b'})
WriteResult({ "nInserted" : 1 })

> db.foo.findOne()
{ "_id" : ObjectId("58fedc47622e89329d123ee8"), "path" : "a:b" }

> db.foo.save({path: 'a:b:c'})
WriteResult({ "nInserted" : 1 })

> db.foo.find({path: /a:[^:]+/})
{ "_id" : ObjectId("58fedc47622e89329d123ee8"), "path" : "a:b" }
{ "_id" : ObjectId("58fedc57622e89329d123ee9"), "path" : "a:b:c" }

> db.foo.find({path: /a:[a-z]+/})
{ "_id" : ObjectId("58fedc47622e89329d123ee8"), "path" : "a:b" }
{ "_id" : ObjectId("58fedc57622e89329d123ee9"), "path" : "a:b:c" }

Clearly the regex /a:[^:]+/ and /a:[a-z]+/ shouldn't match string 'a:b:c', but looks like Mongo failed on this regex, does anyone know what happened here?
It was submitted to MongoDB Jira, as a bug ticket, so is it a bug within MongoDB querying structure?
Answer: The trouble is with the partial matching, since you are not restricting the regex for the whole word, the partial match that exists in a:b:c that is a:b is resulting in you getting that document.
Use the following regex with ^$ that are anchors to represent beginning and the end of the word;
db.foo.find({path: /^a:[^:]+$/})
db.foo.find({path: /^a:[a-z]+$/})

This will make the regex apply for the whole string, and ignore the partial matches as explained above. For more on regex anchors, click here.
So, in summary, there is no bug, just a misuse of regex.

MongoDB regex matching trouble


Area Between Intersecting Lines - Elegant Solution?

Question: I am running simulations, and the output will be a line y = mx+b. I am interested in the area below the line between x=0 and x=1. I am only interested in the area that is below the diagonal y = x.
I have figured out how to determine this area by finding areas of triangles. But to do so, I have to define 6 cases. This requires many if-else statements in my computer program, and is inefficient.
I was wondering if there is an elegant solution to this problem which will not require such a complex program?
In the diagram below, the diagonal line is solid, my line of interest is the dotted line.
Answer: Let $y = mx+b$ be the equation of your line, and then find the point of intersection with $y=x$, which will be $(p,p)$.
Then you need to find two integrals: the integral from $0$ to $p$ of $x-(mx+b)$ and the integral from $p$ to $1$ of the same function. Then pick whichever one is nonnegative!
EDIT: Just realized the lines don't have intersect. If that happens, just take the integral from $0$ to $1$ of $x-(mx+b)$ and if it's negative, return 0.
I guess I only simplified a few cases.


In Angular app, how do I import d3 and use d3.js scripts?

Question: I'm using d3.js version 3 script in my angular app.
I have installed d3 in angular app using command
npm i d3@3

And imported d3 as
import * as d3 from 'd3';

Even though I imported d3 as above,
 I'm getting error
Property 'layout' does not exist on type 'typeof import("C:/Users/srikar.vodeti/Downloads/imp/dashboardVisual/networkDiagram/node_modules/@types/d3/index")'. 106 var tree = d3.layout.tree()

when i use d3. any method
Thanks in advance..
Comment: what error you are getting ? can you add that also in your question?
Comment: yes mentioned the error
Answer: first install d3 and type declaration
npm install d3 --save
npm install --save @types/d3

then import d3
import * as d3 from 'd3';

Please let me know if it is not working.
Comment: you can use var tree = (d3 as any).layout.tree(). then vs code will not show error
Comment: No, it's not working..
Getting error ```Property 'layout' does not exist on type 'typeof import("C:/Users/srikar.vodeti/Downloads/imp/dashboardVisual/networkDiagram/node_modules/@types/d3/index")'.

106 var tree = d3.layout.tree()``` when i use d3.layout.tree();
Comment: please create stackblitz demo. so i can have better look on it
Comment: here is  a d3 working sample , you can refer this. https://stackblitz.com/edit/d3-svr-sample
Comment: After doing the above steps.. got below error and able to solve finally...

https://stackoverflow.com/questions/56400413/d3-js-runtime-error-after-upgrade-to-angular-8


Is there way to display thumbnail gallery using external links to images?

Question: Drupal 7, is there way to display thumbnail gallery using external links to images?(instead of uploading pictures)
Something like
https://wordpress.org/plugins/wp-gallery-custom-links/screenshots
I have Views, Imagecache External, Views Responsive Grid modules installed, but no one of them helps me to achieve this simple task. I want create responsive thumbnail gallery with external images.
Answer: It might be it is the Link Image Formatter module that you are after.
It is a image formatter for a Link field. The modules you mentioned can then be used to construct your gallery (Views, Imagecache External, Views Responsive Grid).
You could also rewrite the field output in Views by using the "token" and wrapping it in the needed HTML to display it as an image, something like:

Make sure you get a plain version of the image URL, so you better check without rewriting first.
Note that using Imagecache External will result in images being stored on your own server. It doesn't free you from copyright issues as with embedded external images (hotlinking). That means you could alternatively use FileField Sources.
An extension module of the last one, Remote File Source, might avoid transfer of the image file on your server. I haven't tested that. You are likely to miss out on Image Styles in that case (e.g. to resize or cache images locally).
Answer: You can use the Flickr module. The only problem would be that all the images would be hosted at Flickr.
Comment: No, that is not suitable for me. I do not want to be glued to their storage, and this requires to upload images anyway.


Functional Component data not re-rendering on update in Framer Preview

Question: I am making a list view which dynamically has to change every few seconds when the data source list updates.
The list from where it is getting the data is essentially
const area = [a1,a2,a3,.....,a50]

From this list, I setState([]) of another list - region which is rendered into a Frame using array.map

I tried various methods from https://www.robinwieruch.de/react-function-component
I am using useEffect()to make changes to the array regions which is supposed to be rendered

export function DynamicList() {
    const [region, setRegion] = React.useState([])
    useEffect(() => {
        setInterval(() => {
            //take a random integer between 0 and length of the main array - areas

            // if it already exists in the smaller array - regions, then delete it at that index
            if (region.indexOf(areas[randNum]) != -1) {
                // find the index to delete
                delIndex = region.indexOf(areas[randNum])
                console.log(areas[randNum] + " " + delIndex)

                //delete the item at that index
                region.splice(delIndex, 1)
            }

            // adding the random itemt o first position
            region.splice(0, 0, areas[randNum])
            region.join()

            setRegion(region)
            console.log(region)
        }, 6000)
}, [])
}

Console.log is functioning and I see the Region array being updated, but it does not render in the preview section
The part for rendering the UI is
return(
   <Stack>
   {region.map((item, index) => {
       return (
           <Frame
            background=""
            key={index}
            defaultValue={item}
            height={10}
            width={200}
            radius="4%"
            color="ffffff"
            style={{
                fontFamily: "Lato",
                fontSize: 10,
            }}
            >
                {item}
            </Frame>
        )
    })}
  </Stack>
)

I expect in the preview, cities to keep updating with every new city being added to region array showing above the already existing list.
EDIT : SOLVED. ANSWER BELOW
Comment: where and how you updated the `region` array?
Comment: Harish, I am updating the ```region``` array every 6 seconds in ```useEffect``` using ```SetInterval```. I am updating the region array and then passing it through ```setRegion()```
Comment: Is your rendering logic and `DynamicList` are in the same functional component?
from the question, it seems to be separate.
Or can you post your complete rending component?
Comment: Possible duplicate of [React Hooks useState+useEffect+event gives stale state](https://stackoverflow.com/questions/55154186/react-hooks-usestateuseeffectevent-gives-stale-state)
Answer: The solution entailed setting region differently.
with setRegion(region) region does not get to know that change has been made to the array.
Therefore, using setRegion([...region]) copies the temp Region to Region.
Thus code becomes
useEffect(() => {
    const id = setInterval(() => {
    randNum = Math.floor(0 + Math.random() * areas.length)

    // if it already exists, then delete it
    if (region.indexOf(areas[randNum]) != -1) {
         // find the index to delete
         delIndex = region.indexOf(areas[randNum])
         console.log(areas[randNum] + " " + delIndex)
         //delete the item at that index
         region.splice(delIndex, 1)
    }

    // adding the random itemt o first position
    region.splice(0, 0, areas[randNum])

    // region.join()
    setRegion([...region])
    console.log(region)
    }, 2000)

}, [region])


Eigenvectors and Eigenvalues - cubic equation?

Question:
So, I have the fact that :
Av =  λv
Where  λ is the eigenvalue. I tried substituting  in v=A^-1*v* λ to the equation but this didn't get me anywhere. Any help???
Comment: Let $A^3-7A^2+I$ act on $v$ and show the result is a multiple of $v.$ That multiple will be its eigenvalue.
Answer: Let $\vec{v}$ be an eigenvector of $A$ with eigenvalue $\lambda$, meaning that we have $A \vec{v} = \lambda \vec{v}$.
Claim: $\vec{v}$ is an eigenvector of $A^3 - 7 A^2 + I$ with eigenvalue $\lambda^3 - 7 \lambda^2 + 1$.
Proof:

First we notice that $A^2 \vec{v} = A (A \vec{v}) = A (\lambda \vec{v}) = \lambda (A \vec{v}) = \lambda ( \lambda \vec{v}) = \lambda^2 \vec{v}$. Thus, $\vec{v}$ is an eigenvector of $A^2$ with eigenvalue $\lambda^2$. If you do the same computation for $A^3$ instead of $A^2$, then you will find out that $\vec{v}$ is an eigenvector of $A^3$ with eigenvalue $\lambda^3$, i.e. $A^3 \vec{v} = \lambda^3 \vec{v}$.
(Note: In general, $\vec{v}$ is an eigenvector of $A^k$ with eigenvalue $\lambda^k$, i.e. $A^k \vec{v} = \lambda^k \vec{v}$ where $k$ is a non-negative integer.)
With that knowledge we obtain $$(A^3 - 7 A^2 + I)\vec{v} = A^3 \vec{v} - 7 A^2 \vec{v} + I \vec{v} = \lambda^3 \vec{v} - 7 \lambda^2 \vec{v} + \vec{v} = (\lambda^3-7\lambda^2+1)\vec{v},$$
so it turns out that $\vec{v}$ is an eigenvector of $A^3 - 7 A^2 + I$ with eigenvalue $\lambda^3-7\lambda^2+1$ which was our claim.
Comment: More generally, if $p(x)$ is any polynomial with real coefficients, then $p(A)$ will have $v$ as an eigenvector with $p(\lambda)$ as an eigenvalue.


Equality of sets when minimizing Shannon's Entropy

Question: Let $P = \{p_1, \ldots, p_n\}$ be a set of probabilities, i.e., $0 \leq p_i \leq 1$. $P$ is such that $\sum_{p_i \in P} p_i = 1$.
I have a set of actions $\mathcal{A} = \{a_1, \ldots, a_N\}$ that can be performed on $P$. Each time an action $a_i$ is performed, some of the probabilities $p_i \in P$ are deleted from $P$, and $P$ is normalized so that the summation is again 1.
Let $H(P)$ be the (Shannon's) entropy of the original set of probabilities in $P$.
Performing one action. $H_a(P)$ is the (Shannon's) entropy of the set of probabilities $P$ after:

$a$ is performed and some of the probabilities are deleted
$P$ is normalized

Performing two actions. $H_a(P|b) = H(P|a,b)$ is the (Shannon's) entropy after:

$b$ is performed on $P$ and some of the probabilities are deleted
$P$ is normalized to sum up to 1
$a$ is performed on the new $P$
$P$ is again normalized

Claim. Let $a_1^* = \arg \min_{a \in \mathcal{A}} H_a(P)$. Prove that the following two sets are equal:
$$
\{a_1^*, \arg \min_{a \in \mathcal{A}\setminus a_1^*} H_a(P|a_1^*) \} = \arg \min_{\{a, b\} \in \mathcal{A}} H(P|a,b)
$$
Comment: I do not understand the notation of the claim. Is it an equality of sets, isn't?
Comment: Exactly. In the left part, $a_1^*$ and another action will be retrieved. In the right part, the best $a$ and $b$ will be retrieved.
Answer: This doesn't seem to be true, if I understand your definitions correctly. Here's a counterexample: Let $P = \lbrace p_1, \dots, p_9 \rbrace$ where each $p_i$ is equal to $1/9$. Let $\mathcal{A} = \lbrace a_1, a_2, a_3 \rbrace$ be such that:

$a_1$ restricts to the set $\lbrace p_1, p_2, p_3, p_4 \rbrace$;
$a_2$ restricts to the set $\lbrace p_1, p_2, p_5, p_6, p_9 \rbrace$;
$a_3$ restricts to the set $\lbrace p_3, p_4, p_7, p_8, p_9 \rbrace$.

It's evident that after performing any number of actions in $\mathcal{A}$, the entropy is $\log(n)$ where $n$ is the number of elements remaining. Since $a_1$ restricts to the smallest number of elements,
$$
\arg \min_{a \in \mathcal{A}} H_a(P) = a_1.
$$
But the smallest double intersection is given by taking $a_2$ and $a_3$, so that
$$
\arg \min_{\lbrace a, b \rbrace \in \mathcal{A} \times \mathcal{A}} H(P|a, b) = \lbrace a_2, a_3 \rbrace
$$
In particular, we have $H(P | a_2, a_3) = 0$, whereas $H(P|a_1, a_2) = H(P|a_1, a_3) = \log(2)$.
Comment: In my context it happens rarely that the set of probabilities contains all the same values. Thus, I was wondering whether you can find a counterexample also in the case the probabilities are different. What is strange to me is that experimentally (i.e., implementing it onto a computer and mediating on different runs) the result is the same, although I cannot understand why.
Comment: The same example ought to work with a lot of different values of $p_i$: all that's required is that $a_1$ gives the minimum for $H_a(P)$, since $H(P|a_2, a_3)$ is always going to be zero.


Error estimate, asymptotic error and the Peano kernel error formula

Question: Find the error estimate by approximating $f(x)$ and derive a numerical integration formula for $\int_0^l f(x) \,dx$ based on approximating $f(x)$ by the straight line joining $(x_0, f(x_0))$ and $(x_1, f(x_1))$, where the two points $x_0$ and $x_1 = h - x_0$ are chosen so that $x_0, x_1 \in (0, l)$, $x_0 < x_1$ and $\int_0^l {(x - x_0) (x - x_1)} dx = 0$.
Derive the error estimate, asymptotic error and the Peano kernel error formula for the composite rule for $\int_a^b f(x) \,dx$.
Use the asymptotic error estimate to improve the integration formula. Find the values of $x_0$, $x_1$.
I know the Peano Kernel formula will take the form $E_n(f)=1/2($$\int_a^b K(t)\ f''(t) \,dx$$)$ with $K(t)$ being the Peano kernel but am having a tough time getting started on the question. Any help will be greatly appreciated. Thanks a lot!
Answer: For this I think you can use trapezoidal rule. You can approximate $f(x)$ by the straight line joining $(a,f(a))$ and $(b,f(b))$ Then by integrating the formula for this straight line, we get the approximation $$I_1(f)=\frac{(b-a)}{2}[f(a)+f(b)].$$ To get the error formula we get $$f(x)-\frac{b-x)f(a)+(x-a)f(b)}{b-a}=(x-a)(x-b)f[a,b,x]$$
I am not sure if this is absolutely correct, maybe someone can verify my answer?
Comment: This gives the idea for how to apply the Peano Kernel formula. However, the question does not necessarily use the trapezoidal rule; it depends on the choice of $x_0$ and $x_1$.
Comment: @JitseNiesen Then I am out of luck because I don't know how to answer that. :( Sorry Jeffery!
Answer: The question seems a bit garbled; it's not clear to me in what order you should do things. But the first part seems to find the numerical integration formula. For this you need to find the formula for a straight line through $(x_0,f(x_0))$ and $(x_1,f(x_1))$ and integrate over the interval $[0,l]$. If you take $x_0=0$ and $x_1=l$ this yields the trapezoidal rule described by user60514. You can find $x_0$ and $x_1$ from the conditions in the question.
Added later: To find a straight line through two points, say $(x_0,y_0)$ and $(x_1,y_1)$, note that a straight line is given by the formula $ax+b$. We need to find $a$ and $b$. The line has to go through the two points, which means that $a$ and $b$ should satisfy $ax_0+b = y_0$ and $ax_1+b = y_1$. These are two (linear) equations in two unknowns ($a$ and $b$), which you can solve.
To find $x_0$ and $x_1$, note that they have to satisfy $x_1 = h-x_0$ and $\int_0^l (x-x_0) (x-x_1) \, dx = 0$. Evaluate the integral in the latter equation and you again get two equations in two unknowns ($x_0$ and $x_1$). Solve these equations; this will give you two solutions (I think). The inequality $x_0 < x_1$ allows you to pick one of these two solutions.
Comment: Jitse can you explain a bit more because I will like to know how to solve this too?
Comment: I'm happy to explain a bit more but I don't want to do the whole question. Which bit are you having trouble with: the formula for the straight line, integrating that formula, or finding $x_0$ and $x_1$?
Comment: I am having trouble with the formula for the straight line and finding $x_0$ and $x_1$.
Comment: ok, I edited my answer to give some details on what you need to do.


In a Quick Tabs module what does this display do in a TAB TYPE view?

Question:
There are two options in my Quick Tabs settings:

display:Master
block:sid(depends on the view you have selected)

I want to know their individual effects on output.
Answer: I would recommend reading this post regarding purpose of Master Display in Views. It contains the standard settings for a view that take a effect when you create a new display in the view. If you don't have specific settings differing from master display in your other displays you could (and maybe should) use it in the Quicktab.


Accessing array declared inside a class via object of that class

Question: I have created a class named as MEMBERS. In this class I have declared an array as a member variable.
class member
{
public $arr_connections;
function connections($id)
{
    $query = mysql_query("Select * from connections where user_id = '$id'");
    while($info = mysql_fetch_array($query))
    {
        $arr_connections[] = $info['connection_id'];
    }

}
}

Then I have created an object of this class as follow
 $user = new member();

After this I am calling the function as
$user->connections($user->id);

Next I am displaying the array
foreach($user->arr_connections as $mem_id)
{
            echo $mem_id;
            $person = new member($mem_id);
            echo "id'>display_picture'/ width = 30 height = 30>";
}

This is not working. I guess my method is wrong. Some constructor was required. But I have to do this without constructor.
Any suggestions?
Answer: You're not assigning it to the class property, because you're missing $this->. Change it into this and it should work for you:
$this->arr_connections[] = $info['connection_id'];


Shared object "libarchive.so.5" not found, required by "pkg"

Question: I just updated my FreeBSD from 9.x to 10.0 (using freebsd-update) and now my pkg isn't working.
# pkg
Shared object "libarchive.so.5" not found, required by "pkg"
#

I know I can use pkg-static meanwhile, but how do I fix my pkg now?
* UPDATE *:
# pkg-static  info pkg
pkg-static: No package(s) matching pkg
# pkg-static install pkg
Updating repository catalogue
pkg-static: http://pkg.freebsd.org/freebsd:10:x86:64/latest/repo.txz: Not Found
#

Comment: (upstream portmaster maintainer here) Sounds like a portmaster bug there. It runs 'pkg info pkg' to see if pkg is installed, and since it is erroring due to the shared lib then it thinks pkg is not installed and uses the old pkg_*. I will try to address that.
Comment: Did you [rebuild all your ports](http://www.freebsd.org/doc/handbook/updating-upgrading-freebsdupdate.html#freebsdupdate-upgrade), e.g. `portmaster -af`?
Comment: when I try doing that, I get : `/usr/local/sbin/portmaster: pkg_version: not found`
Comment: Well now I have to wonder if you ever properly converted to pkgng?
Comment: I just used `freebsd-update` fetch & install && reboot
Comment: @BryanDrewery I just updated my question.
Comment: Rebuild `pkg` from ports: `cd /usr/ports/port-mgmt/pkg && make deinstall reinstall clean`
Answer: Here's what fixed my FreeBSD 9.2-RELEASE -> 10.0-RELEASE update which had the identical issue Shared object "libarchive.so.5" not found required by "pkg", though my pkg-static pkg showed 1.2.6 was installed.
# pkg-static bootstrap -f

Which listed instructions for boot strapping pkg
# pkg-static delete -f pkg
# /usr/sbin/pkg -v

Afterwards pkg seems to behave correctly.
Comment: `pkg-static: 'bootstrap' is not a valid command.`
Comment: I still get: `pkg-static boostrap` `pkg(8) already installed, use -f to force.`
Answer: Options:

Rebuild pkg from ports:
cd /usr/ports/ports-mgmt/pkg && make deinstall reinstall clean

Fix the library link via libmap.conf:
echo "libarchive.so.5 `ls /usr/lib/libarchive.so.*`" >> /etc/libmap.conf

There might be other apps that this fixes the same issue. pkg also relies on 8 other shared libraries. I'm not sure which changed between 9.x and 10.x, but I'd bet there will be others.


Live resources in Akka Stream flow description

Question: There is this note in the akka-stream docs stating as follows:

… a reusable flow description cannot be bound to "live" resources, any connection to or allocation of such resources must be deferred until materialization time. Examples of "live" resources are already existing TCP connections, a multicast Publisher, etc.; …

I have several questions concerning the note:

Apart from the these two examples, what other resource counts as a live?

Anything that cannot be safely (deep)copied? Like a Thread?
Should I also avoid sharing anything that's not thread-safe?

What about an ActorRef existing in the ActorSystem used by the ActorFlowMaterializer?
How to defer allocation until materialization time? Is it safe for example to allocate it in the constructor of a PushPullStage but not in the create function of a FlowGraph?
Comment: From what I understood, your graph should not reference a "resource" directly but rather contain functionality to look up the resource at materialization time. an actor ref should be fine since its pretty much that.
Answer: The problem here is a common problem if we consider webservices, RMI connections or any other communication protocol. It's always recommended sharing "primitive" values then references, because marshalling/unmarshalling or serializing/unserializing is always a headache. Also think of different types of environments communicating each other. Sharing solid values is a safe way to solve communication.
Akka by itself is a good example of "microservices" communicating actors each other. When I read the documentation of Akka, one good word defines Akka actors very well. Actors are like mailbox clients and you can think of each client has a mailbox. When you pass a variable, it's just like you got a new email.
Short result of long story, be avoid sharing "dependent" objects that can be invalidated before it's read from another actor. Additionally, if your system names actorRefs dynamically, avoid calling them by its reference.
"Materializing" is explained in docs of akka-streams.

The process of materialization may be parameterized, e.g. instantiating a blueprint for handling a TCP connection's data with specific information about the connection's address and port information. Additionally, materialization will often create specific objects that are useful to interact with the processing engine once it is running, for example for shutting it down or for extracting metrics. This means that the materialization function takes a set of parameters from the outside and it produces a set of results. Compositionality demands that these two sets cannot interact, because that would establish a covert channel by which different pieces could communicate, leading to problems of initialization order and inscrutable runtime failures.

So use parameters instead of passing "connection" itself.
Deferring a live resource is not a big think. That means if you use one connection for all system, you should keep it alive always. Or when you create a transaction in actor-1 and send it to actor-2, you shouldn't terminate the transaction in actor-1 until actor-2 finished its job with transaction.
Then how you can understand ? Then you use "Future" and "offer()".
Hope I understand your question and hope I can express myself.


Como forçar o typescript a interpretar um parâmetro como uma namespace ao invés de uma classe quando eles tem o mesmo nome - gRPC

Question: Eu estou implementando um pequeno crud usando gRPC e typescript, o meu problema é: Os stubs autogerdos criam uma classe e um "type" para cada parâmetro no protofile. Por exemplo, o parâmetro UserId gera uma classe com getUserId, etc, e uma namespace com o "type" UserId.
O problema é que quando eu tento usar o método no meu client, o typescript interpreta o parâmetro do método como a classe e nāo o tipo.
Então, ao invés de getUsersById({id: 1}, callback)... ele me pede algo como getUsersById(new UserId).
user.Proto:
syntax = "proto3";

package userServicePKG;

message User {
    int32 id = 1;
    string name = 2;
    int32 age = 3;
}

message UserId {
    int32 id = 1;
}

service UserService{
    rpc getUserById (UserId) returns (User);
}

UserServiceClientPb.ts (Protobuf generated) - Definição da Função
methodInfogetUserById = new grpcWeb.AbstractClientBase.MethodInfo(
    User,
    (request: UserId) => {
      return request.serializeBinary();
    },
    User.deserializeBinary
  );

  getUserById(
    request: UserId,
    metadata: grpcWeb.Metadata | null): Promise<User>;

  getUserById(
    request: UserId,
    metadata: grpcWeb.Metadata | null,
    callback: (err: grpcWeb.Error,
               response: User) => void): grpcWeb.ClientReadableStream<User>;

  getUserById(
    request: UserId,
    metadata: grpcWeb.Metadata | null,
    callback?: (err: grpcWeb.Error,
               response: User) => void) {
    if (callback !== undefined) {
      return this.client_.rpcCall(
        new URL('/userServicePKG.UserService/getUserById', this.hostname_).toString(),
        request,
        metadata || {},
        this.methodInfogetUserById,
        callback);
    }
    return this.client_.unaryCall(
    this.hostname_ +
      '/userServicePKG.UserService/getUserById',
    request,
    metadata || {},
    this.methodInfogetUserById);
  }

user_pb.d.ts (Protobuf Generated) - Define os tipos e Classes:
export class UserId extends jspb.Message {
  getId(): number;
  setId(value: number): UserId;

  serializeBinary(): Uint8Array;
  toObject(includeInstance?: boolean): UserId.AsObject;
  static toObject(includeInstance: boolean, msg: UserId): UserId.AsObject;
  static serializeBinaryToWriter(message: UserId, writer: jspb.BinaryWriter): void;
  static deserializeBinary(bytes: Uint8Array): UserId;
  static deserializeBinaryFromReader(message: UserId, reader: jspb.BinaryReader): UserId;
}

export namespace UserId {
  export type AsObject = {
    id: number,
  }
}

Client.Vue:
const client = new UserServiceClient('http://localhost:5001', null, null);

let userId = { id:1 };
client.getUserById(userId, function (error: grpcWeb.Error, response: any) {
     //do something
});

O parâmetro userId causa o seguinte erro:

Argument of type '{ id: number; }' is not assignable to parameter of type 'UserId'.
Type '{ id: number; }' is missing the following properties from type 'UserId': getId, setId, serializeBinary, toObject, and 8 more.Vetur(2345)

Me parece que o typescript deduz que o primeiro parâmetro getUserById é do tipo Class UserId e não do tipo que vem da namespace UserId.
Tem algo que eu possa fazer sobre isso? Ja que foi código autogerado pelo grpc_web, ele deveria interpretar corretamente né? Ah não ser que seja um erro meu na implementação do gRPC ou mal uso do typescript.
Obrigado desde já!
Comment: Agradeço se indicarem problemas com a pergunta também, obrigado.
Comment: A resposta está na mensagem de erro. Quando faz isso `let userId = { id:1 };
client.getUserById(userId, function (error: grpcWeb.Error, response: any) {
     //do something
});` essa variável `userId` não é instancia de `UserId ` e por isso não pode ser passado como parâmetro para essa função. Crie uma instancia da classe, como leitor não posso fazer isso pois a pergunta não fornece informações suficientes para instanciar a classe `UserId` não mostra o constructor e eu conheço 5 libs que possuem o tipo `jspb.Message`, que `UserId` deriva e todos diferentes, impossibilitando uma resposta.
Comment: @AugustoVasques Muito obrigado pela ajuda, `jspb.Message` vem do seguinte import `import * as jspb from "google-protobuf"`, será que ajuda em algo?
Comment: No manual diz para instanciar e  [não subclassear](https://developers.google.com/protocol-buffers/docs/reference/javascript-generated#message) `jspb.Message`. Vai ter que modificar a função.
Answer: Você precisa tipar corretamente sua variável userId. Quando você faz {} para instanciar um objeto, ele vai ser do tipo Object. Faça:
let userId: UserId = new UserId().setId(1); // Tipado como UserId

client.getUserById(userId, function (error: grpcWeb.Error, response: any) {
    //do something
});

Comment: você está certo, eu tinha encontrado a resposta mas acabei não tendo tempo de responder aqui. Inclusive esse link aqui me ajudou bastante https://grpc.io/docs/platforms/web/basics/ . O grande problema é que a maioria dos tutoriais online explicam clients grpc em outras tecnologias e não o gRPC web, porque ainda é muito novo. Muito obrigado pela resposta.


Weighted least-squares negative fitted values

Question: I am running a weighted least-squares regression (where all weights are strictly positive), where my dependent variable is a cross-section of variance values.
Since variance is always positive (>=0), I would expect my fitted values to be positive as well, for them to be meaningful,
$\sigma^2_i = \alpha + \beta * x_i + \epsilon _i$
The problem is that I am getting some negative fitted values:
$\hat{\sigma}^2_i =  \hat{\alpha} + \hat{\beta} * x_i $ for some $i$
Is there any suggestion as to how to constraint the predicted values to be positive?
Thanks!
Comment: You could regress $\log \sigma_i^2$, and then take the exponential of the prediction.
Comment: I am not quite sure how that would solve the issue: you mean use $log\sigma^2_i)$ as my dependent variable, but keep the explanatory variable without log transformation?
Comment: yes, I'll write an answer with more details
Answer: Transform your dependent variable $\sigma^2$ with a logarithm and fit the following model
$$\log \sigma_i^2 = \alpha + \beta x_i + \epsilon_i$$
Get an estimate of the variance $\eta^2$ of the residuals as
$$\hat{\eta^2} = \frac{1}{N}\sum_{i=1}^N (\log \sigma_i^2 - \alpha - \beta x_i)^2$$
Finally, use the estimator
$$\hat{\sigma_i^2} = \exp\left(\hat{\alpha} + \hat{\beta} x_i + \frac{\hat{\eta^2}}{2}\right)$$
The reason there is a $\frac{1}{2}\hat{\eta^2}$ term is because if $\epsilon$ is normally distributed with mean 0, $e^\epsilon$ has expectation $e^{\eta^2/2}$.
Since $\hat{\sigma_i^2 }$ is an exponential, it will always be positive.
Comment: I'll edit the explanation to incorporate that
Comment: I'm not sure what it's called. The log transformation doesn't change anything about how you'd go about estimating beta or alpha, it's a linear model, but for the log of the $\sigma^2$
Comment: Thanks for the thorough explanation. But how can that extra term be estimated?
Comment: Thank you very much. Is this what is called a GLS with log link function? Also, I know the expression of $\hat{\beta}$ in the case of a weighted-least squares, but once I add the log transformation, I don't know how to adjust the \beta expression.
Comment: Can I do this transformation even if this is a WEIGHTED LEAST SQUARES regression, not a simple OLS? If so, how should the above formulas be adjusted to account for the weights?
Comment: Would you please point me to a source where this derivation is done?
Comment: What derivation... I'm not sure what to tell you, this is fairly straightforward... you model the log instead of the value itself... and no it won't be exactly the same model, but you'll get positive values.
Comment: I am not talking about the derivation for log OLS, I am talking about logging the dependent variable for a weighted least squares.
Comment: Ah OK, you wonder if you should adjust the weights. No, there's no particularly principled reason to change the weights. Keep them as is.
Comment: I just re-thought about your method and I have one small doubt about it: For you to introduce the log-transformation in this case,  and derive that final result, you need to assume that $\log{\sigma^2}$ is normally distributed. However, I can not make that assumption here (and this is why I am using weighted-least squares instead of OLS). The only assumption I am making is that the errors have zero mean. Therefore, I am not sure this transformation is valid in this case.
Comment: By definition, the variance is a chi-squared variable.
Comment: If you have more information on the distribution of your variables, you should indicate it. Linear regressions are very common, even when the dependent isn't normally distributed. This is but an approximation.

Also note that not all sample variances follow a chi-square distribution, only those of normal distributions.
Comment: Yes I realize that. In my case, the underlying variable is normal, therefore the variance is approximately a chi-square. Can I still use this transformation, in your opinion? I doubt that though.
Comment: Let us [continue this discussion in chat](http://chat.stackexchange.com/rooms/18745/discussion-between-mayou-and-arthur-b).
Comment: Hi Arthur, I would have a quick follow-up, would you mind jumping back to chat please? Thanks!\
Comment: Hi Arthur, about the taylor expansion you mentioned: in this case let $X = log{\sigma^2}$. Taylor expansion is as follows: $E[f(x)] = f(\mu_x) + f''(\mu_x)/2 * \sigma_x^2$. In this case $f(x) = e^x$. Then the taylor expansion is: $E[e^x] = e^{\mu_x} + e^{\mu_x}/2 * \sigma_x^2$. Which is not what you actually suggested in your answer above. Or am I doing something wrong here?
Comment: yes, you need to expend around mu
Comment: I understand, but this is what you get $\hat{\sigma}_i^2 = exp(\hat{\alpha} + \hat{\beta} * x_i) + \frac{1}{2} exp(\hat{\alpha} + \hat{\beta} * x_i) * \hat{\eta}^2$. This does not correspond to what you suggested above.
Comment: You have to account for the dependency of the higher moments on the second moment. Simpler way to look at it: everything is a Gaussian when you approximate log likelihood to the second order.
Comment: One follow-up: what is the advantage of taking log here (log OLS) as opposed to using GLM with log-link function?


Showing that $S^1$ is orientable

Question: I have a very silly question. While showing that $S^1$ is oriented we use two stereographic projection from the north and south pole. I have the atlas and everything. However, I just could not figure out how to obtain the Jacobian which idefine as follows: $\frac{\partial x^i}{\partial y^j}$. I need to show that the determinant of this Jacobian matrix is positive but I  did not get how to write this matrix.
I try to prove the fact by using Proposition 7.1 in the following link.
Answer: One way to prove that $S^1$ is orientable is by recognizing it as the zero set of $f(x,y)=x^2+y^2-1$ and so $\nabla f$ is a continuous (even smooth) normal vector field defined globally on $S^1$.
Comment: My question is not how to prove it, it is actually how to obtain this Jacobian matrix in terms of chart coordinates. It is may be a problem of linear algebra or calculus than differential geometry.
Answer: The circumference $\mathbf{S}^1$ is an orientable manifold. One standard atlas for $\mathbf{S}^1$ is given by the stereographic projections, defined as $\pi_+ :\mathbf{S}^1-N\to \mathbb{R}$ and $\pi_-:\mathbf{S}^1-S\to\mathbb{R}$:
\begin{equation}
  \pi_+(x,y)= \frac{x}{1-y}, \qquad \pi_-(x,y)=\frac{x}{1+y},
\end{equation}
with inverses
\begin{equation}
  \pi_+^{-1}(t)= \left(\frac{2t}{t^2+1},\frac{t^2-1}{t^2+1}\right), \; \pi_-^{-1}(t)=\left(\frac{2t}{t^2+1},\frac{1-t^2}{t^2+1}\right),
\end{equation}
where $N=(0,1)$ and $S=(0,-1)$ are the north and south poles, respectively.
For instance, $\pi_+$ maps a point $p$ in $S^1$ to $\mathbb{R}$ by computing the intersection of the line by $N$ and $p$ with the horizontal line $y=0$. The other projection $\pi_-$ works analogously with $S$. To check the orientability of $S^1$ the transition matrix has to be taken into analysis. Such matrix is the Jacobian of the transition function between two charts of an atlas. In this case it is given by
$\pi_-\circ\pi_+^{-1}:\mathbb{R}\to\mathbb{R}$ or in the other direction $\pi_+\circ\pi_-^{-1}:\mathbb{R}\to\mathbb{R}$. In the both cases
\begin{equation}
\pi_-\circ\pi_+^{-1} (t) = \frac{1}{t} = \pi_+\circ\pi_-^{-1} (t)
\end{equation}
and its Jacobian, the transition matrix, is $-\frac{1}{t^2}<0$, hence it seems that the circumference is non orientable. However, by changing, for instance the chart $\pi_-$ with $-\pi_-$ the sign reverses and the Jacobian becomes positive, and thus $\mathbf{S}^1$ is orientable. Such construction is possible inductively for all the spheres $\mathbf{S}^n$ by generalising the stereographic projection.
Answer: We have to obtain an $\Bbb R\to\Bbb R$ mapping, by applying stereographic projections first from the North pole, then from the South pole. If you draw it, you can recognise several right triangles and hence some equal angles and similarity of triangles, that would lead to $x\mapsto 4/x$ (unless I miscalculated), if $S^1$ is placed on the unit circle.
The $1\times 1$ Jacobian is now its differentiate, which is $-4/x^2$, actually it seems negative...
This is because we implicitly oriented both our tangent lines from left to right. So, if we consider e.g. the upper line to be scaled from right to left, then the same picture will yield to the function $x\mapsto -4/x$, and this has indeed positive differential.
Comment: As Berci said, the issue is the orientation on the charts that you are using with north and south stereographic projection.  If you want your positive orientation on the circle to be counterclockwise, then standard stereographic projection from the north pole is orientation preserving, whereas standard stereographic projection from the south pole is orientation reversing.  The Jacobian of the transition function will have a negative determinant because of this.

If you don't insist on using stereographic projection (and just want an exercise in following the transition maps), you might be . .
Comment: . . .better served by taking your second chart to be a counterclockwise rotation of your first chart.
Comment: I did not get where $4/x$ comes from actually. What I obtain is from the north pole $(x,y) \mapsto (\frac{x}{1-y})$ and from the south pole $(x,y)\mapsto (\frac{x}{1+y})$. There is this theorem: https://people.maths.ox.ac.uk/hitchin/hitchinnotes/Differentiable_manifolds/Chapter_3.pdf Proposition 7.1, I'm trying to prove the fact by using this proposition.
Comment: Yes. DRAW IT, follow the first $3$ lines of the answer. Anyway, what are the inverses of these functions $\Bbb R\to S^1$?

Showing that $S^1$ is orientable


Barras verticais valoradas com flot.js

Question: Olá.
Utilizo o flot.js para plotar um gráfico "Stacked Bars" exemplo mas eu queria inserir os valores das barras "dentro" da barra, e não simplesmente no tooltip.
Alguém sabe como fazer?
Answer: Existe um plugin para fazer isso. Dei com ele à uns tempos quando estava a trabalhar numa adaptação que eu fiz do Flot para MooTools.
O link do plugin é: https://github.com/leonardoeloy/flot-valuelabels
A parte nova necessária às options é , por exemplo:
series: {
    valueLabels: {
        show: true,
        showAsHtml: true,
        labelFormatter: function (v) {
            return v + '%';
        }
    },

Provavelmente vais ter de adaptar com CSS a posição exata do valor como eu fiz no exemplo usando margin-top: 20px;. Este plugin tem ainda a vantagem de ter uma função para mudar os valores, ie acrescentar o simbolo de percentagem ou correr uma função sobre os valores que mostra.
Nota que existe ainda outro plugin para empilhar as barras, o stack (que juntei ao meu exemplo também).O gráfico funciona também sem ele mas as barras ficam umas atrás das outras em vez de umas em cima das outras.
Exemplo

Barras verticais valoradas com flot.js


Is there a symbol for "never equal to"?

Question: $$A \, \text{never equal to} \, B \implies \, \forall\, \text{valid values of } (A, B)\, , A \text{ is different in value from }B$$
As opposed to $A \neq B$.
$$A \neq B \implies \exists\, \text{ a valid } (A, B)\text{: } A \, \text{is different in value from }B$$

Is there a symbol to conveniently represent the former.

$0$ is both not equal to $1$ and never equal to one. I may be given two functions $f(x)$ and $g(x)$. $f$ and $g$ may produce different results for some $x$ (not equal), always produce the same result (equal) or never produce the same result (never equal).
$A=f$, and $B = g$.
The set of "not equal to" is a proper superset of the set of "never equal to", and both are disjoint with the set of "equal to".
Comment: You can say that for all values of A and B **satisfying a certain property** or within a certain set, $A\neq B$. But given that the characteristics of A and B must be stated, that makes it impossible to state it within a single symbol.  I don't think it's always helpful to rush so quickly to put a question on hold.
Comment: "0 is both not equal to one and never equal to one": I know what idea you have in mind, but this is expressed in an unacceptable way.
Comment: @5xum $A=B+1:A,B\in\mathbb{Z}$ might illustrate what he means. There is some $A$ which equals some $B$ but for all A for all B satisfying the equation they never equal each other.
Comment: How about, $f(x) ≠ g(y)$ for every $x,y$ iff $\operatorname{im} f ∩ \operatorname{im} g = \{\}$
Comment: For numbers, $0\neq 1$ means already "never equal".
Comment: Also, not sure what the juxtaposition of $BA$ in  "$B A ≠ B$" is supposed to mean
Comment: Your notation is too loose to have meaning and allow an answer. Please add some rigor.
Comment: $\forall A \ \forall B \ (A \ne B)$ is simply wrong; obviously, $A=A$.
Comment: What kinds of objects are $A$ and $B$?  IN what sense can they sometimes be the same as opposed to never the same?
Comment: You can make this question more clear by giving a real life example of two mathematical objects for which $A\neq B$ is **not** true, but "$A$ is never equal to $B$" is **true**.
Comment: 0 is both not equal to one and never equal to one. I may be given two functions $f(x)$ and $g(x)$. $f$ and $g$ may produce different results for some $x$ (not equal), always produce the same result (equal) or never produce the same result (never equal).
Comment: @YvesDaoust what would be an acceptable way of expressing it?
Comment: @TobiAlafin: you must make the dependency on some parameter explicit. Otherwise "never" is meaningless. When you compare two values for equality, they don't change their minds every now and then.
Answer: What exactly do you even mean by "never equal to"?
A $x$ is equal to $y$ (in which case it is "always" equal to $y$) or it is not equal to $y$. You'll have to specify exactly what "never" means. How is it different from "not equal"?
For example, you say
$$A \neq B \implies \exists\, A, B: A \, \text{is different in value from }B$$
which is just not true. $A\neq B$ is true if and only if $A=B$ is false. That's all. There are no quantifiers here. We have an element $A$, and an element $B$, and either they are the same element (in which case $A=B$) or they are not (in which case $A\neq B$). There is nothing in between.
Comment: @TobiAlafin Much clearer. I didn't know before you were talking about functions. However I don't know of any notation that would describe what you want.

NOTE: Two functions are equal if they have the same domain, codomain, and they map each element of the domain to the same element of the codomain. But I didn't know you were talking about that. Your notation is very very very sloppy, and that brought a lot of confusion.
Comment: @TobiAlafin And this is exactly where you are sloppy. If $A=f(x)$, then (if $f$ is a real valued function) $A$ is a **number**. It is some very particular value, and an element of $\mathbb R$. However, you are not talking about this. You are talking about the **function**, so what you really want to say is $A=f$, not $A=f(x)$. The difference in meaning between these two expressions is absolutely huge. Also, how can we know that " I'm concerned with the variables denoting the output of the functions, " if you don't tell us that from the beginning?
Comment: Not equal means that there exists a valid ordered pair $(x, y)$ such that $x$ and $y$ have different values. Never equal means that for all valid values of $x$ and $y$, $x$ and $y$ have different values.
Comment: Your definition of "not equal" is isomorphic to my definition of not equal.
Comment: @TobiAlafin Valid ordered pair in which set? Which two things are then equal? Your definition is vague, and therefore mathematically meaningless. For example, is $0$ "not equal" to $1$, or is it "never equal" to $1$? Can you give an example of a pair $A,B$ such that $A$ is "not equal to" $B$?
Comment: 0 is both not equal to one and never equal to one. I may be given two functions $f(x)$ and $g(x)$. $f$ and $g$ may produce different results for some $x$ (not equal), always produce the same result (equal) or never produce the same result (never equal). Is my question clearer now?
Comment: Well, $A = f(x)$, and $B = g(x)$. I'm concerned with the variables denoting the output of the functions, which is why I spoke as I did.
Answer: If we follow your definition(s), yes there is a symbol for that: $F$.
Indeed,
$$\forall A, B\in D:A\ne B$$ is false (take $A=B=C$ where $C\in D$ as a counterexample).
Assuming anyway that $D\ne\emptyset$.
The predicate
$$\exists A, B\in D:A\ne B$$ is false for empty sets and singletons, and true otherwise. Hence it can be written $\#D>1$.

Update:
Speaking of the valid values of the pairs $(A,B)$ implies that you are talking about a binary relation, i.e. a set of pairs. Then you are looking for a way to express that the relation is irreflexive. Such a predicate will involve the relation, not a particular pair $(A,B)$.
I have never seen a specific shorthand, you might write $\text{Irreflexive(R)}$ where $R$ denotes the relation.
Comment: I've edited my question to include "valid values of". There may never be such a situation where we are given $(A, A)$.
Comment: 0 is both not equal to one and never equal to one. I may be given two functions $f(x)$ and $g(x)$. $f$ and $g$ may produce different results for some $x$ (not equal), always produce the same result (equal) or never produce the same result (never equal).
Comment: @TobiAlafin: let $R:=\{x\in\mathbb R:(f(x),g(x))\}$. You can write $\text{Irreflexive}(R)$, which expresses $\forall x\in\mathbb R:f(x)\ne g(x)$.

Is there a symbol for "never equal to"?


Rugby league: does a knock-on require an immediate stoppage of play?

Question: In a few recent rugby league (Australian NRL) games that I have seen, a player will drop a ball that was passed to him, causing it to move forward off of his hands and bounce forward on the ground. Subsequently, a player from the opposing team will rush toward the ball, grab it, and make a mad dash toward their opponent's goal line.
From looking through the official rules, it is my understanding that dropping the ball in a forward motion (except during a charge-down) is a knock-on, which, according to the book, should result in a scrum being awarded to the defense.
Why is the recovering player allowed to take over possession of the ball without a scrum?
The only thing that I can think of is that if a knock-on is considered a penalty, perhaps the opponent is allowed to keep playing so long as they have the advantage?
Answer: Australia's National Rugby League (NRL) is played in accordance with the Rugby League International Federation laws, modulo some minor changes outlined in official documents from the Australian Rugby League (ARL).
The RLIF law regarding knock-on states, with emphasis added, that

[i]f, after knocking-on accidentally, the player knocking-on regains or kicks the ball before it touches the ground, a goal post, cross bar or an opponent, then play shall be allowed to proceed.
Otherwise play shall stop and a scrum shall be formed except after the fifth play-the-ball.

This passage is quite clear: a knock-on requires play to stop.
But in the Glossary Of Terms of those laws, we are provided with the definition of Advantage:

allowing the advantage means allowing play to proceed if it is to the advantage of the team which has not committed an offence or infringement.

In the case that the team recovering the ball has not committed an offence or infringement, and depending on the circumstances, continuing to play on may be to their advantage.
Finally, under the Notes section of laws regarding Match Officials, we are given a clear indication that the referee (and they alone) may decide what advantage is, and whether it has been obtained. They must also allow advantage only when the non-offending team both has an "adequate opportunity" for an advantage and has attempted to use it.
The former explains why play is not necessarily stopped for a scrum: the player gaining the ball may have advantage from playing on. The latter explains why players will immediately try to regather the ball and make a territorial gain from that position: they can only have advantage if they try to make use of a potential advantage.
In the worst case, they are brought back for the scrum, which by custom and by law, almost assuredly gives them possession. In the best case, they make great gains in territory or are able to score a try. Hence, both players and referees have incentive and ability under the laws to play on, not needing to stop play first.

The advantage law applies to all phases of play, but where a team infringes in a strong tactical position the advantage should be allowed only if the ball goes immediately into the possession of the non-offending team.
The Referee is the sole judge of what constitutes an advantage be it tactical or territorial. An infringement is not 'negated' simply because the ball touches or is touched by an opponent.
The opponent must have adequate opportunity to take advantage and endeavour to do so before play is allowed to proceed.


YQL not returning data from balance sheet or income statement

Question: I have been trying to use YQL to access the fundamentals of listed companies. But what is showing up in the Yahoo finance page is not being returned from YQL queries. Specifically I need to retrieve data from balance sheet and income statement, a sample query for Apple in YQL is like:
SELECT * FROM yahoo.finance.balancesheet WHERE symbol='AAPL'
This, however, only returns a time frame (quarterly), and nothing else.
Link to YQL console of my sample query is here
Is the data inaccessible to YQL or is there anything wrong with the way I am running the query? How can I get a complete list of data as in http://finance.yahoo.com/q/bs?s=AAPL through YQL?
Answer: Your query used to work fine. However, a month or two ago, a number of yahoo.finance YQL "tables" stopped working.
IOW, you are doing it right, but YQL is broken.
If you mouse over the yahoo.finance.balancesheet entry in the left column of the YQL console, buttons labeled desc and src appear. If you click src, it fetches the scraping code for you: http://www.datatables.org/yahoo/finance/yahoo.finance.balancesheet.xml. To make the E4X JavaScript legible, right-click and select View Source or use wget or curl from the command line.
Notice that the code fetches http://finance.yahoo.com/q/bs?s=AAPL&quarterly and then uses an XPath query to find the data:
var query = y.xpath(rawresult, "//table[@class='yfnc_tabledata1']/tr/td/table/tr");

If you fetch the page into your browser and inspect the HTML, you find that there is indeed a table with class yfnc_tabledata1. However, it has no tr direct child. Apparently, Yahoo must have decided to add a tbody element. That probably explains why the query no longer scrapes any data.
The code page lists Ryan Hoium as the author. A little googling leads to the github repository where the code lives, alongside the code for the other Yahoo Finance tables.
Sadly, only the yahoo.finance.sectors table has received recent attention. The change was to add double slashes to its XPath expression. Double-slashes relax the "direct child" requirement, allowing, for example, tr to still be found even if there is an intervening tbody. However, it appears the new version has not been pushed out to the public site.
Comment: Indeed, I think it's the problem they are facing right now. But don't know when it's gonna be fixed. From their repo (https://github.com/yql/yql-tables/tree/master/yahoo/finance) it looks like no one has been actively updating it


Mixed strategy nash equilibria in from $2\times N$ bimatrix form

Question: I'm looking for a way of finding (manually!) mixed strategy Nash equilibria in a $2\times N$ game. Calling player 1 the player with two strategies and player 2 the one with $N$ strategies, I've constructed player 2's best response function, however this leaves me only half way and I'm unsure on how to continue.
Ideas?
Thanks in advance!
Answer: For the zero-sum case you should look at Philip Straffin's book: Game Theory and Strategy, Part I, Chapter 3.
Comment: Unfortunately I'm looking for an approach to a non-zero-sum problem, but thanks, +1
Answer: You should construct an "upper envelope diagram" that describes the best response pure strategies and payoffs of player 2 against the mixed strategies of player 1. For an example, see the left part of figure 1 in the following paper:
D. Avis, G. Rosenberg, R. Savani, and B. von Stengel (2010), Enumeration of Nash equilibria for two-player games. Economic Theory 42, 9-37.
http://www.maths.lse.ac.uk/Personal/stengel/ETissue/ARSvS.pdf
(That paper also includes a complete technical exposition of the general problem for m by n games.)
Here is an example of the upper envelope diagram for a 2x5 game, where player I has pure strategies A and B and player 2 has pure strategies a,..,e.

What you are interested in is the "vertices" of this upper envelope. The two vertices at the far left and right correspond to the best responses against the two pure strategies of player one (so for these vertices you just check if the corresponding strategy of player 1 is a best response to this best response of player 2).
Vertices between these correspond to mixed strategies of player 1 that make player 2 indifferent between (at least) two different pure strategies.
Suppose we are at such a vertex defined by the pure strategies of player 2  a and b. For this vertex you need to look at the two columns of player 1's payoff matrix that correspond to a and b and check if the best response of player 1 against a is different from the best response of player 1 against b (or is tied, but let's ignore that case for simplicity). If these two best responses to a and b differ then you can find a mixed strategy for player 2 that makes player 1 indifferent between his two pure strategies. Then this strategy of player 2, paired with the strategy of player 1 given by the point on the x-axis in the best response diagram, is a Nash equilibrium.
You need to check this for every vertex (for the example above, corresponding to {d} at the left, then {d,b},{b,a}, and {a,e} in the interior, and {e} on the far right). Checking the far left and far right vertices correspond to checking for pure Nash equilibria. Checking the "interior" vertices corresponds to looking for equilibria where both players use 2 pure strategies.
Things can be complicated by degeneracies in the payoffs, e.g., three lines meeting in one point on the upper envelope, but I won't go into that here.
To investigate this, you can use our software:
http://www.gametheoryexplorer.org/


Replace strings with new strings

Question: I have a page with list of teasers. It contain links like 1 comment, 1 new comment, add your comment. I want to change 1 comment to 1 response, 1 new comment to 1 new response and add new comment to add new response.
I used string overrides module and tried to change the strings, but i was able to change only add new comment to add new response. How to change 1 comment and 1 new comment? please help.
Comment: Is your site multilingual already?
Comment: @molot : no, it is not multilingual.
Answer: There is another solution to implement hook_preprocess_node to modify the comments links.
You can follow the answers in the Modifying teaser node comment links
Answer: If you need only few strings redefined, String Overrides is a good solution. If you want to redefine most of them, or if your site is multilingual anyway, there is a better way:

Be sure that internationalization modules are installed and enabled
Go to Administration » Configuration » Regional and language
Click Add language, and create something like English GB
"Translate" strings you want to have changed
Comment: Thanks Molot, I tried the steps, but under Translate interface I did not found any string like comment or new comment. Any suggestions ?
Comment: @Nikhil in my setup, you can find *@count new comments* at /admin/config/regional/translate/edit/2050 - others are there to be found, too. Can't quite guess why you cannot. If my address works for you, I can post all the rest as well.
Comment: I tried to find @count new comments and also tried the link /admin/config/regional/translate/edit/2050 but it is showing nothing.

Replace strings with new strings


Não grava no banco de dados e no console aparece como gravado

Question: Tenho um formulário dentro do modal para gravar cadastro, quando insiro os dados dá como se estivesse gravado no console do Eclipse, porém o mesmo não acontece no banco
Mensagem no console como Ok da gravação.
<code>Hibernate:
select
    empresa0_.id as id1_0_,
    empresa0_.cnpj as cnpj2_0_,
    empresa0_.data_fundacao as data_fun3_0_,
    empresa0_.nome_fantasia as nome_fan4_0_,
    empresa0_.razao_social as razao_so5_0_,
    empresa0_.tipo as tipo6_0_
from
    Empresa empresa0_

<p:commandButton id="salvar-button" value="Salvar"
                    action="#{gestaoEmpresasBean.salvar}"
                    process="empresa-dialog" update="empresa-table"
                    oncomplete="PF('edicaoEmpresaDialog').hide()" />

@Inject
private Empresas empresas;

@Inject
private CadastroEmpresaService cadastroEmpresa;

@Inject
private FacesMessages messages;

private List<Empresa> todasEmpresas;
private Empresa empresaEdicao = new Empresa();

public void prepararNovoCadastro() {
    empresaEdicao = new Empresa();
}

public void salvar() {
    cadastroEmpresa.salvar(empresaEdicao);
    consultar();

    messages.info("Empresa salva com sucesso!");
}

public void consultar() {
    todasEmpresas = empresas.todas();
}

public List<Empresa> getTodasEmpresas() {
    return todasEmpresas;
}

public TipoEmpresa[] getTiposEmpresas() {
    return TipoEmpresa.values();
}

public Empresa getEmpresaEdicao() {
    return empresaEdicao;
}

public void setEmpresaEdicao(Empresa empresaEdicao) {
    this.empresaEdicao = empresaEdicao;
}
</code>
Service
<code>@Transactional
public void salvar(Empresa empresa) {
    empresas.guardar(empresa);
}
</code>
Comment: Está dando *commit* após inserir, alterar e deletar as informações do banco? Até onde sei o *auto commit* é `false`.
Comment: Este log só mostra que o registro foi obtido do banco de dados, não mostra que foi persistido. Que tal você mostrar o código do bean (*gestaoEmpresasBean.salvar*)?
Comment: Esse erro abaixo seria do messages.properties no lugar errado?
Caused by: java.util.MissingResourceException: Can't find bundle for base name com.algaworks.erp.Messages, locale pt_BR
Answer: Pessoal consegui resolver, era erro de configuração do messages.properties que estava na pasta errada, faltou também o persistence.xml dentro da pasta META-INF embora eu já tinha criado automático pelo eclipse, fiz manual e deu certo. Abraço.