Campos do tipo Real no banco com problemas ao carregar Model

Question: Há uns 3 ou 4 meses atrás tive esse mesmo problema, que depois de eu remapear toda a minha Model, resolveu. E agora voltou a dar o mesmo problema. Antes era com o float e agora com o tipo Real. Na minha Model está decimal e dá o erro. Já alterei para Single, Decimal, decimal, float, double e continua. Uso Sql Server 2012.

The 'CustoDiario' property on 'Liberacao' could not be set to a
  'System.Single' value. You must set this property to a non-null value
  of type 'System.Decimal'.

A Model
<code>[Table("LIBERACAO")]
    public class Liberacao
    {
        [Key]
        [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
        [DefaultValue(0)]
        [Column("ID_LIBERACAO")]
        public int IdLiberacao { get; set; }
        [Column("FLAG_LIBERACAO")]
        public byte FlagLiberacao { get; set; }
        [DefaultValue(0)]
        [Column("ID_ORCAMENTO")]
        public double IdOrcamento { get; set; }
        [Column("ID_VENDEDOR")]
        public int IdVendedor { get; set; }
        [Column("VENDEDOR")]
        public string Vendedor { get; set; }
        [Column("ID_FILIAL")]
        public int IdFilial { get; set; }
        [Column("FILIAL")]
        public string Filial { get; set; }
        [DefaultValue(0)]
        [Column("DATALIB")]
        public double DataLib { get; set; }
        [DefaultValue(0)]
        [Column("HORALIB")]
        public double HoraLib { get; set; }
        [Column("ID_CLIENTE")]
        public int IdCliente { get; set; }
        [Column("CLIENTE")]
        public string Cliente { get; set; }
        [Column("TIPO_VENDA")]
        public string TipoVenda { get; set; }
        [DefaultValue(0)]
        [Column("JUROS")]
        public double Juros { get; set; }
        [DefaultValue(0)]
        [Column("DESCONTO")]
        public double Desconto { get; set; }
        [DefaultValue(0)]
        [Column("VENCIMENTO")]
        public double Vencimento { get; set; }
        [DefaultValue(0)]
        [Column("ACRESCIMO")]
        public double Acrescimo { get; set; }
        [DefaultValue(0)]
        [Column("ENTRADA")]
        public double Entrada { get; set; }
        [DefaultValue(0)]
        [Column("PRAZO")]
        public double Prazo { get; set; }
        [DefaultValue(0)]
        [Column("TOTAL_LIQUIDO")]
        public double TotalLiquido { get; set; }
        [DefaultValue(0)]
        [Column("MIN_TOTAL")]
        public double MinTotal { get; set; }
        [Column("USUARIO")]
        public string Usuario { get; set; }
        [DefaultValue(0)]
        [Column("CUSTODIARIO")]
        public decimal CustoDiario { get; set; }
        [DefaultValue(0)]
        [Column("MAX_COMI")]
        public decimal MaxComi { get; set; }
        [DefaultValue(0)]
        [Column("VALOR_COMI")]
        public decimal ValorComi { get; set; }
        [DefaultValue(0)]
        [Column("NOVA_COMI")]
        public decimal NovaComi { get; set; }
        [Column("MENSSAGEM")]
        public string Mensagem { get; set; }
        [Column("Menssagem_RET")]
        public string MensagemRet { get; set; }
        [DefaultValue(0)]
        [Column("DataRetorno")]
        public Single DataRetorno { get; set; }
        [DefaultValue(0)]
        [Column("HoraRetorno")]
        public Single HoraRetorno { get; set; }
        [DefaultValue(0)]
        [Column("TempoProcesso")]
        public Single TempoPrecesso { get; set; }
        [Column("Tipo")]
        public int Tipo { get; set; }
        [Column("PROGRAMA")]
        public string Programa { get; set; }
        [Column("NOME_PC")]
        public string NomePc { get; set; }
        [Column("NOME_PROCEDURE")]
        public string NomeProcedure { get; set; }
        [Column("Perc_Juros_Total")]
        public string PercJurosTotal { get; set; }
        [Column("FLAG_CULTURAVENCIDA")]
        public byte FlagCulturaVencida { get; set; }
        [Column("CULTURA")]
        public string Cultura { get; set; }
        [Column("CULTURA_VCTO")]
        public int CulturaVcto { get; set; }
        [Column("FLAG_PRORROGADO")]
        public byte FlagProrrogado { get; set; }
        [DefaultValue(0)]
        [Column("VALOR_PRORROGADO")]
        public Single ValorProrrogado { get; set; }
        [Column("DIAS_ATRASO")]
        public int DiasAtrazo { get; set; }
        [Column("ID_VENDEDOR2")]
        public int IdVendedor2 { get; set; }
        [Column("VENDEDOR2")]
        public string Vendedor2 { get; set; }
        [DefaultValue(0)]
        [Column("COMISSAO_VEND2")]
        public Single ComissaoVend2 { get; set; }
        [Column("FLAG_COTACAO")]
        public byte FlagCotacao { get; set; }
        [Column("TipoVenda")]
        public string TipoVenda1 { get; set; }
        [Column("Flag_Receber_Atrasado")]
        public byte FlagReceberAtrazado { get; set; }
        [Column("Autorizou_Receber_Atrasado")]
        public string AutorizouReceberAtrazado { get; set; }
</code>
o método que está no serviço
<code>[Route("{id}/{value}")]
        public void AtualizaLiberacao(int id, string value)
        {
            try
            {
                var lista = contexto.Liberacoes
                            .Where(l => l.IdOrcamento == id)
                            .ToList();

                lista.ForEach(f =>
                {
                    f.FlagLiberacao = 1;
                    f.AutorizouReceberAtrazado = value;
                });

                contexto.SaveChanges();
            }
            catch(Exception ex)
            {

            }
        }
</code>
EDIT1
Meu contexto
<code>public class AutorizadorContext : DbContext
    {
        public AutorizadorContext()
            : base("VLINK")
        {
            Database.SetInitializer<AutorizadorContext>(null);
        }
        public DbSet<Liberacao> Liberacoes { get; set; }
        public DbSet<ItensLib> ItensLibs { get; set; }
        public DbSet<TabelaLiberacao> TabelaLiberacoes { get; set; }
    }
</code>
Answer: Você precisa alterar o tipo do seu campo CustoDiario de decimal para single, se no banco está como real.
Segue um link abaixo com os tipos de dados no Sql Server e seus equivalentes em C#.
https://docs.microsoft.com/en-us/sql/relational-databases/clr-integration-database-objects-types-net-framework/mapping-clr-parameter-data
Comment: Oi Carlos, como eu disse no post eu fiz isso. Veja que na minha Model eu pus **Single**. Inclusive na Model eu comentei todos os campos **REAL** e continua dando o mesmo erro.
Comment: Você poderia postar o seu contexto também?
Comment: Quando você altera o tipo de Decimal para Single, continua apresentando o mesmo erro?
Comment: Sim, qualquer configuração o erro persiste. Tive esse problema e foi bem discutido aqui. Aí refiz minha Model, baseado no link passado por você, eu já havia visto ele antes. Estava funcionando, tanto que continua funcionando no site, esse erro está dando aqui em localhost. Testo tudo em localhost e depois subo. No site está rodando. Apenas fui acrescentar outro serviço e nada mais e nem testei o novo serviço. Esse serviço já funcionou. O usuário pediu uma alteração, mas não serviço em si, mas colocar um popup e chamar o serviço de lá. Só alterei o lugar da chamada, mas o serviço continua.
Comment: Tá dando erro agora em quase todos os campos aqui. Tá osso.
Comment: Cara, recomendo você refazer o mapeamento.
Comment: Então, fiz vários clean e recompile e reiniciei o VS algumas vezes e de repente voltou a funcionar. Havia comentado alguns campos e descomentei e continuaram a funcionar. Não sei o que realmente aconteceu, mas se voltar a dar pau, posto novamente. Valeu!!
Comment: Beleza,cara. Se precisar de ajuda estamos as ordens. Abraço.


How to show results on desired sheet?

Question: The below code is not showing the results on the "All Stock Analysis" sheet.
I tried doing a test after the activation of each worksheet (Range("I1).Interior.Color = vbGreen) and cell I1 turns green on each of the desired worksheets. What other tests can I try? No error msg pops up.
Sub AllStocksAnalysisRefactored()
    Dim startTime As Single
    Dim endTime  As Single

    yearValue = InputBox("What year would you like to run the analysis on?")

    startTime = Timer

    'Format the output sheet on All Stocks Analysis worksheet
    Worksheets("All Stock Analysis").Activate

    Range("A1").Value = "All Stocks (" + yearValue + ")"

    'Create a header row
    Cells(3, 1).Value = "Ticker"
    Cells(3, 2).Value = "Total Daily Volume"
    Cells(3, 3).Value = "Return"

    'Initialize array of all tickers
    Dim tickers(12) As String

    tickers(0) = "AY"
    tickers(1) = "CSIQ"
    tickers(2) = "DQ"
    tickers(3) = "ENPH"
    tickers(4) = "FSLR"
    tickers(5) = "HASI"
    tickers(6) = "JKS"
    tickers(7) = "RUN"
    tickers(8) = "SEDG"
    tickers(9) = "SPWR"
    tickers(10) = "TERP"
    tickers(11) = "VSLR"

    'Activate data worksheet
    Worksheets(yearValue).Activate

    'Get the number of rows to loop over
    RowCount = Cells(Rows.Count, "A").End(xlUp).Row

    '1a) Create a ticker Index
    Dim tickerIndex As Single
    tickerIndex = 0

    '1b) Create three output arrays
    Dim tickerVolumes(12) As LongLong
    Dim tickerstartingPrices(12) As Single
    Dim tickerendingPrices(12) As Single

    ''2a) Create a for loop to initialize the tickerVolumes to zero.
    For i = 0 To 11

        tickerVolumes(i) = 0

    ''2b) Loop over all the rows in the spreadsheet.
        For j = 2 To RowCount

        '3a) Increase volume for current ticker
            tickerVolumes(tickerIndex) = tickerVolumes(tickerIndex) + Cells(j, 8).Value

        '3b) Check if the current row is the first row with the selected tickerIndex.
        'If  Then
            If Cells(j - 1, 1).Value <> tickers(tickerIndex) And _
              Cells(j, 1).Value = tickers(tickerIndex) Then

                tickerstartingPrices(tickerIndex) = Cells(j, 6).Value

        'End If
            End If

        '3c) check if the current row is the last row with the selected ticker
         'If the next row's ticker doesn't match, increase the tickerIndex.
        'If  Then
            If Cells(j + 1, 1).Value <> tickers(tickerIndex) And _
              Cells(j, 1).Value = tickers(tickerIndex) Then

                tickerendingPrices(tickerIndex) = Cells(j, 6).Value

            '3d Increase the tickerIndex.
                tickerIndex = tickerIndex + 1

        'End If
            End If

        Next j
    Next i

    '4) Loop through your arrays to output the Ticker, Total Daily Volume, and Return.
    For i = 0 To 11

        Worksheets("All Stock Analysis").Activate

    Next i

        'Formatting
    Worksheets("All Stock Analysis").Activate
    Range("A3:C3").Font.FontStyle = "Bold"
    Range("A3:C3").Borders(xlEdgeBottom).LineStyle = xlContinuous
    Range("B4:B15").NumberFormat = "#,##0"
    Range("C4:C15").NumberFormat = "0.0%"
    Columns("B").AutoFit

    dataRowStart = 4
    dataRowEnd = 15

    For i = dataRowStart To dataRowEnd

        If Cells(i, 3) > 0 Then

            Cells(i, 3).Interior.Color = vbGreen

        Else

            Cells(i, 3).Interior.Color = vbRed

        End If

    Next i

    endTime = Timer
    MsgBox "This code ran in " & (endTime - startTime) & _
      " seconds for the year " & (yearValue)

End Sub

Here is how "All Stock Analysis" sheet will look after running the code:
Comment: You are activating the worksheet 12 times instead of doing it once and then writing the result 12 times (once for each `Whatever`).
Comment: It seems to me that you are setting the color of the result cells but not their values. Therefore your result cells are blank.
Comment: Consider this approach:- You need to have 3 values for each of 12 tickers, a total of 36 data. Why not create an array, like `Dim Arr As Variant: Redim Arr(1 To 12, 1 To 3)`, fill all the data into this array, paste the completed array to the result area and end the macro with formatting the cells in the output sheet? It's difficult to help you more without knowing the data in the annual sheets but consider deploying worksheet functions like SUMIFS() instead of loops. Why should you need 150 lines of code to fill 36 cells? Consider `Dim Tickers() As String: Tickers = Split("AY,CSIQ,DQ", ",")`
Answer: You only need to scan the data sheet once if you use a dictionary object to convert the ticker ID to an array index number.
Option Explicit

Sub AllStocksAnalysisRefactored()

    Const SHT_NAME = "All Stock Analysis"

    Dim wb As Workbook, ws As Worksheet, wsYr As Worksheet
    Dim cell As Range, yr As String, iRow As Long, iLastRow As Long
    Dim t As Single: t = Timer

    ' choose data worksheet
    yr = InputBox("What year would you like to run the analysis on ? ", "Enter Year", Year(Date))

    Set wb = ThisWorkbook
    On Error Resume Next
    Set wsYr = wb.Sheets(yr)
    On Error GoTo 0
     ' check if exists
    If wsYr Is Nothing Then
        MsgBox "Sheet '" & yr & "' does not exists.", vbCritical, "Error"
        Exit Sub
    End If

    'Initialize array of all tickers
    Dim tickerID, tickerData(), i As Integer, n As Integer
    Dim dict As Object, sId As String
    tickerID = Array("AY", "CSIQ", "DQ", "ENPH", "FSLR", "HASI", _
                    "JKS", "RUN", "SEDG", "SPWR", "TERP", "VSLR")

    n = UBound(tickerID) + 1
    ReDim tickerData(1 To n, 1 To 5)

    ' create dict id to index
    Set dict = CreateObject("Scripting.Dictionary")
    For i = 1 To n
        sId = UCase(Trim(tickerID(i - 1)))
        tickerData(i, 1) = sId ' id
        tickerData(i, 2) = 0 ' volume
        tickerData(i, 3) = 0 ' start price
        tickerData(i, 4) = 0 ' finish price
        tickerData(i, 5) = 0 ' count
        dict.Add sId, i
    Next

    'Get the number of rows to loop over
    iLastRow = wsYr.Cells(Rows.Count, "A").End(xlUp).Row

    ' Loop over all the rows in the spreadsheet.
    ' A=ticker, F=Price , H=Volume
    For iRow = 2 To iLastRow
        sId = UCase(Trim(wsYr.Cells(iRow, "A")))
        If dict.exists(sId) Then
            i = dict(sId)
            ' volume
            tickerData(i, 2) = tickerData(i, 2) + wsYr.Cells(iRow, "H") ' volume
            ' start price when count is 0
            If tickerData(i, 5) = 0 Then
                tickerData(i, 3) = wsYr.Cells(iRow, "F")
            End If
            ' end price
            tickerData(i, 4) = wsYr.Cells(iRow, "F")
            ' count
            tickerData(i, 5) = tickerData(i, 5) + 1
        End If
    Next

    'Format the output sheet on All Stocks Analysis worksheet
    Set ws = wb.Sheets(SHT_NAME)
    ws.Cells.Clear
    With ws
        .Range("A1").Value2 = "All Stocks (" & yr & ")"
        With .Range("A3:E3")
            .Value2 = Array("Ticker", "Total Daily Volume", "Start Price", "End Price", "Return")
            .Font.FontStyle = "Bold"
            .Borders(xlEdgeBottom).LineStyle = xlContinuous
        End With
       .Range("A4").Resize(n, 4).Value2 = tickerData
       .Range("B4:D4").Resize(n).NumberFormat = "#,##0"
       .Range("E4").Resize(n).NumberFormat = "0.0%"
       .Columns("B").AutoFit
    End With

    ' coloring
    For Each cell In ws.Range("E4").Resize(n)
       cell.FormulaR1C1 = "=(RC[-1]-RC[-2])/RC[-2]" ' end-start/start
       If cell > 0 Then
          cell.Interior.Color = vbGreen
       Else
          cell.Interior.Color = vbRed
       End If
    Next

    ws.Activate
    ws.Range("A1").Select
    MsgBox "This code ran for (" & yr & ")", vbInformation, Int(Timer - t) & " seconds"

End Sub

How to show results on desired sheet?


How to display print dialog in java fx and print node

Question: I'd like to show a dialog prior to printing so that users can choose their preferred printer and also change page setup if possible,
I'm using Java 8 update 31 in a desktop environment (Windows 8 64 bit), my current code like this
Node node = new Circle(100, 200, 200);
PrinterJob job = PrinterJob.createPrinterJob();
if (job != null) {
boolean success = job.printPage(node);
if (success) {
    job.endJob();
}
}

Answer: You can use the showPrintDialog method of PrinterJob.
PrinterJob job = PrinterJob.createPrinterJob();
if (job != null && job.showPrintDialog(node.getScene().getWindow())){
    boolean success = job.printPage(node);
    if (success) {
        job.endJob();
    }
}

Comment: How to resize node if its too big? (cropped on actual printing page). Changing its width and height makes some content not visible if it has a lot of it.


Exposed filter AJAX error

Question: I have put an exposed filter on my page, which is an auto-submit textbox without any submit button. When I put the focus on this textbox and refresh the page with no value inside the textbox, the page gives me an error which is caused by emptiness of the textbox.
**Error:**
An AJAX HTTP request terminated abnormally.
Debugging information follows.
Path: /************/views/ajax
StatusText:
ResponseText:
ReadyState: 4

What is your solution for it?
Answer: When you give the focus to your field, it triggers an ajax call to the server. If you reload the page right away, it breaks the ajax call and throw this error in an alert.
This only happens as you reload the page during an ajax call. As far as i know you can't do anything about it, unless you modify the core I guess - which is "unclean".
You could use the classes added in css to display a loader while there is an ajax call to the server, and let the user know the page is working on something.
EDIT:
Thanks to clive's comment I actually got rid of this alert by overriding Drupal's Drupal.ajax.prototype.error function.
In a js file, you can add :
Drupal.ajax.prototype.error = function (response, uri) {
  // Remove the progress element.
  if (this.progress.element) {
    $(this.progress.element).remove();
  }
  if (this.progress.object) {
    this.progress.object.stopMonitoring();
  }
  // Undo hide.
  $(this.wrapper).show();
  // Re-enable the element.
  $(this.element).removeClass('progress-disabled').removeAttr('disabled');
  // Reattach behaviors, if they were detached in beforeSerialize().
  if (this.form) {
    var settings = response.settings || this.settings || Drupal.settings;
    Drupal.attachBehaviors(this.form, settings);
  }
};

This is a copy of the original error handler callback without the alert() function. This will remove your message, but will also hide any error message returned by Drupal's Ajax.
Comment: The message comes from `Drupal.ajax.prototype.error`, but it's invoked from `Drupal.ajax` itself. The latter would need to be monkey patched to change that behaviour, no need to edit anything in core as such
Comment: Thanks for your wise comment! I just tested, and your right, no need to modify the code. I updated my answer.

Exposed filter AJAX error


Running a script through Django admin interface button/url

Question: I am kinda new to python and Django as well so many things still confuse me!I have my Django admin interface with a database on it!
The thing i want to do now is the following:
I want to be able to run a script from my Djano admin interface either by pushing a "Start" button or clicking on a URL!
Thanks for your time,any small example would be so great!
Have a nice day!
Comment: http://stackoverflow.com/questions/2872605/how-can-i-put-a-process-in-background-using-django
Answer: I would personally look at something like http://www.celeryproject.org/.
You also need to think about what would happen in the following instances.

Someone else logs into the system and clicks run
Is there any output? How will you handle this?
User clicks refresh whilst waiting for the task to complete.
Will the task complete?
Answer: Use Javascript in your template to call the view once a button is clicked, and in your view, call the script.  This question's very similar to this one.


Truncated normal distribution without scaling

Question: My understanding of a truncated normal distribution $\mathcal{N}(\mu,\sigma;a,b)$ is that it results from scaling the values of a normal distribution within the bounds $[a; b]$ such that the area under the curve within these bounds becomes 1 (please correct me, if I'm wrong).
However, in a case where I want to describe a variable $z$ that results from a latent variable $y$ (with normally distributed noise $\sigma$) such that
$
z = \begin{cases}
a & \text{if $y<a$}\\
b & \text{if $y>b$}\\
y & \text{otherwise}
\end{cases}
$
.. the truncated normal distribution in the above form would not be an appropriate distribution for $z$. Indeed, as $\sigma$ increases, the pdf within $]a;b[$ should not be scaled such that the area under the curve is 1 (hence the title "without scaling"); rather, the probability that $z$ is exactly $a$ or exactly $b$ should increase.
Now let's say, I'm not interested in the density per se, but rather in computing the probability $p(x; \epsilon)$ that the true value of whatever $z$ is measuring is $x$ ($\pm \epsilon$). Assuming that I  measured $z=\mu$ and that I know the measurement noise $\sigma$, then I think that $p(x; \epsilon)$ can be described as
$
p(x; \epsilon) = \begin{cases}
\int\limits_{-\infty}^{a+\epsilon}\mathcal{N}(\mu,\sigma) & \text{if $x=a$}\\
\int\limits_{b-\epsilon}^{\infty}\mathcal{N}(\mu,\sigma) & \text{if $x=b$}\\
\int\limits_{x-\epsilon}^{x+\epsilon}\mathcal{N}(\mu,\sigma) & \text{otherwise}
\end{cases}
$

Is this correct?
Is there a name for this form of $p(x;\epsilon)$ or even a name for the underlying probability density, which would seems like a special form of a truncated normal distribution? (-> would help researching on this)
Are there other probability distributions that represent are able to represent a similar scenario as outlined above?
Comment: As you correctly point out, there's a mix of continuous and discrete densities here, in that values a and b exhibit a point-like non-zero probability, which is an infinite in the density. In the signal processing courses this was represented as a Dirac's delta function, which is always zero except that it is infinite at a point (the origin) and the integral is 1. You can take a look here: https://en.wikipedia.org/wiki/Dirac_delta_function#Probability_theory
Comment: Part of it depends on how exactly a and b are defined. In analytical chemistry a is usually set such that it is the lowest value that can be statistically distinguished from zero. I.e. a usually includes the measurement error of a low value observation plus the error of a blank measurement.  It is also common to set values below a to a/2. This means a already includes the $\epsilon$ term.
Comment: Also, since z is imputed below a and above b you cannot assume that $\mu$=a or b is true for the underlying distribution. The probability of where it would lie beyond those limits depends on the probability characteristics of the population of samples the procedure is applied to..
Answer: The observed $z$ is left and right censored (as opposed to truncated), that is, rather than never seeing observations smaller than $a$ and larger than $b$ (truncation), you observe $z=a$ equivalent to the event $y<a$ and $z=b$ equivalent to $y>b$.  The contribution to the likelihood from such observations would be
$$
\begin{cases}
\Phi(\frac{a-\mu}\sigma) & \text{for }z=a \\
\frac1\sigma\phi(\frac{z-\mu}\sigma) &\text{for }a< z <b\\
1-\Phi(\frac{b-\mu}\sigma) & \text{for }z=b,
\end{cases}
$$
where $\phi$ and $\Phi$ is the pdf and cdf of the standard normal distribution.  Note that the events that $y=a$ and $y=b$ both have probability zero when $y$ is continuously distributed so you don't need to add anything extra to the probabilities in the first and third cases above to account for the fact that $z$ can take the values $a$ or $b$ without $y$ being censored.
Another thread has a detailed discussion on this kind of likelihood involving a mix between discrete and continuous observations.
Comment: Also known as a (generalized) *rectified* normal distribution: https://en.wikipedia.org/wiki/Rectified_Gaussian_distribution


jQuery not working after append on the document

Question: Hello I'm using wordpress CMS and I'm currently developing a custom template. My problem is that the jQuery isnt working after receive data from json and append them to the document.
My code is below.

function add_cover( button_class, event_type ){
    $( '.table-insurance-covers' ).on( event_type, '.add-cover', function(){

        console.log("HAS COVER : ");
        console.log($(this).data( "custom-value" ));

        if($(this).data( "custom-value" ) == 0 ){

            //Change the text
            $(this).text( "Αφαίρεση" );

            //Change button effect
            $(this).removeClass( "btn-success" );
            $(this).addClass( "btn-danger" );

            //Change the custom value
            $(this).data( "custom-value", 1 );

            //Change the price, packet price + extra cover = result
            var packet_price = $(this).closest('span.packet-price').text();
            console.log(packet_price);
        }else{

            //Change the text
            $(this).text( "Προσθήκη" );

            //Change button effect
            $(this).removeClass( "btn-danger" );
            $(this).addClass( "btn-success" );

            //Change the custom value
            $(this).data( "custom-value", 0 );
        }
    });
}

        Τύπος
        Όνομα Κάλυψης
        Ποσό
        Προσθήκη / Αφαίρεση

        Οδική Βοήθεια
        €  17
        Προσθήκη

        Θραύση Κρυστάλλων
        €  29
        Προσθήκη

        Μερική Κλοπή
        €  65
        Προσθήκη

        Ολική Κλοπή
        €  78
        Προσθήκη

And my append function.

function create_new_packet( company_name, covers, packet_name, packet_price, extra_covers ){
    //TO DO LIST, take data in covers variable from json
    covers = '

';

    var output_html = '

Καλύψεις πακέτου

€ ' + packet_price + '
' + packet_name + '
Αγορά

Πρόσθεσε Καλύψεις

Τύπος	Όνομα Κάλυψης	Ποσό	Προσθήκη / Αφαίρεση

' + extra_covers + '

';

    jQuery('.insurance-results-list').append(output_html);
}

I have tried to delegate the event, but isnt working. How can I fix this problem?
Comment: where is the `add_cover(button_class, event_type) {` call?
Comment: as @guradio there is missing of some code.
Comment: What part of `jquery` is not working???
Comment: where do you call `create_new_packet`?
Comment: My logic is the following.

There are 2 functions in one js file.
• vehicle_response()
• vehicle_chooser()
• create_new_packet(data)

The vehicle response get the response from the JSON file and then call the vehicle_chooser() to get some extra information. After that the vehicle_chooser() calls the create_new_packet with the whole data. The create_new_packet function append the ready html to the document.

The first block of the code is not working after appending the html. The second block (HTML) is the a table with an exist html code which working fine.
Answer: In the create_new_packet function, you use 'jQuery' to append the output html. In the add_cover function you use '$' with most of your jQuery functions. Wordpress requires that jQuery code uses the 'jQuery' string rather than '$'. Try replacing all of your dollar signs with 'jQuery'.
So $( '.table-insurance-covers' ) becomes jQuery( '.table-insurance-covers' )
If you would like to use the '$' sign please checkout this link: https://digwp.com/2011/09/using-instead-of-jquery-in-wordpress/.


Uploading via default image on Articles not working

Question: I am trying to upload images on the default Article node type on D7.
The upload works and the image is confirmed via Linux on the file system.
However, the icon of the uploaded image is a broken link image and the same when viewing the page.
I get the following error message:
Forbidden

You don't have permission to access /RT/sites/default/files/field/image/prayer.jpg on this server.

Please help.
UPDATE:
I have been looking into permissions as a solution but with no luck. I went as far as assigning 777 permissions to the files folder and all it's sub-folders and even the target image.
Strangely, I tried uploading an image to an article node on a different website running on the same server which worked. I installed a fresh website and tried it there and that also worked.
Basically, it seems one website among three all on the same server is not responding correctly when I attempt to upload images.
Answer: This is a permissions issue. You need to chmod the directory tree.
Edit: A tutorial on setting directory permissions can be found on drupal.org at Securing file permissions and ownership .
Comment: This answer is OK, but explaining how to "chmod the directory tree" would be more helpful.  If the user doesn't understand the message, it is unlikely that he or she understands chmod...
Comment: I have updated my question with some important points
Answer: I had the same problem.
My apache log file said something about ensuring that the blah/sites/default/files/blah/blah/ directory was executable, so after a lot of trial and error I gave execute permission to all in the files folder:
chmod -R a+x files

I'm not saying this is "the solution" and don't know if this brings security issues to the Drupal installation.
Still cannot understand what suddenly happened since I did not modified file permissions my self and everything was working fine. The problem occurred after editing an article entry with an image.


Optimizing memory usage with large images in Python (Pillow)

Question: I'm using pillow and working with pretty large images (at least 10500 x 10500 px), which in turn uses up quite a lot of memory. I was wondering if there was a way to lower it and tried using a compressed image to load (which would be ~400kb instead of 420mb), instead of directly creating a new one.. but the memory usage is the same:
Line #    Mem usage    Increment   Line Contents
================================================
   151   35.969 MiB    0.742 MiB       base = Image.open("C:/Users/Nick/Desktop/transparent.png")
   152  456.992 MiB  421.023 MiB       base.load()
   155  877.641 MiB  420.648 MiB       base_hallway = Image.new("RGBA", (map_width_px, map_height_px))

I also tried using a jpg or Image.new() with RGB only for the second image, but ditching the alpha channel didn't work either.
Line #    Mem usage    Increment   Line Contents
================================================
   151   36.309 MiB    0.766 MiB       base = Image.open("C:/Users/Nick/Desktop/transparent.png")
   152  457.359 MiB  421.051 MiB       base.load()
   156  457.367 MiB    0.008 MiB       base_hallway = Image.open("C:/Users/Nick/Desktop/blackjpg.jpg")
   157  878.312 MiB  420.945 MiB       base_hallway.load()

Mainly the operation being run on the base images is pasting other images on top of them in different positions. The rooms or hallways also have operations on them, but use almost no memory in comparison, such as picking the proper position to paste depending on the previous room or hallway, rotating if necessary, etc. But since it requires dozens or even hundreds of items pasted on top, I can't close the base images after every iteration (so only base OR base_hallway is open at any one time). I tried to open the base and base_hallway images only when needed, which requires a lot of save and close operations as well. That ended up increasing the time it takes for the code to run tenfold.. Simplified:
room = Image.open(open_room)

if next_tile == "room":
    base.paste(room, box=(rand_width_position, rand_height_position), mask=room)
elif next_tile == "hallway" or next_tile == "junction":
    base_hallway.paste(room, box=(rand_width_position, rand_height_position), mask=room)

Is there any way to optimize the memory usage?
Thanks!
Comment: Look at my answer here about using palettised versions of images to reduce memory consumption by 66% https://stackoverflow.com/a/51800547/2836621
Comment: Could you be more specific about the types of operations you are performing on these images? If you can give a complete, short example of the kind of processing you are doing, people can make concrete suggestions to improve it.
Comment: @user894763 I updated the main post with an example of the main operation against the base images. It basically needs to paste several rooms and hallways on top in different positions to generate a dungeon layout. At the end I merge the base and base_hallway images together and crop out the unused space.
Comment: I encountered a similar situation when my Python app in AppEngine started to crash because of exceeding memory limit. The app just resizes images using `Image.new`, `image.paste` and `image.save`. When it encountered an image with 6570x4380 dimensions the process's memory grows up to 530Mb
Answer: I had a go with pyvips. I don't know if that's a possibility for you.
pyvips is a streaming image processing library, so rather than keeping everything in memory, it builds a network of operations and then streams pixels from your source images through the network and straight back to disc.
This program will load an image, paste a lot more images on top at random positions, then write the result back.
import sys
import random
import pyvips

# the access hint means we want to stream this image
base = pyvips.Image.new_from_file(sys.argv[2], access='sequential')

for filename in sys.argv[3:]:
    tile = pyvips.Image.new_from_file(filename, access='sequential')
    x = random.randint(0, base.width - tile.width)
    y = random.randint(0, base.height - tile.height)
    base = base.insert(tile, x, y)

# all the processing happens on the final save as the pipeline executes
base.write_to_file(sys.argv[1])

For test data, I made 100 1,500 x 2,000 pixel images plus a 10,000 x 10,000 pixel background image. I can run it like this:
$ /usr/bin/time -f %e:%M python3 ../insert.py x.jpg ../background.jpg *.jpg
775200:0.75

So that's 0.75s and 780mb of memory for the whole process.
This is a big desktop machine with 32 threads. If I tell vips to run with fewer threads, memory use drops quite a bit:
$ VIPS_CONCURRENCY=1 /usr/bin/time -f %e:%M python3 ../insert.py x.jpg ~/pics/huge.jpg *.jpg
199020:1.38

Under 200mb now, though it's slower.


Revert GPO Settings to Undefined

Question: Revert All GPO settings to Undefined (Not reverse what they are now)
I inadvertently applied GPOs to an entire OU which was not ready to be deployed yet.  I have unlinked the GPOs but of course they have already been applied.  Is there a way to undo these changes (not reverse the setting but make it "clean" aka, "undefined"?
Similar to This answer  but I'm looking for a way to make the server look & behave as if these settings were never applied.  Surely I'm not the first SA to oops like this.  Or even have a machine that needs them unapplied for whatever other reason.
*Note:  I have seen this answer else where but I've never heard anything like this before (actually it contradicts everything I've heard) but I'm hopeful there may be some "trick" like it to make it work:
(paraphrasing) If you have some really weird gp issues...you can delete the security file which is located in windows\security which will force the machine back to the stage where it joined a domain. Then run "gpupdate /force /boot"
Answer: No, you can't turn back time on this one.
The previous state of the computers from before the GPO was applied was not recorded, so when Group Policy changed the state of those configurations, there is now no recorded previous state to revert back to.  If the damage is seriously bad, you'd be looking at restoring the affected computers from a backup after removing the offending GPOs.
Sure, most policies are resistant against "tattooing," as described here, but not all of them. There are certain policy settings that can simply be deleted once the GPO has been removed or the computer/user is no longer in scope of the GPO, but some settings are not that simple.
In other words, imagine that before the GPO, a particular registry entry was set to 1 and was not affected by Group Policy.  Then your Group Policy was applied and set that registry entry to 0.  Now you say "oh no, put it back like how it was!" so you go and put that GPO setting to Not Defined.  But the damage is already done.  Not Defined does not mean "set it back to 1 if it was 0, or set it back to 0 if it was 1."  It simply means that Group Policy will no longer flip that switch one way or the other.
No, of course you are not the first sysadmin to make this mistake.  But Microsoft has already given tools to help you protect you from yourself. (E.g., Advanced Group Policy Management with check-out/check-in, offline editing and approver features, etc.)
I know you don't want to be lectured... you just need to be more careful.
Comment: Well I was afraid this would be the answer, but I was hoping against hope that MS or a 3rd party found a way to do this.  The tools to protect myself were n/a b/c I was turning them on, just to an adjacent OU.  oh well, the lessons learned the hard way are the ones remembered most

Revert GPO Settings to Undefined


Show that $\frac{1}{b-a_{1}} + \frac{1}{b-a_2}+ ...+ \frac{1}{b-a_n} \geq \frac{n}{b-\frac{1}{n}(a_1+a_2+...+a_n)}$

Question: Let, $b> \max\{a_1,a_2,...,a_n\}.$ Show that $\frac{1}{b-a_{1}} + \frac{1}{b-a_2}+ ...+ \frac{1}{b-a_n} \geq \frac{n}{b-\frac{1}{n}(a_1+a_2+...+a_n)}$
f is convex if $f(t_1x_1+t_2x_2+...+t_nx_n)\leq t_1f(x_1)+t_2f(x_2)+...+t_nf(x_n)$
Let, $t_i = 1/n \Rightarrow \sum\limits_{i=1}^n t_i = 1$
Then, $f(\frac{a_1+a_2+...+a_n}{n}) \leq \frac{1}{n}[f(a_1)+f(a_2)+...+f(a_n)]$
NTS: $\frac{1}{b-\frac{1}{n}(a_1+a_2+...+a_n)} \leq \frac{1}{n}[\frac{1}{b-a_1}+...+\frac{1}{b-a_n}]$
Let$f(x) = \frac{1}{b-x}$ In order to prove the inequality, we have to show that $f''(x) \geq 0.$ So, $f''(x) = \frac{2}{(b-x)^3}$
Now,  how can we show that $f''(x) \geq 0$? $b$ can be a negative number, can it?
Comment: note $b-x>0$ because $b>max{a_i}$
Comment: @chenbai Thanks, just to making sure whether or not b can be a negative number.
Answer: I would use the function $g(x)=\frac{1}{x}$ defined on $(0,\infty)$; you can readily verify that $g''(x)>0$ on its domain. (The issue with your $f$ is that $f''(x)>0$ only for $x<b$.) The rest of the argument proceeds similarly: convexity gives
$$
\frac{1}{n}\times\text{LHS}=\frac{1}{n}\sum_{i=1}^ng(b-a_i)\geq g\left(b-\sum_ia_i/n\right)=\frac{1}{n}\times\text{RHS}\implies\text{LHS}\geq \text{RHS}.
$$
Answer: Observe the inequality can be proven using the following inequality:
$(x_1+x_2+\cdots + x_n)\left(\dfrac{1}{x_1}+\dfrac{1}{x_2}+\cdots + \dfrac{1}{x_n}\right)\geq n^2$ with $x_i = b-a_i > 0$. The answer follows.


Change country label mapbox gl js

Question: Can I change the label of a country using Mapbox Gl Js?
When I use mapbox I want to change the label of an country like this
example: united state -> usa
Answer: This tutorial from Mapbox's documentation shows how to customize the label text for a single label. So, you could apply the same logic to the "United States" label to have it read "USA" in your map style. You can then use this custom map style in your GL JS application as shown in this example. The "hosted style ID" that the example calls for can be found through the process documented here.

Change country label mapbox gl js


Contrução de tabelas SQL - usar ou não campos com Not Null?

Question: Estou com uma duvida, referente a construção de tabelas e a utilização de campo Not Null.
Sei que para campos de Primary Key, é necessário ele ser Not Null, porem nos demais campos, qual a necessidade de utilizar Not Null? pelo que entendo se um campo for setado como Not Null, ele não aceitara valores nulos, então caso, a minha aplicação na hora de realizar o insert, não for informado um determinado campo que esteja setado como Not Null, teremos ai uma Exceção?
Se um campo estiver setado como Not Null, fico na obrigatoriedade de sempre mencionar ele na hora do insert?
Quando devo utilizar campos Not Null?
Comment: [Quando devemos permitir que uma coluna de uma tabela de um banco de dados aceite NULL?](http://pt.stackoverflow.com/q/2296/91)
Answer:
Qual a necessidade de utilizar Not Null?

Você deve criar uma coluna como Not Null quando ver a necessidade de que aquele campo tem que ser preenchido no momento do insert. Por exemplo, imagine uma tabela de endereço um campo crucial é o nome da RUA e o CEP esses campos são muito importante serem informados, afinal não adiantaria nada você ter o número da rua sem sabe o NOME ou o CEP.
Algumas colunas em tabelas podem ter seu valor como null pelo fato de existir ou não um dado para aquele determinado objeto.
Um bom exemplo disso é o campo de telefone (celular), algumas pessoas podem não ter um número de telefone para informa no momento do cadastro e outras pessoas terão, nesse caso o campo com o Default null seria muito bom.

Senão for informado um determinado campo que esteja setado como Not
  Null, teremos ai uma Exceção?

Sim, se você tenta fazer um insert ou updade numa coluna sendo not null vai receber uma exceção.
Não é possível inserir o valor NULL na coluna 'Nome', tabela
 'Exemplos.dbo.Tabela'; a coluna não permite nulos. Falha em INSERT.

Se um campo estiver setado como Not Null, fico na obrigatoriedade de
  sempre mencionar ele na hora do insert?

Sim, se não o erro acima será apresentado.

Quando devo utilizar campos Not Null?

Em casos onde o valor do campo tem que existir (IDs como chave primaria) ou campos de devem ser obrigatório como o nome de usuário em uma tabela de usuário, mas isso depende muito da regra de negócio de sua aplicação.
Answer: No caso se seu campo for do tipo "Not Null" você deve sempre atribuir um valor à ele antes de salvar, nem que seja um valor vazio somente as aspas '' no caso de caracteres. Porém há também uma utilização desta funcionalidade, que eu particularmente utilizo muito, se tenho um campo "bool" que seja para gravar um resposta do usuário, caso este campo ainda esteja no banco como "null" sabemos que ainda não foi tomada uma resposta válida para aquela questão. caso seja verdadeiro ou falso sabemos que foi respondida.
Mesma coisa vale para datas, sendo a data null, podemos considerar que um pagamento ainda não foi realizado, e quando preenchida, este foi pago.
Comment: Isso. Para pagamentos não realizados eu deixo o campo Default Null. No SELECT filtro os campos que contenham NULL.
Answer: Olá.
Sempre tenho esse problema do valor default no campo. Primeiro sempre deixava com Default Null, Se o usuário preenchesse ou não a tabela aceitaria. Quando começava o relacionamento com outras tabelas no aplicativo é que via os problemas. Registros que tinham o campos DateTime NULL não eram listados ou até outras consultas que necessitam comparar valores. Como o NULL é desconhecido a consulta ignorava-o no SELECT.
Para permitir que o usuário não precisasse preencher alguns campos, passei a usar um valor Default padrão, no caso de datas CURRENT_DATE, chaves estrangeiras Default '0' ou 'Nenhum selecionado', booleanos Default '0', e por aí vai.
Sempre que um campo for parte de uma consulta prefiro deixá-lo  NOT NULL.
Espero ter contribuído.
Answer: "... é necessario ele ser Not Null, porem nos demais campos, qual a necessidade de utilizar Not Null? ..."
Essa nececidade vai depender de o campo ser referenciado em alguma relação que vc fizer na camada do DB, caso contrario, se for um campo que necessite obrigatoriamente ter um valor para alguma referencia feita com esse campo na camada ou camadas mais superiores ao DB. Sendo assim a escolha para deixar um campo como "NOT NULL" fica a critério do desenho da aplicação.
Em alguns casos, como no uso de relações nas camadas superiores as da camada do DB, o projetista pode deixar um campo setado com um valor "DEFAULT {value}" caso ele precise do valor desse campo para uma referencia no código do aplicativo.
Mas, se a camada do DB, que não pelo fato de ser a primeira camada de uma aplicação é a mais importante, pois o projetista pode desenhar quase todo o software nessa camada, que uma vez estando funcionando bem redondinha, é realmente a camada que vai realizar todo o trabalho do processamento dos dados do aplicativo, assim, vai abranger na aplicação, inumeros aspectos positivos nos quesitos tráfico, velocidade, usabilidade e segurança, uma vez que o processamento da massa de dados está quase que todo sendo feito pelas relações corretas no database, a aplicação somente tem de se preocupar com o "cara-a-cara usuario-dados" o que facilita consideravelmente o desenvolvimento, a usabilidade, a velocidade de processamento e consequentemente a segurança da aplicação.
Sendo assim, todos os campos que forem referenciados precisam estar ou setados como "NOT NULL" ou setados com um valor "DEFAULT {value}".
Eu em alguns caso prefiro fazer essa verificacao nas camadas mais superiores do aplicativo.
Mas por exemplo:
suponhamos que num aplicativo voce tenha definido as relações corretas no database, logicamente você vai depender de horas de trabalho para desenhar e formatar as tabelas no database para atender aos criterios do desenho do seu aplicativo, ora, essas horas que voce vai gastar desenhando bem o database, são as horas que voce vai ganhar no desenvolvimento da UI do aplicativo quando o cliente já vai estar com certeza te "xutando o saco, kkkkkkkkk".
espero que ajude.
Saúde e Paz!


ML inequality on $|\int_{\gamma} e^{iaz^{2}}dz|$ such that $z=Re^{i\theta},\theta \in [0,\frac{\pi}{4}]$

Question: On a contour defined by sector of radius $R$ making an angle of $\frac{\pi}{4}$, I applied the ML inequality on the curvy(angular) part ofcontour and this is what i found $|\int_{\gamma} e^{iaz^{2}}dz|\leq\frac{\pi R}{4}$ since $|f(z)|\leq 1$ and $L=\frac{\pi R}{4}$
But this doesn't seem right as $\lim_{R\to\infty}\frac{\pi R}{4}=\infty$,even though I know that it should go to zero.
I am evaluating the fresnel integrals using this.
Answer: Note that
$$ \left\vert \int_{\gamma} e^{iaz^2} dz \right\vert \le \int_{\gamma} \left\vert e^{iaz^2} \right\vert \left\vert dz \right\vert = \int_0^{\pi/4} e^{-aR^2\sin 2\theta} R \ d\theta $$
You can show geometrically that on $\theta \in [0,\pi/4]$, the function $g(\theta) = \sin 2\theta$ lies completely above its secant line, i.e.
$$ \sin 2\theta \ge \frac{4}{\pi}\theta \implies e^{-aR^2\sin2\theta} \le e^{-4aR^2 \theta /\pi} $$
Hence, the integral is bounded above by
$$ \int_0^{\pi/4} e^{-4aR^2 \theta /\pi} R\ d\theta = \frac{\pi}{4aR}\left(1 - e^{-aR^2}\right) $$
which tends to $0$ as $R \to \infty$


c2280 default constructor for std::vector requires copy constructor for elements despite having move constructor

Question: Title says it all, under what circumstances would the default constructor for std::vector require a copy constructor for the elements and not accept only a move constructor? I am explicitly deleting the copy constructor and explicitly defaulting the move constructor using VS2017.
Comment: Maybe this: http://stackoverflow.com/questions/8001823/how-to-enforce-move-semantics-when-a-vector-grows
Comment: show a minimal complete compilable example, there may be another error being misreported in this way
Answer: Before C++11, std::vector required that the element type is copy-constructible and copy-assignable.
From C++11 onwards the type requirements for the element type of a std::vector have been weakened, and std::vector now only requires the element type to be complete (until C++17) and erasable by the given allocator.
Calling certain member functions however, might impose additional requirements on the element type. The default constructor is not one of them, though.
That means that the element type doesn't need to have a copy-constructor for the vector to be default constructible - in fact you can default construct a std::vector with an element type that is not constructible at all (see here).


Prove $f$ is not Riemann Integrable?

Question:
Let $f:[0,1]\rightarrow\mathbb{R}, f(x)=\begin{cases}
      x &  \text{when $x$ is rational} \\
      1-x & \text{when $x$ is irrational}
    \end{cases}$
  Show that $f$ is not Riemann Integrable.

Can you show provide an argument with upper sum and lower sum?
Any hint will be appreciated.
My attempt:
 $f\in \mathcal{R}[0,1] \Rightarrow f\in\mathcal{R}[0,0.5]$.
Let $\mathbf{P}=\{x_0<\dots<x_n\}$ be a partition, then $U(f,P)\leq\sum_{i=1}^n(1-x_{i-1})(x_i-x_{i-1})$ and $L(f,P)=\sum_{i=1}^n(x_{i-1})(x_i-x_{i-1})$.
But how to show that $f$ is not Riemann, or there does not exist any inf$(U(f,P))$ or sup$(L(f,P))$.
Comment: You'll have to use the fact that the rationals are dense in the reals. This implies that - no matter how fine your partition is gonna be - the upper sum will be always greater than the Riemann-integral of $u(x) = \max\{x,1-x\}$ and your lower sum will be smaller than the integral of $l(x)=\min\{x,1-x\}$. Therefore the lower and upper sum cannot converge to the same number.
Comment: Note that the measure of the set of rational numbers is $0$
Answer: Let $x\in[x_{i-1},x_i]$. As $x\leq \frac12$, we have $1-x\geq \frac12$
If $x$ is irrational then $f(x)=1-x \geq \frac12$
If $x$ is rational then $f(x)=x \leq \frac12$
So $\inf_{x\in [x_{i-1},x_i]} f(x) = \inf_{x\in [x_{i-1},x_i] \cap \mathbb{Q}} f(x)$
Hence $\inf_{x\in [x_{i-1},x_i]} f(x) =  \inf_{x\in [x_{i-1},x_i] \cap \mathbb{Q}} x = x_{i-1}$
Similarly,
$\sup_{x\in [x_{i-1},x_i]} f(x) = \sup_{x\in [x_{i-1},x_i] \cap \mathbb{R}\setminus\mathbb{Q}} f(x)$
Hence $\sup_{x\in [x_{i-1},x_i]} f(x) =  \sup_{x\in [x_{i-1},x_i] \cap \mathbb{R}\setminus\mathbb{Q}} 1-x =1- x_{i-1}$
We deduce that
$L(f,P)=\sum_{i=1}^n (x_{i-1})(x_i-x_{i-1})$
$U(f,P)=\sum_{i=1}^n (1-x_{i-1})(x_i-x_{i-1})$
Let's denote $\Pi$ the set of all the partitions of $\left[0,\frac12\right]$, we have
$L(f)=\sup_{P\in\Pi}L(f,P)=\int_0^{1/2} x dx=\frac18$
and $U(f)=\inf_{P\in\Pi}L(f,P)=\int_0^{1/2} (1-x) dx=\frac38$
$L(f) \neq U(f)$ so $f$ is not Riemann-integrable.

Prove $f$ is not Riemann Integrable?


PHP MongoDB Exclude _id from results

Question: I want to exclude _id field from mongodb search results using PHP.
If I use $param as second search parameter it works but _id obviously gets printed.
Here is my code:
$type['Tipo de objeto']=$_POST[type];
$param = $_POST[field];
$conn = new Mongo();
$db = $conn->selectDB('prov');
$results = $db->$table->find($type, $param);

print_r($param) // Array ( [0] => Título [1] => Descripción [2] => Actos [3] => Formato original [4] => Título [5] => Descripción )

If i use the following code _id gets printed too, don't know what I`m missing:
$results = $db->$table->find($type, array("_id : 0" , "Derechos : 1", "Actos : 0")); //Fields marked with 1 gets printed, fields marked with 0 doesn't, except for _id.

Thanks in advance.
Answer: You are not sending correctly your projection (the thing you are trying to return, second parameter in find)
So instead of this
array(
  "_id : 0" ,
  "Derechos : 1",
  "Actos : 0"
)

which is totally wrong, you have to type
array(
  "_id" =>  0,
  "Derechos" => 1
)

Comment: It was so simple... Thank you very much
Answer: If you've landed here and are using the updated MongoDB Library, you might want to look here: MongoDBCollection-find
and you'll need to do something like this:
    $fields = array(

        'projection'=>array(
            '_id'=>0,
            'Derechos'=>1,
        )

    );

PHP MongoDB Exclude _id from results


Justifying a memory upgrade, take 2

Question: Previously I asked a question on what metrics I should measure (e.g. before and after) to justify a memory upgrade.  Perfmon was suggested.
I'd like to know which specific perfmon counters I should be measuring. So far I got:
<code>PhysicalDisk/Avg. Disk Queue Length (for each drive)
PhysicalDisk/Avg. Disk Write Queue Length (for each drive)
PhysicalDisk/Avg. Disk Read Queue Length (for each drive)
Processor/Processor Time%
SQLServer:BufferManager/Buffer cache hit ratio
</code>
What other ones should I use?
Answer: Those are probably not the best counters. The problem with disk I/O is that is it is not going to be that useful because disk I/O depends a lot more on database optimization unless the whole database was in memory. Operations like table scans and reporting / load scripts will overload your memory. A heavy I/O load will produce I/O on the log file, regardless of memory.
These disk counters are not the best for disk analysis either - queue length isn't always clear because it varies depending on your hardware layout. For example, 250 might not be a bad queue length for your disc, but maybe not if you have a large power SAN which can handle lots of parallel requests.
I rather go with the primary factors: Disk overloaded, I/O takes longer, seconds/read, seconds/wire - this is non-subjective. More primary data such as seconds/read gives a unique number not dependent on the hardware, and lower response times show what you are really looking for.
For memory, I would take:

SQL Memory Manager:Memory Grants Pending
SQL Buffer Manager: Page Life expecancy

The last gives you an idea of how fast pages are getting out again. You have to make sure, though, someone is not forcing this - table scans are perfect for that (as basically you will overload the cache with a table scan, unless the whole table fits in memory).
Comment: An overloaded disk does not necessarily make IOPS take longer.
Comment: It actually does. Not from the DISC point of view, but this is not measuerd. But from the OS point of view - it takes the OS Longer to get responses. Basically it tells you when the queue gets "critical" and has an impact on the IO response time.
Answer: First I would suggest reading my answer on how Windows memory works.  After that let's talk about counters.  From a pure performance monitoring perspective, server memory and SQL Server performance are unrelated primarily because SQL Server (if set up correctly) uses the ability to lock pages in memory to override the default Windows memory management scheme.  Looking at just memory the previously mentioned counters are OK:
SQL Memory Manager: Memory Grants Pending
SQL Buffer Manager: Page Life expecancy
SQL Server Buffer Manager Object: Buffer Cache Hit Ratio
I would also add
SQLServer:Memory Manager: Total Server Memory (KB) - this shows you how much SQL Server is managing.
SQLServer:Memory Manager: Target Server Memory (KB) - this shows you how much SQL Server thinks it would like to have based on the number of buffers reserved by SQL Server when it is first started up.  If total is less than target, it's not likely extra RAM will help.  If target is greater you might benefit from more memory.
See also what should be monitored for baseline SQL Server performance.

Justifying a memory upgrade, take 2


Numbering of indices, is $\mathbf b=(b_0, b_1, \dots, b_{n-1})$ a tuple of $n-1$ components?

Question: I have a couple of questions regarding the numbering of indices for vectors.
For a the vector
$
\mathbf a=(a_1, a_2, \dots, a_n)
$,
I know this is a tuple of $n$ components.
But if I have
$$
\mathbf b=(b_0, b_1, \dots, b_{n-1}) \tag 1
$$
is this a a tuple of $n-1$ components?
And
$$
\mathbf c=(c_2, c_3, \dots, c_{n+1}) \tag 2
$$
is this a a tuple of $n-1$ components?
But if the first index is $1$ and last is $n+1$, i.e.
$$
\mathbf d=(d_1, d_2, \dots, d_{n+1}) \tag 3
$$
is this a a tuple of $n+1$ components?
Or if the first index is $0$ and last is $n+1$, i.e.
$$
\mathbf e=(e_0, e_1, \dots, e_{n+1}) \tag 4
$$
is this a a tuple of $n+2$ components?
And finally, if the first index is $2$ and last is $n$, i.e.
$$
\mathbf f=(f_2, f_3, \dots, f_{n}) \tag 5
$$
is this a a tuple of $n-1$ components?
Comment: The number of components is the number of components. (1) and (2) have $n$; (3) has $n+1$; (4) has $n+2$; (5) has $n-1$. Simples!
Comment: Is $(b_0,b_1)$ a tuple of one component?
Comment: Anything to say, Donsert?
Comment: @GerryMyerson Your comment could be an answer, so I'm satisfied. :)
Comment: OK. I'm glad to see you accepted the answer posted yesterday.
Answer: The number of components in $(b_f, b_{f+1}, \dots, b_l)$ is always $l-f+1$  (last $-$ first $+1$). So, (1), (2), (3), (4), (5) have $n,n,n+1,n+2, n-1$ components respectively. Always try things out for small $n$, and check your answers.


Need the "msacli.exe" file for monitoring P2000 SAN. IOPS values needed

Question: Hi i need some performance stats from our MSA p2000 SAN. The Problem is that i want to have the values i get when i connect via SSH and use the command "show vdisk-statistics". This command shows me the IOPS for all vdisks. But this are values just from the actual moment. I want to have some values over a period of time...
The Webinterface of the p2000 doesn't provide me this values.
Now i found some tips on the internet like here:
http://www.remilner.co.uk/prtg-monitoring-a-hp-p2000-g3-msa/
this would be a great solution for me, but the problem is, that i can not find the msacli.exe anywhere. Does anyone know where to get this file? I didn't found it on official HP sites...
EDIT: HP-Support told me that this tool isn't available anymore... :-/
I also tried to get the values via "POSH-SSH" and Powershell and "plink.exe" but POSH-SSH gets an error and in plink.exe i don't know how i can save the console output...
Answer: You're really not going to be able to get this information out of an MSA or P2000 storage array. At least, no historical information. You could parse the output from the SSL CLI at regular intervals, but that's not ideal.
This is just a disadvantage of the platform.
You may want to check with the OEM, DotHill to see if anything is available from their side.
Comment: ok. thank you ewwhite. I think i try to parse the output... as you said, not ideal, but better than nothing... :-/
Answer: ewwhite was right. For those how want to see how i get the values in PRTG (Networkmonitoring) here are my scripts. I know the following is NOT very nice and seems to be very "froggy", but for me it works and i only need values over a periode of about a week...
The ssh connection is established via "plink.exe" a smart comand line tool as a part of the SSH program "Tutty". P.s. Do first connection manually to "accept" the new "ssh fingerprint"
get_msa_statistics.bat
<code>@echo off
D:
cd D:\p2000-iops
(.\plink.exe -ssh -l USER -pw PASSWORD -m .\empty.txt IP <.\execute.txt)>output.txt 2>>&1
</code>
empty.txt --> is really a empty file but is needed...
output.txt --> the output from SSH Shell.
execute.txt --> put in here SAN commands
<code>set cli-parameters pager disabled
set cli-parameters api-embed
show vdisk-statistics
</code>
p2000-iops.ps1 --> This script is startet every minute from PRTG Monitoring (Custom Sensor)
<code>#start the ssh session to get the row output data
& D:\p2000-iops\get_msa_statistics.bat

$file = "D:\p2000-iops\output.txt"
$src = Select-String -Path $file -Pattern "IOPS"

$iops = @()
foreach ($i in $src){
    $iops += $i.ToString()
}

for ($i=0; $i -lt $iops.Length; $i++){
    $tmp = $iops[$i].Split(">")
    $iops[$i] = $tmp[1]

    $tmp = $iops[$i].split("<")
    $iops[$i] = $tmp[0]

    $iops[$i] = [int]$iops[$i]
}

$sum = $iops | Measure-Object -sum
$sum = $sum.Sum

write-host "<prtg>
<result><channel>IOPS vDISK1</channel><value>$($iops[0])</value></result>
<result><channel>IOPS vDISK2</channel><value>$($iops[1])</value></result>
<result><channel>IOPS Total</channel><value>$sum</value></result>
</prtg>"
</code>
The "write-host" expression is in the format which is needed by PRTG. In PRTG i have now a graphical overview over all my vDISC IOPS (in my case 6 values. the script above is truncated by me) and also the Total sum of IOPS...
Hope this will help some others with similar problems. In this way you can also get other MSA P2000 SSH values in our prevered monitoring tool.
PRTG screenshot:
Comment: np. But a short question what would be correct to mark as "solution"? Because your post brought me the solution...
Comment: I worked at a hosting firm that bought dozens of these P2000 units, and we were surprised that there was no tooling available for reporting. So we searched for a solution, but ended up giving up on the platform and using something a bit more transparent. The answer mark is your choice.
Answer: You can download HP MSA2000 Monitoring Management Pack, msacli.exe is the part of this pack. Also you can use SNMP for monitor perfomance of HP MSA.
Comment: i already found this link. Problem is that your link is dead. I think HP disabled all official sources to this tool...


Does your partner have to also be behind the line when serving in pickleball?

Question: This question is really just to confirm what I've read in the rules or really what is not specifically written in the rules...
USAPA rules state the following:

4.L. Service Foot Faults. During the serve, when the ball is
struck, the server's feet shall:

4.L.1. Not touch the area outside the imaginary extension
of the sideline.
4.L.2. Not touch the area on the wrong side of the
imaginary extension of the centerline.
4.L.3. Not touch the court, including the baseline.

There are no rules specifically about the server's partner, but this has been a point of contention here and there in rec play.
USAPA Rulebook
Answer: Rule 4.B.7 seems to pretty clearly state that any player other than the server can stand wherever they wish (on their side of the net).

4.B.7. Partner Positions. In doubles, with the exception of the server (see 4.A.4) there is no restriction on the position of any player, as long as all players are on their respective team's side of the net. They can be positioned on or off the court. The correct server must serve from the correct service court, and the correct receiver must receive the serve.


have a intenal dns and a external dns with the same domain.

Question: is it possble to have an internal dns with all the internal ip like 192.168.0.0/24 for a domain and an external for the same domain.
i want to have bind resolve all the internal address and if a record is not found forward it to the external dns.
let me illustrate.
domain mydomain.com is hosted in gandi with gandi external dns.. it has the records for mail, www, etc. it is available from anywhere.
on the other side I have an internal dns with the same domain with the internal machines such as nas, raspberry pi etc.
if from the internal network  i want to connect to the nas i put nas.mydomain.com it will be resolved by the internal dns
but if want to conect to the webmail i will go to mail.mydomain.com.. this record does not exist on the internal dns.. then it should forward the query to the external dns
I have configured bind as a cache/forwarder server with one zone 'mydomain.com' but how forward all queries for mydomain.com for which no record is found in the internal dns
Comment: https://en.wikipedia.org/wiki/Split-horizon_DNS
Answer: The name of the concept is indeed split DNS or DNS views (as BIND configures them using view statements [documentation]). However, this alone does not answer your question as you want to forward the query from the internal view to the external view if the record does not exist in the internal view. I believe this is not possible. (I also believe this exact question has been asks many times before on ServerFault so you should've done some better searching. But as I myself was not able to find similar questions quickly, I'll forgive you and answer the question here again).
Split DNS is not an exact match for the question you're asking as it assumes you're going to set up a single DNS server which will provide different answers depending on which client (source IP address) asks the question. You want two DNS servers with forwarding between them. So let's give that a shot.
Your internal DNS server will be the master for all internal records and all external records. Your external DNS server -- hosted in a DMZ -- will only be the master for the external records. To avoid having to enter the external on both DNS servers, you should put those in a separate file, rsync that file between both DNS servers, and $INCLUDE [documentation; search for "INCLUDE"] it in both zone files. The internal server will then look something like this:
/etc/bind/named.conf.local
zone "example.com" {
   type master;
   file "/etc/bind/db.example.com";
};

/etc/bind/db.example.com (on the internal DNS server)
example.com.   SOA   ns1.example.com. hostmaster.example.com. (
                            2017030300 ; serial
                            3600       ; refresh
                            1800       ; retry
                            604800     ; expire
                            600 )      ; ttl
               NS   ns1.example.com.
               NS   ns2.example.com.
ns1            A    192.168.0.53
ns2            A    192.168.0.153

$INCLUDE /etc/bind/db.example.com.external

internal1      A    192.168.0.5
internal2      A    192.168.0.12
client5        A    192.168.0.23

/etc/bind/db.example.com.external
This file needs to be synchronized manually or via cron between both DNS servers.
example.com.   A    203.0.113.80
               MX   10 mail.example.com.
mail           A    203.0.113.25
www            A    203.0.113.80

Some things to keep in mind are the SOA and NS records which need to be defined on both DNS servers and need to be specific for the internal or external zone. So everything above the $INCLUDE statement needs to be custom fit for each DNS server. Next both internal and external DNS servers include the external entries. Finally only the internal server specifies the internal records.
A small issue is that you cannot overwrite entries. So if you have a public entry (e.g. www.example.com pointing to 203.0.113.80) but you want to overwrite that for the internal DNS server to point to 192.168.0.80 that this needs to be done by not listing that entry in the shared file but specified separately underneath the $INCLUDE statement on both servers.
Answer: Yes, you can have the same domain in the internal dns and in the external dns (but different dns servers). This configuration is called split brain dns.
Please check this


Am I the only one to hear Cb instead of B here?

Question: This comes from BWV 847 (the C minor fugue from the Well Tempered Clavier).
Look at the third beat from measure 28.
I can't help but hear an A flat minor chord here, that is Eb, Cb, Ab. Especially when playing with an "organ" sound on a synthesizer or something rich (because of the harmonics of the Eb at the bass, I suppose). Try to add the Eb above middle C to the chord to see what I mean.
I know that the harmony is supposed to be a G dominant over the Eb (that is a vanilla V/I movement over the Eb), and you can suppress any tentative to think otherwise by adding the D to the chord (I even have an edition at home which suggest that there is at least one manuscript where the copier added this D).
Am I the only one to hear this "C flat" ? Is there any actual example of chromatic mediant movement in Bach by the way ? Would you add the D to the chord ?
EDIT: here I can hear it a lot :

 (at 3:28)
Comment: @EricDuminil the question is whether you hear a G dominant over the Eb, or something stranger (Ab minor chord). In the second case, the B would have been noted CB instead. To hear the difference, play the circled chord adding respectively the D or the Eb above middle C.
Comment: Did you mean an Abm chord?
Comment: @Tim Yeah, of course. Fixed.
Comment: What's the difference between Cb and B? Shouldn't they be the same with well temperament?
Answer: Sure, if you listen to this chord out of context, it sounds like a 2nd inversion Ab minor chord.  But in context, at least to me, the chord and its resolution on the second eighth note seem to be a perfectly straightforward, and typical for Bach, dominant to tonic motion, where the dominant is a dimished seventh chord (missing its third and fifth), and the tonic is in the first inversion and anticipated in the bass.
And there's no room for a D in the chord- this is a three voice fugue.
Comment: @AlexandreC. - yes, adding a D to the chord would strengthen the dominant feeling.  But it would disrupt the fugue.
Comment: @MichaelCurtis - the way I hear it- and this is of course subjective- is that the part circled in red is a dominant, in the form of a diminished seventh chord, very typical for Bach, which would be completely spelled out as B-D-F-Ab, but in this case, is missing the third and the fifth, but is also complicated by its resolution to the tonic being anticipated in the bass, in the first inversion.  But there's such a thing as getting too wound up in analysis.
Comment: Yeah, it's a 3 voice fugue, but if I were to disambiguate, that's what I would do (adding F to the chord would imply resolving onto a doubled Eb -- not good).
Comment: @ScottWallace, if I follow your answer, the essential harmony at the part circled in red is V-V4/2-i6, right? The B natural is then a suspension/retardation and the A flat above an appoggiatura?
Answer: The way you've phrased your question is a little strange, since the only possible answer would be "no, you are undoubtedly not the only one."
I hear it a little differently from Scott, but it doesn't really make sense as a full chord.  I hear the B and the Ab as simple accented non-chord tones, with a chromatic rise (B-C) and descent (Ab-G) to the expected i6 chord.
That seems fairly clear to me on reading it, and is also how I hear it when performed:
Comment: @AlexandreC. I just listened to your recording.  If anything, it seems even *more* startling there. It feels too out of place to be a fundamental harmonic idea.  That's NCT territory :)
Comment: @ScottWallace Ah, I see.  For some reason, I didn't catch that from your answer.  Then we are in total agreement, because the two NCTs are certainly dominant-ish :)
Comment: BenI, @ScottWallace Of course, being non-chord tones, this is not a "strict" chromatic mediant movement or anything like that, and the voice movement is what it is : B goes to C. But I definitely hear something funny in the organ version, and adding the D (using an organ sound on my keyboard) does change completely the quality of the chord to me. But maybe it's because of the repeated listening. Anyway thanks for taking the time to listen to this.
Comment: @AlexandreC. - I can't argue with that, and after repeated listenings, I too managed to hear an Ab minor chord there.  I'm sure my perception is also colored by the fact that I've played this piece many times, and tend to hear Bach along the lines I'm accustomed too.  And thanks for pointing this out- it's interesting in any case.
Comment: It depends on the instrument. Eg. https://www.youtube.com/watch?v=3ceiQadblRQ (at 3:28)
Comment: Ben- I suspect I hear it pretty much the same as you.  I hear the i6 chord with two accented non-chord tones as well.  It's just that the non-chord tones imply a dominant to me.
Comment: @ScottWallace: On the piano, I would agree that I have to force myself to hear it differently. On the organ though, (see link just above) those two notes imply something very different to me -- the B doesn't feel like a leading tone but rather as the third of the implied harmony (Cb).
Comment: @AlexandreC. - of course, we all hear things differently.  But even in the organ version, since the B goes up to C, and because a dominant makes harmonic sense in the context, I still hear it that way.
Answer: There is no c-flat in the key of c minor, and that's what key we're in here.
The b-natural has a scale-degree function to move to c, and that's what it does here. C-flat doesn't have that role.
There is no harmonic function of a-flat minor in this spot. B and a-flat are non-harmonic tones resolving to c and g in the c minor triad in first inversion.
For those reasons, I'd say Bach notated this correctly.
Comment: There is absolutely no question that the intended harmony requires B -> C (V to I, over a pedal of Eb, if you want). Moreover, an accidental Cb would have to go down to Bb. This is only a matter of acoustics -- the chord _sounds_ like an Ab minor chord (and thus a "chromatic mediant" movement) when played on an organ.


Why does not java.net.URI parse authority part?

Question: Why does the following code print Illegal character in scheme name at index 0: 184.108.40.206:80 ?
try {
  URI uri = new URI("22.214.171.124:80");
  System.out.println(uri.getAuthority());
} catch(Exception e){
  System.out.println(e.getMessage());
}

Are numeric addresses accepted? On wikipedia, examples list telnet://192.0.2.16:80/ as a valid URI example. Also, documentation  for URI class says that scheme is optional.

At the highest level a URI reference (hereinafter simply "URI") in string form has the syntax
[scheme:]scheme-specific-part[#fragment]
Answer: Apparently, scheme-specific-part includes // and so without it parsing fails. When string is defined as "//188.8.131.52:80" output is, as expected, "22.214.171.124:80"


checkbox change event record penalty or discount jquery

Question: DEMO
I am trying to get a penalty or discount depending on the quarter chosen and the current quarter. For example user choose first quarter since it long passed there will be penalty. Basically if the quarter is passed there will be penalty. My question is like this. How to make it in a way that the values will persist and not disappear example we go on and click first quarter there will be a penalty and if user clicks on second quarter the penalty will accumulate. Since its currently in third quarter there should be a discount which is happening but the penalty is lost. I want the penalty to persist. How is this possible.

$('table#table').on('change', 'tr input:checkbox.quarter', function() {
  var checked = $(this).closest('tr').find('input:checkbox.quarter:checked').length;
  var value = $(this).closest('tr').find('input.quarter').val();
  var date = new Date();
  var quarter = parseInt(date.getMonth() / 3) + 1;
  var quaeternow = quarter;
  var tax = (value * checked).toFixed(2);
  var discount = 0;
  var penalty = 0;
  console.log(quaeternow);
  if (checked) {
    if (checked >= quaeternow) {
      //alert('discount');
      discount = (tax * .1).toFixed(2);
      //penalty = 0;
    } else {
      //alert('interes');
      //discount=0;
      penalty = (tax * .02).toFixed(2);

    }

    $('#div').append('discount ' + discount + '
');
    $('#div').append('penalty ' + penalty + '

');
    console.log(discount);
    console.log(penalty);
  }
});

        <input type="checkbox" value="75" id1="1stqtr" id="9/29/2015" class="quarter">first quarter

        <input type="checkbox" value="75" id1="2ndqtr" id="9/29/2015" class="quarter">second quarter

        <input type="checkbox" value="75" id1="3rdqtr" id="9/29/2015" class="quarter">third quarter

        <input type="checkbox" value="75" id1="4thqtr" id="9/29/2015" class="quarter">fourth quarter

Comment: why there are same `id` for all the `checkbox`?
Comment: http://jsfiddle.net/arunpjohny/qcbm0cfg/2/ ?
Comment: @GuruprasadRao i fix will that i didn't see that on i will change it to `data attr`
Comment: @ArunPJohny i will check again the computation i make the result is a bit different `my calculation i think is a bit off`
Comment: @ArunPJohny can you please explain a bit i been trying to understand the code for a while now but i cant seem to get how you made it.
Comment: @Pekka which part of the code?
Comment: @ArunPJohny `+$(this).attr('id1').match(/^\d+/),` what is `+` for `$(this).data('discount', dis).data('penalty', pen);` i been trying to check this in dev tools i cant find it. This should be in the checkbox since `$(this)` referes to checked checkbox i cant find it. also `if (this.checked)` what is the difference between `if ($(this).checked)`
Comment: @Pekka that is the [unary plus](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Operators/Arithmetic_Operators#Unary_plus_()) operator... to convert the returning string to a number
Comment: Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/90945/discussion-between-arun-p-johny-and-pekka).
Answer: Form what I understand, you could do something like

var discount = 0;
var penalty = 0;
var quarter = parseInt(new Date().getMonth() / 3) + 1;

$('#table').on('change', 'input.quarter:checkbox', function() {
  var cquater = +$(this).attr('id1').match(/^\d+/),
    tax = +this.value,
    dis,
    pen;

  if (cquater < quarter) {
    pen = tax * .02;
    dis = 0;
  } else {
    dis = tax * .1;
    pen = 0;
  }
  if (this.checked) {
    penalty += pen;
    discount += dis;
  } else {
    penalty -= pen;
    discount -= dis;
  }

  $('#div').append('discount ' + discount + '
');
  $('#div').append('penalty ' + penalty + '

');
});

        <input type="checkbox" value="75" id1="1stqtr" id="9/29/2015" class="quarter">first quarter

        <input type="checkbox" value="75" id1="2ndqtr" id="9/29/2015" class="quarter">second quarter

        <input type="checkbox" value="75" id1="3rdqtr" id="9/29/2015" class="quarter">third quarter

        <input type="checkbox" value="75" id1="4thqtr" id="9/29/2015" class="quarter">fourth quarter

Comment: arun i have one question what if there are multiple row. my problem is the pen and dis is being shared i mean it is increasing. how can i make it in a way that the var dis and pen should only be used in its respective row only.
Comment: that was so simple that i missed it i was concentrating on making different variables for each row. the fiddle works great.


Is it possible to learn to play the violin for a year and be able to play in an amateur orchestra afterwards?

Question: A little bit of background: when I was younger (around middle school) I played the piano for approximately 4 years. We're talking about around 10 years ago. I used to take regular lessons and also played in my school orchestra. Since then I didn't take any other lessons, but sometimes played the piano by myself.
I would really really like to join my university orchestra. I remember being in love with playing music with others. The only problem is that there's no need for pianists, since there are many available right now.
My idea is to learn the violin for a year and then try to join my university orchestra in late 2020. The orchestra is entirely composed by amateurs, not professional musicians. I have never played the violin seriously but I tried (back when I was in middle school) and enjoyed it. I'm also, of course, able to read and comprehend sheets very rapidly, so I guess that would be an advantage. Do you think it would be possible for me to reach an adequate level to play in an orchestra if I took lessons (once a week, with an experienced teacher) for a year? Thank you so much.
Comment: Why not chat with the conductor of the orchestra? They already know the technical standard of the pieces you'd be playing. If they think that getting to that level in a year on violin is too ambitious, they may be able to suggest a different way in.
Comment: Each person learns at a different pace.  If you want to learn violin, then go learn violin!  It may take more than a year to win an audition to any given orchestra, but if your only goal is to play with others, why not look into other musical genres & small -group play?
Comment: It would depend on your talent and work-rate. You'd stand a lot more chance with a viola.
Answer: Like a lot of things, you get out of it what you put into it. If you're practicing consistently (15 minutes a day, every day, is better than 3 hours one day a week), taking lessons with an experienced musician AND teacher (being a good teacher is just as if not more important than being a good musician), listening to music, performing when and where appropriate (perhaps with a community orchestra), and attending rehearsals and/or performances of the ensemble in question, then there's a good chance that the answer is yes. This is going to largely depend on the skill level of the target orchestra, but I'd say it's certainly within the realm of possibility.


Laravel Api , 2 Type of users , separate them or make one table

Question:
I build Laravel Api  application
i have 2 type of user on my application
Doctor
Patient

Each user type will have different user interface and access different types of data.
Their only similarity is they are using one web application
and the same Authentication mechanism
i will use JWT Auth
-Is it better to put them all in one user table   or make two table for each type
Comment: It's depend how you are managing different interface for two different users. You can add type enum field in users table to store users type. It's simplest as well as easy to implement.
Comment: that's good , thank u
Answer: Create a middleware to seperate users with different roles


Como ocultar arquivos no GitHub?

Question: Quero deixar alguns projetos do meu GitHub públicos, mas alguns arquivos deles possuem informações confidenciais (como senhas de acesso a banco de dados).
É possível deixar esses arquivos específicos ocultos para que as pessoas vejam somente os outros arquivos?
Sei que dá pra fazer isso escrevendo o nome do arquivo no .gitignore, mas também quero fazer deploy desses projetos no Heroku usando o repositório do GitHub. Quando faço isso, o Heroku não reconhece os arquivos que foram descritos no .gitignore e a aplicação dá erro.
Comment: Não é possível fazer isso. Talvez você devesse considerar ter essas configurações em outra fonte como variáveis de ambiente ou aplicações feitas pra isso.
Comment: Se é uma estrutura nova e quer fazer algo bem feito, recomendo dar uma olhada no Azure KeyVault que é feito exatamente pra isso: https://docs.microsoft.com/PT-BR/azure/key-vault/general/basic-concepts
Comment: Nunca coloque senhas no github. Isso é uma falha tremenda de segurança.
Comment: Entendi, valeu pela dica!
Answer: Não inclua arquivos de senhas no Git. Como você comentou, você usa GitHub e Heroku. Isso abre duas opções.

Automatizar seu deploy com GitHub Actions, que suporta secrets. Esses valores secretos vão ficar disponíveis no fluxo de deploy dentro do Actions.
Usar variáveis de ambiente no Heroku e consumi-las na sua aplicação. Você pode configurar na sua aplicação dentro do Heroku uma lista de variáveis de ambiente, por exemplo DATABASE_URL, DATABASE_PASSWORD. Os valores ficam fora do código, e você não expõe nada.

Lembrando que ao subir seu projeto Git pro GitHub, os commits históricos terão as suas senhas. Por isso, recomendo que use o git-forget-blob, e confira mil vezes ao subir pro remoto.
# "esquece" os arquivos do histórico do git
sudo wget https://raw.githubusercontent.com/nachoparker/git-forget-blob/master/git-forget-blob.sh -O /usr/local/bin/git-forget-blob
sudo chmod +x /usr/local/bin/git-forget-blob

git-forget-blob /arquivo/para/esquecer.txt
git-forget-blob /arquivo/para/esquecer-2.txt
git-forget-blob /arquivo/para/esquecer-3.txt

# faz um push sobrescrevendo o remoto, caso não tenham
# alterações mais novas por lá
git push origin <branch> --force-with-lease

Como ocultar arquivos no GitHub?


Differences between different MIM stratocasters

Question: I was wondering if all ordinary and plus Fender Standard Stratocasters (Made in Mexico) have the same quality. For example, does the 150 euro more expensive Fender Standard Stratocaster Plus Top Tobacco Sunburst PF have better pickups and better wood than the Fender Standard Stratocaster Brown Sunburst PF or is the difference just in the looks? By 'better' I mean higher quality pickups (more expensive) and higher quality woods (probably also more expensive, even if it made from the same type of wood).
I tried looking for answers on the Internet but I couldn't find any. I only saw forums about the differences between MIM and MIA strats.
I do not mean the differences between the Classic player series and the Highway One series, just the differences in the actual standard series.
Comment: 'more expensive' doesn't always mean 'higher quality'. Some cheap things are great, and some expensive things aren't so good. What the ability to spend more money *will* give you, though, is a wider choice.
Answer: If you're asking specifically about the difference between the Standard versus the Standard Plus, Standard HSS versus Standard HSS Plus, and Standard with Floyd Rose versus Standard with Floyd Rose Plus, then it looks like the answer is the same for each:
The main differences are the Plus models have flamed/figured maple tops and different finish options. There are few other quirky things. For example the non-Plus Standard with Floyd Rose is only available with a pau ferro fingerboard, while the Plus of the same guitar is only available with a maple fingerboard.
But, that doesn't mean the only difference is looks! A maple top will definitely change the sound, although less so on Strats than on something like a Les Paul. It may make it a bit brighter and more focused sounding.


Injeção de Dependência em Controller Base

Question: Bom estou aprendendo a trabalhar com a injeção de dependências agora e gostaria de aplica-lá no meu projeto. Porém me deparei com a seguinte dificuldade, possuo um controller base onde o mesmo é herdado por mais outros três controllers base que realizam a sobrecarga e assim consigo realizar todas as funções necessárias no meu sistema.
Porém ao tentar aplicar a injenção de dependencia as classes filhas pedem para que eu passe o objeto construtor, então gostaria de saber como lidar com isso.
Estou usando o unity para fazer a injeção de dependencias.
Abaixo segue o código da controller pai:
public class BaseController : ApiController
{
    public string[] includes = null;

    private readonly IFiltroServico servico;
    public BaseController(IFiltroServico _servico)
    {
        servico = _servico;
    }
}

Contoller filha, aqui é gerado o erro pois é necessário passar o IFiltroService devido o construtor da classe pai:
public abstract class BaseController<R> : BaseController
        where R : class
    {
 //services da controller;
    }

Quero saber qual a melhor forma de fazer isso e como passar o construtor a partir daqui.
Answer: Quando você herda uma classe que tem um construtor com parametros é necessário passar isso para a base dele, ou seja, você precisa passar o IFiltroServico no base
public abstract class BaseController<R> : BaseController
        where R : class
{
    public BaseController(IFiltroServico servico)
        :base(servico)
    {

    }
}

obs: o underline antes do nome da variavel é uma convenção para indicar que as variaveis são privadas, no caso ele "deveria" estar na propridade privada, uma vez que o IFiltroServico passado como parametro no construtor só está naquele escopo.
EDIT
Segue um exemplo que costumo usar quando uso o padrão Repository
public abstract class CrudRepository<TEntity, TKey> : ICrudRepository<TEntity, TKey>
    where TEntity : class
{
    protected DbContext _context;
    public CrudRepository(DbContext context)
    {
        _context = context;
    }

    //Codigo aqui
}

public class UsuarioRepository : CrudRepository<Usuario, int>
{
    public UsuarioRepository(DbContext context) : base(context)
     { }
}

Comment: Ah sim entendi, eu até havia começado a passar o construtor para as classes filhas, porém ainda me resta uma dúvida além das quais já me sanou. Para a realização da Injeção de Dependência isso seria uma boa prática, no caso passar o construtor para as classes filhas?
Comment: Eu não havia visto ainda essa abordagem em `Controllers`, porém utilizo ela quando desenvolvo com padrão `repository` e `service`, no caso da repository, eu costumo criar uma classe generica que injeta o `Context`, logo preciso passar esse `Context` nas classes que herdam ela.
Comment: Entendo, esse padrão de controller também é um pouco novo para mim, porém gostei muito de como trabalhar com ele. Mas em relação a injeção de dependência pelo que vi vou usar um protected readonly na classe pai e chamar somente o construtor nas filhas. Isso até onde vi resolve meu problema e ainda é uma boa prática. Valeu
Comment: Sim, Sim, é assim mesmo, como disse, quando a classe pai tem um construtor parametrizado, deve ser passado na `base` das classes filhas.
Comment: Caso a resposta tenha resolvido seu problema, não esquece de dar OK, para que a pergunta seja finalizada.
Comment: Beleza valeu, vou fechar o tópico aqui valeu man.
Answer: Só para complementar a resposta, após algumas pesquisas e dá resposta do manolo acima resolvi meu problema da seguinte forma:
Ao realizar a instancia do IFiltro eu o crio como protected e readonly, isso na base controller pai, segue abaixo:
 public class BaseController : ApiController
    {
        public string[] includes = null;
        protected readonly IFiltroServico _servico;
        public BaseController(IFiltroServico servico)
        {
            _servico = servico;
        }
    }

Nas classes filhas, basta seguir o exemplo do construtor da resposta acima.
Answer: Em injeção de dependência, é possível você injetar um construtor.
Ex:
container.RegisterType<IDbGerenciador, DbGerenciador>(new InjectionConstructor(Provedor.PostgreSql, _conexaoString));

Comment: Interessante, você teria algum artigo mostrando mais do uso do D.I assim?


gcc and llvm linux shutdown function from c code

Question: Linux x86-64 compiling and statically linking with gcc I have:
#include <sys/reboot.h>

if (str[0] == 'r')
  reboot(0x1234567);

but I can't seem to find the equivalent function call for shutdown. I'd also like to know the llvm function if different.
Comment: Check the documentation. http://linux.die.net/man/2/reboot . However, only call reboot() if you really, really know what you're doing - it does an unsafe shutown/reboot of your system - you'd have to defer to the /sbin/shutdown or /sbin/reboot command to do it safely.
Answer: From sys/reboot.h :
/* Perform a hard reset now.  */
#define RB_AUTOBOOT     0x01234567

[...]

/* Stop system and switch power off if possible.  */
#define RB_POWER_OFF    0x4321fedc

So reboot(0x4321fedc); or reboot(RB_POWER_OFF); should work.
Comment: Ah so Shutdown is a special case of Reboot. Maybe because I started out as a windows user, I think of Reboot as being a special case of Shutdown.
Answer: Try
system("shutdown -h now");

Comment: That didn't seem to work. The only things I have on the system are the kernel in the /boot directory and my statically compiled init file in the /sbin directory.


Show with induction that $\sum_{k=1}^{n} \frac{k^{2}}{2^{k}} = 6 - \frac{n^2+4n+6}{2^{n}}$

Question: Show with induction that
$\sum_{k=1}^{n} \frac{k^{2}}{2^{k}} = 6 - \frac{n^2+4n+6}{2^{n}}$
n = 1
$LHS = \frac{1}{2}$
$RHS = 6 - \frac{1+4+6}{2} = \frac{1}{2}$
n = p
$LHS_{p} = \frac{1^{2}}{2^{1}} + \frac{2^{2}}{2^{2}} + \frac{3^{2}}{2^{3}} + ... \frac{p^{2}}{2^{p}}$
$RHS_{p} = 6 - \frac{P^2+4p+6}{2^{p}}$
n = p + 1
$LHS_{p+1} = \frac{1^{2}}{2^{1}} + \frac{2^{2}}{2^{2}} + \frac{3^{2}}{2^{3}} + ... \frac{p^{2}}{2^{p}} + \frac{(p+1)^{2}}{2^{(p+1)}}$
$RHS_{p+1} = 6 - \frac{(p+1)^2+4(p+1)+6}{2^{(p+1)}}$
Show that, $RHS_{p+1} = RHS +  \frac{(p+1)^{2}}{2^{(p+1)}}$
$6 - \frac{(p+1)^2-4(p+1)+6}{2^{(p+1)}} =  6 - \frac{P^2+4p+6}{2^{p}} + \frac{(p+1)^{2}}{2^{(p+1)}}$
Comment: It appears you have a typo. Look at when you plug in $n=1$. The formula does not match.
Comment: Oh I see what you mean it should be + 4n
Answer: I will assume the correct formula is:
$$\sum_{k=1}^n \dfrac{k^2}{2^k} = 6-\dfrac{n^2+4n+6}{2^n}$$
Assume this is true for $n=p$ and try to prove for $n=p+1$:
$$\begin{align*}\sum_{k=1}^{p+1} \dfrac{k^2}{2^k} & = \sum_{k=1}^p \dfrac{k^2}{2^k} + \dfrac{(p+1)^2}{2^{p+1}} \\ & = 6-\dfrac{p^2+4p+6}{2^p}+\dfrac{(p+1)^2}{2^{p+1}} \qquad \text{ by the induction assumption}\\& = 6-\dfrac{p^2+4p+6}{2^p}\cdot \dfrac{2}{2} - \left(-\dfrac{p^2+2p+1}{2^{p+1}}\right) \\ & = 6 - \dfrac{2p^2+8p+12}{2^{p+1}} -\left(- \dfrac{p^2+2p+1}{2^{p+1}}\right) \\ & = 6 - \left( \dfrac{2p^2+8p+12}{2^{p+1}} - \dfrac{p^2+2p+1}{2^{p+1}}\right) \\ & = 6 - \dfrac{2p^2+8p+12-(p^2+2p+1)}{2^{p+1}} \\ & = 6 - \dfrac{p^2+6p+11}{2^{p+1}} \\ & = 6 - \dfrac{(p^2+2p+1)+(4p+4)+6}{2^{p+1}} \\ & = 6 - \dfrac{(p+1)^2+4(p+1)+6}{2^{p+1}}\end{align*}$$
Comment: On the third row, how can you write -p² - 2p -1 ? When the second row have (p² + 2p +1) ?
Comment: I updated it with a couple of steps. Adding something is the same as subtracting a negative. $$6-a+b = 6-(a-b)$$ To see this is true, just distribute the negative.
Comment: Right, and when you makes something share a denominator, its the same thing as making it share parentheseses?
Comment: That is correct
Answer: Hint: The left-hand side is given by $$\frac{(k+1)^2}{2^{k+1}}-\frac{k^2-4k+6}{2^k}=-2^{-k-1} \left(k^2-10 k+11\right)$$
and the right-hand side: $$-{\frac {{k}^{2}-2\,k+3}{{2}^{k+1}}}$$ so your formula is not true.


One filter criteria for two different displays of the same view?

Question: Hi there drupal wizards.
I want to be able to filter two different view displays and display the search results of a filter query simultaneously on the same page with only one shared filter criteria search that works on both views.
I have no problem to do the filter criteria for each one, but I want one common filter search criteria that filters both views and displays them one after the other on the same page.
How do I do this?
If possible I don't want to hack code, just configure things.
To be more precise:
I have one map search working based on location data. The filter is exposed as a block. However I've created a block display showing the same view as a table list that the filter block query does not seem to affect at all. I'm using context to display the second view display block In the same path.
Answer: Seems like you want to display two different views with a common shared exposed filter in the same page (or as you said "same path"), instead of making two displays of the same view:

After created your view and your primary "view block", add the needed filter to that block, make sure that the filter is valid for all pages.
Then create an Attachment (you can find it in view configuration page Add>Attachment), and attach its to the block in
Attachment settings by chosing "Attach to:Block" and set a preferred
display position of that attachment (Attachment position)
Configure your Attachment with your needed format and fields, making
sure that these configurations are for "this Attachment
only"(*override)
Finally Set to Yes the "Inherit exposed
filters:" in Attachment settings
Et voilà enjoy your block+attachment with the same shared filter!

If you want to share the same filter in more than one views globally in the entire site, you can take a look to modules like Views Global Filter
Answer: This might work :) If you have two views, which both have the same field exposed as a filter, you could set the Filter identifier to the same value. Go to the filter on both views and under More you will find "Filter identifier", set it to the same value.
Comment: Thanks. Didn't work exactly though. However I've now taken this route for finding a solution by using two drupal views. The problem is just to make the two views share the same exposed filter block but on different pages, as the exposed block is situated in the place of the menu sub-links. (I want to find a solution that replaces the id of the block when I switch page so I can have the different search in the same place on the page as on the other page.

My new question is here:
http://drupal.stackexchange.com/questions/40283/rewrite-id-of-a-exposed-filter-block


Getting the difference of two dataframes in R

Question: If, I have two dataframes each containing 12 columns and have 4781 and 4807 rows respectively, then, I want the intersection of these two dataframes. I did use the compare command in the compare package, and I found that one is a subset of another. But, how do I get the difference of the two? Thanks!
If a1 and a2 are the two dataframes, then,
class(a1)     class(a1$V1)
data.frame    factor

class(a2)     class(a2$V1)
data.frame    factor

I need those elements which are present in the bigger dataframe and not in the other dataframe
Comment: If A1 **is a subset** of A2, then A1 **is the common elements**. Problem solved
Comment: Could you provide reproducible data? Meanwhile I think you want to try `intersect()`.
Comment: I have added the link for the two files. Also, intersect works on vectors, I guess.
Comment: @chan chong You can use `intersect` from `dplyr` which works on data.frames.
Comment: You could provide reproducible data for this by creating a couple of ~10 line data frames within your question, for illustration purposes, rather than us have to download some text files and then work out the exact read.csv call...
Comment: @chanchong I see 4470 rows after using `intersect()`. I think `intersect()` is working for you. @akrun Thanks for providing additional info.
Comment: A1 is also the **intersection** if A1 is a subset of A2. Maybe you don't mean subset.
Comment: I meant, I need those elements which are present in the bigger dataframe and not in the other dataframe. My bad for poor choice of words.
Comment: Are all your rows unique? If not, how many copies of duplicated rows do you want in your output?
Comment: Yes, all rows across the 10 columns are unique.
Answer: Test data set:
> aa = data.frame(x=1:10,y=letters[1:10])

split into two overlapping data frames. These are like your data - there's some rows common to each and some rows unique to each:
> a1 = aa[1:8,]
> a2 = aa[5:10,]
> a1
  x y
1 1 a
2 2 b
3 3 c
4 4 d
5 5 e
6 6 f
7 7 g
8 8 h
> a2
    x y
5   5 e
6   6 f
7   7 g
8   8 h
9   9 i
10 10 j

Then use dplyr operators:
Unique to a2:
> dplyr::setdiff(a2,a1)
   x y
1  9 i
2 10 j

That might be what you want. I'll illustrate some other set operations anyway:
Unique to a1:
> dplyr::setdiff(a1,a2)
  x y
1 1 a
2 2 b
3 3 c
4 4 d

in both:
> intersect(a1,a2)
  x y
1 5 e
2 6 f
3 7 g
4 8 h

Those are the three parts of the Venn diagram of a1 and a2. So if we put those three parts together we should get our whole set back:
> rbind(setdiff(a1,a2), intersect(a1,a2), setdiff(a2,a1)) ==  aa
      x    y
1  TRUE TRUE
2  TRUE TRUE
3  TRUE TRUE
4  TRUE TRUE
5  TRUE TRUE
6  TRUE TRUE
7  TRUE TRUE
8  TRUE TRUE
9  TRUE TRUE
10 TRUE TRUE


Como organizar questões para exibir na tela

Question: boa noite.
Tenho um atributo do tipo String que recebe uma pergunta vinda diretamente de um textArea. O meu problema é que não consigo deixar as questões na hora de exibir igual como cadastro elas.
Ex:
Cadastro uma questão assim:
Questão?
A)
B)
C)
D)

Recupero as questões e jogo em uma List, uma List<Questoes> questoes e na hora de exibir a questão em um dataTable elas são exibidas assim:
Questão?  A) B) C) D)

ou seja, tudo na mesma linha. Alguém pode me ajudar? Segue os códigos relacionados.
@Column(name = "PERGUNTA")
private String pergunta;

XHTML:

DataTable aonde são exibidas as perguntas:

Answer: Primeiramente: Tá faltando um
 aí, pra fechar seu tag

Tenta colocar assim:

    <h:outputText value="#{questao.pergunta}"/>

Comment: Não foi brother.