Problema de performance com fotos dentro de uma caixa de listagem com scroll

Question: Explicação:
Dentro de um container com scroll, tenho uma lista de dados que é carregado por duas  APIS, uma que traz os dados dos usuários e outra que carrega asyncronamente as fotos. Conforme as fotos começam a ser exibidas nessa caixinha, o sistema começa a travar, o problema é que são tantas fotos, que o navegador não aguenta, trava o rolamento da tela, e do container.
Pensando em uma solução, acredito que a melhor maneira de resolver isso seria limitar a quantidade de fotos que são acrescentadas no DOM enquanto eles não são necessárias:

Solução proposta:
A ideia para corrigir o problema é remover as fotos quando elas não estão sendo visualizadas dentro desse container, ou seja, na área escondida do scroller, eu removeria elas da tela através de uma simples condição booleana "showImage" nessa imagem.
Isso evitaria uma sobrecarga da tela devido a enorme quatidade de imagens.

Exemplo do uso da condição:

Resta agora saber como eu poderia identificar quais destas imagens não estão disponíveis visualmente.
Como obter aquilo que não é enxergado?
Então, chegamos ao ponto do problema em questão, de que maneira eu poderia identificar que uma imagem não está sendo enxergada dentro de desse container? Essa é a questão.
Aqui está um exemplo simples com menos imagens da modelagem que preciso:
Fiddle de exemplo
A mesma coisa se pensar o inverso, poderia talvez funcionar, como acionar uma classe de estilo apenas para o que está dentro da área visível do container.
Outra referência
Comment: Para a situação que descreves eu recomendaria o uso de intersection observer (https://developer.mozilla.org/en-US/docs/Web/API/Intersection_Observer_API).
Comment: @dfvc, obrigado pela dica, vou tentar ir por esse caminho.
Comment: Tem que testar bem os pressupostos. Em tese, o browser já determina o que tem na viewport e renderizar só o necessário, se o scroll dá problema há chance grande de ter elementos fazendo recálculo - ou simplesmente o "peso" é por falta de serialização apropriada da sua rotina de carga da API, tentando carregar tudo de uma vez. A parte de "detectar o que é visível", se separada da premissa inicial, acho que vira uma ótima pergunta, mas atualmente o post me dá impressão de relacionar problemas distintos. Um [mcve] com o problema de performance faz falta para aferir.
Comment: Lembrando que no site já tem posts detalhados de como carregar imagem com scroll, de repente em vez de aferir o retângulo bastaria ver se o scroll Y (ou X) chegou na imagem, sem complicar muito (mas ainda acho que se separar a parte de como detectar se um elementou está numa viewport ou retângulo, pode ser uma ótima pergunta).
Answer: Além da sugestão sobre Intersection Observer dada por @dfvc, talvez possa fazer sentido, como está trabalhando com Angular, o uso de Virtual Scrolling.
Usando o <cdk-virtual-scroll-viewport> faz com que grandes listas de elementos sejam renderizadas de forma mais performática, visto que faz renderizar somente o que está visível na tela naquele momento.
Exemplo de implementação:
<cdk-virtual-scroll-viewport itemSize="50" class="example-viewport">

{{item}}

</cdk-virtual-scroll-viewport>

Onde o *cdkVirtualFor substitui o *ngFor dentro do elemento <cdk-virtual-scroll-viewport>, suportando exatamente a mesma API como o *ngFor faz.
Comment: Como está escrito atualmente, sua resposta não é clara. Por favor, pode [edit] para adicionar mais detalhes, que ajudarão outras pessoas a entender como isso resolve a pergunta feita. Você pode encontrar mais informações sobre como escrever boas respostas [na Central de Ajuda](/help/how-to-answer).
Comment: @nncl, pode fazer sentido mesmo, vou experimentar, valeu! Tem como editar a pergunta e colocar um exemplo prático do uso desse componente, para ajudar outros da comunidade além de mim.
Comment: @IvanFerrer feito!


show progress dialog from custom dialog

Question: I am trying to show a progress dialog from a custom dialog while an image get uploaded to a server. Here is what I have:
final Dialog mDialog = new Dialog(this, R.style.CustomDialogTheme);
mDialog.setContentView(R.layout.sendimage_dialog);
ImageView im = (ImageView)mDialog.findViewById(R.id.image_to_upload);
                        im.setImageURI(Constants.currImageURI);

Button upload = (Button)mDialog.findViewById(R.id.upload);

upload.setOnClickListener(new OnClickListener(){

@Override
public void onClick(View view) {
    mDialog.dismiss();

});

mDialog.show();

mDialog.setOnDismissListener(new OnDismissListener(){

@Override
    public void onDismiss(DialogInterface di) {

                                ProgressDialog progress = new ProgressDialog(CameraActivity.this, R.style.CustomDialogTheme);
                                progress.setProgressStyle(ProgressDialog.STYLE_SPINNER);
                                progress.setMessage("Please wait while your photo is being uploaded.");
                                progress.show();

                                String response = uploadUserPhoto(new File(getRealPathFromURI(Constants.currImageURI)));
                                try {
                                    parseResponse(response);
                                } catch (JSONException e) {
                                    Log.d(TAG, e.getMessage());
                                    e.printStackTrace();
                                }

                                progress.dismiss();
                                Toast.makeText(getApplicationContext(), "Using your computer, log into your graFighters account and your image will be waiting for you.", Toast.LENGTH_SHORT).show();

                            }

                        });

The problem is, when I hit the upload button, my progress dialog never shows. Any ideas why this might be?
Answer: It is because you're performing the network call (uploadUserPhoto) in the main (UI) thread, which means that the UI won't be updated between the calls to show() and dismiss(). If you want this to work, you could launch a separate worker Thread that performs the uploadUserPhoto instead. After the worker Thread has finished, it must then signal the Activity to remove the dialog.
Comment: I just edited my code to use OnDimissListener - do you think it is the same issue you just outlined?
Comment: I just solved by using a separate thread. You were right...Thanks.
Answer: You are showing and  dismissing your ProgressDialog in the click method. As for
mDialog.dismss

It should be dismissing. If you created a custom dialog we may need to see more of it to get a better idea.
EDIT: and then your calling the dialog to show outside of your onClick method.
Answer: You should use an AlertDialog. Here is an example that should fit your code pretty well:
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Alert")
       .setMessage("Please wait while your photo is being uploaded.")
       .setNeutralButton("OK", new DialogInterface.OnClickListener() {
               @Override
               public void onClick(DialogInterface dialog, int which) {
                   dialog.dismiss();
               })
       .show();

I also recommend looking into using an AsyncTask and a ProgressDialog.

show progress dialog from custom dialog


Scheduled run not running even though it was set up correctly?

Question: I've added a schedule block to my pipeline that backs up my RDS database. This is the main yaml file for the pipeline, and yaml validator finds no errors. So why is it not running? Nothing shows up in Scheduled Runs section in the UI, and I actually waited 3 hours for it to run, to no avail. What am I missing?
name: $(Date:yyyyMMdd)$(Rev:.r)
variables:
  - template: ../global-vars.yml

resources:
  repositories:
    - repository: self
      type: git
      name: Deployment
      trigger: none
      schedules:
      - cron: "0 */3 * * *"
        displayName: DB backup every 3 hours
        branches:
          include:
            - master
        always: true

stages:
  - stage: DBBackup
    displayName: DB Backup
    jobs:
      - template: /templates/db/backup.yml

Answer: There is no property schedules which can be placed in resources > repositories > repository according to YAML syntax documentation
https://learn.microsoft.com/en-us/azure/devops/pipelines/yaml-schema/resources-repositories-repository?view=azure-pipelines
You can add schedules on the top level of YAML
https://learn.microsoft.com/en-us/azure/devops/pipelines/yaml-schema/schedules-cron?view=azure-pipelines
try something like this sample
name: $(Date:yyyyMMdd)$(Rev:.r)
variables:
  - template: ../global-vars.yml

schedules:
- cron: "0 */3 * * *"
  displayName: DB backup every 3 hours
  branches:
    include: master
  always: true

resources:
  repositories:
    - repository: self
      type: git
      name: Deployment
      trigger: none

stages: (...)

Comment: That did indeed work, I don't know why I thought it had to be under something. Thanks!


Differentiate $e^{9x}/(-8x^5-4x)$

Question: I have used the quotient rule to differentiate the expression, but I'm not sure how to simplify from here:
$$\frac{  (9e^{9x})*(-8x^5-4x) - (e^{9x}*-40x^4-4) }{(-8x^5-4x)^2}$$
Comment: You need to clean up your parentheses so that the Order of Operations is more clear.
Comment: Also, the derivative of $9e^{9x}$ is $81e^{9x}$, not $9e^{9x}$.
Answer: $$\frac{  (9e^{9x})*(-8x^5-4x) - (e^{9x}*-40x^4-4) }{(-8x^5-4x)^2}$$
Pay attention to your parentheses
$$\frac{  (9e^{9x})*(-8x^5-4x) - e^{9x}*(-40x^4-4) }{(-8x^5-4x)^2}$$
$$\frac{  (9e^{9x})*(-2x^5-x) - e^{9x}*(-10x^4-1) }{(4x^5+2x)^2}$$
$$\frac{  e^{9x}(-18x^5+10x^4-9x+1) }{4x^2(2x^4+1)^2}$$
Comment: Can you just divide one expression with 2 and the other one with 4?
Comment: oh @maria at the denominator you have an exponent 2 so $2^2=4$ thats why
Comment: I don't understand how the $(9e^{9x})$ disappear?
Comment: It didnt disapear it's still there since i multiplied by a factor 9 what was inside the parentheses... @Maria  Example you can do this $$9e^{9x}(x-2)=e^{9x}(9x-18)$$
Answer: After getting to the following result by doing some math:
$$\frac{  e^{9x}(-18x^5+10x^4-9x+1) }{(4x^5+2x)^2}= \frac{  e^{9x}(-18x^5+10x^4-9x+1)} {16x^{10}+16x^6+4x^2}$$
you can perform long division of the polynomial of the denominator by the polynomial of the denominator. And this is a much more simplified from.
Comment: I don't understand how the $(9e^{9x})$ disappear?
Comment: $e^x$ is the common factor and you factorize.
Comment: Oh okey but when I factorize I get: $ e^{9x}(9*-8x^5-4x+40x^4+4) $
Comment: It's $e^{9x}(9*(-8x^5-4x)+40x^4+4) $ which extends to what I wrote.

Differentiate $e^{9x}/(-8x^5-4x)$


Significance of Classifier Performance using Bootstrapping

Question: I'm evaluating a classifier performance on a hold out test set, using AUC (and other metrics).
I'm using bootstraps to calculate the confidence intervals of the metrics.
How should I calculate if there is a sigficance difference between two classifiers?
I was going to compare the two distributions (calculated independently). But I'm beginning to think I should calculate the distribution of the differences calculated using the same bootstrap sample for each classifier?
Answer: If you've bootstrapped out of sample performance for two models, you will obtain an approximation to the sampling distribution of the test statistic (here, the AUC).  You can compute then compute the probability that one model's AUC is larger than the other using these samples.  Shown below is an example using sklearn

import numpy as np
from sklearn.utils import resample
from sklearn.linear_model import LogisticRegression, LogisticRegressionCV
from sklearn.metrics import roc_auc_score
from sklearn.datasets import make_classification
from sklearn.model_selection import train_test_split
import matplotlib.pyplot as plt
%matplotlib inline

X,y=make_classification(n_classes=2, n_samples=1000, n_features=5, random_state=0)
Xtrain, Xval, ytrain, yval = train_test_split(X,y,train_size = 500)

model_1 = LogisticRegression(penalty = 'none', solver='lbfgs').fit(Xtrain, ytrain)
model_2 = LogisticRegressionCV(Cs = [0.004], penalty = 'l1', solver = 'liblinear', max_iter = 1000, cv = 5).fit(Xtrain, ytrain)

model_1_auc = []
model_2_auc = []

for _ in range(1000):

    Xvalb, yvalb = resample(Xval, yval)

    model_1_p = model_1.predict_proba(Xvalb)[:,1]
    model_2_p = model_2.predict_proba(Xvalb)[:,1]

    model_1_auc.append(roc_auc_score(yvalb,model_1_p))
    model_2_auc.append(roc_auc_score(yvalb,model_2_p))

Here is the result for such a procedure

I'm not a big fan of using the term "significant difference" in this case.  That makes it sound like you have tested hypothesis about the difference between AUC, and that isn't as easy as it sounds (at least, I don't think it is).  What you can do is use these bootstraps to look at the difference between AUCs for each model.  You may do something like the following...
diff_in_auc =  np.array(model_1_auc)-np.array(model_2_auc)

np.mean(diff_in_auc)

>>>0.00322

So the average difference in the AUC between the two models is on the order of 1e-3.  Not a big difference.  You could also determine the proportion of the pairs in which model_1 had a larger AUC using similar techniques.  I think most people would interpret that as the probability that model_1 has a superior AUC as compared to model 2.
Finally, I would caution you in using AUC as a metric on which to choose models.  If I have understood Frank Harrell correctly, the metric isn't sensitive enough to pick up on meaningful improvements between models. EDIT: See this comment by Frank for the fuller story.  Thanks to Dave for finding that.
Comment: Harrell has posted on here that AUC is solid as a diagnostic of whether or not a particular model is any good, but he also mentioned that AUC was not so great for comparing models. Anyway, log loss, which I know sklearn can do, is a performance metric that he promotes quite heavily.
Comment: Found it: https://stats.stackexchange.com/a/210718/247274. His "argue harder" comment is wonderful.
Comment: I'm completely in agreement about the AUC, I'm not a big fan of it. I was just using it to illustrate my question.
Comment: Many thanks for the illustrated answer and for confirming it is the **proportion of the pairs** (distribution of the differences) I should be using.
Comment: I also understand your concerns about using significance difference. I'm in the position however, where it is expected to be reported.
Comment: @Dave, yes thank you that *is* what Frank says.


How does one find $\mathscr{L}^{-1}\left\{\frac{3}{(s-1)^2} \right\}$?

Question: I am trying to solve
$$\mathscr{L}^{-1} \left\{\frac{3}{(s-1)^2} \right\}$$
However, it seems worse than easy. We can write this out as
$$\mathscr{L}^{-1} \left\{\frac{3}{(s-1)}\frac{1}{(s-1)} \right\}, $$ where the factor $\dfrac{1}{s-1}$ recurs, so the answer must have the inverse of this in it, so we can write $$\mathscr{L}^{-1} \left\{\frac{3}{(s-1)}\frac{1}{(s-1)} \right\} = e^t \, f(t).$$
We can then consider the damping rule which says that $\mathscr{L}^{-1} \left\{F(s+b) \right\} =e^{-bt} \, f(t).$
Then, with $b=-1$, we obtain:
$$\mathscr{L}^{-1}\left\{ \frac{3}{(s-1)}\frac{1}{(s-1)} \right\}=F(s-1).$$
But the question now is, what is $F(s)$?
Any ideas how to solve this?
Thanks
Answer: If $L\{f(t)\}=F(s)$, then we have $L\{tf(t)\}=-F'(s)$ (this link); and note that:
$$\frac {3}{(s-1)^2}=-\left(\frac {3}{s-1}\right)'.$$
Moreover we have $L\{3 \, e^t\}=\frac {3}{s-1}$; therefore:
$$L^{-1} \left\{ \frac{3}{(s-1)^2} \right\}=3 \, t \, e^t.$$


How to lock in the Sort Order for view display?

Question: I've got a View of 10 images displaying inline, the first and last images are different (have rounded corners), and it is really important that the order for all 10 images is locked in. Is there a way to do this, without having to edit all the nodes in order to get them displaying in the correct order?
Answer: You want the Nodequeue module.
You can make a queue and add nodes to it an arbitrary order. All queues have an associated view that gets created, and can be used anywhere you use a view.


Get truncated when insert data by stored procedure

Question: This is my stored procedure:
CREATE PROC InsertTINH
    @MaTinh char(4),
    @TenTinh varchar(50),
    @MaNuoc char(2)
as
begin
    if exists (select * from TINH where MaTinh = @MaTinh)
    begin
        print 'Ma Tinh already exists'
        return
    end
    else
    begin
        if not exists (select * from NUOC where MaNuoc = @MaNuoc)
        begin
            print 'Ma nuoc does not exist'
            return
        end
        else
        begin
            insert into TINH
            values ('@MaTinh', '@TenTinh')

            insert into SQL_HOME.QLXNK.dbo.TINH
            values ('@MaTinh', '@MaNuoc')

            print 'Inserted successfully ' + @TenTinh
        end
    end
end
GO

I have 2 tables in 2 different host which is TINH in local and the second is SQL_HOME.QLXNK.dbo.TINH

Table1 (MaTinh char(4) primary key not null, TenTinh varchar(50))
Table2 (MaTinh char(4) primary key not null, MaNuoc char(2))

When I execute
exec InsertTINH 'VN01','Ho Chi Minh','VN'

I get an error:

String or binary would be truncated

but just insert normally --> it works!
insert into TINH
values ('VN01', 'Ho Chi Minh')

insert into SQL_HOME.QLXNK.dbo.TINH
values ('VN01','VN')

What is the problem in my stored procedure?
Answer: You need to remove ' around variables/parameters:
insert into TINH values (@MaTinh,@TenTinh)
insert into SQL_HOME.QLXNK.dbo.TINH values (@MaTinh,@MaNuoc)

@MaTinh - variable, '@MaTinh' - string
DECLARE @MaTinh char(4) = 'VN01';
SELECT @MaTinh, '@MaTinh';

LiveDemo

It is a good practice to specify column names in INSERT list:
INSERT INTO TINH(col_name1, col_name2) VALUES (@MaTinh,@TenTinh);

Comment: Oh GOD!! THANKS U SO SO SO MUCH!! I take 2 hours to figure it out but still get not thing.
Comment: I accept right a way and it said need 5 min to accept :)


A function whose graph has vertical asymptotes at $x=+2$ and $x=-2$, and a horizontal asymptote at $y=0$

Question: Determine a function whose graph has vertical asymptotes at $x=+2$ and $x=-2$, and a horizontal asymptote at $y=0$?
I don't know to satisfy these conditions.
Comment: What does having vertical and horizontal asympotes mean? Think of appropriate denominator
Answer: $$\frac{1}{(x+2)(x-2)}$$
Can you see why it works?
Comment: How did you get it?
Comment: @Rich If it has to have an vertical asymptote it means the the denominator vanishes at $x=2$ and $x=-2$. This is the simplest function that satisfies the requests. You can see that is also has an horizontal asymptote at $y=0$. If you wanted, say, and horizontal asymptote at $y=2$, this would not work. Can you see how to fix this function so that it has a astympote in $y=2$ instead of $y=0$? What the numerator would look like in this case=
Comment: I get it now, thank you!
Answer: There are countless examples of such functions: $$f(x)=\begin{cases}c\cdot\tan^k\bigg(\dfrac\pi4x\bigg),\qquad x\in(-2,2)\\\\\dfrac a{(x+2)^n},~\qquad\qquad~ x<-2\\\\\dfrac b{(x-2)^p},~\qquad\qquad~ x~>~2\end{cases}\qquad\qquad\qquad\qquad\qquad\begin{align}&a,b,c\in\mathbb R^*\\\\&k,n,p\in\mathbb N^*\end{align}$$


Permutation method generating results arbitrarily

Question: I am using the permutations() function from the itertools module. I have to compare two strings. The strings can be considered equal as long as one is a permutation of the other.
The documentation for itertools.permutations() says:

itertools.permutations(iterable[, r])
Return successive r length permutations of elements in the iterable.
If r is not specified or is None, then r defaults to the length of the iterable and all possible full-length permutations are generated.

This is my code:
import itertools
mystr = []
for i in range(0, 2):
    mystr.append(input())

plist = itertools.permutations(mystr[0])
for i in plist:
    print(i)
if any(x == mystr[1] for x in plist):
    print("Yes")
else:
    print("No")

But generating plist takes too long. And when I try to print elements of plist, the process eventually gets killed because it is making too many permutations. But it should make only the permutations of length of the string itself.
My inputs are:
Dcoderplatform
patlodercDmfro

I am expecting the output to be Yes. But I get the opposite output (No).
How can I improve my algorithm?
Answer: Even if you only generate permutations that are the same length as the input string, the number of permutations can be very large. Consider the string in your example: Dcoderplatform. The number of permutations is the factorial of the length of the string. In this case 14! or 87178291200 permutations. So you can expect your process to be terminated when given an input string of any significant length.
Fortunately, there's an easier way to do this. Assuming you aren't required to use the permutations() function, you should use the following method.
Given two strings, str1 and str2, you can check if one is a permutation (an anagram) of the other like this:
str1 = 'Dcoderplatform'
str2 = 'patlodercDmfro'
if ''.join(sorted(str1)) == ''.join(sorted(str2)):
    print('{} and {} are anagrams'.format(str1, str2))

Answer: I think you should compare like this:
if(any("".join(x)==mystr[1] for x in plist)):


Formattedtextfield and DateTime in JAVA

Question: How can i automatically write current system date as "YYYY-MM-DD HH:MM:SS" to formatted text field after program is launched in JAVA?
Actually i have two formatted text field. One of must be shown current system date - 5 Min  second must be shown current system date after program is launched.
When i run this program Jpanel comes. Ihave these 2 formattedtextfield in this panel.
Left one: must be show current system date - 5min (2013-12-22 21:00:00.000)
Right one: must be show current system date (2013-12-22 21:05:00.000)
How can i code it for automaticly appear this values to fields?
P.S: sorry i dont attach image because i dont have 10 rep yet :(
Comment: Your question is unclear. Further explain _"5 Min second must be shown current system date after program is launched."_ and _"And these formatted text fields can be editable but only date and time changing._". And show us some code of what you have attempted.
Comment: I have just edit my question.
Answer: For setting the current system date you need:
JFormattedTextField ftf = ...;
ftf.setValue(new Date());

For setting the right format you need a DefaultFormatterFactory and the DateFormatter:
DateFormatter df = new DateFormatter(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
DefaultFormatterFactory factory = new DefaultFormatterFactory(); // other ctors possible
factory.setDefaultFormatter(df); // here simple default solution
ftf.setFormatterFactory(factory);

Note: You should read the javadoc. There are several variations for edit and display mode. So in your scenario you need two fields (and therefore two dates):
JFormattedTextField ftfLeft = ...; // create and set the format
JFormattedTextField ftfRight = ...; // create and set the format
Date now = new Date();
Date nowMinusFiveSeconds = new Date(now.getTime() - 5 *1000);
ftfLeft.setValue(nowMinusFiveSeconds);
ftfRight.setValue(now);

Comment: Thanks Meno, i can try these codes in Netbeans. I am confused sometimes because Netbeans has Designer Gui as you know. I must entegration these codes to right place first.
Comment: In your question it is not clear if you mean 5 seconds or five minutes. I have now posted an example code for the case in seconds. For minutes you need to multiply the factor 5 by 60.
Comment: Thanks for the simple solution Meno.
Answer: You can use a SimpleDateFormat the set the text of the textfield with the current time
    Date date = new Date();
    SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    String dateString = formatter.format(date);
    formatText = new JFormattedTextField(createFormatter("####-##-## ##:##:##"));
    formatText.setColumns(20);
    formatText.setText(dateString);

If you need to get the date value of the input text, just parse it.
   Date date;
   try {
       date = formatter.parse(formatText.getText());
   } catch (ParseException ex) {
       ...
   }

And to set the field editable with the desired format, you can use a MaskFormatter. See my example. It runs
import java.awt.BorderLayout;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.swing.JFormattedTextField;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.text.MaskFormatter;

public class MaskFormatterTest1 extends JPanel {

    private JFormattedTextField formatText;

    public MaskFormatterTest1() {
        Date date = new Date();
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        String dateString = formatter.format(date);
        formatText = new JFormattedTextField(createFormatter("####-##-## ##:##:##"));
        formatText.setColumns(20);
        formatText.setText(dateString);

        setLayout(new BorderLayout());
        add(new JLabel("Enter Date and Time in YYYY-MM-DD HH:MM:SS format"), BorderLayout.NORTH);
        add(formatText, BorderLayout.CENTER);
    }

    private MaskFormatter createFormatter(String s) {
        MaskFormatter formatter = null;
        try {
            formatter = new MaskFormatter(s);
        } catch (java.text.ParseException exc) {
            System.err.println("formatter is bad: " + exc.getMessage());
            System.exit(-1);
        }
        return formatter;
    }

    public static void main(String[] args) {
        javax.swing.SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                JFrame frame = new JFrame("MaskFormatter example");
                frame.add(new MaskFormatterTest1());
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.setLocationByPlatform(true);
                frame.pack();
                frame.setVisible(true);
            }
        });
    }
}

Comment: You should use HH, not hh in SimpleDateFormat-pattern (hour from 0 to 23).
Comment: Thanks to you peeskillet. I already take some codes in your code table.
Comment: Ah i am new in stackoverflow. So i dont know general deportments yet sorry :)

Formattedtextfield and DateTime in JAVA


Genesis' bVII-V-I cadence

Question: In the verse part of Genesis' "Behind the Lines", the last line of the chord progression goes:
F   C   Dm   Bb G -> C (resolution)
What is that cadence? What is the theory for that bVII - V - I?
I've heard a lot of times the double plagal cadence that goes IV/IV (bVII) - IV - I, for example in the outro of Hey Jude. But I could not find the correlation between the bVII and V chords.
I thought maybe it could be kind of a resolution where D stays the same, Bb goes to B and F goes to G (if voiced and inverted correctly); but it's kind of disorienting that the Bb is chromatic to the key...
Comment: Maybe because it wouldn't be used in the common practice preiod, there's no official name for it.
Comment: @Tim I'm not looking for a name but for a common analysis
Comment: What is the bass doing through these changes?
Comment: @MichaelCurtis that's a very good question, that I don't know the answer to.
Answer: Rock harmony tends to be mostly root position, but if the bass held a D for the Dm and the Bb, you could possibly talk about passing motion, especially if there is a line like A Bb B C.
Mixolydian coloring may be the most straight forward way to describe this. Exclude the Bb...
F C Dm ... G -> C
...and you have common progressions IV I then ii V I.
Inserting a Mixolydian (borrowed) bVII between ii and V doesn't really change the essential harmony of root progression by fourths and fifths.
In terms of technical jargon borrowed chord, mode mixture, etc. are terms that could be used.
Comment: [Wikipedia: Borrowed Chord](https://en.wikipedia.org/wiki/Borrowed_chord) _"Chord progressions may be constructed with borrowed chords, including two progressions common in rock music, I–♭VII–♭VI–♭VII, common everywhere, and I–♭VI–IV, used by bands like **Genesis**, Yes, and Nirvana."_
Comment: That would be a good explanation. I don't know if there is criteria or theory for passing chords so...
Comment: passing motion, chords, etc. basically can be used when the tones don't fit a well defined, common progression, but the _linear_ motion is step wise. A classic passing chord is the `V6/4` in something like `I6 V6/4 I`. Passing chord in invoked for that description, because `6/4` chords (second inversion chords) are expected to be part of a cadence of pedal bass.
Comment: Try looking up passing tone, passing chord for a more complete description. Some counterpoint knowledge helps complete the understanding.
Answer: I think it could be considered a line cliché where the A in the Dm chord goes to Bb and then to B in the G chord.
Comment: I was going to call it that, but isn't a line cliché a progression where only one note changes chromatically (and the others stay the same)?
Comment: But it would actually make sense, since then it resolves to C (going A Bb B C)
Comment: I don't think it's necessary for all the other notes to stay the same. *Stairway to Heaven* has other notes move.
Answer: The B♭ chord could very well be a borrowed chord from C Minor. In C Minor, it behaves as an ordinary non-tonic, non-dominant chord. In C Major, it will behave the same way.
In any cadence, it's the last two chords that are by far the most important. I wouldn't put any significance on the ♭VII part of a ♭VII - V - I cadence.

Genesis' bVII-V-I cadence


Background color won't take up whole element

Question: I have a drop down menu button that turns grey when hovered over. However, the grey does not expand throughout the whole button, but stops at the where I set the padding.
HTML:

#dropdown {
  list-style: none;
  display: none;
  position: absolute;
  background-color: #fff;
  padding: 10px;
  z-index: 99999;
  width: 230%;
}

#dropdown li:hover,
#dropdown li:active {
  background-color: #e3e3e3;
}

#dropdown.active, #menu:target #dropdown {
  display: block;
}

    Help▾

Give

Get Help

Get Involved

What I want is for the grey to take up all of the drop-down menu when hovered over, as opposed to just stopping at the padding.
EDIT: I should have clarified, when I meant I want it to take up "all" of the drop down menu, I meant just the "li" when I hover over that.
Comment: so move the padding to the li ...
Comment: please fix your snippet
Comment: I changed the snippet so that the dropdown becomes visible. but I'm afraid it raises more question than it answers. I mean, why is the width 230%? And if you want "the grey to take up all of the drop-down menu when hovered over" then why do you only apply it to the individual items in the list?
Comment: I think he confused `%` for `px` and wanted to give each li a width of 230px.
Comment: The width is 230% because the background color only expands through the whole word at that width.
Comment: @RGao Did my answer help in any way? Do you need any further help?
Comment: Sorry for the late response, your answer helped and the problem is solved now.
Answer: Is this what you were looking for?

#dropdown {
  list-style: none;
  display: none;
  position: absolute;
  background-color: #fff;
  padding: 10px;
  z-index: 99999;
  width: 230%;
}

#dropdown:hover {
  background-color: #eee;
}

#dropdown li:hover,
#dropdown li:active {
  background-color: #e3e3e3;
}

#dropdown.active, #menu:target #dropdown {
  display: block;
}

    Help▾

Give

Get Help

Get Involved


What elementary matrices affect the following elementary row operations of a 4x4 matrix?

Question: This question is in a review sheet without answers for my class, but I don't understand the question very well.
A) Exchange Row 2 and 4,
B) Row 1 +2(Row 3),
C) Multiply Row 3 by -2.
Am I just supposed to make a basic 4x4 and solve for the elementary matrix or is there a certain matrix that has problems with these operations?
Thanks.
Comment: You probably mean [*effect*](https://www.merriam-webster.com/dictionary/effect), rather than [*affect*](https://www.merriam-webster.com/dictionary/affect).
Comment: More context is required.
Answer: It seems like the question is asking for the elementary matrices that perform the specified action. For instance, if one wishes to exchange row 2 and row 4, then one multiplies on the left by the elementary matrix
\begin{align*}
\begin{pmatrix}
1 & 0 & 0 & 0\\
0 & 0 & 0 & 1\\
0 & 0 & 1 & 0\\
0 & 1 & 0 & 0
\end{pmatrix}.
\end{align*}
To add twice row 3 to row 1, one multiplies on the left by the matrix
\begin{align*}
\begin{pmatrix}
1 & 0 & 2 & 0\\
0 & 1 & 0 & 0\\
0 & 0 & 1 & 1\\
0 & 0 & 0 & 1
\end{pmatrix}.
\end{align*}
Finally, to multiply row 3 by -2,
\begin{align*}
\begin{pmatrix}
1 & 0 & 0 & 0\\
0 & 1 & 0 & 0\\
0 & 0 & -2 & 0\\
0 & 0 & 0 & 1
\end{pmatrix}.
\end{align*}
Comment: The matrices are obtained by performing the corresponding row operation on the identity matrix.


HTML tr for widths but hide

Question: I have a normal HTML table (no fancy stuff): https://jsfiddle.net/Ljo9gkud/
-> The table uses the first
 for the column size definitions, like so:

Goal: I want to hide this first
 because it creates an unnecessary gap. "CSS display: none;" does not work because then the column size definitions are ignored:

With display: none -> https://jsfiddle.net/Ljo9gkud/1 (ignored widths)
Problem:
Even when setting height: 0 etc. on both
 and I cannot get rid of the space (gap) it creates. Any help? How do I not show the first
but keep column size definition from it?
Comment: would `table-layout: fixed` on the main table CSS yield the result you want without the need for additional empty TR / TD elements?
Comment: Why not put the spacing on the table header:?https://jsfiddle.net/mplungjan/xvLw60p4/ - I put the last 10% on the next row
Answer: Remove your spaces from your first tr:

Add this to your css (instead of display none):
.Cdef td {
    padding: 0;
}

https://jsfiddle.net/Ljo9gkud/9/
Comment: Good job. Thank you very much!
Answer: You can also put the spacing on a table header - I put the last spacing on the first cell row

body {
  font-family: Arial, 'Helvetica Neue', Helvetica, sans-serif;
  font-size: 12px;
  margin-left: 1%;
  margin-right: 1%;
  margin-bottom: 50px;
}

body table {
  border-collapse: collapse;
  border-spacing: 0;
  font-family: Arial, 'Helvetica Neue', Helvetica, sans-serif;
  font-size: inherit;
}

html .k-radio:disabled+.k-radio-label,
html .k-checkbox:disabled+.k-checkbox-label {
  color: #000000 !important;
}

html .k-radio:disabled+.k-radio-label {
  height: 16px;
}

html .k-checkbox:checked:disabled+.k-checkbox-label:active:before,
html .k-checkbox:checked:disabled+.k-checkbox-label:before,
html .k-checkbox:checked:disabled+.k-checkbox-label:hover:before,
html .k-checkbox:disabled+.k-checkbox-label:before {
  background-color: #fff;
  border-color: #ccc;
  color: #000;
  font-weight: bold;
}

html .k-checkbox:checked+.k-checkbox-label::before {
  content: "✓";
}

html .k-radio:disabled:checked+.k-radio-label::after {
  background-color: #333333;
  opacity: 1
}

html input.k-textbox,
html textarea.k-textbox {
  color: #000;
  /* font-style: italic; */
}

/*
 Style from .jsp
*/

section#matrix {
  font-size: 12px;
}

.clientHeader,
.clientHeader * {
  font-size: 100%;
}

.HTitle {
  line-height: 80px;
  font-size: 116%;
  text-align: center;
  font-weight: bold;
  height: 80px;
  position: relative;
}

.HTitle .logoprint {
  height: 80px;
  max-width: 120px;
  position: absolute;
  right: 0;
  top: 0;
}

.clientHeader .matrix table {
  border-spacing: 0;
  border-collapse: collapse;
}

.clientHeader .matrix td {
  padding: 5px 5px;
  border: #C9CAD4 thin solid;
}

.clientHeader .matrix td i {
  font-size: 92%;
}

.legalText {
  text-align: justify;
}

/* Form Style */

.div3 {
  width: 100%;
  white-space: nowrap;
}

.div3>div {
  width: 33.333333%;
  display: inline-block;
}

td {
  padding: 10px 5px;
  border: #C9CAD4 thin solid;
}

.div3 {
  text-align: center;
}

.div3>div:nth-of-type(1),
.div3>div:nth-of-type(2) {
  border-right: #C9CAD4 thin solid;
}

.matrix2 tr td:nth-of-type(2),
.matrix2 tr td:nth-of-type(3),
.matrix2 tr td:nth-of-type(4),
.matrix2 tr td:nth-of-type(5) {
  text-align: center;
}

.h1 {
  font-size: 150%;
  font-weight: bold;
}

.h2 {
  font-size: 130%;
  font-weight: bold;
}

.h3 {
  font-size: 120%;
  font-weight: bold;
}

.h4 {
  font-size: 110%;
  font-weight: bold;
}

.footer {
  padding: 20px 0;
  width: 100%;
  text-align: center;
}

.berater>div {
  padding: 5px 5px;
  border: #C9CAD4 thin solid;
  width: 40%;
}

.berater>div:first-of-type {
  border-bottom: none;
}

textarea.k-textbox {
  width: 100%;
}

.singleQComment>.fcontainer {
  display: flex;
  justify-content: space-between;
}

.singleQComment>div {
  /* width: 100%;
 width: calc(100% - 10px);  */
  padding: 5px 5px;
  border-top: #C9CAD4 thin solid;
  border-right: #C9CAD4 thin solid;
  border-bottom: none;
  border-left: #C9CAD4 thin solid;
}

.singleQComment>div:last-of-type {
  border-bottom: #C9CAD4 thin solid;
}

.singleQComment>div label:last-of-type {
  margin-right: 0;
}

.singleQComment>div label {
  margin-right: 10px;
}

#matrix>* {
  margin-top: 20px;
}

.signature>span {
  display: block;
  margin-bottom: 20px;
}

.signature .signElements,
.signature .signElements2 {
  display: flex;
  justify-content: space-between;
}

.signature .signElements>div {
  background-color: #dde4ff;
}

.signature .signElements>div,
.signature .signElements2>div {
  height: 80px;
  flex-basis: 48%;
}

        keine
        bis 2'000 €
        2'001 bis 5'000 €
        über 5'000 € (Betrag in €)

        Nichtselbständige Tätigkeit (Lohn / Gehalt)

          <input type="radio" name="RegNicht" id="RegNicht1" class="k-radio" disabled="disabled" checked="checked">

          <input type="radio" name="RegNicht" id="RegNicht2" class="k-radio" disabled="disabled">

          <input type="radio" name="RegNicht" id="RegNicht3" class="k-radio" disabled="disabled">

          <input type="radio" name="RegNicht" id="RegNicht4" class="k-radio" disabled="disabled">

          <input type="text" class="k-textbox k-state-disabled" value="" placeholder="" disabled="disabled">

        Selbständige Tätigkeit / Gewerbebetrieb / Freiberufler

          <input type="radio" name="RegSelb" id="RegSelb1" class="k-radio" disabled="disabled">

          <input type="radio" name="RegSelb" id="RegSelb2" class="k-radio" disabled="disabled" checked="checked">

          <input type="radio" name="RegSelb" id="RegSelb3" class="k-radio" disabled="disabled">

          <input type="radio" name="RegSelb" id="RegSelb4" class="k-radio" disabled="disabled">

          <input type="text" class="k-textbox k-state-disabled" value="" placeholder="" disabled="disabled">

        Rente / Pension

          <input type="radio" name="RegRent" id="RegRent1" class="k-radio" disabled="disabled">

          <input type="radio" name="RegRent" id="RegRent2" class="k-radio" disabled="disabled">

          <input type="radio" name="RegRent" id="RegRent3" class="k-radio" disabled="disabled" checked="checked">

          <input type="radio" name="RegRent" id="RegRent4" class="k-radio" disabled="disabled">

          <input type="text" class="k-textbox k-state-disabled" value="" placeholder="" disabled="disabled">

        Vermietung / Verpachtung

          <input type="radio" name="RegVerm" id="RegVerm1" class="k-radio" disabled="disabled">

          <input type="radio" name="RegVerm" id="RegVerm2" class="k-radio" disabled="disabled" checked="checked">

          <input type="radio" name="RegVerm" id="RegVerm3" class="k-radio" disabled="disabled">

          <input type="radio" name="RegVerm" id="RegVerm4" class="k-radio" disabled="disabled">

          <input type="text" class="k-textbox k-state-disabled" value="" placeholder="" disabled="disabled">

        Kapitalvermögen

          <input type="radio" name="RegKap" id="RegKap1" class="k-radio" disabled="disabled" checked="checked">

          <input type="radio" name="RegKap" id="RegKap2" class="k-radio" disabled="disabled">

          <input type="radio" name="RegKap" id="RegKap3" class="k-radio" disabled="disabled">

          <input type="radio" name="RegKap" id="RegKap4" class="k-radio" disabled="disabled">

          <input type="text" class="k-textbox k-state-disabled" value="" placeholder="" disabled="disabled">

        Sonstige regelmäßige Einkünfte

          <input type="radio" name="RegSon" id="RegSon1" class="k-radio" disabled="disabled">

          <input type="radio" name="RegSon" id="RegSon2" class="k-radio" disabled="disabled">

          <input type="radio" name="RegSon" id="RegSon3" class="k-radio" disabled="disabled">

          <input type="radio" name="RegSon" id="RegSon4" class="k-radio" disabled="disabled" checked="checked">

          <input type="text" class="k-textbox" value="6'500" placeholder="" disabled="disabled">

HTML tr for widths but hide


Calculate the min and max time with disconnection intervals SQL Server

Question: I need to calculate the time between two dates; the problem is that I have the data of x-person in two rows starting at day 1 at x time and finishing day 2 at x time and start over again the day 2 at x time until day 3 at x time...
So what I need is to determine the duration of each person per day.
Hope you guys can help me!!!
Thank you in advance.
I´ve tried some options but I can't get the result I'm looking for.
-- Table example

DECLARE @tbl TABLE(person varchar(10), startDate DATE, startTime TIME(0), endDate DATE, endTime TIME(0))

INSERT INTO @tbl
SELECT 'PERSON A' person, '2019-06-06' startDate, '02:14:00' startTime, '2019-06-06' endDate, '06:00:00' endTime

INSERT INTO @tbl
SELECT 'PERSON A' person, '2019-06-06' startDate, '22:00:00' startTime, '2019-06-07' endDate, '06:00:00' endTime

SELECT * FROM  @tbl -- > This would be the table example

The expected result would be
First_Row = (2019-06-06 06:00:00 - 2019-06-06 02:14:00) => 03:46:00
Second_RowA = (2019-06-06 22:00:00 - 2019-06-06 24:00:00) => 02:00:00
Second_RowB = (2019-06-07 02:14:00 - 2019-06-07 00:00:00) => 02:14:00 because the remaining time is being calculated by the first row between
So finally the result would be:
First_Row + Second_RowA + SecondRowB = 08:00:00
UPDATE:
The answer didn't work for what I need to do, but I know the question is a little tricky (sorry my English is not good), I'll try to explain better so here I go:
I have data for login and logout of call center agents, these agents have a work shift from 22 to 06, so what I need to calculate is the min of loginTime and max of logOutTime, but this is where it becomes complex, because there are cases where an agent is disconnected during that time range, then another login event is created in the database on the same day where another shift begins and so on.
So my question is: how can I determine the min and max I need, to be displayed only once per agent and per date?
Here's the data:
DECLARE @tbl TABLE(agentId VARCHAR(10), position VARCHAR(10), loginDate DATE, loginTime TIME(0), logoutDate DATE, logoutTime TIME(0))

INSERT INTO @tbl SELECT '311338', '230025', '2019-06-03', '21:59:00', '2019-06-04', '06:00:00'
INSERT INTO @tbl SELECT '311338', '230025', '2019-06-04', '21:59:00', '2019-06-04', '23:30:00'
INSERT INTO @tbl SELECT '311338', '230025', '2019-06-04', '23:31:00', '2019-06-05', '06:01:00'
INSERT INTO @tbl SELECT '311338', '230038', '2019-06-05', '21:59:00', '2019-06-06', '02:13:00'
INSERT INTO @tbl SELECT '311338', '230038', '2019-06-06', '02:14:00', '2019-06-06', '06:00:00'
INSERT INTO @tbl SELECT '311338', '230037', '2019-06-06', '22:00:00', '2019-06-07', '06:00:00'
INSERT INTO @tbl SELECT '311338', '230038', '2019-06-07', '21:59:00', '2019-06-08', '00:53:00'
INSERT INTO @tbl SELECT '311338', '230038', '2019-06-08', '00:53:00', '2019-06-08', '06:00:00'
INSERT INTO @tbl SELECT '311338', '230038', '2019-06-09', '22:00:00', '2019-06-10', '06:09:00'

SELECT agentId
    ,position
    ,(CAST(loginDate AS DATETIME) + CAST(loginTime AS DATETIME)) loginTime
    ,(CAST(logoutDate AS DATETIME) + CAST(logoutTime AS DATETIME)) logoutTime
  FROM @tbl

Result for agentId 311338 would be:
Day 2019-05-06:
minLogin = 2019-06-05 21:59:00.000
maxLogout = 2019-06-06 06:00:00.000
Day 2019-06-06:
minLogin = 2019-06-06 22:00:00.000
maxLogout = 2019-06-07 06:00:00.000
Day 2019-06-07:
minLogin = 2019-06-07 21:59:00.000
maxLogout = 2019-06-08 06:00:00.000
Answer: The following code demonstrates how to use a Common Table Expression (CTE) to convert the date and time pairs into DateTime values, calculate the differences, total the values and convert the result to a string.
Note that your sample data has an incorrect endTime in the second row.
Your question is a bit unclear, but it seems that you only want the final sum. There is no need to break rows into daily intervals as you have proposed (Second_RowA and Second_RowB), you can simply take the difference and sum it.
Since Time is limited to values less than 24 hours I have taken the differences in seconds, summed them, and converted the result to a string that may have a number of hours greater than 24. You could modify the code to format the result as "ddd hh:mm:ss" if you like.
There are several select statements commented out at the end of the code sample. You can replace the final select with one of the others to see the intermediate results of the CTE.
DECLARE @tbl TABLE(person varchar(10), startDate DATE, startTime TIME(0), endDate DATE, endTime TIME(0))

INSERT INTO @tbl
SELECT 'PERSON A' person, '2019-06-06' startDate, '02:14:00' startTime, '2019-06-06' endDate, '06:00:00' endTime

INSERT INTO @tbl
SELECT 'PERSON A' person, '2019-06-06' startDate, '22:00:00' startTime, '2019-06-07' endDate, '02:14:00' endTime

SELECT * FROM  @tbl;

with
  DateTimes as ( -- Assemble the   Date   and   Time   into   DateTime    values.
    select Cast( StartDate as DateTime ) + Cast( StartTime as DateTime ) as StartDT,
      Cast( EndDate as DateTime ) + Cast( EndTime as DateTime ) as EndDT
      from @tbl ),
  DeltaTimes as ( -- Calculate the number of seconds between   StartDT   and   EndDT.
    select DateDiff( second, StartDT, EndDT ) as Seconds
      from DateTimes ),
  TotalTime as ( -- Sum all of the periods.
    select Sum( Seconds ) as TotalTime
      from DeltaTimes )
  -- You can replace the final   select   statement with one of these to display the intermediate results.
  --select * from DateTimes;
  --select * from DeltaTimes;
  --select * from TotalTime;
  select Cast( TotalTime / 3600 as VarChar(6) ) +
    ':' + Right( '0' + Cast( TotalTime / 60 % 60 as VarChar(2) ), 2 ) +
    ':' + Right( '0' + Cast( TotalTime % 60 as VarChar(2) ), 2 ) as TotalTime
    from TotalTime;

Comment: OK thank you, you just give me an idea of how to resolve this, plus... there's no incorrect data, actually I'm taking info from two different sources, that's why you see I'm trying to limit the endTime of second-row example, to be more specific on what I needed.
Comment: I made some changes because the question was not clear.
Comment: @Steven (1) Your update should be a new question since it has only a passing similarity to the original question. (2) You provided sample data, but not the expected results. Then added the expected results without explanation. (3) It still doesn't make sense. If a shift is from `22:00` through `06:00` then `21:59` and `06:09` should be discarded as invalid times.
Comment: I can't discard those times as I need them to determine attendance kpi, so they still being valid times. I will post a new question, thank you for the advice and your time to answer it was help full.
Comment: Posted a new question for this issue: https://stackoverflow.com/q/56650802/9829961


Como implementar um LOG de atualizações com ASP.NET MVC?

Question: Eu gostaria de ideias sobre como implementar um LOG de atualizações genérico no DB (Entity Framework 6+) que me permita descobrir informações como por exemplo: usuário do sistema X na data Y alterou nome e data de nascimento (de, para) no cadastro de clientes.
Penso que seja possível implementar algo assim de forma genérica, sem que seja necessário criar as entradas de log para cada action em cada controller, utilizando ActionFilter e/ou EntityFramework Interceptor.
Comment: Bom tem esse link: `http://msdn.microsoft.com/pt-br/library/dn630210.aspx` seria a base da sua pergunta !!!
Answer: Passo 1. Crie um Model para registrar as ações
namespace SeuProjeto.Models
{
    public class ActionsLog
    {
        [Key]
        public Guid ActionsLogId { get; set; }
        public String Controller { get; set; }
        public String Action { get; set; }
        public String Ip { get; set; }
        public DateTime DateAndTime { get; set; }
        // Coloque aqui os campos extras que deseja usar para o registro
    }
}

Passo 2. Implemente um Filter derivado de ActionFilter
namespace SeuProjeto.Filters
{
    public class CustomActionFilter : ActionFilterAttribute, IActionFilter
    {
        void IActionFilter.OnActionExecuting(ActionExecutingContext filterContext)
        {
            // Coloque aqui algumas regras de negócio que quiser antes de fazer o log.

            // Aqui é o registro propriamente dito
            var contexto = new MeuProjetoContext();

            var log = new ActionsLog()
            {
                ActionsLogId = Guid.NewGuid(),
                Controller = filterContext.ActionDescriptor.ControllerDescriptor.ControllerName,
                Action = filterContext.ActionDescriptor.ActionName + " (Logged By: Custom Action Filter)",
                Ip = filterContext.HttpContext.Request.UserHostAddress,
                DateAndTime = filterContext.HttpContext.Timestamp
                // Coloque aqui os campos extras para inclusão
            };

            contexto.ActionsLogs.Add(log);
            contexto.SaveChanges();

            this.OnActionExecuting(filterContext);
        }
    }
}

Passo 3. Registre seu ActionFilter no Controller desejado
[CustomActionFilter]
public class MeuController : Controller
{
    ...
}

Ou então decore as Actions individualmente
[CustomActionFilter]
public ActionResult Index()
{
  ...
}

[CustomActionFilter]
public ActionResult Search(string term)
{
  ...
}

Comment: É uma boa ideia gravar em BD?
Comment: `foreach (var campo in filterContext.HttpContext.Request.Form.ToList()) { ... }`
Comment: E teria como eu pegar os parametros passados por post?
Comment: Você pode gravar onde quiser. O exemplo é para log em banco, que é mais fácil. Para pegar os parâmetros por `POST`, use `filterContext.HttpContext.Request.Form`.
Comment: Teria algum exemplo de como utilizar o filterContext.HttpContext.Request.Form?


Needing to have a form in every instance of a content type that can be submitted once per node - Drupal 7

Question: So here's the situation and I cannot figure out how to accomplish it.
I have a content type called "Alert". Each instance of this content type needs to have a webform (really just a submit button with hidden fields), that users click to acknowledge they have read and understand the alert. Ideally once submitted, the form should be replaced with a message along the lines of "You have marked this alert as read."
I do have a webform created (displaying as a block to be able to place within the variant page set up for the Alert type) and can get it to appear on each instance, but users can submit multiple times on each alert (submissions are set to unlimited as if i set it to 1 submission per user, the form does not render after the first submission on any alert). Additionally, once they click on one instance of the form, every additional instance will result in a message stating they have already submitted the form.
So I really have two issues. First, and most importanlty, allow a single submission per node (without the "already submitted" notice). Second, not required but would be nice, once it has been submitted for a specific node, the form no longer renders on that node for that particular user. Anyone have any ideas on the best way to accomplish these two aspects?
I'm running on Drupal 7.56, using the AT_Panels_Everywhere theme, Webform module Version: 7.x-4.15.
Comment: Are the users anonymous or logged in users??
Comment: Yep. If you have logged users add some field to user profile to mark is user clicked already or not. If no, use the cookie to store that info.
Comment: @Sanjok they would be logged in (authenticated role).
Comment: @MilanG The issue with that is that the webform would be submitted multiple times, but would need to be limited to once per node per user. Unless I am misunderstanding your suggestion.
Comment: Just a though , create a new table and name it whatever you want and have at least three fields in it like , nid, uid, visited(bool). Once the user clicks the button you can save the nid value, uid value and set True or 1 as a visited value. Next time you load the webform node you can do a query and check whether that uid has visited that node before and disable or hide the form if the visited value is true.
Comment: Yes, so when user submits the form for the first time just set it a cookie with form id or something. And when ever form should be displayed check for that cookie. If cookie with form id exists just don't display the form, but text "already submitted" instead.
Answer: In drupal 7, with webform 7.x-4.0, you can enable webforms within a content type.  To do so:
Go to Structure > Content Types
[Respective content type] > Edit
In the bottom left section, find the Webforms Tab and choose Enable webforms for this content type.
Based on your use case, I'd recommend enabling that and installing the node clone module. Then you can make one alert node, setup the webform, limited to one submission per user and allow content managers to clone content.  That node can serve as a template.


Finding the number of Jordan Form Matrices

Question: I'm asked to find the number of Jordan form matrices $A$ with $A^n = O$ for $n \in \mathbb{Z}^+$ such that $\dim (\text{Null} A^2) = 7, \dim(\text{Null} A^5) = 14$ and
$\dim (\text{Null} A^5 \cap \text{Range} A^5) = 1$ with all the ways the Jordan blocks can be ordered.
I been at this question for majority of the day now. It can be noted that $A^n = O$ means the only eigenvalues of $A$ is 0, so I think I only need to somehow determine how many blocks there are of each size, but I'm struggling with it. So far, I was able to count 36 of such matrices. Any help would be appreciated!
Comment: You're missing some information. What is the size of $A$? What exactly do we mean by the "number of Jordan form matrices" in this context? In particular, the matrices
$$
\pmatrix{0&1\\&0\\&&0}, \quad \pmatrix{0\\&0&1\\&&0}
$$
are effectively the same Jordan form since they are similar, but should these count as two distinct Jordan forms in this context?
Comment: In other words, when you say "with all the ways the Jordan blocks can be ordered", I don't understand if you mean that these two matrices are considered distinct or that they are considered the same.
Answer: Suppose that $A$ has size $m \times m$ and $m_j$ Jordan blocks of size $j$ for $j = 1,2,3,\dots$. The fact that $\dim [\operatorname{null}(A^5) \cap \operatorname{range}(A^5)] = 1$ tells us that $A$ has exactly one Jordan block with size greater than $5$. In general,
$$
\dim [\operatorname{null}(A^5) \cap \operatorname{range}(A^5)] \geq
\dim [\operatorname{null}(A) \cap \operatorname{range}(A^5)]
\\ = m_6 + m_7 + \cdots = m - (m_1 + \cdots + m_5),
$$
but the fact that $A$ is nilpotent implies that $\dim \operatorname{range}(A^5) > 0 \implies \dim [\operatorname{null}(A) \cap \operatorname{range}(A^5)] > 0$.
On the other hand, we have
$$
m = m_1 + 2m_2 + 3m_3 + \cdots\\
\dim \operatorname{null}(A^2) = m_1 + 2m_2 + 2m_3 + \cdots
\\ = m - m_3 - 2m_4 - 3m_5 - \cdots,
\\ \dim \operatorname{null}(A^5) = m_1 + 2m_2 + 3m_3 + 4m_4 + 5m_5 + 5m_6 + \cdots
\\ = m - m_6 - 2m_7 - \cdots.\\
$$
This is all the information that we have about $A$.
Comment: Hmm interesting. Thank you for this. I am now more convinced of my answer 36. I'll upload my solution once I'm officially complete it. Thanks for the help.
Comment: @sharkeater123 I would be interested in seeing even one matrix that satisfies the criteria given in the problem.
Comment: yeah, I make a program to search for it based on the criteria to see if I can find any and it was able to give me back 36. I'm coming up with something for it tho, hopefully I can do it by end of today.
Comment: I just posted by answer, feel free to check it out. It probably can be shortened a bit by omitting some details.
Comment: @sharkeater finally figured out my mistake; obviously $m$ is not the sum of all $m_j$.
Answer: Since $A^n = O$ for some $n\in \mathbb{Z}^+$, then for any eigenvector $v$,
$$ 0 = A^nv = A^{n - 1} \lambda v = \dots = \lambda^n v = 0.$$
Hence, $\lambda = 0$ is the only suitable eigenvalue of $A$. This means,
\begin{align*}
    A = \begin{pmatrix}
     J_0^{m_1} & & \\
     & \ddots & \\
     & & J_0^{m_l}
    \end{pmatrix}
   \end{align*}
Now, for any single Jordan block $J = J_0^m$. $J^k = 0$ for $k = m$ since $J$ has
$1$ above the diagonal. For $0 \le k \le m$, we have the $1$'s shifted towards the upper
right corner. So then for $0 \le k \le m$, $\text{Null}(J^k) = \{e_1, \dots, e_k\}$ and Range$(J^k) = \{e_1, \dots, e_{m-k}\}$.
So we have nullity$(J^k) = k$ and rank$(J^k) = m - k$ and $\dim(\text{Null}(J_k) \cap \text{Range}(J^k)) = \min(k, m - k)$.
Noting that for $k > m$, $\dim(\text{Null}(J_k) \cap \text{Range}(J^k)) = 0$. Let $a_j$ be the
number of Jordan blocks of size $m = j$ and $b_j$ be the number of Jordan blocks size $m \ge j$. Then,
$$\text{nullity}(A^k) = a_1 + 2a_2 + 3a_3 + \dots + (k-1)a_{k-1} + kb_k = b_1 + \dots + b_k.$$
From the premise, we know $\text{nullity}(A^2) = 7$ and $\text{nullity}(A^5) = 14$, and so,
$b_1 + b_2 = 7$ and $b_1 + \dots + b_5 = 14\iff b_3 + b_4 + b_5 = 7$. Let $B = \text{Null}(A^5) \cap \text{Range}(A^5)$
and $B_i = \text{Null}(J_0^{m_i})^5 \cap \text{Range}(J_0^{m_i})^5$. Since $\dim(B) = 1$, exactly
one of the Jordan blocks $J'$ must have $\dim(B_i) = 1$ and the rest must have $\dim(B_i) = 0$ and
so for those Jordan blocks with dimension 0, $m_i \le 5$ so $\text{rank}(J_0^{m_i})^5 = 0$. For the
jordan block with dimension 1, we must have $m = 6$ and thus $\text{rank}(A^5) = \sum^l_{i = 1}\text{rank}(J_0^{m_i})^5 = 1$.
By the rank nullity theorem, the size of $A$ is therefore $\text{rank}(A^5) + \text{nullity}(A^5) = 1 + 14 = 15$.
Since exactly one Jordan block has $m = 6$ and $m \le 5$ for all others, we must have $a^6 = 1$ and $a_j = 0$
for all $j > 6$.
Given the above and $b_1 + b_2 = 7 = b_3 + b_4 + b_5$, and that $b_1 \ge b_2$, we have three options,
$(b_1, b_2) \in \{(6,1), (5, 2), (4, 3)\}$.
We can see the only viable choice is $(b_1, b_2) = (4, 3)$ as all other choices results in a invalid partition
of 15. Consider $(6, 1)$, by definition of $a_j$, $b_j$, we have $a_1 = b_1 - b_2$ and so it requires,
$a_1 = 5, a_6 = 1$ and all other $a_j$ to be $0$ and corresponds to the partition $(1, 1, 1, 1, 1, 6)$.
Similarly, for $(b_1, b_2) = (5, 2)$ results in another invalid partition $(1, 1, 1, 6, 6)$ because
it would make $a_6 = 2\not = 1$.
Now, given $b_1 = 4$ and $b_2 = 3$. We have $a_1 = a_6 = 1$, so there remain two blocks we can
use to partition 15. Hence, the size of these two blocks sums to $15 - 6 - 1 = 8$ and the size
of these two blocks satisfies the condition $b_3 + b_4 + b_5 = 7$. It can be seen that the following
block sizes, $(1, 3, 5, 6)$ and $(1, 4, 4, 6)$ satisfy these requirements. With the first block size
combo having $4!/2$ permutations and $4!$ permutations for the second choice for a total of 36 matrices.


Asymmetry of definition of regular value and critical value

Question: Let $f: U \subseteq \mathbb R^n \to \mathbb R^m$ be a smooth map. We say $y \in \mathbb R^m$ is a regular value of $f$ if and only if all points in the set $f^{-1}(y)$ are regular. (see e.g. the definition 4.12 given here).
A critical value on the other hand, is defined to be any $y=f(x)$ such that $x$ is a critical point.

Why is a critical point not defined to be any point $y$ such that all
  points in $f^{-1}(y)$ are critical?
Answer: It's very simple. You want to get all points, not some. Regular values are well-behaved and then there's everything else. By the way, it would be a rare occasion indeed for every point with the same value to be a critical point. (Just draw graphs of functions $\Bbb R\to\Bbb R$.)


Como resolver a exceção CSharp_EIDMW_ERR_PINREF_NOT_FOUND_get

Question: Eu tenho um projeto em C# que utiliza a biblioteca do Gov para aceder a dados de um smartcard (cartão de cidadão), a Biblioteca chama-se pteidlib_dotnet, que podem encontrar aqui
Eu necessito de criar uma funcionalidade que me permite assinar digitalmente documentos pdf com o Cartao de cidadao, e penso ter o codigo correto (como está no manual que vem com as bibliotecas, que podem encontrar aqui em pdf), o problema agora, é que quando tento assinar a biblioteca lança uma exceção qual eu  não consigo encontrar a solução na internet para resolver.
Já pesquisei bastante e penso que o problema esteja relacionado com o metodo init
 da biblioteca que não reconhece o nome do meu smartcard reader, mas ainda assim não consigo resolver (função init penso que é chamada internamente, pelo que no meu codigo não a chamo.)
Queria vir aqui então pedir ajuda caso alguem saiba porque da exceção.
Inner Exception - em pt.portugal.eid.pteidlib_dotNetPINVOKE.SWIGExceptionHelper..ctor() em pt.portugal.eid.pteidlib_dotNetPINVOKE..cctor()
Message - O inicializador de tipo para 'pt.portugal.eid.pteidlib_dotNetPINVOKE' accionou uma excepção.
StackTrace - em pt.portugal.eid.pteidlib_dotNetPINVOKE.PTEID_ReaderSet_instance() em pt.portugal.eid.PTEID_ReaderSet.instance()
Codigo:
<code>private static void AssinarFicheiros(string[] ficheiros)
{
    ficheiros[0] = @"c:\teste\fich1.pdf";
    //ficheiros[1] = @"c:\teste\fich2.pdf";
    if (ficheiros is null)
        return;

    string destino = Directory.GetCurrentDirectory() + @"\ficheiros_assinados.zip";

    string localizacao = "local";
    string razao = "razao";
    int pagina = 1;
    int sector = 2;
    bool isLandscape = false; // TODO: Pode não estar correcto para todos os casos, visto que não conseguimos indentificar se os documentos estão na horizontal.

    try
    {
        using (PTEID_ReaderSet readerSet = PTEID_ReaderSet.instance())
        {
            for (int i = 0; i < readerSet.readerCount(); i++)
            {
                using (PTEID_ReaderContext context = readerSet.getReaderByNum(unchecked((uint)i)))
                {
                    if (context.isCardPresent())
                    {
                        using (PTEID_EIDCard card = context.getEIDCard())
                        {
                            using (PTEID_PDFSignature signature = new PTEID_PDFSignature())
                            {
                                if (ficheiros.Length == 1)
                                {
                                    signature.addToBatchSigning(@"c:\teste\fich1.pdf");
                                    signature.enableSmallSignatureFormat();
                                    signature.enableTimestamp();

                                    // Aqui lança a exceção CSharp_EIDMW_ERR_PINREF_NOT_FOUND_get quando tenta executar esta linha de código.
                                    card.SignPDF(signature, pagina, sector, isLandscape, localizacao, razao, destino);
                                }
                                else
                                {
                                    //card.SignPDF(destino, ficheiros, unchecked((uint)ficheiros.Length));
                                }
                            }
                        }
                    }
                }
            }
        }
    }
    catch (Exception exc)
    {
        MessageBox.Show(exc.ToString());
    }
}
</code>
Se alguem me puder guiar na direção onde possa encontrar a solução já ajudaria bastante.
Agradeço desde já qualquer resposta.
Comment: Adicione também os detalhes da exceção, como message, stacktrace e inner exception.
Comment: Não é relacionado ao seu `destino`? O arquivo existe e ele vai, de fato, conseguir incluir o documento assinado dentro de um `.zip`?
Comment: A postagem já foi atualizada, obrigado!
Comment: Funcionou! Muito obrigado, vi que o manual "Middleware, continha um erro! O destino deve ser uma pasta e não um arquivo!
Answer: Neste caso, o erro encontra-se na documentação, e a solução encontrada, foi apenas a remoção da extensão do ficheiro destino, pois o destino precisa ser uma pasta!!!


indicator variable - dirac delta or step function

Question: I am trying to solve the following equation,
\begin{equation}
= \int_{-\infty}^{\infty}   \frac{1}{\sqrt{ (2\pi)^{k_{Y}} | \Sigma |}} \cdot \mathrm{exp}   \{ -\frac{1}{2}  (Y - Xm)^{T} \Sigma^{-1} (Y - Xm)  \}  \times \delta(m - \beta) \mathrm{d} m
\end{equation}
where $\delta$ is an indicator variable; and $m$ is multidimensional variable. Assume, m is in size $1 \times n$;
I am not sure, if I should deal with $y = \delta(x)$ as a Dirac delta function $y=1$ if and only if $m = \beta$ and $y=0$ for the rest; or as a step function $y = 1$ for $m-\beta > 0$ is one and elsewhere 0;
From what I read about indicator variable in wikipedia, it is a step function, meaning for ; however,
1) It is not intuitive for me to understand the role of indicator variable
2) Reaching the the integral would be more difficult than assuming a Dirac delta function (I might be wrong).
I tried to crack the integral by assuming the indicator variable as Dircal Delta function; I am not sure I have been successful !
\begin{equation}
= \int_{-\infty}^{\infty} \int_{-\infty}^{\infty} \cdots \int_{-\infty}^{\infty}  \frac{1}{\sqrt{ (2\pi)^{k_{Y}} | \Sigma |}} \cdot \mathrm{exp}   \{ -\frac{1}{2}  (Y - Xm_i)^{T} \Sigma^{-1} (Y - Xm_i)  \}  \times \delta(m_i - \beta) \mathrm{d} m_i |_{i=\{1\cdots n\}}
\end{equation}
\begin{equation}
\frac{1}{\sqrt{ (2\pi)^{k_{Y}} | \Sigma |}} \cdot \mathrm{exp}   \{ -\frac{1}{2}  (Y - X\beta)^{T} \Sigma^{-1} (Y - X\beta)  \})
\end{equation}
I am not sure if it is the correct ! I appreciate if you help me to understand how to work with indicator variables in such cases;
Comment: Indeed:  merely set $m_i = \beta$ and remove the integral signs, as you have.  Just put in your equal sign so your result is typographically correct.
Comment: The answer you referred to was for a slightly different problem:  censoring on a finite support.  You have a function on infinite support (which happens to be a multivariate Gaussian) times a Dirac delta.
Comment: Thank you - but I saw http://stats.stackexchange.com/questions/129169/dirac-delta-function-in-likelihood-function - that the indicator variable bounded the integral (treated as a step function).
Comment: What @DavidG.Stork points out in his first comment is the very *definition* of $\delta$.
Answer: In general, the indicator variable $\theta$ of a set $A$, that is, $\theta (A): A \subset \Omega$ is $=1$ on $A$ and $0$ on the complement of $A$.
A distribution satisfies certain properties, such as positivity $\delta(x) > 0, \forall x$, and normalization $\int_\Omega \delta(x) dx = 1$ and the Dirac delta in particular $\delta(x-x_0)$ is "localized" at $x_0$, while retaining the unit integral.
The Heaviside step function is the indicator function of the positive real axis $\mathbb{R}_+$, which is infinitely extended, so how could its integral be normalizable?
Clearly, the Dirac delta and the Heaviside cannot be used interchangeably (however, the Dirac delta can be seen as the generalized (distribution-valued) derivative of the Heaviside function with step at $x_0$).
We use this fact when "measuring" a function $f$ over a set $\Omega$, with a distribution (i.e. measure) $\delta$: $\int_\Omega{f(x) \delta(x-x_0)}$. In the vanishing width limit (a number of distribution converge to the Dirac) the previous integral becomes $= f(x_0)$, the "sampling" property of the Dirac measure.
In your example above it amounts to evaluating the multivariate Gaussian at $\beta$, as you correctly did. What this means w.r.t. your problem I have no idea though :D


Additive commutators and the center of a division ring

Question: Can someone please explain me the following proof?
Proposition: If $D$ is a division ring, then the division ring $R$ generated by $Z(D)$ and all additive commutators (elements of the form $xy-yx$) is the whole of $D$.
Proof: Let $x$ be a member of $Z(D)$. Then there exists $y$ in $D$, such that $xy\neq yx$, therefore $x(xy - yx)$ is in $R^*$, and $xy - yx$ is in $R^*$, thus $x$ is in $R^*$.
Thanks!
G.
Comment: Maybe you want to say $x\notin Z(D)$.
Comment: even if x is not in Z(D), I still don't understand the proof
Comment: what is [x,xy]?
anyway, the way I look at it, we need to take an element of R, and show it is an element of D. I don't see where is it done here.
Comment: yep, the converse. just confused, sorry. so any idea?
Answer: Let $x\in D$. If $x\in Z(D)$, then $x\in R$. If $x\notin Z(D)$ then there is $y\in D$ such that $xy\neq yx$. But $xy-yx\in R^*$ and $x(xy-yx)=x(xy)-(xy)x\in R^*$, so $x\in R$.
Comment: how do we know that xy-yx is invertible in R?
Comment: you are correct, I said that R is a division ring. Thanks you for your help. my problem is a bit different, the following: show that as a Z(D) algebra, D is generated by the commutators


Class variable based on a class - unclear

Question: I have the following method within a class that I do not understand its purpose:
private PageInfo getPage(){}  (note that PageInfo is capitalized).
PageInfo is a class which makes this different as getters are typically used within methods in a class.
I can create a Class variable as: private PageInfo page;
I can then create a getter for it as: public PageInfo getWebpage() {return webpage;}
However, this is unclear what is its purpose and why.
I would greatly appreciate a response and thanks in advance!
private PageInfo getWebPage(URL url, URL parentUrl) throws IOException
{
    HttpURLConnection connection = (HttpURLConnection)url.openConnection();
    int responseCode = connection.getResponseCode();
    String contentType = connection.getContentType();
    // Note: contentLength == -1 if NOT KNOWN (i.e. not returned from server)
    int contentLength = connection.getContentLength();
    PageInfo p = new PageInfo(url,parentUrl,contentType,contentLength,responseCode);
    InputStreamReader rdr =
        new InputStreamReader(connection.getInputStream());
    p.extract(rdr);
    rdr.close();
    connection.disconnect();
    return(p);
}

RESOLVED:
The above method has been written within a different class, and preceding the methods' name is the name of its class.  the method's name doesn't comply to the naming convention (doesn't need to). Its method access modifier is void by default as no modifier has been declared, and as such it supposedly doesn't return anything however there is an acception to the rule. Accordingly it can return the initialization of its Class PageInfo. Otherwise, it can be set as return null (return: null;).
private MyClass getInfo() {
    int e = 300;
    int t = 10;
    MyClass z = new MyClass(22);

    return  z; // z is the initialization of MyClass
               // return null; is also valid

}
Comment: The purpose of the function shown is to: 1) retrieve content from the given URL; 2) get the `responseCode`, `contentType` and `contentLength` for the sole purpose of constructing a `PageInfo` object in step 3) instantiate `PageInfo` 4) Read the stream from the connection 5) Use `PageInfo` extract method against stream 6) return the PageInfo object. Seems straight forward, what _precisely_ don't you understand?
Answer: It sounds like you're expecting this method to be an accessor based on its naming convention.
Instead it looks like it's a private helper method for generating a PageInfo object from the provided urls(in fact it makes a call to a constructor that requires additional paramerers, which it derives from the provided parameters). Without seeing the larger context I can't tell you exactly what the purpose is, but it's certainly not doing the same thing you described with your private class variable and public accessor example.
Hopefully this helps - if not, I'd recommend clarifying your question, or providing additional code.
Edit: you flagged this with intellij-idea - if that's the IDE you're using, try highlighting the method name and pressing alt-f7 to find usages. This should provide you with some insights about where this method is being called and why.
Comment: Yes, thank you for clarifying the method accessor aspect.  The above method has been written within a different class.  The method access modifier is void by default as no modifier  has been declared.  Accordingly, as it is void, it shouldn't return anything. however to my astonishment it does return the initialization of Class PageInfo.  Otherwise, it can only return null (return: null;).


How do I update core to 8.4?

Question: I checked the other questions related to this topic, but half of them didn't get any useful answer and the other half didn't help me out.
I face with several issues building up a site using Drupal 8:

The view exposed date filter doesn't work properly in 8.3.x
The administrative theme doesn't work for roles other than administrator users

I wanted to upgrade a site from 8.3 to 8.4 as most of the patches are provided for 8.4, and I hoped that I would get less troubles.
Drupal 8.4 is just available as development snapshot, at this moment, and Drush didn't let me update the site to this version.
On top of all, the installed Drush version (v8.1.9) is not compatible with Drupal 8.4.
How do I update Drupal to 8.4 using the version of Drush I installed?
Answer:
Make a database backup.
Make a Drupal code source backup.
I had to know which drush I use:
$ drush version
Drush Version   :  8.1.9

which isn't good for me.
I had to find out whether it is a local or a global installation
$ locate drush
/usr/local/bin/drush
$ dpkg -l | grep drush
rc  drush    5.10.0-2ubuntu1

it looks like the ubuntu package was removed before
and it wasn't installed by pear:
$ pear list

Installed packages, channel pear.php.net:
=========================================
Package          Version State
Archive_Tar      1.4.0   stable
Console_Getopt   1.4.1   stable
HTTP_Request2    2.2.1   stable
Net_URL2         2.2.0   stable
PEAR             1.10.1  stable
PEAR_Manpages    1.10.0  stable
PHP_CodeSniffer  2.5.1   stable
Structures_Graph 1.1.1   stable
XML_Util         1.3.0   stable

So, it can be only a global phar installation.

I chose the WRONG WAY of the installation in the beginning which resulted a lot of more issues (I don't list them here) and finally a drush installation which I wasn't able to update my drupal
Just for the record here is the wrong way: I decided I install drush by composer and if the global version confuses its functionality I will remove the old one from the file system manually
I ran this command from the root directory of my drupal project
$ composer require drush/drush
This installed a lot of other packages and updated my drush from 8.1.9 to 8.1.12. Everything looked good at this point.
$ drush version

Drush Version   :  8.1.12

$ drush up drupal
resulted

Unable to load class \Drush\VersionControl\Backup.

I removed the drush 8.1.12 and installed the drush 9.x version.
I wasn't able to update my drupal site, so I removed the local drush package and its dependencies.

the WORKING WAY
remove the composer version if that exists and install drush globally by phar

# Download latest stable release using the code below or browse to github.com/drush-ops/drush/releases.
wget https://github.com/drush-ops/drush/releases/download/8.1.16/drush.phar

# Test your install.
php drush.phar core-status

# Rename to `drush` instead of `php drush.phar`. Destination can be anywhere on $PATH.
chmod +x drush.phar
sudo mv drush.phar /usr/local/bin/drush

I updated my drupal from 8.3.4 to 8.3.5
$ drush up drupal
I got the package name of the drupal 8.4 by this command
$ drush dl drupal-8 --select

 [0]  :  Cancel
 [1]  :  8.4.x-dev  -  2017-Jul-22  -  Development
 [2]  :  8.3.5      -  2017-Jul-05  -  Supported, Recommended
 [3]  :  8.3.4      -  2017-Jun-21  -  Security

I chosed 0

I updated my drupal from 8.3.5 to 8.4
$ drush pm-update drupal-8.4.x-dev

Update information last refreshed: Mon, 06/26/2017 - 18:31
 Name    Installed Version  Proposed version  Message
 Drupal  8.3.5              8.4.x-dev         Specified version available

Do you really want to continue? (y/n): y

At the end I got 3 errors, but the update was successful.
Unfortunately the drupal 8.4.x-dev version didn't fix any of my issues.
Comment: Your test is exactly what is expected from this issue https://www.drupal.org/node/2874827. Drush 8.1.12 site-local Drush + Drupal 8.4.x: **Does not work** - Drush 8.1.12 phar + Drupal 8.4.x: **Works** (Not officially supported, this configuration runs with two autoloaders: one from Drush, and one from Drupal. This is a fragile configuration that can be broken over time)
Answer: It's best to update dependencies using composer:
composer update drupal/core --with-dependencies

Have a look at https://www.drupal.org/docs/8/update/update-procedure-in-drupal-8
Note that you'll also need drush 9.x:
    composer require drush/drush:9.*
See https://github.com/drush-ops/drush/issues/2738.
Comment: Drush version 9 is not required for Drupal 8.4.x; only drush 8.1.15 or newer is required (see 'current status' at https://www.drupal.org/node/2874827 )
Comment: For those who are not familiar with drush commands we can go option 1 or option 2 specified in https://www.drupal.org/docs/8/update/updating-drupal-8-overview-of-options this page. Option2 helped me as i didn't installed drupal using composer/drush
Answer: A tutorial is related to the update of 8.3 to 8.4 'Update to Drupal core 8.4, a step by step guide'
Also, not a direct answer to the question, but a good place to mention that this Drupal Composer helper intends to facilitate the update process.

The motive behind writing this plugin was to make a Drupal composer based setup more maintainable. It is easy to start with the template provided by drupal-composer/drupal-project but upgrading it is difficult. The plugin solves that problem by keeping all the code outside your project and in the plugin which would make upgrading as easy as running composer update.
Answer: When I ran composer update drupal/core --with-dependencies, I got the following error:

Package "drupal/core" listed for update is not installed. Ignoring.

So I moved "drupal/core": "~8.3" from the replace to the require section of the composer.json file.
I think it isn't recommended, but it works.

How do I update core to 8.4?


Why do string players tend to breathe heavily in performance?

Question: Recently, I've started to develop an interest in classical music, specifically chamber music and, more specifically, piano trios. Having listened to a few performances now, I can't help but notice some heavy breathing going on with violin and/or cello players, which I, quite frankly, find utterly annoying. It kind of ruins the performance, for me.
Here is such an example, of the kind of breathing I'm talking about.
What is up with that? Is that really necessary? Forgive me my possible ignorance, but it sounds a bit like posturing to me.
Comment: I find it interesting that the breathing ruins that performance for you more than the shiny velvet suit!
Comment: If you find the breathing in this recording annoying, I am afraid you will find some audible breathing in certain solo cello performances (as well as singing along) unbearable, as there is only one instrument, recorded at close distance.
Comment: I'm not really sure where these close votes are coming from, so I've edited the title to make it a bit clearer.
Comment: A bit late to this party, but I would note that for someone coming into classical music for the first time, you're probably coming from pop (I hate to make assumptions, but hey) or some other more modern style. The thing about these is that the music is "very recorded," meaning, there's more of an emphasis on editing out artifacts like heavy breathing, whereas in styles like classical, they're treasured for the most part.
Comment: @NReilingh Yeah, that's actually cringe-worthy as well. Didn't really notice it yet, as I was listening to it, rather than watching it, while doing other some work on my computer.
Comment: Sharp breathing is a fad. Recently I found that violinist Jascha Heifetz does not breathe heavily in his recordings. I'm sure there are others out there if you look.
Comment: I listened and observed for a bit more than three minutes and did not hear or see any heavy breathing.  Can you give us some specific timestamps and identify either the violinist or the cellist or both?
Comment: To make this claim, you have to listen to so many samples from so many violinists to draw a conclusion. On the other hand, just from a personal perspective, none of the violinists I know breathe heavily during a performance or rehearsal.
Answer: There may be a small amount of "performance practice fad" about that, but for the most part it does serve a purpose.
Breath is used in many styles of music as a cue. If you think about wind instrument players, for example, every phrase is preceded by a breath, and experienced players will take that breath in rhythm. As a rhythmic gesture, it can be used to communicate time between an ensemble of players.
String instrument players don't need to breathe to play, but they still do it for reasons of cuing/communication. Chamber music is often heavily involved in this kind of dynamic cuing, where it's not so much a single conductor leading the ensemble, but the ensemble players showing each other how and when they're going to play a certain phrase, when that phrase occurs in tandem with another player.
Now, I mentioned how as well as when, and that's because the nature of the breath can also communicate the way something will be played. The particular breath you referenced sounded a bit like a nostrils-flared angsty-breath, which would not be out of place given the music that they are playing, though whether it was slightly overdone in that situation is a matter of opinion.
Lastly, the more meticulous of us out there will say that you never want to breathe audibly in a recording scenario, because it'll be picked up by the mics, and if you're a wind player after all you should be breathing through your mouth (in fact audible breathing can be used as a diagnosis for excess neck tension in wind instrumentalists). But, frankly, it's become a bit of an idiom in classical string performance, and audiences like to be wowed by how "emotional" a performance is even if they have no idea how to perceive emotion in classical music.
Personally, I don't find myself bothered by it, as it only tends to fill otherwise empty space instead of interrupting a musical gesture.
Answer: It can be used for communication, as already pointed out - and this certainly seems to be the most cited explanation when you query that of a musician who seems to be doing it excessively! Showing emotion is also a common reason given, that it somehow brings out more authenticity and heartfelt contrast in the piece.
However:

What is up with that? Is that really necessary? Forgive me my possible ignorance, but it sounds a bit like posturing to me.

Despite the above, this is a pretty common perception, and despite the fact people with this opinion seem to be often looked down on by professional string players as if they have no business critiquing their performance in such a way, there is definitely an element of truth to it (in some performances anyway.) When used moderately I have no problem with it at all, but even as a violin player I must admit some parts in some performances, including the above, do sound a little "overdone" in this respect. The same goes for physical movements; I'm no fan of completely rigid performances and indeed I'll do this myself to a certain extent mainly for benefits of communication - but some guys just take it to the extreme, and you're definitely not the only one that can find that off putting!
Having said that, it'd be unfair to say that everyone who seems to be doing this is doing it deliberately - apparently I have a tendency to overly excessively move my eyebrows when playing. No idea I was doing it until a friend mentioned it!
Answer: I have been a string player for many years (Double Bass), and the fact of the matter is that bowing an instrument is a very aerobic exercise, especially at a fast tempo; but, even doing long slow notes is a kin to sustaining a long hum vocally.
Answer: Performing classical music is difficult. Many performers are nervous and anxious and their breathing can become shallow fast and noisy. I doubt that any string player would breathe heavily for effect. As an ex- professional l know that any player can be struck by bouts of heavy breathing, especially in situations where their careers are on the line. Flight or fight response.
Answer: Although an amateur performer, I tend to take deep breaths regularly during concerts/performances, even when just playing little songs at church. These help me to re-focus on the task at hand, and think 'it's a new passage here,' etc.
Answer: The answer to this question depends of course from person to person.
Myself and many colleagues think of the bow to the violin as the diaphragm is to a singer. Like that we talk sometimes about "breathing" with the bow. Not forced rule like bow up = breath in but to phrase a melodywith the bow as if it was air inside the lungs that has to be enough to sing out the phrase with nice legato. If you understand this analogy I would say that the bow sings and the breathing is done by the musician.
Another reason is to give a cue, and there it's exactly the same body breathing/muscles like a pianist or conductor.
Comment: This! Breathing really helps keep track of melody and phrasing, it helps deliver emotion, and communication. Music is made by humans, after all. We can hear people breathe as they talk, sing. And Cello is said to be the closest to the human voice as well!
Answer: My personal opinion is that when you play a very moving piece like this one, you kind of forget to breathe normally! I know that when I get very into a guitar piece or something, I find that I have been holding my breath because of the beauty of the music. And sometimes it's kind of physically exerting.
Answer: Many years ago I used to play in the UK Midland Youth Orchestra and one Saturday they invited Simon Rattle to come and take part of the practice. I was awestruck - such charisma. The one piece of advice I remember him giving the strings was to breathe as they played. They looked at him like it was a mad suggestion but they sounded like a different section when they did as he said.
He didn't want audible breathing, but exhaling can suggest phrase shape and length.
Answer: You think that's bad?  Glenn Gould would SING everything - and yes he did it in public performance as well as in filmed documentaries!
An extreme example of a performer getting overcome by the emotion and physicality of performance.  And , yes, it can be off-putting for the audience!
Answer: Are the players supposed to hold their breath for 20 minutes?!?
If the idea is the breath at 1m49s is an affection, I don't find it annoying, and I've attended quite a few concerts.
I can say this much: that breath was not nearly as annoying as the people sitting nearby flipping the pages of their program, clearing their throats, and rushing to silence their ringing phones. After you gain some concert going experience you may find many other things far more annoying than the musical performers.
Answer: "How do you make your instrument a breathing part of your own body, rather than a piece of wood?" [Daniel] Heifetz said. "How does the big black piano become an extension of your arms instead of a big box that you're sitting at? Do you know how your body responds, when you're feeling an emotion? If you're about to play a big, dramatic note, what is the feeling? The magic is the breath before the first note. If you're a stiff vessel, no emotion is going to come out. It's certainly not going to go through the breathing instrument and it's certainly not going to go over the footlights and reach the last person in the balcony." https://www.violinist.com/blog/laurie/20164/19506/


Number Theory Maths

Question: How to find the least number whose last digit is 7 and which becomes 5 times larger   when the last digit is carried to the beginning of the number?
Comment: Welcome to MSE. Your question is phrased as an isolated problem, without any further information or context. This does not match [many users' quality standards](http://goo.gl/mLWc8), so it may attract downvotes, or be put on hold. To prevent that, please [edit] the question. [This](http://goo.gl/PlJyVQ) will help you recognise and resolve the issues. Concretely: please provide context, and include your work and thoughts on the problem. These changes can help in formulating more appropriate answers.
Comment: Please say more precisely what is meant by "last digit is carried..."
Answer: Solve for increasing $n = 1, 2, \dots$ until you find a solution with integer $x$:
$$5\cdot (10x + 7) = 7\cdot 10^n + x$$
Then check whether the solution actually works, since $n$ needs to be $1 + \lfloor\log_{10} x\rfloor$.
Comment: Thank you Sir for your help
Answer: Answer: $142857$.
Let our number be $x \cdot 10+7$ and have $k+1$ digits. Then $5(10x+7)=7\cdot 10^k+x$. Then $7x+5=10^k$. Since $10^k \equiv 5 (\mod{7})$ then $k=6n+5$, where $n \ge 0$. For least number we have $n=0$. Then $x=14285$.
Comment: Many thanks, Sir
Comment: You are welcome!
Comment: Why does $10^k \equiv 5 \pmod 7$ mean that $k =7n +5$?
Comment: If $n =1$ then $k=12$ we do not have $10^{12}\equiv 5 \pmod 7$.
Comment: By Fermat's little theorem, the remainders are repeated with a period 6. Mistake $k=6n+5$.
Answer: So the number is $N= 10A + 7$.  If we assume $N$ has $n+1$ digits and $A$ has $n$ digits, the putting the $7$ to the front is $7*10^n + A$.
So we want to solve $7*10^n + A  = 5(10A + 7)$.
So to solve for $A$ we have $49A =7*10^n - 35$ or
$7A = 10^n - 5$
We need to find the smallest value of $n$ where $10^n -5$ is divisible by $7$ or in other words where $10^n\equiv 5 \pmod 7$.
Or $3^n\equiv 5\pod 7$.  I'm not sure there is any option but brute force but $10, 7$ are relatively prime so we know there will be on value between $1$ and $6$.
$3^2 =9\equiv 2\pmod 7$.  $3^3 \equiv 3*2\equiv -1\pmod 7$.  $3^4 \equiv -3\equiv 4\pmod 7$.  And finally $3^5 \equiv (-3)*3\equiv -9\equiv -2\equiv 5 \pmod 7$.
So
$7A = 10^5 - 5 = 99995$ and $A = 14285$ and $N=142857$.
If I did this right we'd have $5*142857 = 714285$
Comment: Thank you so much, Sir.

Number Theory Maths


Dockerfile alternative for VM

Question: Dockerfile helps a lot in terms tracking the packages being installed and needed on the system, but I couldn't find any reliable alternative to manage a VM and spawn it back with the same state as before.
making an AMI helps in the aspect of spawning it back to the same state but it doesn't help much to review or check the modifications done to the VM.
so is there any alternative of Dockerfile for VM,

to track the packages being installed on a VM
any changes i.e file changes like config, etc,
network changes etc,..
spawn a similar VM on demand
Answer: Write install scripts that can take a base OS install to the desired state. Add logging as required. Commit these to a version control system.
Use your preferred flavor of configuration management or automation tool to help write the scripts. They are good at installing software and templates for configuration. Possibly they will help with logging and reporting on configuration differences.
Decide how you deploy and manage. You might be able to deploy a new VM every time, either from a template VM or your "bare metal" install scripts.  Otherwise, you will also need the ability to apply changes to already running hosts.
Answer: Packer from Hashicorp has a concept of packer files that have a similar purpose. https://www.packer.io/
There are a lot of examples of using these, for example, https://github.com/boxcutter

Dockerfile alternative for VM


Postgres 9.4 Add INDEX USING GIN

Question: I am using Postgres 9.4, JSONB fields, those are working good.
But when I add GIN index doctrine migration fails to created index.
class Version20160314132147_Gin_Indexes_content   extends AbstractMigration {

public function up(Schema $schema) {
    $this->addSql('CREATE INDEX contents_properties_ix ON contents USING gin (properties);');
}

/**
 * @param Schema $schema
 */
public function down(Schema $schema) {
    $this->addSql('DROP INDEX contents_properties_ix;');
}
}

Error:
[Doctrine\DBAL\Driver\PDOException]
  SQLSTATE[42704]: Undefined object: 7 ERROR:  data type json has no default operator class for access method "gin"
  HINT:  You must specify an operator class for the index or define a default operator class for the data type.
Composer.json
    {
        "slim/slim": "~2.6",
        "doctrine/orm": "~2.5",
        "doctrine/dbal": "2.5",
        "symfony/yaml": "2.8.@dev",
        "doctrine/cache": "~1.5@dev",
        "symfony/console": "2.8.@dev",
        "symfony/class-loader": "^2.7.4",
        "doctrine/migrations": "~1.0",
        "predis/predis": "~1.0.1",
        "guzzlehttp/guzzle": "~5.0",
        "twig/twig": "~1.0",
        "php-di/php-di": "^5.1.0",
        "monolog/monolog": "~1.15@dev",
        "boldtrn/jsonb-bundle": "~1.0",
        "opsway/doctrine-dbal-postgresql": "~0.1",
        "fzaninotto/faker": "~1.3.0",
        "aws/aws-sdk-php": "^3.9"
    }
Answer: Postgres seems to be whining about your column properties not being a text type and therefore not being able to index it using GIN.
You may have success casting the column to text:
CREATE INDEX contents_properties_ix ON contents USING gin (properties::text);

Postgres 9.4 Add INDEX USING GIN


Flex 4.5 TextArea height to match .text height?

Question: Is it possible to have the textarea height be dynamically adjusted to the .text in a spark TextArea?
Answer: Got this while googling for the same query
http://polygeek.com/2342_flex_setting-a-textareas-height-to-its-contentheight


Cannot access url for ActiveStorage::Attached::One instance when debugging

Question: I have this controller action:
def view_pdf
  redirect_to @report.pdf.url
end

When I access the route for view_pdf everything works as expected: it redirects to the pdf URL.
However, when I open a pry-byebug session with byebug I get this error when trying to access the URL:
@report.pdf.url
#=> *** NameError Exception: uninitialized constant ActiveStorage::Blob::Analyzable

Also printing the URL works fine. I'm just confused why I cannot access it from the byebug console.
Answer: Well, it was as easy as including ActiveStorage::Blob::Analyzable:
include ActiveStorage::Blob::Analyzable

That made the trick.
Comment: including it where?
Comment: Include it in your controller @StevenAguilar