Script ou comando para somar todos os diretórios e mostrar o tamanho total

Question: Estou desenvolvendo um script onde a partir de uma lista de texto onde terá o nome dos diretórios, o script pegar o nome de cada diretório, mostrar o tamanho de cada diretório e depois o total.
Exemplo:
Preciso somar o tamanho total de algumas contas no servidor, digamos que eu tenho os seguintes diretórios:
/home/conta1
/home/conta2
/home/conta3
/home/conta4
/home/conta5
/home/conta6

Por questão de um filtro, eu irie criar um arquivo de texto com o nome lista.txt e nele irei colocar o nome dos diretórios que eu desejo mostrar o tamanho individual depois a soma de todos:
cat lista.txt
conta2
conta4

Digamos que eu deseje o tamanho dos diretórios acima, eu tentei fazer um for, mas não deu certo:
for i in $(cat lista.txt); do du -hcs /home/$i;done

O resultado dele sai assim, mostrando cada conta e o total em baixo.
684K    /home/conta2
684K    total
732K    /home/conta4
732K    total
1,1M    /home/conta5
1,1M    total

Para que apareça da maneira que eu desejo, tem que rodar o comando assim:
du -shc /home/conta1 /home/conta2 /home/conta3

Existe alguma maneira de fazer o script pegar o nome de cada diretório, somar a quantidade de diretórios, jogar em uma variável cada nome e em seguida executar assim:
du -shc /home/$1 /home/$2 /home/$3

Answer: Faça assim:
for i in $(cat lista.txt); do pastas="$i $pastas";done; du -hcs $pastas

Explicação:
no loop, cria-se uma variável chamada pastas que é a concatenção (com espaço) dos diretórios contidos em lista.txt
Após terminar o loop, executa-se o comando du, passando como parametro a variável pastas.
Answer: du -hcs $(sed 's!^!/home/!' lista.txt)


For which values of p and q does an improper integral converge

Question: I am to find for which values of p and q the following integral converges:
$$\int_0^\infty \frac{x^p}{1+x^q}\,dx\quad (q>0)$$
As I tested the limit of the above function with $\frac{x^p}{x^q}$, and found it was $1$, I let myself separate the boundaries from $0$ to $1$, and from $1$ to infinity of the later function.
From $0$ to $1$ it's a normal integral, that leaves us to check what the divergence of the integral from $1$ to infinity, which by the comparison test happens as $q>$$1$+$p$
Thanks for the quick replay.
Comment: The integral $\int_0^1\frac{x^p}{1+x^q}\,dx$ is proper, and thus converges for all values of $p,q$.
Comment: That should be correct.
Comment: I failed to notice that. That leaves us with q>p+1?
Comment: Thanks. I should edit it.
Comment: I believe that if $p<0$ than that is not true.
Comment: Ugh.  I can't believe I missed that.  Yes, if $p\lt0$, then $\int_0^1\frac{x^p}{1+x^q}\,dx$ diverges
Answer: Hint : Use the fact that $\zeta(k)=\sum_{n=1}^\infty\frac1{n^k}$ diverges for $k\leqslant1\iff k=q-p>1$ .


can you major in choral works as an instrumentation or is it just voice?

Question: Sorry for, like, the dumb question, but do people actively try to join choral ensembles (and thus major in the choir as an instrumentation), or do they just go into voice for their majors?
Answer: When people study music they can pick a concentration: voice, a instrument, composition, and conducting are all quite common. A person can focus graduate studies in choral conducting, but it is not possible to concentrate on choirs as an instrument.
People who study voice are often required to sing in choirs, and this is where their choir experience comes from.


no changes in bg color

Question: have inspected element for this site and try as I might changing bg color in body for style.css makes no difference no matter how much caches are cleared.
I want to leave the tiled background and just change the inset white to another color. I didn't see background color in LAYOUT REGION sorry..this has been solved now.
Comment: it was just a css question not php or sql but i just should have studied the style sheet longer to find corresponding area.
Comment: both answers had no way of knowing which background I meant - my apologies for that.
Answer: The reason why the color is not showing is because you have this already:
body {
    background: url(images/body.png) fixed;
}

from my_elegant.css.
You have a background image already set. If you want to use a css color then you need to tweak the css for body to something like this:
body {
  background-color: #000;
}

or you can have an image background and a color at the same time:
body {
  background: #fff url(images/body.png) no-repeat center top;
}

If you are using style.css make sure that the file is properly added otherwise it could result to 404 and all the css in that file will not get applied. You can use drupal_add_css() api to add new css file or in the .info of your theme.
Comment: I want to leave the body.png and just change color of the white inset- how do I do that please?
Answer: It's not Drupal issue, it's a CSS issue; looks like your site doesn't load style.css but it using my_elegant.css file"http://krom.club/sites/all/themes/my_elegant/my_elegant.css?nssjk2". Also you need to remove the background image and apply your desired background color
body {
background-image: none;
background-color: #FFF; /* yout color */
}

Comment: I don't mean the tiled background I mean the inset white I'm trying to change..

no changes in bg color


How to generate an [error] instead of an [info] upon seeing a wrong value in expect()

Question: Consider the following code:
import chisel3._
import chisel3.util._
import chisel3.iotesters._

class Inverter extends Module {
  val io = IO(new Bundle {
    val a = Input(UInt(4.W))
    val s = Output(UInt(4.W))
  })
  io.s := ~io.a
}

class InverterTester(c: Inverter) extends PeekPokeTester(c) {
  poke(c.io.a, 8)
  step(1)
  expect(c.io.s, 8) // Should be 7 here
}

object TestMain extends App {
  chisel3.iotesters.Driver.execute(args, () => new Inverter()) {
    c => new InverterTester(c)
  }
}

Now I run sbt 'test:runMain TestMain' and got this line (info is in purple):
[info] [0.002] EXPECT AT 1   io_s got 7 expected 8 FAIL

And the exit value of sbt is zero.
I need that line to be an error (with red color):
[error] [0.002] EXPECT AT 1   io_s got 7 expected 8 FAIL

As well as making the above sbt command exit with a non-zero value.
How can I achieve it with minimal change to existing code?
Answer: First the easy part. You can get a non-zero result code by using the result of chisel.execute like this.
  val result = chisel3.iotesters.Driver.execute(args, () => new Inverter()) {
    c => new InverterTester(c)
  }
  System.exit(if(result) 0 else 1)

Changing the logging level, unfortunately requires changing each of the separate backends in the chisel-testers repo. The following is an example of changing the TreadleBackend.scala, one of the three.
  def expect(signal: InstanceId, expected: BigInt, msg: => String)
    (implicit logger: TestErrorLog, verbose: Boolean, base: Int) : Boolean = {
    signal match {
      case port: Element =>
        val name = portNames(port)
        val got = treadleTester.peek(name)
        val good = got == expected

        if (!good) {
          logger error
                  s"""EXPECT AT $stepNumber $msg  $name got ${bigIntToStr(got, base)} expected ${bigIntToStr(expected, base)}""" +
                          s""" ${if (good) "PASS" else "FAIL"}"""
        }
        else if (verbose) {
          logger info
                  s"""EXPECT AT $stepNumber $msg  $name got ${bigIntToStr(got, base)} expected ${bigIntToStr(expected, base)}""" +
                          s""" ${if (good) "PASS" else "FAIL"}"""
        }
        if(good) treadleTester.expectationsMet += 1
        good
      case _ => false
    }
  }

This would not be an unreasonable issue to file, I think a logger.error would make more sense on an expect failure.  There is some concern that changing this could have unexpected consequences for existing users, who are looking for that string.
But I'd like to encourage you to take a look at freechipsproject/chisel-testers2 repo. It's where the team is putting most of their testing development time. It would be easier to change, it has a lot of other nice features for building unit tests, and we are looking at ways we can make it better than chisel-testers.


How to implement field formatters for entity properties

Question: I created a custom entity using Entity API that has certain properties defined in hook_schema() and also declared in entityPropertyInfo(), a class extending EntityDefaultMetadataController.
So far so good.
Now I'd like for users to be able to customize if and how these properties get displayed when viewing the entities so I implemented hook_field_extra_fields() and declared them.
Then, in my Controller which extends EntityAPIController I added the properties to the $content array in buildContent() as, outlined here.
It actually works pretty well and properties are rendered and respect the order and visibility settings in "Manage Display".
However, I can't seem to figure out how to add settings in Manage Display to customize the label positioning (inline/above/hidden) and, more importantly, how to specify custom formatters for these properties.
Any clues?
Comment: Do properties even support formatters? Since "Node" doesn't have "Title" under "Manage display", my first guess would be no. +1 for a good question though.
Comment: Entity properties don't support formatters, no. You would need to implement that whole mechanism yourself
Comment: I was fearing that was the case
Answer: You could create a module providing a "property" field type. Store the the property to be formatted as an instance setting and then apply a formatter to that. It should be relatively straightforward. Relation module has a dummy field module which might help you in figuring out how to code this.
Comment: The [Entity Property Field](https://www.drupal.org/project/entity_property_field) module is another starting point for this approach.
Answer: as you can see in field_ui_display_overview_form in modules/field_ui/field_ui.admin.inc the page Display setting will fill with $instances and $extra_fields:
$instances = field_info_instances($entity_type, $bundle);
$field_types = field_info_field_types();
$extra_fields = field_info_extra_fields($entity_type, $bundle, 'display');

in this function there is two loops which create the page:
foreach ($instances as $name => $instance) {
   ...
}

and
foreach ($extra_fields as $name => $extra_field) {
   ...
}

and only in first loop which iterate in fields there is options for label and formatter
so if you want this functionality on your properties (as @Clive said):

You would need to implement that whole mechanism yourself


Contextual filter in views

Question: I have a form on my site. Each time a user submits the form they are directed to a confirmation page like this;

eform/help-request/confirm?entityform_id=1

I want to create a view that has a contextual filter that picks the last form submitted by the user and displays the fields from that form only.
I have a view that shows the field content from the form as it was submitted by the user but i cannot get the view to only display the latest form submission from the user...
As i have it my view is displaying all the forms the user has ever submitted ... which i don't want.
Any help appreciated. I know I am close (ish)
Answer: Sort the view by created desc.
Then limit the view to only show 1 row.
The remaining item will be the last form submitted.
Comment: I tried this initially and had some trouble - I believe because of my pager settings.

Use pager: Display a specified number of items | 1 item

Worked...Thanks for the pointer!
Comment: Glad you got it sorted.

Contextual filter in views


Jquery função click em links dinâmicos PHP

Question: Estou tentando criar um script para quando a pessoa clicar em Curtir ela vai curtir o post, e quando clicar em Descurtir, vai descurtir o post, óbvio, consegui fazer isso com sucesso, porém tive que fazer isso colocando o script jquery no PHP, fazendo com que a cada resultado, um novo script fosse criado, isso ficaria muito grande. Queria deixar somente 1 código, como eu faço pra pegar os IDS ali no caso dos resultados dinâmicos?
Vou explicar resumidamente, por que ficou meio confuso, quero ao em vez de ter que colocar esse javascript no select dinâmico, colocar apenas 1 código pra todos.
JQUERY
    $(document).ready(function(){
    // like and unlike click
    $("#like<?php echo $row['idd']; ?>, #unlike<?php echo $row['idd']; ?>").click(function(){

         var iconCarregando = $(' arregando. Por favor aguarde...');

                $('#statuslike<?php echo $row['idd']; ?>').html(iconCarregando);

            $.ajax({
        type: "GET",
        url: 'acoes.php?like=1&id=<?php echo $row['idd']; ?>',
        success: function(data){
      $(iconCarregando).remove();
    } });
    });
});

HTML
(o código está pela metade, por que não consigo botar o código completo)
a href="javascript:void(0);" id="like'.$msg_id.'" title="Like" rel="Like"> Aplaudir

Comment: Precisamos ter noção do que você já fez e como está fazendo, para poder ajudar.
Comment: Mas eu já botei ali o.O
Comment: O jeito que eu fiz, e como eu queria que fosse, eu não sei fazer...
Answer: Você não precisa chamar o evento do clique pelo ID do botão. Você pode dar uma classe comum a todos (ex. curtir) e capturar todos os cliques ali. Depois de capturado você usa $(this) pra identificar qual botão foi clicado. Se não tiver a informação do ID em outro atributo, basta quebrar o ID pela parte conhecida. Ex.:
$(document).ready(function(){
    // like and unlike click
    $(".curtir").click(function(){ // captura todos os cliques de curtir

         var iconCarregando = $(' arregando. Por favor aguarde...');

        var ID = $(this).attr('id').split('like')[1]; // pega o ID e retira a parte "like"

                $('#statuslike'+ID).html(iconCarregando);

            $.ajax({
        type: "GET",
        url: 'acoes.php?like=1&id='+ID,
        success: function(data){
      $(iconCarregando).remove();
    } });
    });
});

Comment: eu fiz como você falou e coloquei isso no html  Curtir mas não acontece nada ao clicar
Comment: usa só `class="curtir"` não precisa do msg_id ali
Comment: Amigo não da mesmo assim :\ já tentei ver o console e não aparece nenhum erro, o que pode ser?
Comment: será que é pq ele não ta conseguindo pegar o id? é oq eu acho pq como ele sabe qual é o id??
Comment: tinha um errinho ali, você precisa do índice [1], nao [0]. Alterei.
Comment: Muito obrigado, deu certo, obrigado de coração
Answer: Se o elemento foi criado dinamicamente utilize on do jQuery no elemento BODY ao invés de click direto e é claro insira este id no elemento que contém a classe clicável ex:

   curtir

$(body).on('click', '.classe_clicavel', function(){

    var id = $(this).attr('id');

    // ex de teste ou sua lógica
    alert(id);
});


What's the term for ending a melody on a non chord tone?

Question: If i play a melody with a static chord rhythm of 1 the tonic chord (G major in this case) but if i end the melody on a non chord tone, lets say a C note. What is the term for that? The last note of a melody being a non chord tone.
Comment: Wait, are you saying you play the C note and then the C chord is played? Doesn't that make the C note a chord tone? If you play a note and hold it until it becomes a chord tone, that's called *anticipation*.
Comment: I'm voting to close this as it is currently unclear what exactly you are asking. If the OP could provide an extract then this question can be answered but as is it cannot.
Comment: It's not called anything in particular.
Comment: Janice - what do you mean by "static chord rhythm?"
Comment: No what i mean if i just don't hold it, also it dosen't have to be the C note, it could just be any other non chord tone that the melody ends on.
Comment: Well, that was a right waste of time... Laurence is right: it isn't called anything in particular, just "surprise ending" maybe.
Answer: It depends on which chord you end on.

V: Half cadence
vi: Deceptive (or interrupted) cadence

In other cases you might call it a weak cadence, or simply not refer to it as a cadence at all.  "Hanging chord" might describe it, or "suspension" might describe what it is doing.
Wikipedia has some more detail.
Comment: I think the question does not refer to the phrase ending on a chord different from I, but to the melody ending on a non-chord note.
Comment: Seems like it'll be a perfect (authentic) cadence, as the OP says it goes V > I , only with the melody note being not part of that V chord. 'Odd' could be a descrpitive term...
Comment: You definitely could be right.  Hard to say what they're asking for sure on a second glance, hopefully we get some clarification.
Comment: As thSoft said, i mean when the melody ends on a non-chord tone. Nevermind the candences lets just say no chords come after, just what is the term when a melody ends on a non chord tone?
Answer: Sounds like the penultimate chord becomes a sus4. In C, the V chord is G, or G7, but if the melody is C at that point, the harmony overall will be Gsus4, or more properly, if the whole G chord, inc. its B note, is played, then the harmony becomes G11, or Gadd4, or G7sus, maybe.It's anticipating the home/root note.
Answer: In your example, the non chord tone anticipates a future chord, this is an anticipation.
https://en.wikipedia.org/wiki/Anticipation_(music)
The other way round is a suspension.  https://en.wikipedia.org/wiki/Suspension_(music)
To verify if that's actually relevant to your specific melody though, we'd need an example, written or recorded, of the melody to which you're referring
Answer: So, your melody's phrase is cadencing to the tonic while the dominant is still playing in the accompaniment, and that dominant resolves to the tonic after the melody ends (goes silent?).
There's no specific term for it, but unresolved anticipation probably describes it quite well if the melody arrived there by a process of ellipsis, that is, by leaving something out of the middle of the phrase (possibly by shortening the expected duration of the penultimate melody note, although there is more than one way to skin that cat).
There's another way you might have got there. Let's consider for a moment the situation where the accompaniment ends on the tonic while the melodic phrase is stretched (perhaps by internal expansion of the phrase) so that a harmony note from the dominant is still sounding in the melody while the accompaniment finishes at the expected time: you might consider this a suspension with delayed resolution. Now, if you flip the roles so that the accompaniment's phrase is stretched instead of the melody's, and the notes of the accompaniment all resolve by step, then it might be possible to consider the accompaniment's movement as a multiple delayed-resolution suspension instead.
That's probably why none of us have a specific term for what you're doing: how the dissonance is perceived is going to depend somewhat on voice leading, and quite a bit on the listeners' expectations of phrase length and rhythm.
Now, you didn't say specifically whether whether we're talking about the phrase endings of the melody and accompaniment of the very final phrase of the work, or whether another phrase follows. If the latter is the case, and one (or more) voice(s) is (are) ending a phrase and beginning a new one while the other voice(s) is (are) still finishing the first phrase, then the process is called dovetailing. Note that whether these phrase endings involve dissonance is immaterial to dovetailing - they may or may not - so explaining what you are doing here still needs a bit of an analytical eye.


Drupal theme bare minimum

Question: I'm looking for the most absolute basic way to create a custom theme.  By this I mean, what are the absolute bare minimum requirements for Drupal to run my theme.  So, basically, I guess what files does Drupal need and what settings absolutely need to be specified?  I tried looking at the Theming Guide over at drupal.org but I didn't find it to be very helpful.
Cheers.
Answer: If you're using D7, it ships with the stark theme which is a pretty good example of how basic you can get.
Comment: +1, Stark is great if you want to understand the basics of Drupal theming. Be aware that 'great to start learning' does not necessarily mean 'great to start building'. There are many [starter themes](http://drupal.org/node/323993), based on the best practices of experienced themers, that will give you a head start when building your custom theme.
Comment: After looking through the Stark folder, it is indeed ultra simple.  It's not joking when it says all the HTML generated comes straight from the Drupal core.  Great to start with.  +1
Comment: I admit, I tried Zen but it was just so bloated in terms of CSS files, I couldn't handle it.
Answer: You need a .info file to tell about your theme. That should be enough or you might need to include an empty template.php file as well.
The rest you don't need which are

template files (.tpl.php)
CSS files
JS files
Theme overrides located in your template.php file.
Answer: Check out Creating a CSS-only theme, which shows you how to make an entire theme with basically two files (minimum): a .info file and a .css file.
Comment: I accepted the answer given by Nigel because, essentially, Stark gave me a visual representation of this answer.  Cheers.
Answer: Checkout the omega theme. It has everything you need and a pretty good backend interface to start.
There's lots of great documentation on the omega theme website as well on how to get started and theme your website.

Drupal theme bare minimum


How can a Router talk to a View other than using a global variable?

Question: I can not understand why in my Backbone app (Todo app) after I reload a page (CTRL+F5) a filterTodos method does not get called. When I simply click on links to filter Todos ("Active", "Completed") - it does get called.
You can see this feature in links below. No matter how many times you click Refresh in Browser - correct filtered results are displayed:
http://todomvc.com/architecture-examples/backbone/#/completed
http://todomvc.com/architecture-examples/backbone/#/active
I have a theory that it's because I am triggering a filter event from Router too early - a TodosView is not initialized yet and therefore it does not listenTo filter event yet.
But how a Router can inform a View to re-render itself (based on filter) if this View does not exist yet? Can't it be achieved via triggering some event in Router as I do? One possible option is to have a global variable app.FilterState.
Is there any other methods of communications between a Router and a non-constructed yet View?
For app.FilterState I will set its state in Router and then check it in View and call filterTodos function manually like so and it will work:
views/todos.js
render: function() {
    app.Todos.each(function(todo) {
      this.renderTodo(todo);
    }, this);
    if (app.FilterState !== 'all') { // <--- ADDED CODE
      this.filterTodos(app.FilterState);
    }
    return this;
  }

Existing source code:
routers/router.js
var app = app || {};

var Router = Backbone.Router.extend({
  routes: {
    'all': 'all',
    'active': 'active',
    'completed': 'completed'
  },
  all: function() {
    console.log('all');
    app.Todos.trigger('filter', 'all');
  },
  active: function() {
    console.log('active');
    app.Todos.trigger('filter', 'active');
  },
  completed: function() {
    console.log('completed');
    app.Todos.trigger('filter', 'completed');
  }
});

app.Router = new Router();
Backbone.history.start();

views/todos.js
var app = app || {};

app.TodosView = Backbone.View.extend({
  el: '#todo-list',

  initialize: function(todos) {
    console.log('initialize begin');
    app.Todos.reset(todos);
    this.listenTo(app.Todos, 'add', this.addOneTodo);
    this.listenTo(app.Todos, 'filter', this.filterTodos);
    this.render();
    console.log('initialize end');
  },
  render: function() {
    app.Todos.each(function(todo) {
      this.renderTodo(todo);
    }, this);
    return this;
  },
  renderTodo: function(todo) {
    var todoView = new app.TodoView({model: todo});
    this.$el.append(todoView.render().el);
  },
  addOneTodo: function(todo) {
    this.renderTodo(todo);
  },
  filterTodos: function(filterType) {
    console.log('filter'); // <--- CODE DOES NOT REACH THIS LINE WHEN CALLED ON BROWSER'S REFRESH (F5)
    var active = app.Todos.active();
    var completed = app.Todos.completed();

    if (filterType === 'active') {
      // hide remaining
      _.each(completed, function(todo) {
        todo.trigger('hide');
      });
      //show active
      _.each(active, function(todo) {
        todo.trigger('show');
      });
    }
    else if (filterType === 'completed') {
      _.each(completed, function(todo) {
        todo.trigger('show');
      });
      //show active
      _.each(active, function(todo) {
        todo.trigger('hide');
      });
    }
    else if (filterType === 'all') {
      app.Todos.each(function(todo) {
        todo.trigger('show');
      });
    }
  }
});

Answer: Have you considered using Backbone Marionette? It comes with a built in pub sub communication system built in that makes it super easy to do this. Overall it gives you a great organization/modularization of your code by utilizing the pub sub system.
Comment: Also, it costs a little money but it's THE BEST Backbone/Marionette tutorial out there and comes with quite a bit of production ready code if you follow it all the way through - http://www.backbonerails.com/


accept only a single digit in java

Question: I am writing a simple program that takes multiple inputs and displays the largest then second largest.  My only problem is that I want the program to accept only single digits.  I know this goes back to basics, but bear with me.  The code I have written so far is:
import javax.swing.JOptionPane;

public class Largest
{
    public static void main (String args[])
    {
        /*Set variables and include a while function to force the program to take
        * ten numbers before proceeding to the rest of the program. */
        int counter = 0;
        int number = 0;
        int largest = 0;
        int second = 0;

        while (counter < 10)
        {
            // Set the counter
            counter++;
            //Input integer, set the largest number as the first output
            number = Integer.parseInt(JOptionPane.showInputDialog("Enter integer"));
            if (number >= largest) {
                largest=number;
            } else if (number >= second && number <= largest) {
                // Set the second largest integer as the output
                second=number;
            }
        }

        //Display the largest number, followed by the second largest number
        System.out.println("Largest number input: " + largest);
        System.out.println("Second largest input: " + second);

        System.exit(0);             //terminate the application
    }                   //end method main
}                       //end class

Comment: Do you mean you only want them to able to physically enter one digit (like it won't let you enter 2 characters), or it should only accept one digit (like it would throw an error if it got anything above 9) ?
Comment: Just realized, the program will always display the second highest number as 0 if it is entered.  Not sure why....
Comment: It should not allow a double digit in any entry.  Going back to VB I remember setting the variable to only allow a single digit I believe but that was so long ago
Comment: @user1798926 see my answer. you should just ask again if it is invalid
Answer: For this type of problem, personally, I would use a DocumentFilter
It allows you to restrict the type of characters coming into the field as well as the number of characters.

public class RestrictInput {

    public static void main(String[] args) {
        new RestrictInput();
    }

    public RestrictInput() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException ex) {
                } catch (InstantiationException ex) {
                } catch (IllegalAccessException ex) {
                } catch (UnsupportedLookAndFeelException ex) {
                }

                JTextField field = new JTextField(2);
                field.setHorizontalAlignment(JTextField.RIGHT);
                ((AbstractDocument) field.getDocument()).setDocumentFilter(new RestrictFilter());
                JPanel panel = new JPanel(new GridBagLayout());
                GridBagConstraints gbc = new GridBagConstraints();
                gbc.gridx = 0;
                gbc.gridy = 0;
                panel.add(new JLabel("Please enter a integer:"), gbc);
                gbc.gridx++;
                gbc.anchor = GridBagConstraints.WEST;
                gbc.weightx = 1;
                panel.add(field, gbc);

                int result = JOptionPane.showConfirmDialog(null, panel, "Input", JOptionPane.OK_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE);
                if (result == JOptionPane.OK_OPTION) {
                    System.out.println("Use entered " + field.getText());
                }

            }
        });
    }

    public class RestrictFilter extends DocumentFilter {

        public void insertString(DocumentFilter.FilterBypass fb, int offset, String text, AttributeSet attr) throws BadLocationException {
            String currentText = fb.getDocument().getText(0, fb.getDocument().getLength());
            if (currentText.startsWith("-") || text.equals("-") || fb.getDocument().getLength() < 1) {
                String value = text.substring(0, 1);
                if (value.equals("-")) {
                    if (currentText.startsWith("-")) {
                        super.remove(fb, 0, 1);
                    } else {
                        super.insertString(fb, 0, value, attr);
                    }
                } else if (fb.getDocument().getLength() < 2 && (value.equals("-") || Character.isDigit(value.charAt(0)))) {
                    super.insertString(fb, offset, value, attr);
                }
            }
        }

        public void replace(DocumentFilter.FilterBypass fb, int offset, int length, String string, AttributeSet attr) throws BadLocationException {
            if (length > 0) {
                fb.remove(offset, length);
            }
            insertString(fb, offset, string, attr);
        }
    }
}

Check out MDP's Weblog and Text Component Features, in particular the section of Implementing a Document Filter
Answer: //Set the counter
counter++;
while (true) {
    //Input integer, set the largest number as the first output
    number = Integer.parseInt(JOptionPane.showInputDialog("Enter integer"));
    if (number < 10 && number > -10) break; //If it's one digit, it's OK
    JOptionPane.showMessageDialog(null, "Enter only one digit",
        "Too many digits", JOptionPane.ERROR_MESSAGE);
}

What this does is start an infinite loop. If the number is only one digit, it will end the loop and continue on. Otherwise, it will start from the beginning of the loop again and ask for a valid number.
Comment: You should check for `number >= 0` as well, or the user could enter negative values with several digits.
Comment: Thank you, that is very close to what i just tried.  I'm still having a problem with Zero always popping up though, I think I'm going to have to restrict users from entering a zero
Answer: Just use a custom JOptionDialog where you restricted the JTextField to 1 char width.
Comment: http://stackoverflow.com/questions/3519151/how-to-limit-the-number-of-characters-in-jtextfield
Comment: Thank you for the link, I have yet to use limiters
Comment: @MadProgrammer That is what I meant - I was sure JTextField had a "display width" and a "max input length", but then I realised I am confusing it with HTML forms! your answer is definitely more complete, and enforces numeric characters.

accept only a single digit in java


Cython implementation no faster than pure python

Question: For an exercise I've written a XOR doubly-linked list
%%cython

from cpython.object cimport PyObject
from cpython.ref cimport Py_XINCREF, Py_XDECREF
from libc.stdint cimport uintptr_t

cdef class Node:
    cdef uintptr_t _prev_xor_next
    cdef object val

    def __init__(self, object val, uintptr_t prev_xor_next=0):
        self._prev_xor_next=prev_xor_next
        self.val=val

    @property
    def prev_xor_next(self):
        return self._prev_xor_next
    @prev_xor_next.setter
    def prev_xor_next(self, uintptr_t p):
        self._prev_xor_next=p

    def __repr__(self):
        return str(self.val)

cdef class CurrentNode(Node):
    cdef uintptr_t _node, _prev_ptr
    def __init__(self, uintptr_t node, uintptr_t prev_ptr=0):
        self._node = node
        self._prev_ptr= prev_ptr

    @property
    def val(self):
        return self.node.val
    @property
    def node(self):
        ret=<PyObject *> self._node
        return <Node> ret
    @property
    def prev_ptr(self):
        return self._prev_ptr

    cdef CurrentNode forward(self):
        if self.node.prev_xor_next!=self._prev_ptr:
            return CurrentNode(self.node.prev_xor_next^self._prev_ptr, self._node)

    cdef CurrentNode backward(self):
        if self._prev_ptr:
            pp=<PyObject*>self._prev_ptr
            return CurrentNode(self._prev_ptr, self._node^(<Node> pp).prev_xor_next)

    def __repr__(self):
        return str(self.node)

cdef class XORList:
    cdef PyObject* first
    cdef PyObject* last
    cdef int length

    def __init__(self):
        self.length=0
    @property
    def head(self):
        return (<Node> self.first)

    @property
    def tail(self):
        return (<Node> self.last)

    cdef append(self, object val):
        self.length+=1
        #empty list
        if not self.first:
            t=Node(val)
            tp=(<PyObject*> t)
            self.first=tp
            Py_XINCREF(tp)
            self.last=tp
            Py_XINCREF(tp)

        #not empty
        else:
            new_node=Node(val, <uintptr_t> self.last)
            new_ptr=<PyObject*> new_node
            cur_last=<Node>self.last
            cur_last.prev_xor_next=cur_last.prev_xor_next^(<uintptr_t> new_ptr)
            Py_XINCREF(new_ptr)
            self.last=new_ptr
            Py_XINCREF(new_ptr)

    cpdef reverse(self):
        temp=self.last
        self.last=self.first
        self.first=temp

    def __repr__(self):
        return str(list(iter_XORList(self)))
    def __len__(self):
        return self.length

def iter_XORList(l):
    head=<PyObject*>l.head
    cur=CurrentNode(<uintptr_t> head)
    while cur:
        yield cur
        cur=cur.forward()

import time

start=time.time()
cdef XORList l=XORList()
for i in range(100000):
    l.append(i)
print('time xor ', time.time()-start)

start=time.time()
l1=[]
for i in range(100000):
    l1.append(i)
print('time regular ', time.time()-start)

using the builtin list above I consistently get ~10x worse performance on the cython linked list.
time xor  0.10768294334411621
time regular  0.010972023010253906

When I profile the loop for the xorlist I get:
         700003 function calls in 1.184 seconds

   Ordered by: standard name

   ncalls  tottime  percall  cumtime  percall filename:lineno(function)
        1    0.000    0.000    1.184    1.184 <string>:1(<module>)
        1    0.039    0.039    1.184    1.184 _cython_magic_14cf45d2116440f3df600718d58e4f95.pyx:108(list_check)
   100000    0.025    0.000    0.025    0.000 _cython_magic_14cf45d2116440f3df600718d58e4f95.pyx:11(__init__)
    99999    0.019    0.000    0.019    0.000 _cython_magic_14cf45d2116440f3df600718d58e4f95.pyx:16(__get__)
    99999    0.018    0.000    0.018    0.000 _cython_magic_14cf45d2116440f3df600718d58e4f95.pyx:19(__set__)
        1    0.000    0.000    0.000    0.000 _cython_magic_14cf45d2116440f3df600718d58e4f95.pyx:60(__init__)
   100000    0.937    0.000    0.999    0.000 _cython_magic_14cf45d2116440f3df600718d58e4f95.pyx:70(append)
   100000    0.113    0.000    1.146    0.000 line_profiler.py:111(wrapper)
        1    0.000    0.000    1.184    1.184 {built-in method builtins.exec}
        1    0.000    0.000    0.000    0.000 {method 'disable' of '_lsprof.Profiler' objects}
   100000    0.018    0.000    0.018    0.000 {method 'disable_by_count' of '_line_profiler.LineProfiler' objects}
   100000    0.015    0.000    0.015    0.000 {method 'enable_by_count' of '_line_profiler.LineProfiler' objects}

So, ignoring the calls to append it seems most of the time is spent in the special methods.
This brings me to my questions:

how can I speed this up
I thought extension types in Cython are implemented underneath via structs so what is causing the initializations of them to take so long

I also tried another custom implementation of an oridnary doubly-linked list in pure python and the timings of it and the cython xorlist are similar within 10% difference on my machine.
Comment: The built-in `list` is *also* written in C, but it's an arraylist. Of course it's faster.
Comment: @user2357112 okay so I guess two things: I knew that but I thought the builtin would reallocate 20% larger and copy all the pointers once full and I assumed that would take enough time to close the gap; That doesn't seem to get at my final comment about a simple pure python doubly-linked list nearing the cython performance
Answer: The three culprits from your profiling look to be Node's __init__ (which is unavoidable here), and __get__ and __set__ for the prev_xor_next property. My view is that you don't want the prev_xor_next property (or if you do it should be read-only) since it makes what should be a Cython internal accessible in Python.
Whether you delete the property or not, you are working in Cython here so you can write directly to the underlying C attribute _prev_xor_next. You may need to set cdef Node cur_last at the start of append (and maybe in other functions) to ensure that Cython knows the type of cur_last - I think it should be able to work it out but if you get AttributeErrors at runtime then this is what you need to do.
This change gives me a 30% speed increase (i.e. it's still slower than a regular list, but it's a noticeable improvement).

I'll outline a more drastic change that I possibly should have suggested on your first question about this problem. This really is a vague outline so no effort has been made to get it to work...

Node is entirely internal to your XORList class: it should not be used from Python and the lifetime of all the Nodes in an XORList is tied directly to the list. Therefore they should be destructed on the destruction of their owning XORList (or if the list shrinks, etc) and so do not need to be reference counted. Therefore Node should be a C struct rather than a Python object:
cdef struct Node:
    uintptr_t prev_xor_next
    PyObject* val

# with associated constructor- and destructor-like functions:
cdef Node* make_node(object val, uintptr_t prev_xor_next):
    cdef Node* n = <Node*>malloc(sizeof(Node))
    n.val = <PyObject*>val
    Py_XINCREF(n.val)
    n.prev_xor_next = prev_xor_next
    return n

cdef void destroy_node(Node* n):
    Py_XDECREF(n.val)
    free(n)

XORList needs a __dealloc__ function that loops through the list calling destroy_node on each Node (it needs a __dealloc__ function anyway in your version too!)
CurrentNode needs to remain a Cython class, since this is your "iterator" interface. It can obviously no longer inherit from Node. I'd change it to:
cdef class XORListIterator:
    cdef Node* current_node
    cdef XORList our_list

the point of the attribute our_list is to ensure that the XORList is kept alive at least as long as the CurrentNode - if you end up with an iterator for an XORList that no longer exists that the current_node attribute will be invalid. current_node is not owned by XORListIterator so no need for a destructor.

The danger with this scheme I think is making sure that if any changes to the XORList don't completely invalidate any existing XORListIterators to the point where you get crashes. I suspect this would also be an issue with your current version.

I suspect the built-in list will still remain competitive, since it is a well-written, efficient structure. Remember that list.append is usually a simple Py_INCREF, with an occasional array reallocation and copy. Yours always involves creation of a new Python object (the Node) as well as some associated reference counting.
My alternative scheme avoids a lot of reference counting (both in terms of computational time and "you having to think about it" time), so I'd expect it to be much closer. It retain the disadvantage of a small memory allocation each append, which is unavoidable for a linked-list structure.

Addendum: to address the comment about "the convenience of a Cython class". In my view the two advantages of using a Cython class vs a struct are:

You get something fairly close to a struct, but don't have to worry about C pointers and the reference counting is taken care of. It's pretty clear that for this problem you're doing odd things to pointers and having to handle reference counting explicitly, so I don't think this is applies to you.
You can use it from Python - you aren't just restricted to Cython. In this case I think it's entirely an implementation detail of the XORList that shouldn't be exposed to Python users.

Therefore I think the main reasons to use Cython classes specifically don't apply to your problem. (For a lot of code the advantages do apply, of course!)
It's probably also worth adding that constructing Cython classes is probably one of their slower features - to support possible inheritance the construction process is quite "indirect". You've managed to create a benchmark that turns out to be almost all constructing - I'd guess it's a slightly skewed benchmark and the real case might not be that bad.
Comment: thanks for another good answer. I'll try both approaches but your second has occurred to me so I'll work more on it. My second list item sort of alludes to it but when I began converting Node to a struct I stopped because as I read on page 82 of "Cython a guide for python programmers" extension types are converted to a c struct so I imagined the convenience of the python class would be nicer than any small performance gains but it seems that wasn't true. Could you talk a little about this?
Comment: I've added a small edit at the bottom that gives my reasoning on this


Four Fundamental subspaces

Question: Given an $m \times n$ matrix, where $m$ is the number of rows and $n$ is the number of columns.

Four Fundamental Subspaces

The row space is $C(A^t)$, a subspace of $\mathbb{R}^n$.
The column space is $C(A)$, a subspace of $\mathbb{R}^m$.
The nullspace is $N(A)$, a subspace of $\mathbb{R}^n$.
The left nullspace is $N(A^t)$, a subspace of $\mathbb{R}^m$. This is our new space.

If the column space is the space that is spanned by the column vectors, why is it that it is a subspace of $\mathbb{R}^m$ and not $\mathbb{R}^n$, since the dimension of the columns should be $n$ instead?
Or am I missing something fundamental here?
Answer: Convince yourself with an example. I'll take $$\begin{pmatrix} 1 & 2 & 3 \\ 4 & 5 & 6 \end{pmatrix}$$ which is a $(2 \times 3)$-matrix, and the columns $$\begin{pmatrix}1 \\ 4 \end{pmatrix}, \begin{pmatrix} 2 \\ 5 \end{pmatrix}, \begin{pmatrix} 3 \\ 6 \end{pmatrix}$$ belong to $\mathbb{R}^2$ rather than $\mathbb{R}^3$.
Answer:
Since the dimension of the columns should n instead?

No, you're misinterpreting the dimensions of a matrix. Given an $m\times n$ matrix (I'm going to stick with lowercase letters), then as you said correctly yourself,

M is number of rows and N is number of columns.

So $n$ is the number of columns, but not their dimension (or size). Each column has $m$ entries in it because there are $m$ rows in the matrix, i.e. $m$ is the "height" of the matrix and thus the "height" of each column. That's why each column is an element of $\mathbb{R}^m$.

Four Fundamental subspaces


Função JavaScript não funciona

Question: Estou fazendo esta função:

function toDate(data) {
  let partes = data.split('/');
  return new Date(partes[2], partes[1] - 1, partes[0]);
}
var atual_data1 = toDate($("#txtDataInicio").val());
$("#txtVencimentoC").val() = (atual_data1.format("dd/MM/yyyy HH:mm:ss"));
var tol = ($("#txtTolerancia").val());
atual_data1.setDate(atual_data1.getDate() + parseInt(tol));
$("#txtDataTolerancia").val(atual_data1.format("dd/MM/yyyy HH:mm:ss"));

Porém ele me retorna o seguinte erro:

ReferenceError: Invalid left-hand side in assignment

Nesta linha:
$("#txtVencimentoC").val() = (atual_data1.format("dd/MM/yyyy HH:mm:ss"));

Já tentei fazer assim também porém não deu certo:
$("#txtVencimentoC").val(atual_data1.format("dd/MM/yyyy HH:mm:ss"));

Comment: Acredito que se mudar: `$("#txtVencimentoC").val() = (atual_data1.format("dd/MM/yyyy HH:mm:ss"));` para `$("#txtVencimentoC").val((atual_data1.format("dd/MM/yyyy HH:mm:ss")));` lembre que `val()` é para settar um valor e não receber com o operador de atribuição (`=`)
Comment: seu problema https://stackoverflow.com/a/9132972/2740371
Comment: Uncaught TypeError: atual_data1.format is not a function
Answer: O val() do jQuery é um método, sendo assim você precisa tratá-lo diferentemente de uma variável (que armazena um valor e é possível alterá-la com a sintaxe que você utilizou). Para setar o valor de dentro de um elemento com esse método utilize:
$("#txtVencimentoC").val(atual_data1.format("dd/MM/yyyy HH:mm:ss"));

Outra questão é que não existe o método format em objetos Date em Javascript. Para formatar a data do mesmo modo que você descreveu, use a função nativa toLocaleString():
$("#txtVencimentoC").val(atual_data1.toLocaleString());

Caso você precise de algo mais específico ou de outro tipo de formatação, dê uma olhada nas respostas desta pergunta.
Veja as correções no seu código:

function toDate(data) {
  let partes = data.split('/');
  return new Date(partes[2], partes[1] - 1, partes[0]);
}

var atual_data1 = toDate($("#txtDataInicio").val());

$("#txtVencimentoC").val(atual_data1.toLocaleString());

var tol = $("#txtTolerancia").val();

atual_data1.setDate(atual_data1.getDate() + parseInt(tol));

$("#txtDataTolerancia").val(atual_data1.toLocaleString());

Data Inicio: <input type="text" id="txtDataInicio" value="04/07/2013">

VencimentoC: <input type="text" id="txtVencimentoC">

Tolerancia: <input type="text" id="txtTolerancia" value="1">

Data Tolerancia: <input type="text" id="txtDataTolerancia">

Comment: Deu certinho, obrigado.
Comment: Eu tentei desta forma, me retorna outro erro: Uncaught TypeError: atual_data1.format is not a function
Comment: Alterei a resposta!

Função JavaScript não funciona


List files on a directory on C

Question: I am starting to learn c and i need a little help understanding this code:
#include "apue.h"
#include <dirent.h>
int main(int argc, char *argv[])

{
        DIR             *dp;
        struct dirent   *dirp;

        if (argc != 2)
                err_quit("usage: ls directory_name");

        if ((dp = opendir(argv[1])) == NULL)
                err_sys("can't open %s", argv[1]);
        while ((dirp = readdir(dp)) != NULL)
                printf("%s\n", dirp->d_name);

        closedir(dp);
        exit(0);
}

So, i know that the first if will tell you that you are missing the directory from which you want to list the files, but i´m totally lost with the next if and the while, which i know that will print the files but i fail to understand the conditions of the while, any help would be appreciated, thanks!
Comment: Perhaps the man-pages for [opendir](http://man7.org/linux/man-pages/man3/opendir.3.html) and [readdir](http://man7.org/linux/man-pages/man3/readdir.3.html) will help.
Answer:
If condition will open main directory from which you want to read files.It will return NULL if it fails to open it.
Second , while condition will read files from given directory one by one and printing name of files.
readdir will read first file form directory and and will return NULL if it fails in reading file.
So in while condition if readdir is successfully read file then it will not return NULL.So now condition becomes like while(dirp != NULL).

List files on a directory on C


MariaDB REGEXP_REPLACE with semicolon in replace string throws error

Question: For Youtube videos inside news articles I'm trying to replace all old <object> html tags (flash) to  tags. But there is a huge problem as the database throws a syntax error when I use semicolons (;) in the replace string. Even when I escape them, the error persists
UPDATE
  `news_items`
SET
  `content` = REGEXP_REPLACE(content,
                '(?sm)<object.*?width\="([0-9]+)".*?height\="([0-9]+)".*?value\="((http://|https://).*?)".*<\/object>',
                '<\/iframe>')
WHERE
  ID = 9551;

It happens at allow="accelerometer;.
How can I escape this?
Edit: I replaced the delimiter to %%, ran the query, and put ; delimiter back, this worked
Comment: show the exact error you are seeing?  and what does `select version();` show?
Comment: works just fine for me: https://dbfiddle.uk/?rdbms=mariadb_10.6&fiddle=bd756798cdb83e484cb1dcfa398a07a4
Comment: It didn't work for me, But i now found out that it has something to do with the delimiter. I changed the delimiter to `%%` , then performed the query and then changed the delimiter back to `;` This works. (version is 10.4.21)
Comment: is this in a stored procedure declaration or something, not just a query you are running?
Comment: No, it's really just a query, I'm running it from the console . But it's solved by temporarily replacing the delimiter :)
Comment: I tested the query on MariaDB 10.5 and it worked. I suspect you ran into the common problem of mismatched quotes or similar quotes in the replace string data.
Comment: Try it on 10.4.21 the only solution for me was to temporarily change the delimiter symbol because it clashed with the ; in the query string.
Answer: Somehow, because the string in the query contains a character that clashes with the sql delimiter. I replaced the delimiter to %%, ran the query, and put ; back as delimiter. This worked.


workaround for column specification in select clause not having intellisense in ssms till your specify the table

Question: In ssms, intellisense doesn't kick when specifying column names in select until afteryou specify the table name in the from clause.
This makes sense cuz ssms can't read your mind.
However it is a pain in the neck because we write the select clause before the from clause.
I am not able to perfectly verbalize what i am looking for but what would be ideal is to be able to specify the from clause before the select clause.
I don't want every single column in the database to be in the list obviously.
The way one typically writes a sql statement is kind of weird and unwieldy, with select clause coming before the 'from' clause thus depriving us of the advantage of intellisense, unless we go back to column list after you write from 'tablename'. Just feels weird and annoying and there has to be a better way
Comment: Well quite frankly the way the SQL language is constructed was decided decades before IntelliSense was ever even a concept. There is no "better way" unless you want to write your own parser for T-SQL that will parse something like `FROM dbo.table SELECT ...`. I agree with you that that would be a more natural way to write queries, but that doesn't make it possible.
Comment: So what do you want? Every single column in your database to be in the list from the start? What if you have `EmployeeID` in 40 different tables? What if you don't even know what columns are in the table you're after? This requirement doesn't make any sense to me at all. Just type `SELECT FROM dbo.tablename` and then go back to the column list.
Comment: I don't want every single column in the database to be in the list obviously. I was just pointing out that the way one typically writes a sql statement is kind of weird and unwieldy, with select clause coming before from column thus depriving us of the advantage of intellisense, unless we do what you say which is go back to column list after you write from 'tablename'. Just feels weird and annoying and there has to be a better way
Answer: You can't change the way SQL Server parses a SELECT statement. You can, however, change how you write it. Just write:
FROM dbo.tablename

Then move your cursor above that, and type SELECT and then you will have IntelliSense.
Another really hacky and bad idea would be:
;WITH x AS (SELECT * FROM dbo.tablename)
SELECT ... FROM x;

But this is really bad news and you still have to type all of that stuff before Management Studio can read your mind.
Sorry, but you're looking for an answer that doesn't exist.
Comment: lol. the 'from' clause coming before 'select' clause is what we have in c# linq. Such a pity we don't have the same in ssms.
Comment: @JayJayJay the order of clauses in a SELECT statement has nothing to do with SSMS. C# LINQ re-writes your query for you - SSMS doesn't do that. The query they both send to the server still has to conform to the standard, not the format that would be slightly more convenient for you.


What are the steps to make this dob calculator work ? JavaScript

Question: Hey i'm doing a homework on how to make a dob calculator on JavaScript. I'm a beginner by the way. This exercice is about calculating age based on 3 select and then i display it with an alert()  i need some of you to help me on what to do on JavaScript.
I create some variable to get the values of these select but it doesn't work as i expected. I don't know what are the steps make it functional
<form action="#" method="post">

                        Day:
                        <select name="dob-day" id="dob-day">
                            <option value="1">1</option>
                            <option value="2">2</option>
                            <option value="3">3</option>
                            <option value="4">4</option>
                            <option value="5">5</option>
                            <option value="6">6</option>
                            <option value="7">7</option>
                            <option value="8">8</option>
                            <option value="9">9</option>
                            <option value="10">10</option>
                            <option value="11">11</option>
                            <option value="12">12</option>
                            <option value="13">13</option>
                            <option value="14">14</option>
                            <option value="15">15</option>
                            <option value="16">16</option>
                            <option value="17">17</option>
                            <option value="18">18</option>
                            <option value="19">19</option>
                            <option value="20">20</option>
                            <option value="21">21</option>
                            <option value="22">22</option>
                            <option value="23">23</option>
                            <option value="24">24</option>
                            <option value="25">25</option>
                            <option value="26">26</option>
                            <option value="27">27</option>
                            <option value="28">28</option>
                            <option value="29">29</option>
                            <option value="30">30</option>
                            <option value="31">31</option>
                        </select>

                        Month:
                        <select name="dob-month" id="dob-month">
                            <option value="1">Janvier</option>
                            <option value="2">Février</option>
                            <option value="3">Mars</option>
                            <option value="4">Avrl</option>
                            <option value="5">Mai</option>
                            <option value="6">Juin</option>
                            <option value="7">Juillet</option>
                            <option value="8">Août</option>
                            <option value="9">Septembre</option>
                            <option value="10">Octobre</option>
                            <option value="11">Novembre</option>
                            <option value="12">Décembre</option>
                        </select>

                        Year:
                        <select name="dob-year" id="dob-year">
                            <option value="1955">1955</option>
                            <option value="1956">1956</option>
                            <option value="1957">1957</option>
                            <option value="1958">1958</option>
                            <option value="1959">1959</option>
                            <option value="1960">1960</option>
                            <option value="1961">1961</option>
                            <option value="1962">1962</option>
                            <option value="1963">1963</option>
                            <option value="1964">1964</option>
                            <option value="1965">1965</option>
                            <option value="1966">1966</option>
                            <option value="1967">1967</option>
                            <option value="1968">1968</option>
                            <option value="1969">1969</option>
                            <option value="1970">1970</option>
                            <option value="1971">1971</option>
                            <option value="1972">1972</option>
                            <option value="1973">1973</option>
                            <option value="1974">1974</option>
                            <option value="1975">1975</option>
                            <option value="1976">1976</option>
                            <option value="1977">1977</option>
                            <option value="1978">1978</option>
                            <option value="1979">1979</option>
                            <option value="1980">1980</option>
                            <option value="1981">1981</option>
                            <option value="1982">1982</option>
                            <option value="1983">1983</option>
                            <option value="1984">1984</option>
                            <option value="1985">1985</option>
                            <option value="1986">1986</option>
                            <option value="1987">1987</option>
                            <option value="1988">1988</option>
                            <option value="1989">1989</option>
                            <option value="1990">1990</option>
                            <option value="1991">1991</option>
                            <option value="1992">1992</option>
                            <option value="1993">1993</option>
                            <option value="1994">1994</option>
                            <option value="1995">1995</option>
                            <option value="1996">1996</option>
                            <option value="1997">1997</option>
                            <option value="1998">1998</option>
                            <option value="1999">1999</option>
                            <option value="2000">2000</option>
                            <option value="2001">2001</option>
                            <option value="2002">2002</option>
                            <option value="2003">2003</option>
                            <option value="2004">2004</option>
                            <option value="2005">2005</option>
                        </select>

                        <button type="button" id="run">Run</button>

                </form>

Here's my code on JavaScript...
let now = new Date();
let day = document.getElementById("dob-day").value;
let month = document.getElementById("dob-month").value;
let year = document.getElementById("dob-year").value;

(function() {

document.getElementById("run").addEventListener("click", function(){

    })
})();

Comment: Your handler function appears to be empty at the moment. The first step is to make an attempt yourself.
Comment: i deleted it because it has no sense
Comment: You need to set the variables from the selects when the user clicks on the button. You're setting them when the page first loads.
Comment: I'm not sure why, but this is a very common beginner mistake.
Comment: In the JavaScript `Date` functions, month numbers start at `0`, not `1`. You should adjust the values of the `dob-month` options accordingly.
Answer: YOu will not need an iife and get the value of day,month and year inside the click function.
Then using Date function convert the input to date and subtract from current date and get the number of days.

document.getElementById("run").addEventListener("click", function() {
  let now = new Date();
  let day = document.getElementById("dob-day").value;
  let month = document.getElementById("dob-month").value;
  let year = document.getElementById("dob-year").value;
  var timeDiff = Math.abs((new Date(`${month}/${day}/${year}`)).getTime() - now.getTime());
  var diffDays = Math.ceil(timeDiff / (1000 * 3600 * 24));
  console.log(diffDays)
})
<form action="#" method="post">

    Day:
    <select name="dob-day" id="dob-day">
      <option value="1">1</option>
      <option value="2">2</option>
      <option value="3">3</option>
      <option value="4">4</option>
      <option value="5">5</option>
      <option value="6">6</option>
      <option value="7">7</option>
      <option value="8">8</option>
      <option value="9">9</option>
      <option value="10">10</option>
      <option value="11">11</option>
      <option value="12">12</option>
      <option value="13">13</option>
      <option value="14">14</option>
      <option value="15">15</option>
      <option value="16">16</option>
      <option value="17">17</option>
      <option value="18">18</option>
      <option value="19">19</option>
      <option value="20">20</option>
      <option value="21">21</option>
      <option value="22">22</option>
      <option value="23">23</option>
      <option value="24">24</option>
      <option value="25">25</option>
      <option value="26">26</option>
      <option value="27">27</option>
      <option value="28">28</option>
      <option value="29">29</option>
      <option value="30">30</option>
      <option value="31">31</option>
    </select>

    Month:
    <select name="dob-month" id="dob-month">
      <option value="1">Janvier</option>
      <option value="2">Février</option>
      <option value="3">Mars</option>
      <option value="4">Avrl</option>
      <option value="5">Mai</option>
      <option value="6">Juin</option>
      <option value="7">Juillet</option>
      <option value="8">Août</option>
      <option value="9">Septembre</option>
      <option value="10">Octobre</option>
      <option value="11">Novembre</option>
      <option value="12">Décembre</option>
    </select>

    Year:
    <select name="dob-year" id="dob-year">
      <option value="1955">1955</option>
      <option value="1956">1956</option>
      <option value="1957">1957</option>
      <option value="1958">1958</option>
      <option value="1959">1959</option>
      <option value="1960">1960</option>
      <option value="1961">1961</option>
      <option value="1962">1962</option>
      <option value="1963">1963</option>
      <option value="1964">1964</option>
      <option value="1965">1965</option>
      <option value="1966">1966</option>
      <option value="1967">1967</option>
      <option value="1968">1968</option>
      <option value="1969">1969</option>
      <option value="1970">1970</option>
      <option value="1971">1971</option>
      <option value="1972">1972</option>
      <option value="1973">1973</option>
      <option value="1974">1974</option>
      <option value="1975">1975</option>
      <option value="1976">1976</option>
      <option value="1977">1977</option>
      <option value="1978">1978</option>
      <option value="1979">1979</option>
      <option value="1980">1980</option>
      <option value="1981">1981</option>
      <option value="1982">1982</option>
      <option value="1983">1983</option>
      <option value="1984">1984</option>
      <option value="1985">1985</option>
      <option value="1986">1986</option>
      <option value="1987">1987</option>
      <option value="1988">1988</option>
      <option value="1989">1989</option>
      <option value="1990">1990</option>
      <option value="1991">1991</option>
      <option value="1992">1992</option>
      <option value="1993">1993</option>
      <option value="1994">1994</option>
      <option value="1995">1995</option>
      <option value="1996">1996</option>
      <option value="1997">1997</option>
      <option value="1998">1998</option>
      <option value="1999">1999</option>
      <option value="2000">2000</option>
      <option value="2001">2001</option>
      <option value="2002">2002</option>
      <option value="2003">2003</option>
      <option value="2004">2004</option>
      <option value="2005">2005</option>
    </select>

    <button type="button" id="run">Run</button>

</form>


Linear Algebra Word Question (school play audience numbers and ticket prices)

Question:
A school play ran for two nights, with
  audiences totaling 1390 adults and
  students. They paid 4285 dollars for
  admission. One adult ticket cost 4 dollars
  and one student ticket cost 2.50 dollars. The
  ratio of adults to students was 3:5
  for the first night and 2:3 on the
  second night. How many students
  attended each night?

I have determined that there was 850 students and 540 adults on both nights, but for the life of me couldn't figure out how to incoporate those ratios into finding how much students were per day.
This is marked as a homework question so please don't give me the full answer but how to go about it.
I also have the answers if that is any help: for the first night, there were 400 students on the first night, and 450 on the second.
Answer: I have verified that the adult/student totals you got is correct.
For the second part:
Suppose a total of $x$ people (i.e. including students and adults) attended the first day and total $y$ people attended the second day.
What is the total number of students in terms of $x$ and $y$?
Comment: @Moron- That was so obvious I can't believe I didn't see that. I keep thinking about the ratios.... Well, thanks, I got the answer! Thanks for wasting your time with me :)
Comment: One more hint please? It seems to me that I'm back where I started if I do that.
Comment: @high: Do the same with number of adults. You have 2 variables, 2 equations. I believe you already know how to solve that.
Comment: Still stuck. I figured out that on the first night, there would be 240 adults and then 300 on the second day, but I'm still unsure how it all fits together...
Comment: So if you have the number of adults each night (which I have not verified) the ratios give the number of students
Comment: @high: On the first day, for every 3 adults, there were 5 students. So for 240 adults there must be how many students?
Comment: @Moron- 400. However, the only reason I knew there was 240 adults was by 'reverse-engineering' the answer I was given. I'm still not sure how to reach 240 adults though!
Comment: @user1827- which is 3:5. How do I take this ratio and find the number of adults in the first place though?
Comment: @high: Did you understand my comment about two equations two variables (x and y)?  If x is total number of people on day 1, how many of them are students, given the ratio 3:5?
Comment: @Moron- Unfortunately, no. EDIT: 0.6?
Comment: @high: Not 0.6. It is 5x/8. Similarly you can find the number of students on the second day in terms of y. Since you know the total number of students you get 5x/8 + something in terms of y  = 850. You get a similar equation for adults. Is it clearer?
Comment: @Moron- Maybe I'm tired, but how did you get 5x/8 from 3:5?
Comment: @high: If there were 8 people, there would be 3 adults and 5 students, so if there were x people, how many adults and how many students?
Comment: @Moron- Would I be correct saying it is `5x/8 + 3y/5`?
Comment: @high: Correct. 5x/8 + 3y/5 = 850. Now form another equation for adults, and solve for x and y.
Comment: @Moron-So I formed 3x/8+2y/5. Is this still correct?
Comment: @high: Yes, looks right.
Comment: @Moron- So if I solve `5x/8+3y/5=850`, I get x=8, y=-25. Then `3x/8+2y/5=540` gives me x=16, y=-15. What now?
Comment: @high: Can you find _one_ value of x and _one_ value of y so that both the equations are true?
Comment: @Moron- Would x=640, y=750 be correct?
Comment: @high: Looks right (you can verify it yourself by substituting it back in those two equations). So now you know how many total people attended on day1 and how many on day2.
Comment: @Moron- So how do I incorporate the ratios into the numbers?
Comment: @high: You already did when you formed the equation 5x/8+3y/8 = 850 and also in the other one. Wasn't 5x/8 the number of students on day1?
Comment: @high: No worries. Glad to have helped.


Git merge says already up-to-date with master but my branch doesn't contain the latest changes

Question: I'm working on a branch "ABC" cloned from master and since someone's changes just got merged to master branch my code needs their latests changes. I used git merge and sent everything in a new commit, However, when I use hit pull, git merge, and fetch it says "already up-to-date", not sure if I did something wrong but my code isn't synced with what's on master.
Git status says "Your branch is up to date with origin/feature/ABC"
Ps: I can't modify master without approval, so preferably I'd like to not mess with master if possible
Comment: How about `git merge master` or `git rebase master`.
Comment: Git merge master says "already up-to-date" and can I use rebase if I don't want to modify master in remote?
Comment: My understanding is `merge` and `rebase` effectively do the same thing -- the difference is in the history.
Comment: The thing you probably didn't notice is that your local `master` branch doesn't contain the latest changes either. [@torek's answer](https://stackoverflow.com/a/73941010/184546) will get you where you need to be.
Answer: git pull means:

run git fetch, then
run a second Git command, git merge by default, but you can set things up to be different if you like.

If you run it with no arguments (as you presumably did), this means:

git fetch origin (usually and in your case), and then
git merge HEAD@{upstream} (assuming your chosen second command is git merge).

The upstream is a setting, per-branch: you can change it if you want, but that's not what you want here.  Your git status output shows that the upstream of your feature/ABC is your origin/feature/ABC, which is correct.
But what this all means is:

the git fetch step obtains all the new commits, including those on their master branch, so that your origin/master is updated, and then
the git merge step merges with the old commits you already had all along on your origin/feature/ABC that corresponds to your feature/ABC.

Hence, git pull is not what you want!
What you want, presumably, is:

run git fetch or git fetch origin; then
run git merge origin/master.

As you're a Git newbie, I recommend avoiding git pull.  Run separate git fetch and second-command steps, so that you know exactly which step failed if one step does fail.  This is important later when it comes to recovering from this failure.
If you prefer to run git pull, though, the combined convenience form is—partly for historical reasons—git pull origin master, rather than git pull origin origin/master, even though you want the merge step to use origin/master.
Comment: This answer is probably 100% accurate, but it is way to complex for the simple question being asked! It's clearly a newb question, and so an answer that covers all the nuances only a pro will want to know is too confusing! ;)

Git merge says already up-to-date with master but my branch doesn’t contain the latest changes


Proving convegence of sequence

Question: How do I prove
$w_{k+1} = \frac{-(2 (3 - 4 e + 2 e^2) g )}{(-5 + 4 e)} \times w_k$
converges to $0$ over $k\rightarrow \infty$ and say $w_0=1$
Possible bounds are: $0<e<1$ and $0<g<1$.
Also $e$ is just another variable, not Euler number
Comment: Looking at this in greater detail... isn't every term zero regardless what $e,g$ are?  You have $a_1 = \lambda \cdot 0 \cdot a_0=0$ where $\lambda=\frac{-2(3-4e+2e^2)g}{(-5+4e)}$ and so $a_2 = \lambda \cdot 1 \cdot a_1 = \lambda \cdot 1\cdot 0 = 0$... and by induction you see everything is zero from then on... Are you certain you have no typos in what you wrote?  It seems a very silly question otherwise...
Comment: Series or sequence ?
Comment: @TheSilverDoe I want to prove that any values of coefficient of $a_k$ will eventually make $a_{k+1}$ converge to zero with infinite number of multiplications or iterative calculation of $a_{k+1}$.
Comment: So you are interesting of the convergence of the *sequence* $a_k$, not the series ? Your title mentions the word series.
Comment: Yeah ...sorry will fix that
Comment: What is general approach for this?
Comment: What is $e$ and $g$?  "*Wolfram says so*" that the sequence converges *when $g=0$*... but of course... if $g=0$ you have $a_k=0$ for all $k>0$ so that is hardly interesting
Comment: Ok I definitely made mistake there. I fixed it. Now I dont know I was looking at wolfram in right direction.
Comment: Now, this is just a geometric sequence... Just see if the ratio is $|.|>1$ or $|.|<1$.
Comment: Yeah I know I have to prove coefficient of $w_k<1$ for $w_k$ to converge to zero. But unable to do that.
Answer: For $g=0.9$ and $e=0.1$, then $$\left| \frac{-(2 (3 - 4 e + 2 e^2) g )}{(-5 + 4 e)}\right| >1$$
So the sequence diverges.
Comment: seems that I have messed up with this

Proving convegence of sequence


list comprehension on a dictionary giving empty list

Question: I have a dictionary as below :
 'give': (('VBP', 6), ('VB', 15)),
 'discounts': ('NNS', 1),
 'maintaining': ('VBG', 4),
 'increasing': ('VBG', 18),
 'spending': (('NN', 24), ('VBG', 2)),
 'become': ((('VBN', 7), ('VB', 15)), ('VBP', 1)),
 'permanent': ('JJ', 2),
 'fixtures': ('NNS', 1),
 'news': ('NN', 24),
 'weeklies': ('NNS', 2),
 'underscore': ('VBP', 1),
 'fierce': ('JJ', 2),
 'competition': ('NN', 10)

I am writing a list comprehension as below :
result = [x for x in mydict.items() if type(x[1][0]) == 'str']

But this results in an empty list, whereas if I see there are many elements in dictionary, for which this condition satisfies.
Comment: The type is never a string but a class.
Comment: @arsho It's better to use the `isinstance()` function.
Comment: What are you trying to do? What is the expected output? You can use `type(var) is str` for type matching.
Answer: Either you can change 'str' to str i.e.
result = [x for x in mydict.items() if type(x[1][0]) == str]

or may be you can try with isinstance method to check if it is the instance of string (details):
result = [x for x,value in mydict.items() if isinstance(x[1][0],str)]
print(result)

Result:
['increasing', 'maintaining', 'fierce', 'permanent', 'fixtures', 'underscore', 'news', 'weeklies', 'discounts', 'become', 'give', 'competition', 'spending']


Use the Law of Quadratic Reciprocity and the Chinese Remainder Theorem to determine when $6$ is a quadratic residue modulo $p$.

Question: I'm working on the following problems concerning quadratic reciprocity.

a)  Use the Law of Quadratic Reciprocity and the Chinese Remainder
Theorem to determine for which primes $p$, $-50$ is a quadratic
residue modulo $p$.
b) Use the Law of Quadratic Reciprocity and the Chinese
Remainder Theorem to determine when $6$ is a quadratic residue modulo
$p$.

So for (a), you'd say that $-50$ is a quadratic residue $\text{mod}$ $p$ if there exists an integer, say $x$, such that $x^2 \equiv(-50) \text{mod } p$.
I'm not exactly sure how to proceed from here. Any pointers?
Comment: Do you know what the Law of Quadratic Reciprocity is?
Comment: I know the general idea of it. The general statement is that $({p}\over{q})({q}\over{p}) = (-1)^{{p-1}\over{2}{q-1}\over{2}}$ So -50 is q and I need to determine what p is?
Answer: We may prove in a elementary way that for every prime $p\geq 5$
$$\left(\frac{-1}{p}\right)=1\Longleftrightarrow p\equiv 1\pmod{4}$$
$$\left(\frac{-3}{p}\right)=1\Longleftrightarrow p\equiv 1\pmod{3}$$
$$\left(\frac{2}{p}\right)=1\Longleftrightarrow p\equiv \pm 1\pmod{8}$$
and since $6=(-1)\cdot(-3)\cdot(2)$ and $\left(\frac{ab}{p}\right)=\left(\frac{a}{p}\right)\cdot \left(\frac{b}{p}\right)$, by the Chinese remainder theorem we get that $6$ is a quadratic residue $\pmod{p}$ iff $\color{red}{p\!\pmod{24}\in\{1,5,19,23\}}$.
In a similar way, since $-50=(-2)\cdot 5^2$, for every prime $p\geq 7$ we have that $-50$ is a quadratic residue $\!\!\pmod{p}$ iff $-2$ is a quadratic residue, i.e. iff $\color{red}{p\pmod{8}\in\{1,3\}}$.
Answer: Hint: Try writing the conditions in terms of quadratic residues. Specifically, note that $-50=-2(5^2)$, so $-50$ being a quadratic residue $\mod p$ is equivalent to $-2$ being a quadratic residue $\mod p$ (when $p\neq 5$).


A Question about Product Measures

Question: I'm working on the following problem:

Let $\mathcal{M}$ be a $\sigma$-algebra on subsets of $X$ and $\mathcal{N}$  be a $\sigma$-algebra on $Y$. Discuss the validity of the following statement: $A \times B \in \mathcal{M} \otimes \mathcal{N}$ iff $A \in \mathcal{M}$ and $B \in \mathcal{N}$.

I have the forward direction. My book is saying the reverse direction is false. I have a "proof" that it's true. I trust the book, so what's wrong with my "proof"?

To show $A \times B \in \mathcal{M} \otimes \mathcal{N}$ check that the $x$-sections and $y$-sections are $\mathcal{N}$ and $\mathcal{M}$ respectively. $(A\times B)_x = \{y \in Y : (x,y) \in A\times B\} = B$ and $B$ is in $\mathcal{N}$ by assumption. Same for the y-section. Thus we are done.

For the forward direction:

Assume $A \times B \in \mathcal{M} \otimes \mathcal{N}$. The x-section $(A\times B)_x = \{y \in Y : (x,y) \in A\times B\} = B$. $B \in \mathcal{N}$ beacuse of Proposition 2.34 in Folland. (This reads: if $E \in \mathcal{M} \otimes \mathcal{N}$ then $E_x \in \mathcal{N}$ for all $x \in X$ and $E_y \in \mathcal{M}$ for all $y \in Y$) Same argument for the y-section.
Answer: You have proved that $A \in \mathcal M$ and $B \in \mathcal N$ implies $A\times B \in \mathcal M \otimes \mathcal N$. I don't see any proof of the converse. It is the converse that is false. For example if we take both $X$ and $Y$ to be  the real line with the Borel sigma algebra then $\Delta=\{(x,x):x \in \mathbb R\}$ belongs to $\mathcal M \otimes \mathcal N$ but it cannot be written as $A\times B$.
Comment: If $\Delta =A \times B$ what are $A$ and $B$? For any $x \in X$ note that $(x,x) \in \Delta=A\times B$ which implies $x \in A$. Thus every point of $X$ is in $A$ and $A=X$. Similarly, $B=Y$. But then $A\times B =X\times B$ contradicting the fact that $\Delta =A \times B$. (I am assuming that $X$ or $Y$ has at least two points). @yoshi
Comment: I provided a proof for the forward direction. Is $\Delta$ open in $\mathcal{B}(\mathbb{R}) \otimes \mathcal{B}(\mathbb{R})$?
Comment: $\Delta$ is closed in $\mathbb R^{2}$ and this implies that it belongs to $\mathcal B \otimes \mathcal B$. @yoshi
Comment: I'm having trouble seeing why $\Delta$ cannot be written as $A \times B$ could you elaborate or provide a reference?
Comment: I think it should be $A \times B = X \times Y$, right? I dont think this is correct. The X-section and Y-sections of $\Delta$ are in $\mathcal{B}$ (because they are single points and single points are in Borel set of $\mathbb{R}$). So $\Delta$ is in $\mathcal{B} \otimes \mathcal{B}$. Right?
Comment: @yoshi That was a typo. I meant $A \times B=X\times Y$.

A Question about Product Measures


How to analyze and obtain useful information from a score

Question: I'm a self taught musician. I have learned music theory, composition, and instrument performance by myself. I would like to improve my composition techniques and I believe that I should begin analyzing scores. I know that score analysis is a component of studying music in a college.
What sort of things does a college analysis class consist of and what should I look out for while analyzing scores?
Answer: A lot of things come into play here. Often, the harmonies are analyzed (using Roman Numerals if it's Common Practice Tonality, using something like set theory if it's post-tonal, etc.) in order to see where the composer has followed standard progressions and, more interestingly, when they haven't. We look at the specific voicings of the harmonies and see how that influences the overall sound. In common-practice music, we look at the specific ways the melody interacts with the harmony, where are non-chord tones used, do particular patterns emerge, etc. We look for the ways that particular motives get mutated, copied or adapted.
Depending on the instrumentation, we often spend a lot of time on specific orchestrational choices by the composer. What's the effect of choosing one instrument or another? Would another instrument have been more traditionally suited to the material, is the standard range being stretched, etc. If the piece is serial, what is the tone row, and how does it manifest in vastly different situations across the piece? In what ways does it retain similarities despite these differences?
Do certain rhythmic, harmonic, motivic or timbral patterns recur in later situations? How are they similar and how are they different?
There are many, many other things that are specific to particular music. Score study of a fugue is very different from score study of a Bartokian exploration of pitch-space symmetry, but ultimately I'd say that the main benefit of score study is that you notice things in the pieces that you haven't noticed before. I'm often surprised by how much I learn about a piece I thought I already knew well even by just following along with the score before I've even done any actual analysis. If you can get a book that contains scores alongside analytical commentary that can help, or if you have access to JSTOR or something similar you could look up analyses of pieces you know and have scores to.


Find min and max of $A = \sqrt{x-2} + 2\sqrt{x+1} + 2019 -x$

Question:
Find minimum and maximum of $$A = \sqrt{x-2} +  2\sqrt{x+1} + 2019 -x$$

How to solve this problem without using derivatives?

Michael Rozenberg's edit:
Because with a derivative it's not so easy:
$$A'(x)=\frac{1}{2\sqrt{x-2}}+\frac{1}{\sqrt{x+1}}-1=\frac{1}{2\sqrt{x-2}}-\frac{1}{2}+\frac{1}{\sqrt{x+1}}-\frac{1}{2}=$$
$$=\frac{1-\sqrt{x-2}}{2\sqrt{x-2}}+\frac{2-\sqrt{x+1}}{2\sqrt{x+2}}=$$
$$=(3-x)\left(\frac{1}{2(1+\sqrt{x-2})\sqrt{x-2}}+\frac{1}{2(2+\sqrt{x+1})\sqrt{x+2}}\right),$$
which gives $x_{max}=3.$
Comment: Derivatives are really the best way to go in maximization and minimization problems
Comment: Tthe limit is minus infinity when $x\to\infty$. Thus, there is no minimum.
Comment: @MichaelRozenberg Sometimes, with some difficulty/cleverness you can find elementary solutions to such problems, but differentiation is a systematic approach that will work on a large range of problems, and won't require any tricks specific to a given problem.
Comment: @ Wlod AA So what is the maximum value of $A$?
Comment: Ooops, I've misread the Q. :)
Comment: Dear @Zarrax I really don't agree with you! See please my solution.
Comment: @Zarrax The topic starter knows this. By using derivatives, this problem is obvious for him. He looked for a way without using derivatives.
Answer: Let $f(x) = \sqrt{x-2} +  2\sqrt{x+1} + 2019 -x$ then
$$
f'(x) = \frac{1}{2\sqrt{x - 2}} + \frac{1}{\sqrt{x+1}} - 1
$$
Equating this to zero for real $x$, we get $x = 3$. The second derivative is negative hence the global maximum is $f(3) = 2021.$
Comment: If not using the derivative of the function, how is this problem solved?
Comment: @Success Well in that case, you should first mention in your question that you want to maximum without using derivative
Comment: @Nilotpal Kanti Sinha,  one tag is "algebra-pre-calculus". So, the banning of derivatives seems clear enough.
Comment: It's easier to see and say that the first derivative is decreasing for $\,x>2.\ $ To look at the 2nd derivative would be a pain in the neck.
Comment: @BernardMassé That's OK but if you want something specific, mentioning it in the question makes it less likely to be over-sighted
Answer: By C-S and AM-GM we obtain:
$$\sqrt{x-2}+2\sqrt{x+1}-x+2019=\sqrt{x-2}+4\sqrt{\frac{x+1}{4}}-x+2019\leq$$
$$\leq\sqrt{(1+4)\left(x-2+4\cdot\frac{x+1}{4}\right)}-x+2019=\sqrt{5(2x-1)}-x+2019\leq$$
$$\leq\frac{5+2x-1}{2}-x+2019=2021.$$
The equality occurs for $x=3,$ which says that we got a maximal value.
The minimum does not exist. Try $x\rightarrow+\infty.$
Comment: A very good solution. Thank you very much!
Comment: @Success You are welcome!
Comment: Can down-voter explain us why did you do it?
Answer: $$ \forall_{y\ge -1}\quad\sqrt{1+y}\ \le\ 1+\frac y2 $$
hence
$$ \forall_{x\ge 2}\quad\sqrt{x-2}\ =\ \sqrt{1+(x-3)}\ \le\ 1 +\frac{x-3}2 $$
and
$$ \forall_{x\ge -1}\quad\sqrt{x+1}\ =\ 2\cdot\sqrt{1+\frac{x-3}4}\ \le
           \ 2+\frac{x-3}4 $$
hence
$$ \forall_{x\ge 2}\quad\sqrt{x-2}\ +\ 2\cdot\sqrt{x+1}\ \le\ 2+x $$
i.e.
$$ \forall_{x\ge 2}\quad\sqrt{x-2}\ +\ 2\cdot\sqrt{x+1}\ -\ x\ \le\ 2 $$
where the equality holds only for $\ x=3.\ $ Thus A (see the OP Question) attains its maximum $A=2021$ at $x=3$.   Great!
Comment: Nice; you could say $\forall y\color{red}\ge-1$ and $\forall x\color{red}\ge2$, right?
Comment: @J.W.Tanner, right! Thank you -- I'll implement your improvement.


How to configure squid4 as transparent proxy?

Question: There are many posts how to do that, most for older versions.
According to this post, to setup squid as transparent server for port 80 it should be as simple as this:
//squid.config
http_port 3128 transparent
http_port 80 accel #vhost option is deprecated
http_port 443 accel #not forget https

but can't put it to work. i can't figure out if is my ip tables configuration, or the squid configuration.
Squid runs on the same pc as the gateway and dhcp server.
The iptables configuration:
# Generated by xtables-save v1.8.2 on Sun Feb  2 14:05:24 2020
*mangle
:PREROUTING ACCEPT [512813:147258305]
:INPUT ACCEPT [505693:146550975]
:FORWARD ACCEPT [5559:319150]
:OUTPUT ACCEPT [485369:200427691]
:POSTROUTING ACCEPT [486362:200704832]
COMMIT
# Completed on Sun Feb  2 14:05:24 2020
# Generated by xtables-save v1.8.2 on Sun Feb  2 14:05:24 2020
*filter
:INPUT ACCEPT [505677:146546207]
:FORWARD DROP [5532:317382]
:OUTPUT ACCEPT [485351:200422918]
-A FORWARD -p icmp -j ACCEPT
-A FORWARD -p tcp -m tcp --dport 80 -j ACCEPT
-A FORWARD -p tcp -m tcp --dport 443 -j ACCEPT
-A FORWARD -p tcp -m tcp --dport 25 -j ACCEPT
-A FORWARD -p tcp -m tcp --dport 110 -j ACCEPT
-A FORWARD -p tcp -m tcp --dport 993 -j ACCEPT
-A FORWARD -p icmp -j ACCEPT
COMMIT
# Completed on Sun Feb  2 14:05:24 2020
# Generated by xtables-save v1.8.2 on Sun Feb  2 14:05:24 2020
*nat
:PREROUTING ACCEPT [55608:3516287]
:INPUT ACCEPT [48615:2816337]
:POSTROUTING ACCEPT [4525:272304]
:OUTPUT ACCEPT [17086:1270605]
-A PREROUTING -i eth0 -p tcp -m tcp --dport 80 -j REDIRECT --to-ports 3128
-A PREROUTING -i wlan0 -p tcp -m tcp --dport 80 -j DNAT --to-destination 127.1.1.0:3128
-A PREROUTING -i wlan0 -p tcp -m tcp --dport 80 -j REDIRECT --to-ports 3128
-A POSTROUTING -o eth0 -j MASQUERADE
-A POSTROUTING -o wlan0 -j MASQUERADE
COMMIT

The squid.config file:
acl LocalNet src 192.168.4.0/24 #my network .
http_access allow LocalNet

acl localnet src 0.0.0.1-0.255.255.255
#acl localnet src 10.0.0.0/8
#acl localnet src 220.127.116.11/10
#acl localnet src 169.254.0.0/16
#acl localnet src 172.16.0.0/12
#acl localnet src 192.168.0.0/16
acl localnet src fc00::/7
acl localnet src fe80::/10
acl SSL_ports port 443
acl Safe_ports port 80  #http
acl Safe_ports port 21  #ftp
acl Safe_ports port 443 #https
acl Safe_ports port 70  #gopher
acl Safe_ports port 210 #wais
acl Safe_ports port 1025-65535  #unregisted ports
acl Safe_ports port 280 #http-mgmt
acl Safe_ports port 488 #gss-http
acl Safe_ports port 591 #filemaker
acl Safe_ports port 777 #multilining http
acl CONNECT method CONNECT
http_access deny !Safe_ports
http_access deny CONNECT !SSL_ports
http_access allow localhost manager
http_access deny manager
#include /etc/squid/conf.d/*
http_access allow localhost
http_access allow all

#for explicit proxy
#http_port 3128
#http_port 3129 tproxy

#for transparent proxy
http_port 3128 transparent
http_port 80 accel
http_port 443 accel

#cache
cache_dir ufs /var/spool/squid 100 16 256
coredump_dir /var/spool/squid
refresh_pattern ^ftp:           1440    20%     10080
refresh_pattern ^gopher:        1440    0%      1440
refresh_pattern -i (/cgi-bin/|\?) 0     0%      0
refresh_pattern .               0       20%     4320
cache_effective_user proxy
cache_effective_group proxy

#log file
logformat timeread %tl %6tr %>a %Ss/%03Hs %<st %rm %ru %un %Sh/%<A %mt
access_log daemon:/var/log/squid/access.log timeread

The squid start log:
squid[23403]: Starting Squid Cache version 4.6 for arm-unknown-linux-gnueabihf...
squid[23403]: Service Name: squid
squid[23403]: Process ID 23403
squid[23403]: Process Roles: worker
squid[23403]: With 1024 file descriptors available
squid[23403]: Initializing IP Cache...
squid[23403]: DNS Socket created at [::], FD 5
squid[23403]: DNS Socket created at 0.0.0.0, FD 9
squid[23403]: Adding domain Home from /etc/resolv.conf
squid[23403]: Adding nameserver 192.168.1.254 from /etc/resolv.conf
squid[23403]: Logfile: opening log daemon:/var/log/squid/access.log
squid[23403]: Logfile Daemon: opening log /var/log/squid/access.log
squid[23403]: Unlinkd pipe opened on FD 15
squid[23403]: Local cache digest enabled; rebuild/rewrite every 3600/3600 sec
squid[23403]: Store logging disabled
squid[23403]: Swap maxSize 102400 + 262144 KB, estimated 28041 objects
squid[23403]: Target number of buckets: 1402
squid[23403]: Using 8192 Store buckets
squid[23403]: Max Mem  size: 262144 KB
squid[23403]: Max Swap size: 102400 KB
squid[23403]: Rebuilding storage in /var/spool/squid (clean log)
squid[23403]: Using Least Load store dir selection
squid[23403]: Set Current Directory to /var/spool/squid
squid[23403]: Finished loading MIME types and icons.
squid[23403]: HTCP Disabled.
squid[23403]: Pinger socket opened on FD 22
squid[23403]: Squid plugin modules loaded: 0
squid[23403]: Adaptation support is off.
squid[23403]: Accepting NAT intercepted HTTP Socket connections at local=[::]:3128 remote=[::] FD 18 flags=41
squid[23403]: Accepting reverse-proxy HTTP Socket connections at local=[::]:80 remote=[::] FD 19 flags=9
squid[23403]: Accepting reverse-proxy HTTP Socket connections at local=[::]:443 remote=[::] FD 20 flags=9
squid[23403]: Done reading /var/spool/squid swaplog (0 entries)
squid[23403]: Store rebuilding is 0.00% complete
squid[23403]: Finished rebuilding storage from disk.
squid[23403]:         0 Entries scanned
squid[23403]:         0 Invalid entries.
squid[23403]:         0 With invalid flags.
squid[23403]:         0 Objects loaded.
squid[23403]:         0 Objects expired.
squid[23403]:         0 Objects cancelled.
squid[23403]:         0 Duplicate URLs purged.
squid[23403]:         0 Swapfile clashes avoided.
squid[23403]:   Took 0.05 seconds (  0.00 objects/sec).
squid[23403]: Beginning Validation Procedure
squid[23403]:   Completed Validation Procedure
squid[23403]:   Validated 0 Entries
squid[23403]:   store_swap_size = 0.00 KB
squid[23403]: storeLateRelease: released 0 objects

Update
iptables configuration update below, according to @Piotr P. Karwasz. Also i add log that can be see at /var/log/messages.
# Generated by xtables-save v1.8.2 on Wed Feb  5 18:05:20 2020
*mangle
:PREROUTING ACCEPT [26643:2488050]
:INPUT ACCEPT [26417:2421007]
:FORWARD ACCEPT [203:57945]
:OUTPUT ACCEPT [46685:14572738]
:POSTROUTING ACCEPT [47031:14661263]
COMMIT
# Completed on Wed Feb  5 18:05:20 2020
# Generated by xtables-save v1.8.2 on Wed Feb  5 18:05:20 2020
*filter
:INPUT ACCEPT [26404:2417368]
:FORWARD ACCEPT [7:448]
:OUTPUT ACCEPT [46671:14569146]
-A INPUT -j LOG
-A FORWARD -j LOG
-A FORWARD -m conntrack --ctstate RELATED,ESTABLISHED -j ACCEPT
-A FORWARD -o eth0 -j ACCEPT
-A OUTPUT -j LOG
COMMIT
# Completed on Wed Feb  5 18:05:20 2020
# Generated by xtables-save v1.8.2 on Wed Feb  5 18:05:20 2020
*nat
:PREROUTING ACCEPT [612:69658]
:INPUT ACCEPT [577:59792]
:POSTROUTING ACCEPT [26:2979]
:OUTPUT ACCEPT [543:44473]
-A PREROUTING -j LOG
-A PREROUTING -i wlan0 -p tcp -m tcp --dport 80 -j REDIRECT --to-ports 3128
-A POSTROUTING -j LOG
-A POSTROUTING -o eth0 -j MASQUERADE
-A OUTPUT -j LOG
-A OUTPUT -o lo -p tcp -m tcp --dport 80 -j REDIRECT --to-ports 3128
COMMIT
# Completed on Wed Feb  5 18:05:20 2020
# Warning: iptables-legacy tables present, use iptables-legacy-save to see them

For clarity, here the command i use to filter for dns query hits:
tail -f /var/log/messages |grep -wi --color  -w 'UDP.*DPT=53'

Update 2
Bind 9 was blocking the dns querys. even stoped. Guess is not a regular service. I changed bind9 settings to allow dns querys from anyplace.
Now i got hits like this on the log, for port 53:
Feb  5 18:36:43 MyLinuxBox kernel: [11771.211903] IN=wlan0 OUT= MAC=b8:27:eb:35:e4:5b:48:43:7c:04:7e:55:08:00 SRC=192.168.42.19 DST=192.168.42.1 LEN=59 TOS=0x00 PREC=0x00 TTL=255 ID=43761 PROTO=UDP SPT=63906 DPT=5

It seams the dns query pass through the linux-box, from wlan0 to eth0, as is supposed too, but the response doesn't reach the client, resulting in a dns query timeout.
It is possible bind9 is still messing with the query.
Comment: Which of your network interfaces is the external one (the one with a public IP)? If you are testing on the same machine as the router, the `PREROUTING` chain will never be hit.
Comment: The eth0 has the public ip. Squid runs o a pc that as the 2 interfaces and routes traffic through him. The linux box should work as an hotspot.
Comment: Your WiFi clients are using Bind9 as their `DNS` server (the `DHCP` server provides the configuration). Therefore you need to set `allow-recursion { localhost; 192.168.42.0/24; };` in the `options` section of Bind's config and keep it running. If everything passes through Bind, there is no need to accept `DNS` traffic in the `FORWARD` chain.
Answer: Your iptables nat table should look like this:
-A OUTPUT -o lo -p tcp -m tcp --dport 80 -j REDIRECT --to-ports 3128
-A PREROUTING -i wlan0 -p tcp -m tcp --dport 80 -j REDIRECT --to-ports 3128
-A POSTROUTING -o eth0 -j MASQUERADE

This way both the web traffic from the wireless network and the machine itself will be sent to Squid. No masquerading is needed when sending packets to the wlan0 interface.
With a working Squid you can also delete the rule:
-A FORWARD -p tcp -m tcp --dport 80 -j ACCEPT

in the filter table.
Edit: Your DNS resolution problem comes from the restrictive FORWARD policy you have. At first you might start by allowing all outgoing traffic and the return packets:
-A FORWARD -m conntrack --ctstate ESTABLISHED,RELATED -j ACCEPT
-A FORWARD -o eth0 -j ACCEPT

and only when you know what kind of services you need, replace the second rule with more specific ones, e.g.:
-A FORWARD -o eth0 -p icmp -m icmp --icmp-type echo-request -m comment --comment ping -j ACCEPT
-A FORWARD -o eth0 -p udp -m udp --dport 53 -m comment --comment DNS -j ACCEPT
-A FORWARD -o eth0 -p tcp -m tcp --dport 53 -m comment --comment DNS -j ACCEPT
-A FORWARD -o eth0 -p tcp -m multiport --dports 25,465,587 -m comment --comment SMTP -j ACCEPT
-A FORWARD -o eth0 -p tcp -m multiport --dports 110,995 -m comment --comment POP3 -j ACCEPT
-A FORWARD -o eth0 -p tcp -m multiport --dports 143,993 -m comment --comment IMAP -j ACCEPT

Comment: can't put it to work with this configuration too. Squid is blocking the way, with access denied. Yet, if i send the traffic to port 3128, by setting proxy manually, it works.
Comment: Sorry, the `OUTPUT` rule I gave previously causes a redirection loop. It should be fixed now (with the `-o lo` option).
Comment: It works, but dns query won't pass througth.I can only get sites by ip.
Comment: Yes, the devices on your WiFi network must be allowed to query a DNS server (port 53 of both udp and tcp), unless you install a `DNS` resolver like **unbound** on the router. I edited the answer with some details.
Comment: I clear all rules, changed every default to accept, add the rules you mention. Still didn't work, so i stop the squid but still not working. I added log to every rule and then look for UDP packets on port 53. I only see hits coming from the localhost. i will update the post
Comment: Made some progress. Somehow the bind9 service was blocking requests that come from the wlan0. When i set allow dns query from any place, requests start to appear on eth0, coming from wlan0. But still got dns timeout, so i thing the responses is not going back to the sender.. i will post details on question again.
Answer: If your Squid proxy runs on your gateway, you would need the following iptables to redirect the traffic on HTTP/HTTPS to Squid (note here ens33 is the NIC facing the local network), see complete tutorial at https://docs.diladele.com/tutorials/transparent_proxy_debian/final.html.
# redirect HTTP to locally installed Squid instance
-A PREROUTING -i ens33 -p tcp --dport 80 -j REDIRECT --to-ports 3126

# redirect HTTPS to locally installed Squid instance
-A PREROUTING -i ens33 -p tcp --dport 443 -j REDIRECT --to-ports 3127

If you need to run your Squid on a separate box than your router/gateway, you'd need to use policy based routing, see tutorial at https://docs.diladele.com/tutorials/policy_based_routing_squid/index.html.