Using Java 8 lambda expressions, filter a List of objects by property of an inner list

Question: I'm new to Java lambda expressions and have been struggling with the following problem:
I'm trying to filter the following List of Activity objects down to the single Activity with the most recent start time:
{
     Name: "activity1"
     Id: "abc-123"
     Fields: [
          { key: "startTime", value: "2018-08-24T12:00:01" },
          { key: "foo", value: "bar" },
          { key: "baz", value: "zoop" }
     ]
},
{
     Name: "activity2"
     Id: "def-456"
     Fields: [
          { key: "bat", value: "zap" },
          { key: "startTime", value: "2018-08-23T12:00:01" },
          { key: "cat", value: "dog" }
     ]
},
{
     Name: "activity3"
     Id: "ghi-789"
     Fields: [
          { key: "flim", value: "flam" },
          { key: "boop", value: "bop" },
          { key: "startTime", value: "2018-08-22T12:00:01" }
     ]
}

Basically, each object has an inner List of fields that appear in no particular order, and I want to filter the parent collection down to one item based on the "startTime" field with the max date.
For the example data, the goal would be to return only the object with the name "activity1". Note that the Field objects appear in no particular order in my data. Also, if the startTime for an activity matches that of another activity, the code should take whichever item comes first in the collection.
Assuming that the activities and fields are in a List, and there are getters/setters on my Activity class, this is what I have started with, but I know it's not correct:
activities().stream().filter(activity ->
    activity.getFields().stream()
            .filter(field -> field.getKey().equals("startTime"))
            .max((field1, field2) -> {
                Date date1 = Date.from(Instant.parse(field1.getValue()));
                Date date2 = Date.from(Instant.parse(field2.getValue()));
                return date1.compareTo(date2);
            }).isPresent()
).findAny().get();

Any help or an example of how I should approach this would be really appreciated. Thanks!

Edit-1:
The actual Activity and Field classes I'm working with are being retrieved from a 3rd party library, and are not of my own design. Here's an idea of what they look like:
public class Activity {
     private String id;
     private String name;
     private List<Field> fields;

     public String getId() {
         return id;
     }

     public void setId(String id) {
         this.id = id;
     }

     public String getName() {
         return name;
     }

     public void setName(String name) {
         this.name = name;
     }

     public List<Field> getFields() {
         return fields;
     }

     public void setFields(List<Field> fields) {
         this.fields = fields;
     }
 }

public class Field {
     private String key;
     private String value;

     public String getKey() {
         return key;
     }

     public void setKey(String key) {
         this.key = key;
     }

     public String getValue() {
         return value;
     }

     public void setValue(String value) {
         this.value = value;
     }
 }

Comment: Can you provide your classes of list items?
Comment: Since your date-time strings don't have an offset, `Instant.parse` hardly works. Use `LocalDateTime.parse`. And don't use the long outdated and poorly designed `Date` class at all, there's no reason to since both `LocalDateTime` and `Instant` are directly comparable.
Comment: @EmreSavcı I've added edit-1 to the question, with an example. Thanks!
Answer: You probably want to define a function that extracts the date, and then use Collectors.maxBy. For instance:
// Somewhere in your class:
Instant startDate(Activity activity) {
  return activity.getFields()
    .stream()
    .filter(field -> field.getKey().equals("startTime"))
    .map(field -> Instant.parse(field.getValue()))
    .findAny()
    .get();
}

// .. and then to use it:
Optional<Activity> maxStartDateActivity = activities()
    .stream()
    .max(Comparator.comparing(MyClass::startDate));

Side note: you probably shouldn't be representing your data the way you are. It's worth the trouble to define an interface for your Activity values that lets you do things like get the parsed start time as a single call that can then be used in a stream pipeline. Doing so will help decouple how activities are represented from what you're trying to do with them, which will make your overall program easier to read, easier to add more features to, and easier to change in the future.
Comment: The difference is mainly that I forgot `Stream.max` takes a comparator. Updated with both edits, thanks!
Comment: Thanks for the input @jacobm. I didn't mention in the original question that the data structure is not of my choosing, it's due to some results I'm retrieving from a 3rd party library. Sorry, I should have included that detail. In either case, I was able to create a `startDate` function, and it works the same using your approach. The function is just not part of the `Activity` class. Thanks!


Help solving: Normal Distribution problem without using the table OR with a given std

Question: For a recent history test, scores follow the normal distribution with a mean of 70 points. 80% of the students scored below 88 points. What is the standard deviation of the scores?
I have done a lot of research into the question and eventually broke down and used the standard table. The answer I got through that was a std of 21.387.
I know I need to use the z score formula (x-mean)/std = z   but I am searching for two of those variables and would need the z score at least to find the std.
A push in the right direction would be greatly appreciated.
Comment: Why can't you use the standard table?
Comment: I'm not entirely sure. The professor told us up front that the table with not be given on exams and therefore shouldn't be used on outside assignments to give us better practice. It's ridiculous, I know. But he says it's possible to do.
Comment: Then the professor would be the person to ask about this.
Answer: The only way I can see how to answer this question with pencil and paper only--no tables, no calculators--is to have the quantiles of the standard normal distribution memorized:
$$\begin{align*} \Pr[Z \le 0.8] &\approx 0.842 \\ \Pr[Z \le 0.9] &\approx 1.282 \\ \Pr[Z \le 0.95] &\approx 1.645 \\ \Pr[Z \le 0.975] &\approx 1.96 \\ \Pr[Z \le 0.995] &\approx 2.576. \end{align*}$$  Most statisticians should be familiar with all but the first one.  The first one is not commonly encountered.
One can also remember the 68-95-99.7 rule (also called the "empirical rule"):  $$\begin{align*} \Pr[-1 \le Z \le 1] &\approx 0.68, \\ \Pr[-2 \le Z \le 2] &\approx 0.95, \\ \Pr[-3 \le Z \le 3] &\approx 0.997.\end{align*}$$
But if none of these memorized values apply, then I don't see how it is reasonable to do the calculation with sufficient precision to be meaningful.  If you have a calculator such as a TI-83, you can use the invNorm() and normalcdf() functions.


Horizontal scrolling background-image with jQuery

Question: Here's my attempt at the jQuery:
$(document).ready(function(){
$('#bg').animate({ backgroundPosition: '320px 0px'}, 10000, 'linear');
});

Here's CSS for bg:
#bg {
    background: url('scribbles.png') repeat-x 320px 0px;
    position: absolute;
    top: 0;
    bottom: 0;
    left: 0;
    right: 0;
}

Here's the HTML:

I want the background image to move across the screen slowly. Any suggestions?
Thanks!
Answer: Is the image to continue scrolling forever? If not, the the following may be a good starting point:
$('#bg').animate({ backgroundPosition: '+=100% 0px'}, 10000, 'linear');
If it is to repeat forever, then consider the following solution with a recursive call-back:
var animateBackground = function()
{
    $('#bg').animate
    (
        {
            backgroundPosition: '-=100px 0px'
        },
        10000,
        'linear',
        function()
        {
            animateBackground(); // recursive call back
        }
    )
};

$( // short-hand for "$(document).ready"
    function()
    {
        animateBackground(); // initial call that starts everything off
    }
);

Comment: actually, it scrolls along nicely, but it has moved by background image down the sceen by a hundred pixels or so. Any idea why?
Comment: I forgot that background position works like this:

`background-position: [horizontal] [vertical]`

The answer has been updated.
Answer: Background position is same for the both css & jquery cases. They should be different. Unless why would it move? Set a previous position in css & give the final position in the jquery part of the code. It'd work!


Rotação de imagem em java

Question: Estou precisando de um algoritmo para girar uma imagem em java. Na internet eu achei um algoritmo promissor neste link, e dei uma arrumada nele e adaptei para utilizar ângulos em graus. Ficou assim:
public static BufferedImage rotateImage(BufferedImage rotateImage, double angle) {
    AffineTransform tx = new AffineTransform();
    tx.rotate(Math.toRadians(angle), rotateImage.getWidth() / 2.0, rotateImage.getHeight() / 2.0);

    double ytrans = tx.transform(new Point2D.Double(0.0, 0.0), null).getY();
    double xtrans = tx.transform(new Point2D.Double(0, rotateImage.getHeight()), null).getX();

    AffineTransform translationTransform = new AffineTransform();
    translationTransform.translate(-xtrans, -ytrans);
    tx.preConcatenate(translationTransform);

    return new AffineTransformOp(tx, AffineTransformOp.TYPE_BILINEAR).filter(rotateImage, null);
}

No entanto, este método não funciona corretamente para ângulos maiores do que 90 graus (e provavelmente para menores que -90 também). Resolvi isso com uma gambiarra que depende de uma imagem intermediária:
public static BufferedImage rotateImage(BufferedImage rotateImage, double angle) {
    angle %= 360;
    if (angle < 0) angle += 360;
    int quadrants = (int) angle / 90;
    double restAngle = angle % 90;
    if (restAngle < 0) restAngle += 90;

    AffineTransform tx = new AffineTransform();
    tx.rotate(Math.toRadians(restAngle), rotateImage.getWidth() / 2.0, rotateImage.getHeight() / 2.0);

    double ytrans = tx.transform(new Point2D.Double(0.0, 0.0), null).getY();
    double xtrans = tx.transform(new Point2D.Double(0, rotateImage.getHeight()), null).getX();

    AffineTransform translationTransform = new AffineTransform();
    translationTransform.translate(-xtrans, -ytrans);
    tx.preConcatenate(translationTransform);

    BufferedImage b2 = new AffineTransformOp(tx, AffineTransformOp.TYPE_BILINEAR).filter(rotateImage, null);

    AffineTransform fix = AffineTransform.getQuadrantRotateInstance(
            quadrants, b2.getWidth() / 2.0, b2.getHeight() / 2.0);
    return new AffineTransformOp(fix, AffineTransformOp.TYPE_BILINEAR).filter(b2, null);
}

Funcionou. No entanto, eu sei que é possível resolver isso sem precisar de uma imagem intermediária. Já quebrei bastante a cabeça e não consigo fazer isso funcionar de um jeito melhor, só tive imagens cortadas e deformadas como resultado. Alguém tem uma ideia?
Edit: Achei um bug: Ele não funciona corretamente para imagens que não forem quadradas, e eu não sei porquê.
Answer: A resposta do @RodrigodeBonaSartor funciona perfeitamente e a grande sacada é que o algoritmo faz um ajuste considerando os cantos da imagem que são "escondidos" após a rotação, como forma a evitar que a imagem seja truncada nessas regiões.
O gráfico da própria resposta do Rodrigo ajuda bastante nesse entendimento, mas vou tentar explicar com um pouco mais de detalhes. Vou usar como exemplo a seguinte imagem (quadrada) da Lenna:

A rotação é uma operação que simplesmente transforma cada pixel da imagem segundo um ângulo dado (veja essa página da Wikipedia para mais informações). Ao se aplicar uma rotação de 45º sem fazer a translação de ajuste, o resultado faz com que o canto superior esquerdo (coordenada (0,0)) e o canto inferior esquerdo (coordenada (0, height)) sejam posicionados fora da área original da imagem, produzindo o seguinte resultado:

Um código como...
Point2D ponto = tx.transform(new Point2D.Double(rotateImage.getWidth(), 0.0), null);

...simplesmente mapeia o ponto original (no exemplo acima, (width, 0)) segundo a transformação descrita por tx (que poderia ter uma série de transformações concatenadas - o resultado seria o mapeamento final após todas as transformações sobre o ponto). Note que no código dessa pergunta isso é equivalente a calcular a rotação do ponto (x' = x * cosseno(angulo) - y * seno(angulo), y' = x * seno(angulo) + y * cosseno(angulo)), uma vez que a transformação tx inclui apenas uma rotação.
Com um ângulo de 45º, a rotação de cada canto da imagem produz os seguintes resultados:
Point2D.Double(0.0, 0.0) => Point2D.Double[127.99999999999999, -53.01933598375615]
Point2D.Double(rotateImage.getWidth(), 0.0) => Point2D.Double[309.01933598375615, 128.0]
Point2D.Double(0.0, rotateImage.getHeight()) => Point2D.Double[-53.019335983756164, 128.00000000000003]
Point2D.Double(rotateImage.getWidth(), rotateImage.getHeight()) => Point2D.Double[128.0, 309.01933598375615]

Como na linguagem Java o sistema de coordenadas tem origem (coordenada (0,0)) no canto superior esquerdo, pode-se observar que os cantos "escondidos" (isto é, fora da área original da imagem por estarem à esquerda ou acima da origem) tem coordenadas mapeadas em valor negativo. Isso vale tanto para o eixo X como para o eixo Y.
Assim, o que o algoritmo proposto pelo Rodrigo faz é simplesmente verificar quais cantos estão "escondidos" (de acordo com o intervalo do ângulo dado) e calcular a diferença de translação por eixo de forma a "mover" os cantos excondidos para o limite visível da imagem (isto é, para próximo da origem (0,0)). É uma sacada simples, e que funciona.
Porém, para tornar o código um pouco mais enxuto (e, potencialmente, mais simples de entender), basta calcular a rotação para os quatro cantos da imagem e escolher, dentre os resultados, os menores valores negativos para os eixos X e Y.
Eis um exemplo:
public static BufferedImage rotateImage(BufferedImage rotateImage, double angle) {
    AffineTransform tx = new AffineTransform();
    tx.rotate(Math.toRadians(angle), rotateImage.getWidth() / 2.0, rotateImage.getHeight() / 2.0);

    // Rotaciona as coordenadas dos cantos da imagem
    Point2D[] aCorners = new Point2D[4];
    aCorners[0] = tx.transform(new Point2D.Double(0.0, 0.0), null);
    aCorners[1] = tx.transform(new Point2D.Double(rotateImage.getWidth(), 0.0), null);
    aCorners[2] = tx.transform(new Point2D.Double(0.0, rotateImage.getHeight()), null);
    aCorners[3] = tx.transform(new Point2D.Double(rotateImage.getWidth(), rotateImage.getHeight()), null);

    // Obtém o valor de translação para cada eixo com um canto "escondido"
    double dTransX = 0;
    double dTransY = 0;
    for(int i = 0; i < 4; i++) {
        if(aCorners[i].getX() < 0 && aCorners[i].getX() < dTransX)
            dTransX = aCorners[i].getX();
        if(aCorners[i].getY() < 0 && aCorners[i].getY() < dTransY)
            dTransY = aCorners[i].getY();
    }

    // Aplica a translação para evitar cortes na imagem
    AffineTransform translationTransform = new AffineTransform();
    translationTransform.translate(-dTransX, -dTransY);
    tx.preConcatenate(translationTransform);

    return new AffineTransformOp(tx, AffineTransformOp.TYPE_BILINEAR).filter(rotateImage, null);
}

Tal como na resposta do Rodrigo, esse algoritmo também ajusta corretamente a imagem para evitar recortes:

No caso da imagem de exemplo anterior, é fácil notar que o montante necessário de translação é o mesmo tanto no eixo X como no eixo Y (53 pixels aproximadamente), mas isso se deve ao ângulo utilizado (45º) e ao fato da imagem ser quadrada. Como o algoritmo proposto faz a verificação dos montantes individualmente por eixo, funciona corretamente para outros exemplos, como abaixo (rotação de 260º e imagem retangular - note que há dois valores negatívos para o eixo Y, mas o algoritmo escolhe o menor = -104 aproximadamente):

Point2D.Double(0.0, 0.0) => Point2D.Double[123.93876331951267, 328.9969705899713]
Point2D.Double(rotateImage.getWidth(), 0.0) => Point2D.Double[54.47949225274054, -64.92613061491193]
Point2D.Double(0.0, rotateImage.getHeight()) => Point2D.Double[345.52050774725944, 289.926130614912]
Point2D.Double(rotateImage.getWidth(), rotateImage.getHeight()) => Point2D.Double[276.06123668048735, -103.99697058997123]

Translação necessária: em X = [0.0], em Y = [-103.99697058997123]
Comment: Ok, gostei da resposta. Infelizmente eu não posso aceitar as duas respostas, então vou pensar um pouquinho para decidir qual eu aceito.
Comment: Valeu. Eu só ofereci uma explicação adicional. A ideia original do algoritmo é do @RodrigodeBonaSartor. :)
Answer: Pelo que eu testei aqui, assim funciona:
public static BufferedImage rotateImage(BufferedImage rotateImage, double angle) {
    angle %= 360;
    if (angle < 0) angle += 360;

    AffineTransform tx = new AffineTransform();
    tx.rotate(Math.toRadians(angle), rotateImage.getWidth() / 2.0, rotateImage.getHeight() / 2.0);

    double ytrans = 0;
    double xtrans = 0;
    if( angle <= 90 ){
        xtrans = tx.transform(new Point2D.Double(0, rotateImage.getHeight()), null).getX();
        ytrans = tx.transform(new Point2D.Double(0.0, 0.0), null).getY();
    }
    else if( angle <= 180 ){
        xtrans = tx.transform(new Point2D.Double(rotateImage.getWidth(), rotateImage.getHeight()), null).getX();
        ytrans = tx.transform(new Point2D.Double(0, rotateImage.getHeight()), null).getY();
    }
    else if( angle <= 270 ){
        xtrans = tx.transform(new Point2D.Double(rotateImage.getWidth(), 0), null).getX();
        ytrans = tx.transform(new Point2D.Double(rotateImage.getWidth(), rotateImage.getHeight()), null).getY();
    }
    else{
        xtrans = tx.transform(new Point2D.Double(0, 0), null).getX();
        ytrans = tx.transform(new Point2D.Double(rotateImage.getWidth(), 0), null).getY();
    }

    AffineTransform translationTransform = new AffineTransform();
    translationTransform.translate(-xtrans, -ytrans);
    tx.preConcatenate(translationTransform);

    return new AffineTransformOp(tx, AffineTransformOp.TYPE_BILINEAR).filter(rotateImage, null);
}

Segue uma imagem para ajudar a entender a lógica:
Comment: Ok, gostei da resposta. Infelizmente eu não posso aceitar as duas respostas, então vou pensar um pouquinho para decidir qual eu aceito.

Rotação de imagem em java


Get field value and label for a content type using REST API

Question: I need to create a REST API endpoint with GET operation in Drupal 8. The API should return all fields of a given content type. Right now I am only able to fetch the title.
Also, I am not supposed to use the REST Export option in views module but the expected output is same as what we get using the Views REST Export option.
This is the code I have written for the get() method and right now only title is being displayed. I want to output the remaining fields as well.
<code>public function get() {
    if (!$this->currentUser->hasPermission('access content')) {
        throw new AccessDeniedHttpException();
    }

    $query = \Drupal::entityQuery('node')
      ->condition('status', 1)
      ->condition('type', 'schemes_funds_nav')->execute();

    $nodes = \Drupal\node\Entity\Node::loadMultiple($query);

    foreach ($nodes as $entity) {
        $result[$entity->id()] = $entity->title->value;
    }

    $response = new ResourceResponse($result);
    $response->addCacheableDependency($result);

    return $response;
}
</code>
Any help is highly appreciated. Thanks in advance.
Answer: In the foreach you add just title so it's normal to have only title displayed:
you should populate your array result with the values from your entity, something like:
<code>  foreach ($nodes as $entity) {
    $result[] = [
      'nid' => $entity->id(),
      'title' => $entity->title->value,
      'FIELD_NAME_1' => $entity->FIELD_NAME_1->getValue(),
      'FIELD_NAME_2' => $entity->FIELD_NAME_2->getValue(),
       // And so on with other fields.
    ];
  }
</code>
Comment: Any help on getting this output without using [$entity->id()] in the result array. because of  [$entity->id()], I am getting nid as well in the output.
Comment: you can do it by removing it check my update:


How to add custom slider for textfield

Question: I read:

Best way for including javascript/jQuery OnLoad in EVERY page on my site
How to get jquery working on Drupal 7 - for Newbies
How to include jQuery UI on a page without PHP?

I'm using jQuery Update module. Tried different versions of jQuery.
I have theme tao_test (that is subtheme of Tao). In tao_test.info I added:
scripts[] = scripts/ranger.js

And inside of this js file is this code:
(function($){

    Drupal.behaviors.tao_test = {
      attach: function(context, settings) {

          $("input#edit-field-range-test").before("

");

          $(".range-slider").slider({
              range: "min",
              value: 1,
              step: 1000,
              min: 0,
              max: 5000000,
              slide: function( event, ui ) {
                  $( "input#edit-field-range-test" ).val( ui.value );
              }
          });

      }
    };
}(jQuery));

Now problems:

When logged in as admin, slider kinda works, but looks strange:

There is no knob and overall it looks graphically broken. Also it only works if I set "CDN jQuery and jQuery UI" in jquery_update settings to some value.

When watching as anonymous user, I'm getting in firebugs console:

TypeError: $(...).slider is not a function

What I'm doing wrong?
Added: Oh, I realized that this slider is supposed to be unusable without theming. However the problem with anonymous user is still current.
Answer: It appears that:
function THEME_preprocess_html(&$variables) {
    drupal_add_library('system', 'ui.slider');
}

is needed for query_ui to be available for anonymous users on every page.

How to add custom slider for textfield


If $\lim_{x \to x_0} f(x) = f(x_0)$, as $x \to x_0$, can we always say $f(x) \to f(x_0)$

Question: Assuming $$\lim_{x \to x_0} f(x) = f(x_0)$$
As $x$ approaches $x_0\ $i.e. $(x\to x_0)$, can we always say $f(x)$ approaches $f(x_0)\ $ i.e. $(f(x)\to f(x_0))$? From what I understand, this is the motivation for the $\epsilon$-$\delta$ definition of limit.
The $\epsilon-\delta$ definition states that- $\forall \epsilon$, $\exists \delta$, such that:
$0<|x-x_0|<\delta\Rightarrow|f(x)-L|<\epsilon$. For any value of $\epsilon$ if I can provide a $\delta$, then $L$ is the limit of $f(x)$ at $x_0$.
Approach is apparently an informal idea, and not what the limit defines. So the idea of $f(x)$ getting closer to $f(x_0)$, as $x$ gets closer to $x_0$ is inaccurate and not always true.
Update: The statement apparently is true, when $f(x)$ is continuous at $x_0$. Though I have been unable to find a general proof for it yet.
Comment: Why this wouldn't be true for constant functions?
Comment: sure you can. $\epsilon - \delta$ definition doesn't fail in your example. The word approach may imply some kind of motion in some sense, but if you think about it there isn't any better approach of $a$ than itself.
Comment: @CélioAugusto, this is just my understanding but, if $f(x)=a$, then for any value of $x$, $f(x)$ is always constant. If I'm trying to find its limit at a point $x_0$, as $x$ approaches $x_0$, I cannot say $f(x)$ approaches $a$.
Comment: @alphaomega, if I don't think of approach as some kind of change occurring, I can probably say that. Thanks.
Comment: Also as long as $\epsilon-\delta$ is satisfied, can we say for any function there is an approach?
Comment: You could, but remember that "approach" is just an intuitive concept, not a formal one.
Comment: Yes, but I've thought about limits in terms of approach until now.
Answer: Yes. If $\lim_{h\to 0}f(x_0+h)=L$ then for every $\varepsilon>0$ there exists $\delta>0$ such that whenever $|h|<\delta$ then $|f(x_0+h)-L|<\varepsilon$.
This means, for the same value of $\varepsilon$ and $\delta$, if $|x-x_0|<\delta$ then, setting $h=x-x_0$ we have $|f(x)-L|=|f(x_0+h)-L|<\varepsilon$, so the definition of $f(x)\to L$ as $x\to x_0$ is satisfied.
Note that this is actually slightly stronger than saying $f(x)\to L$ as $x\to x_0$, as $\lim_{h\to 0}f(x_0+h)=L$ also implies that $f(x_0)=L$, whereas in the definition of "$f(x)\to L$ as $x\to x_0$" it doesn't matter whether $f(x_0)$ even exists (or, if it does, what value it takes).
Comment: How does $\lim_{h\to 0}f(x_0+h)=L$, mean $L=f(x_0)$? $f(x_0)$ could be undefined. Also does $x \to x_0$ always imply $f(x) \to L$? You have me confused.
Comment: @KraZZ the point is that in the definition of $f(x)\to L$ as $x\to x_0$ we generally take the extra condition that $x$ is not allowed to actually equal $x_0$ (as in the definition you give above).


Example of entity-within-entity subform processing

Question: Suppose that, in Drupal 7, EntityA includes one or more instances of EntityB.
Is there an example of building the create/edit form for EntityA that includes one or more edit forms for EntityB, and that can ajax in a new create form for a new EntityB?
Comment: You might want to have a look at [Node Connect](http://drupal.org/project/nodeconnect), it's not AJAX but will get you the workflow you're after.
Answer: It's not really that hard. You would want to create form elements that use the #tree attribute, to make sure the data for instances of EntityB will be well structured.
In order to make add another functionality you need to:

Keep track of the count in the $form_state.
if (empty($form_state['count'])) {
  $form_state['count'] = 2;
}

Add a button somewhere to add another.
$form['entity_b']['add_another'] = array(
  '#type' => 'submit',
  '#value' => t('Add another'),
  '#limit_validation_errors' => array(),
  '#submit' => array('add_another_submit_handler'),
);

function add_another_submit_handler(&$form, &$form_state) {
  // Add one to our counter and rebuild the form
  $form_state['count'] += 1;
  $form_state['rebuild'] = TRUE;
}

The above will work with no JavaScript. If you want to Ajax-enable it, you need to do some work on the wrapper.

Add a CSS ID that is used from the Ajax callback.
$form['entity_b'] = array(
  '#tree' => TRUE,
  '#attributes' => array('id' => array('add-another')),
  // ...
);

Add the #ajax element.
 // ...
 '#ajax' =>  array(
  'callback' => 'add_another_ajax',
  'wrapper' => 'add-another',
  'effect' => 'fade',
 ),
 // ...

Add the Ajax callback function.
function add_another_ajax($form, &$form_state) {
  return $form['entity_b'];
}

Comment: This is a great description of how to manage the count with ajax. What about the bit that loads and shows the edit and create forms for EntityB?
Comment: @JoeBeuckman All you really need to do, is too loop through `range(0, $form_state['count'])` and create the form for the entity B, maybe through some wrapper function or directly in the form, depending on how you want to mange it.
Comment: I'm taking this approach and have run into another problem: http://drupal.stackexchange.com/questions/25381/how-to-manage-ajax-in-nested-forms
Answer: See my approach at rszrama's sandbox: Commerce Inline Product Form.
I am planning to promote it to a full project this week. I am going to call it "Entity Inline Form" or "Inline Entity Form", since it can support any entity type.
Basically, you're either doing what that module does (having custom built forms for the embedded entity B), or using Subform to embed the original add / edit form of entity B. A third option would be to have a dialog in which the add / edit form is displayed (so that it's not embedded into the main form at all), and JS code that notes the final entity ids after the dialog is closed.


Do I have to enable authentication in Mongo for a self-managed server?

Question: Up to this point, my server was a development environment. As such, authentication was off in MongoDb.
It's now time to get into production. I looked up how to do authentication. However, given the following circumstances:

No remote connection is allowed. I use a tunnel to administer it.
There will be 4 apps running, all controlled by us
We have a number of automatic db scripts in place for deployment
This is our own server

Does it actually make any sense turning on security, other than looking good to management? Especially considering that:

We would create one user per app
Each server would need the password in the source code to connect to the db
Some of the admin scripts are run automatically. So, those scripts would also include the password

I guess having to go around and fish DB passwords might make the life of an intruder a little harder (they will need to figure out where the apps are, and that might take 10 minutes or so, rather than just dumping mongo's DB). But is this one really the only real reason?
Comment: You know there are more methods of authentication, other than by username and password? You might want to look into [x.509 certificate, or kerberos, or ldap authentication](https://docs.mongodb.com/manual/core/authentication/)
Comment: When you say "no remote connection is allowed" - how do your 4 apps connect? I hope you're not intending to run them all on the same box in production?
Answer: I expect that this developer also thought that enabling authentication would not be needed. Look at how well that worked out for them...
And that is just one example of many thousands unsecured Mongo instances found online.

Does it actually make any sense turning on security, other than looking good to management?

I'm sure that your manager is a firm believer in "there is is no such thing as bad publicity" but making headlines because your lack of basic security measures exposed all your company's records and customer data is usually a "career limiting move".
That is a polite way of saying that not taking basic security measures is considered negligent and incompetent.
Comment: Your points are totally fair. But... the database _isn't_ online, and regardless of this, the passwords would still be easy to find. I guess it will still raise the bar...
Comment: The thing with bad security practices is that it makes life *slightly* easier during initial development.  Correcting for them after you have a nearly finished product is immensely more difficult than taking security into account early on. The second thing is that now you may run your whole stack on a single server, you may not always do so. `-|-` Your remark: *"the password in the source code"* makes me cringe too, you should have a configuration file that you load where you can change options and settings without modifying your code...
Comment: It *is* in a config file. But the difference is pointless. It's in the clear somewhere, as it needs to be. My problem is that while I agree with all of your points (regardless of the way you are putting them across), I am asking if there is a REAL reason why a db server that is NOT listening to a TCP port should be password protected -- especially when the password would need to be in the clear SOMEWHERE in the config files used to running the client programs


Given an array of ints, return true if the sequence of numbers 1, 2, 3 appears in the array somewhere

Question: Basically i'm trying to return true, if 1, 2, 3 in that specific order are in the array, i cant work out how to do that though.
Ive already tried using some for loops and if statements but i dont know if that actually is the best way to do it
public static boolean arrayOneTwoThree(int[] nums) {
    for(int i = 0; i < nums.length - 2; i++) {
       if(nums[i] == 1 && nums[i + 1] == 2 && nums[i + i] == 3){
           return true;
       }
   }
   return false;
}

it only returns true if 1s 2s and 3s are in the array i want it to only return true if 1,2,3 are in they specific orderenter image description here
Comment: This literally returns `true` for every single array, you do not do anything with `result`.  Please post the actual code you used, this is not the same code.
Comment: Consider using only one loop with end condition `i < nums.length-2`. In the loop, check the values of `nums[i] `, `nums[i+1] ` and `nums[i+2] ` .
Comment: This equals `public boolean arrayOneTwoThree(int[] nums){ return true; }`
Answer: public boolean arrayOneTwoThree(int[] nums) {

    // variables declaration.
    boolean result = false;
    int counter = 0,index = 0;
    int arr[] = {1,2,3};

     // base condition check. like array length should not be less than 3.
    if(nums.length < 3){
         return result;
    }

    //for loop for iterating over array and finding desired pattern
    for(int i = 0; i < nums.length; i++){

        //pattern found in array
        if(counter == 3){
          result = true;
          return result;
        }

        if(nums[i] == arr[counter]){
             index++;
             counter++;
        }
        else if(counter != 0){
             i = index-1;
             counter = 0;
        }
    }
    if (counter == 3) {
        result = true;
        return result;
    }
    return result;
}

Complexity of this solution is O(n).
Answer: There are quite a few things wrong with you current code.

You return true for every single case.
You create a result variable and never do anything with it.
You create three loops when you can use just a single one.
You never actually check to see if the values are next to each other.

For the first problem, we will return true only when the 1, 2, 3 are next to each other, and return false; for EVERY other case.  This is done by using return false; after the loop.
For the next problem, result is not needed, you do not actually need to count anything, so remove this.
For the third issue, combine all the loops into a single loop.  However, we will need to loop to the condition of nums.length - 2 instead of the length because we will comparing 3 values at the same time, and we do not want to get an ArrayOutOfBoundsException.
Finally, to check to see if all the values are next to each other, simply compare the values at the current Array index, the next one, and the index two values over with 1, 2 and 3 respectively.
This would look like if (nums[i] == 1 && nums[i + 1] == 2 && nums[i + 2] == 3).  If this condition is true, we will return true immediately.
Here is how the code will look with all these fixes:
public static void main(String[] args) {
    // test cases
    int [] arr = {1, 1 ,2, 1, 2, 3};
    System.out.println(arrayOneTwoThree(arr));

    int [] arr2 = {3, 2, 3};
    System.out.println(arrayOneTwoThree(arr2));
}

public static boolean arrayOneTwoThree(int[] nums) {
    for(int i = 0; i < nums.length - 2; i++) {
       if(nums[i] == 1 && nums[i + 1] == 2 && nums[i + 2] == 3){
           return true;
       }
   }
   return false;
}

Test Runs:

true
false

Note:  Remove static from the arrayOneTwoThree(int [] nums) if you need to use it in non-static context, I used static to test it from my main.
Answer: Please try this solution and you may able to solve all your test cases
public static boolean find123(List<Integer> numbers) {

boolean isOneExist=false;
boolean isTwoExist=false;
boolean isThreeExist=false;
                        for(Integer n1:numbers)
            {
                    if(n1==1)
                {
                        isOneExist=true;
                }
                if(n1==2 && isOneExist)
                {
                    isTwoExist=true;
                }
                if(n1==3 && isTwoExist)
                {
                    isThreeExist=true;
                }

            }

            if(isOneExist && isTwoExist && isThreeExist)
            {
            return true;
            }

        return false;
    }


What is the best way to do a search in a large file?

Question: I'm looking to apply a KMP (or similar) search to a large file (> 4GB).
I'm expecting this to give me problems though.I can't copy it all to memory because there isn't enough space there.
My question is, what is the best way to go about doing this search? Should I simply create a FILE* and do the search directly in the file, should I copy blocks (say 4k) to memory and search those, or something else completely?
Answer: If you are using a platform that supports it, you can use mmap().
Pagination of the file is also a possibility, but remember to keep the buffer as large as possible to reduce the IO overhead, and to be careful between boundaries of two pages (suppose a string is matching, but is splitted by the page boundary)
Alternatively, I suggest you to build an index of some sort, and use the index to restrict the search. KMP search is not particularly efficient. This of course depends on the nature of your file, how it gets created, etc.
Comment: +1 for using mmap. It should just be noted that you will still need to mmap in blocks, on 32 bits machines, because the address space is not enough.
Comment: Yes, mmap (at least on OSX, but it's stardard BSD) accepts size_t len and off_t offset. The OP needs to check if these types hold 64 bit values, otherwise he will never be able to address past the 4 GiB limit.
Answer: For the file access I would recommend to use memory mapped file to avoid the data copy. It is trivial on unix machines. You may have to split the file mapping into smaller blocks if it can't be allocated in one block. I can provide some code if you are interested.
For the search I would recommend using the Boyer More search algorithm.
Answer: Searching directly in the file would be very slow, using buffering will give much better performance. But note that your buffer has to be bigger than what you search (SearchLength), of course, and you have to refresh the buffer when being SearchLength bytes before its end.
Answer: Best approach is to read it in blocks and search that. You should make the block size a parameter, so you can experiment with what gives the best performance.
However, it is usually more efficient to try and index the file in some way so that you don't have to linearly search through the whole file. For example, KMP is a string searching algorithm - are you just looking for occuences of a word? Then you can just create a hash table (on disk) of the words and their location in the file and have very efficient search.
Comment: Well I'm trying to do a search for all occurrences of a hex string in a user supplied file. Since the file will be different everytime and since I'm searching for hex values, hash tables seem like they wouldn't be worth the cost.
Comment: True, that's why I said "usually" :) Every search problem is somewhat different. I would advocate just paging, but again, always use parameters so you can tune the settings for your particular setup.


Custom DialogPreference not showing ImageView properly

Question: I have a custom DialogPreference:
    <com.myapp.MyPreferenceDialog
        android:key="dialog_key"
        android:title="Test MyDialogPreference"
        android:positiveButtonText="ok"
        android:negativeButtonText="cancel"
        />

The dialog code is the following:
class MyDialogPreference extends DialogPreference
{

    public MyDialogPreference( Context context, AttributeSet attrs )
    {
        super(context, attrs);
        setDialogLayoutResource( R.layout.test );
    }
}

The layout xml code is the following:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <ImageView
        android:id="@+id/imageView2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:srcCompat="@drawable/image" />
</LinearLayout>

When i launch the app settings and touch "Test MyDialogPreference", a dialog is shown but the imageview does not display any image. I know how to fix this programmatically (just override onBindDialogView() and set the ImageView image resource to its drawable), but i would like to understand why i have to do it programmatically.
Comment: have you tried changing `LinearLayout` size to `wrap_content`?
Comment: @Pawel Yes, that does not fix it.
Answer: add following to your build.gradle file
defaultConfig {
 vectorDrawables.useSupportLibrary = true
}

Comment: Not working. I am not using vector drawables for this example.
Comment: try using android:src="" instead of app:srccompat
Comment: Using android:src= works! It seems that DialogPreference does not work with app:srcCompat. Thank you.
Comment: Glad that it helped...u can accept the answer then!!
Comment: Yes, but you should update it, because the solution was android:src="..." and not updating the gradle file.


didSelectRowAtIndexPath not pushing new view

Question: I'm having a problem with didSelectRowAtIndexPath I know there are other queries on this point but none seem to solve my problem. Basically the tableview loads but it does't do anything when a cell is clicked, i.e it doesn;t push the new xib. Any help would be great.
@implementation ViewController
@synthesize TableViewControl;
@synthesize tableList;

#pragma mark - View lifecycle

- (void)viewDidLoad
{
    [super viewDidLoad];

    self.title = @"The Bird Watching App";
    // Do any additional setup after loading the view, typically from a nib.

    tableList = [[NSMutableArray alloc] initWithObjects:@"Map",@"My Profile",@"Bird Info", nil];

    TableViewControl.dataSource = self;
    TableViewControl.delegate = self;

}

-(void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{

    [tableView deselectRowAtIndexPath:indexPath animated:YES];

    if ([[ tableList objectAtIndex:indexPath.row] isEqual:@"Map"])
    {
        Map *map = [[Map alloc] initWithNibName:@"Map" bundle:nil];
        [self.navigationController pushViewController:map animated:YES];

    }

    else if ([[ tableList objectAtIndex:indexPath.row] isEqual:@"My Profile"])
    {
        MyProfile *myprofile = [[MyProfile alloc] initWithNibName:@"My Profile" bundle:nil];
        [self.navigationController pushViewController:myprofile animated:YES];
    }

    else if ([[ tableList objectAtIndex:indexPath.row] isEqual:@"Bird Info"])
    {
        BirdInfo *birdinfo = [[BirdInfo alloc] initWithNibName:@"Bird Info" bundle:nil];
        [self.navigationController pushViewController:birdinfo animated:YES];
    }

 }

@end

Answer: The isEqual: method on NSString performs pointer comparison and not comparison between the actual contents of the string. Your if statements need to use isEqualToString: to make the proper comparison.
-(void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{

    [tableView deselectRowAtIndexPath:indexPath animated:YES];

    if ([[ tableList objectAtIndex:indexPath.row] isEqualToString:@"Map"])
    {
        Map *map = [[Map alloc] initWithNibName:@"Map" bundle:nil];
        [self.navigationController pushViewController:map animated:YES];

    }

    else if ([[ tableList objectAtIndex:indexPath.row] isEqualToString:@"My Profile"])
    {
        MyProfile *myprofile = [[MyProfile alloc] initWithNibName:@"My Profile" bundle:nil];
        [self.navigationController pushViewController:myprofile animated:YES];
    }

    else if ([[ tableList objectAtIndex:indexPath.row] isEqualToString:@"Bird Info"])
    {
        BirdInfo *birdinfo = [[BirdInfo alloc] initWithNibName:@"Bird Info" bundle:nil];
        [self.navigationController pushViewController:birdinfo animated:YES];
    }

 }

Comment: Thank you for your reply Mark. Just tried that but still the same problem :(
Comment: Can you confirm that `self.navigationController` isn't nil?
Comment: I copied what you posted so all the self.navigationController are followed by pushViewController..
Comment: I'm very new to ios development so I am sorry if you meant something else
Comment: That's okay. In this case `self.navigationController` points to the `UINavigationController` object that holds this current view controller and allows you to "push" on a new view controller. If this property is nil, then no navigation controller exists and asking it push a new view controller will do nothing. Add `NSLog(@"%@", self.navigationController);` to `-viewDidLoad` and see what it logs. If it's nil, we have our culprit.
Comment: I decided to start this project again using a storyboard. Thanks for your help it was really useful.


How to get test results of multiple test classes ,after all tests run using Junit

Question: I have 5 test classes and each testclasses include 2 @Test
example:
<code>    class1:
    @Test
    public void c1_test1(){
    //...
    }
    @Test
    public void c1_test2(){
    //...
    }

    class2:
    @Test
    public void c2_test1(){
    //...
    }
    @Test
    public void c2_test2(){
    //...
    }
    ...
</code>
I want to get tests result after all Test Suite(All test classes) run
Such As:
Class1: c1_test1 : failed
Class1: c1_test2 : success
Class2: c2_test1 : failed
class2: c2_test2 : success
tried RunListener class but I got results after test level,but how to get results after suite level. Is it possible in Junit?
Comment: What do you use for running your tests?
Comment: I use maven, junit and selenium. I want to get test results and send email whole tests result. @BorisvanKatwijk
Comment: Do you want to code a reporter or use one? If it's the latter, maybe  https://stackoverflow.com/questions/2846493/is-there-a-decent-html-junit-report-plugin-for-maven could be of help.
Answer: Its possible to implement a listener in a way that it will store the results in some "predefined" file or series of files so that after all the tests will be done the result will appear in a file.
Another option is to use the output of the build tool, for example in maven, when you work with surefire/failsafe plugins it produces a "surefire-reports" where the same information is accessible. If you use it - check the "target" folder.


How to combine multiple rows into one row with different column in sql server

Question: I have table like this i want to get only one row for given budget id
Here is the data.
INPUT:

OUTPUT:
Comment: You can group the data by BudgetId, but you need to decide how you want to summarize the other columns if you want to display the other columns.  Because you're trying to display the "Initiator" for both 10002 rows in the same cell, how should the "Null" and "2" be handled?  You need to summarize them with an aggregate function like `MIN` or `AVG`
Answer: Use Min/Max aggregate
SELECT MontlyBugetId,
       Min(Initiator),Min(Stage1),Min(Stage2),Min(Stage3),Min(Stage4),Min(StatusId)
FROM   yourtable
GROUP  BY MontlyBugetId

If this is your table data, then you need to update the records instead of insert to avoid duplicate records


Bash Command Substitution Giving Weird Inconsistent Output

Question: For some reasons not relevant to this question, I am running a Java server in a bash script not directly but via command substitution under a separate sub-shell, and in the background. The intent is for the subcommand to return the process id of the Java server as its standard output. The fragement in question is as follows:
launch_daemon()
{
  /bin/bash <<EOF
     $JAVA_HOME/bin/java $JAVA_OPTS -jar $JAR_FILE daemon $PWD/config/cl.yml <&- &
     pid=\$!
     echo \${pid} > $PID_FILE
     echo \${pid}
EOF
}

daemon_pid=$(launch_daemon)

echo ${daemon_pid} > check.out

The Java daemon in question prints to standard error and quits if there is a problem in initialization, otherwise it closes standard out and standard err and continues on its way. Later in the script (not shown) I do a check to make sure the server process is running. Now on to the problem.
Whenever I check the $PID_FILE above, it contains the correct process id on one line.
But when I check the file check.out, it sometimes contains the correct id, other times it contains the process id repeated twice on the same line separated by a space charcater as in:
34056 34056

I am using the variable $daemon_pid in the script above later on in the script to check if the server is running, so if it contains the pid repeated twice this totally throws off the test and it incorrectly thinks the server is not running. Fiddling with the script on my server box running CentOS Linux by putting in more echo statements etc. seems to flip the behavior back to the correct one of $daemon_pid containing the process id just once, but if I think that has fixed it and check in this script to my source code repo and do a build and deploy again, I start seeing the same bad behavior.
For now I have fixed this by assuming that $daemon_pid could be bad and passing it through awk as follows:
mypid=$(echo ${daemon_pid} | awk '{ gsub(" +.*",""); print $0 }')

Then $mypid always contains the correct process id and things are fine, but needless to say I'd like to understand why it behaves the way it does. And before you ask, I have looked and looked but the Java server in question does NOT print its process id to its standard out before closing standard out.
Would really appreciate expert input.
Comment: The same behavior is observed when java is replaced with a simple script that does nothing, so the java is irrelevant.  I suspect this is a bug in bash, related to the sub-bash not flushing an output stream, but I cannot see the details yet.
Comment: Is there any service monitoring. If so, it might kick off another one concurrently. Obviously I'm just trying to rule something out rather then answering.
Comment: I'm a little leery of <&- in context.
Comment: I can't see any way you could get a repeated pid like that unless the java daemon is printing it. You say you've checked that by code inspection; have you tried adding `>/dev/null` to the java line to make absolutely sure?
Comment: Programs are entitled to have a standard input that's open. If you want it to be harmless, redirect it from `/dev/null`, rather than closing it.  Similarly for unwanted standard output and standard error (though I recommend against throwing away error messages).
Comment: @user2456600: there is certainly a race condition in your launch_daemon function, since if the `/bin/bash` terminates before your java server manages to detach itself, then the java server will be killed. That wouldn't result in a duplicated pid, though; it would result in a meaningless pid. Anyway, I believe you've tested it, but I don't see that it would hurt to try adding `>/dev/null` and verify.
Comment: I stand by 'standard I/O channels should be open'.  However, it probably isn't the cause of the trouble you're seeing.  My best guess is that PID_FILE is not always set; you might get the double PID in `daemon_pid` when it is not set. I emphasize 'guess'; we can't see enough code to know whether that could happen, or how that could happen.
Comment: Yes; so my guess is that somehow the `launch_daemon` function is echoing the PID twice. I'm not convinced that $PID_FILE unset is relevant; it gives a syntax error — consider that withdrawn. Is there any danger that the `bash` inside the function could be echoing the PID of the background process automatically? Seems a little unlikely, but we're all clutching at straws here. Have you run the code with `set -x` sprinkled around liberally, so you can see what `bash` thinks it is doing? You'll probably need a `set -x` in the function, and also in the script that's run by `bash` from the function.
Comment: @user2456600: bash doesn't print that message unless it's interactive, and it doesn't consider itself interactive if stdin is redirected (as with `<<EOF`) unless you specify `-i`. Anyway, if it does print that message, it goes to `stderr` afaik. But it's still a possibility.
Comment: @user2456600: I don't believe the claim about a shell not exiting. It's easy enough to test. (An interactive shell will ask for verification about exiting while there are unterminated jobs. But that's quite different.)
Comment: @WilliamPursell: Good point, and a very helpful observation. But I'm pretty sure it's a race condition, not a failure to flush. See my answer for the gories.
Comment: As an aside, the Awk hack is needlessly complicated. `${daemon_pid%% *}` will expand to the value with anything after the first space trimmed.
Comment: How are you guarding against concurrent runs? Perhaps upstart is executing your script too?
Comment: Good question, it is not really protected against that. The build and deploy is via our own Jenkins box and the server is our own, so we're in control so I'm pretty sure that's not happening. Plus I have seen the same behavior, though not always and not consistently, when running the start.sh script that contains the above fragment directly from the command line on the box being deployed to.
Comment: Also, we're not running via upstart as a standard daemon. We have an ansible playbook based process for deployment and running that just runs the start.sh script. In a previous step in the ansible playbook, it kills any existing running daemon.
Comment: There is monitoring, but at least currently there is no automatic restart. We're just at the beginning of the project so we might add that later but right now that's not an issue. Plus the repeated process id is the same, with a restart or concurrent running issue you'd think they would be two different pid's, although the mechanism would still have to be explained.
Comment: I got that from some blog post while cobbling this together, to my understanding that closes standard input for the Java daemon. I'm not sure now that is really required but why would it be hurting? The Java daemon is not reading from standard input anyway, I'm guessing if it were to attempt that at some point it would throw an exception for trying to read from a closed file. But I'm not seeing that.
Comment: @rici it's not just code inspection, I have run the same daemon many times from the command line directly on the same box, it only prints to standard error if it has an initialization error and then quits, if no error it doesn't print anything to standard out or standard error, closes them both and continues running. Of course it continues logging to a file based on its configuration, but standard out and standard error are closed.
Comment: @rici but still a useful suggestion, I will try that just to make 100% sure.
Comment: @Jonathan But this is a daemon process that does NOT read anything from standard in, or write to standard out or error once successfully initialized. So I'm doing those on purpose, and like I said the daemon process is working perfectly fine.
Comment: @rici good point hadn't thought of that race condition. That doesn't really seem to be the issue though. I'm wondering if it is bash printing the pid of the Java daemon being run in the background. For example if I run "ls &" bash prints the pid before the ls output.
Comment: @Jonathan earlier in the script, before the definition of launch_daemon I have "PID_FILE=web_api.PID". In any case, like I said that web_api.PID file always exists and has the right contents. It's the variable $daemon_pid that has the repeated value.
Comment: @rici I copied this scheme from http://barelyenough.org/blog/2005/03/java-daemon/ (not all the way though) which claims that a shell won't exit while it has programs attached to its standard out and standard err, so wouldn't that mean there is no race condition? In any  =case I am in the middle of trying your suggestion because I guess standard err is not being redirected so if that blog post is true that would still serve the purpose of avoid that race condition. Trying your suggestion takes some time though because I want to do it properly all the way through Jenkins and ansible deployment.
Comment: @rici redirecting standard out /dev/null in line running the Java daemon didn't fix it :-( Still get the process id double printed in the check.out file (which comes from $daemon_pid) but fine in web_api.PID (which comes directly from $pid in the launch_daemon function)
Comment: Thanks @triplee for increasing my bash/awk fu
Answer: Following the hint by @WilliamPursell, I tracked this down in the bash source code. I honestly don't know whether it is a bug or not; all I can say is that it seems like an unfortunate interaction with a questionable use case.
TL;DR: You can fix the problem by removing <&- from the script.
Closing stdin is at best questionable, not just for the reason mentioned by @JonathanLeffler ("Programs are entitled to have a standard input that's open.") but more importantly because stdin is being used by the bash process itself and closing it in the background causes a race condition.
In order to see what's going on, consider the following rather odd script, which might be called Duff's Bash Device, except that I'm not sure that even Duff would approve: (also, as presented, it's not that useful. But someone somewhere has used it in some hack. Or, if not, they will now that they see it.)
/bin/bash <<EOF
if (($1<8)); then head -n-$1 > /dev/null; fi
echo eight
echo seven
echo six
echo five
echo four
echo three
echo two
echo one
EOF

For this to work, bash and head both have to be prepared to share stdin, including sharing the file position. That means that bash needs to make sure that it flushes its read buffer (or not buffer), and head needs to make sure that it seeks back to the end of the part of the input which it uses.
(The hack only works because bash handles here-documents by copying them into a temporary file. If it used a pipe, it wouldn't be possible for head to seek backwards.)
Now, what would have happened if head had run in the background? The answer is, "just about anything is possible", because bash and head are racing to read from the same file descriptor. Running head in the background would be a really bad idea, even worse than the original hack which is at least predictable.
Now, let's go back to the actual program at hand, simplified to its essentials:
/bin/bash <<EOF
cmd <&- &
echo \$!
EOF

Line 2 of this program (cmd <&- &) forks off a separate process (to run in the background). In that process, it closes stdin and then invokes cmd.
Meanwhile, the foreground process continues reading commands from stdin (its stdin fd hasn't been closed, so that's fine), which causes it to execute the echo command.
Now here's the rub: bash knows that it needs to share stdin, so it can't just close stdin. It needs to make sure that stdin's file position is pointing to the right place, even though it may have actually read ahead a buffer's worth of input. So just before it closes stdin, it seeks backwards to the end of the current command line. [1]
If that seek happens before the foreground bash executes echo, then there is no problem. And if it happens after the foreground bash is done with the here-document, also no problem. But what if it happens while the echo is working? In that case, after the echo is done, bash will reread the echo command because stdin has been rewound, and the echo will be executed again.
And that's precisely what is happening in the OP. Sometimes, the background seek completes at just the wrong time, and causes echo \${pid} to be executed twice. In fact, it also causes echo \${pid} > $PID_FILE to execute twice, but that line is idempotent; had it been echo \${pid} >> $PID_FILE, the double execution would have been visible.
So the solution is simple: remove <&- from the server start-up line, and optionally replace it with </dev/null if you want to make sure the server can't read from stdin.

Notes:
Note 1: For those more familiar with bash source code and its expected behaviour than I am, I believe that the seek and close takes place at the end of case r_close_this: in function do_redirection_internal in redir.c, at approximately line 1093:
check_bash_input (redirector);
close_buffered_fd (redirector);

The first call does the lseek and the second one does the close. I saw the behaviour using strace -f and then searched the code for a plausible looking lseek, but I didn't go to the trouble of verifying in a debugger.
Comment: Wow, for some reason I moved on after doing my workaround but was never notified of this answer. This is most comprehensive, thanks for digging so deep :-)
Comment: Now that I come back after some time to check my question picked up another useful tip on simplifying my awk hack too. I hang my head in shame.


What's the (official) motivation for requiring cars to have at least one liter of fuel post-race?

Question: I've read in the news about the rule regarding fuel left

Vettel was disqualified from second place after his car was found to have less than the mandatory one litre of fuel required for post-race testing. [...]
stewards said that the article in the F1 rules relevant to the case "unequivocally call for a remaining amount of one litre [of fuel] and does not allow any exceptions under which circumstances or for what reasons" less was available.
Therefore, the reason for the lack of fuel [a leak] was deemed "not relevant" to the disqualification, and the team's case was rejected.

What's the official motivation for requiring at least one liter of fuel left in the tank?
Answer: It allows for sufficient samples of fuel to be taken after the race to confirm that it complies with regulations.
From an autosport.com article:

The FIA needs that much fuel because initially it provides three samples, one that is tested by the FIA fuel specialist at the track, one that goes to an independent lab, and one that is retained by the team. Some is also kept should a more detailed form of testing be required later.


How to use peek () with filter () java8?

Question: I have a LinkedHashMap.
sorted:{0=[1, 2], 5=[4, 3], 1=[2, 0, 3], 2=[4, 0, 1], 3=[4, 5, 1], 4=[5, 2, 3]}

I tried filtering the values of each key based on its size. For example for the entry 2=[4, 0, 1], I need to filter the values such that the key should only have values whose size is greater than or equal to (>=) it
Consider 2=[4, 1]: since 0 has only two elements, we remove it. 4 and 1 have three elements which is equal to the size of 2, so we keep it.
The final output should be :
nodes_withHighDegreee :{0=[1, 2], 5=[4, 3], 1=[2, 3], 2=[4, 1], 3=[4, 1], 4=[2, 3]}

I tried :
Map<Integer, List<Integer>> nodes_withHighDegree = sorted.entrySet().stream()
                .peek(e -> e.getValue().filter((a,b)-> map.get(a).size() >= map.get(b).size()))
                .collect(LinkedHashMap::new, (m, e) -> m.put(e.getKey(), e.getValue()), (m0, m1) -> m0.putAll(m1));
System.out.println("After sort" + nodes_withHighDegree);

How to use filter function here?
Comment: @tobias_k I don't think you understood what is asked here. Maybe OP can clarify but what I understood was: let's take `4=[5, 2, 3]` which is of length `3` as example. in the initial map `5` is associated with a list of length `2` so we remove it (`2<3`); then `2` is associated with a list of length `3` so we keep it (`3>=3`), etc.
Comment: @tobias_k I am guessing the count should be based on the initial map.
Comment: Note that a single pass will not be enough. Since the number of elements in a key can decrease, you will have to check again.
Comment: @Tunaki You are right, I did not understand it, but your interpretation seems to make sense.
Comment: @tobias_k For the key 5, the values will be retained 5: [4, 3 ] because the size of key " 4 " is 3. Since it has three values  5, 2, 3. (see initial mapping) Similarly, size of  key "3"  is also 3. both sizes are greater than size of  key "5". (since the size of key "5" is two  having two values 4,3) .
Answer: You could do it quite simply using Map.replaceAll. Assuming the data is inside a LinkedHashMap called sorted:
Map<Integer, List<Integer>> filtered = new LinkedHashMap<>(sorted);
filtered.replaceAll((k, v) -> v.stream()
                               .filter(i -> sorted.get(i).size() >= v.size())
                               .collect(Collectors.toList()));

Output:
{0=[1, 2], 5=[4, 3], 1=[2, 3], 2=[4, 1], 3=[4, 1], 4=[2, 3]}

This code creates a copy of the map to hold the filtered instance. Then it replaces each value by filtering it and only keeping the integers whose count have a greater value than the current count.

In your current approach, you are using peek to modify the value which is a bad practice. Quoting from its API note:

This method exists mainly to support debugging, where you want to see the elements as they flow past a certain point in a pipeline.
Comment: @priya Oracle has published [online turials](https://docs.oracle.com/javase/tutorial/collections/streams/index.html) that you can follow. Playing with the API and reading the documentation itself is also great for learning.
Comment: @priya: [Are](http://docs.oracle.com/javase/8/docs/api/java/util/stream/package-summary.html#package.description) [you](http://docs.oracle.com/javase/8/docs/api/?java/util/stream/Stream.html) [kidding](http://docs.oracle.com/javase/tutorial/collections/streams/)?
Comment: Thanks a lot:)   Is there any tutorial to learn stream functions? I couldn't find a proper material.


Constant function defined by an integral

Question: (a) Use the derivative to prove that the function
$$F(x) = \int_1^x \frac{1}{1+t^2}dt+\int_0^{1/x} \frac{1}{1+t^2}dt$$
is constant in the interval $(0, +\infty)$.
(b) Determine the constant value of the function in part (a) and then interpret (a) as a
identity involving the arctangent function.
I thought about using the fundamental theorem of calculus to calculate the derivative and prove that it is equal to $0$, but the result was not necessarily $0$. For letter (b) I have no idea, honestly. Can anybody help me?
Comment: Please show your work. We can point out why you didn't get $0$ for (a) if you show your work.
Comment: The second integral needs you to also differentiate the 1/x in the upper limit. This is basically the chain rule, although it's sometimes called the Liebniz rule in this context.
Comment: I considered $$F'(x)=\frac{1}{1+x^2}+\frac{1}{1+(1/x)^2} = \frac{1}{1+x^ 2}+\frac{x^2}{x^2+1}=1$$
Comment: Regarding question (b). Use the substitution $t = tan(u)$.
Comment: $$\int_0^{1/x} \frac{dt}{1+t^2}\overset{t=\frac1s}{=}\int_x^\infty\frac{ds}{1+s^2}\,\Rightarrow\,F(x)=\int_1^\infty\frac{dt}{1+t^2}$$
Comment: Similar to @Svyatoslav but $t\mapsto 1/t$ for the first integral gives
$$F(x)=\int_{1/x}^1\frac{1}{1+t^2}\ dt+\int_0^{1/x}\frac{1}{1+t^2}\ dt=\int_0^1\frac{1}{1+t^2}\ dt$$
which is constant.
Answer: (a)
We have with the help of Leibniz integral rule :
$$
F'(x) = \frac{1}{1+x^2} - \frac{1}{x^2}\frac{1}{1+1/x^2} = 0
$$
$\Rightarrow$ $F$ is constant function.
(b)
Let's choose $x = 1$ in order to kill the first integral, hence :
$$
F(x) = F(1) = \left.\int_0^1 \frac{\mathrm{d}t}{1+t^2} = \arctan(t)\right|_0^1 = \frac{\pi}{4} - 0 = \frac{\pi}{4}
$$


Relationship between the number of divisors of two numbers if their GCD is not equal to 1 (not co-prime)

Question: If d(n) is a function that gives the number of divisors (positive) of n, then is there any relation between d(n1), d(n2), d(n1*n2) and GCD(n1,n2)? I was wondering if any mathematical formula existed that related the above elements.
Comment: A similar question but does not explain the case where `GCD!=1` https://math.stackexchange.com/questions/1198639/is-there-any-formula-for-number-of-divisors-of-a-times-b
Comment: It's a slightly different question, but note that $d(n_1)d(n_2) = d(\mathop{\rm lcm}(n_1,n_2))d(\gcd(n_1,n_2))$.
Comment: But no: given values for $d(n_1)$, $d(n_2)$, and $\gcd(n_1,n_2)$, there can be multiple possible values for $d(n_1n_2)$. An example is $d(n_1)=4$, $d(n_2)=4$, and $\gcd(n_1,n_2)=2$: each of $n_1$ and $n_2$ must be either $8$ or $2p$ for an odd prime $p$, but their product could be either $64$ or $16p$ or $4p^2$ or $4pp'$, which have $7$ or $8$ or $9$ or $12$ divisors, respectively.
Answer: If the prime factorization of $n_1$ and $n_2$ are
$$ n_1 = 2^{a_0}3^{a_1}5^{a_2}7^{a_3}\cdots
\qquad\qquad
n_2 = 2^{b_0}3^{b_1}5^{b_2}7^{b_3}\cdots $$
then the divisor counts are the products
$$ d(n_1) = \prod_{i\ge 0}(a_i+1) \qquad
d(n_2) = \prod_{i\ge 0}(b_i+1) \qquad
d(\gcd(n_1,n_2)) = \prod_{i\ge 0}\min(a_i+1,b_i+1) $$
(each of these products is finite because only finitely many of the $a_i$s and $b_i$s can be nonzero).
This does not seem to lead to any particularly useful relation between the divisor counts. We cannot choose $d(n_1)$, $d(n_2)$ and $d(\gcd(n_1,n_2))$ completely independently from each other, but there's still a lot of freedom.


Can I create non-default EntityReferenceSelection?

Question: I have the following EntityReferenceSelection plugin:
/**
 * Provides an entity reference selection for my_entity.
 *
 * @EntityReferenceSelection(
 *   id = "extra:my_entity",
 *   label = "...",
 *   entity_types = {
 *     "my_entity"
 *   },
 *   group = "extra",
 *   weight = 1
 * )
 */
class MyEntityExtraSelection extends DefaultSelection {

  protected function getAllowedIds() {
    return [...];
  }

  protected function buildEntityQuery($match = NULL, $match_operator = 'CONTAINS') {
    $query = parent::buildEntityQuery($match, $match_operator);
    $query->condition('id', $this->getAllowedIds(), 'IN');
    return $query;
  }

  public function validateReferenceableNewEntities(array $entities) {
    $entities = parent::validateReferenceableNewEntities($entities);
    $allowed = $this->getAllowedIds();
    return array_filter($entities, function ($entity) {
      return in_array($entity->id(), $allowed);
    });
  }

}

I'd like to call it extra:my_entity because I don't want this filtering to occur by default, every time I use it, only when I refer to it using the 'handler' => 'extra' setting explicitely.
But the core plugin manager gives these errors:
Warning: uasort() expects parameter 1 to be array, null given in Drupal\Core\Entity\EntityReferenceSelection\SelectionPluginManager->getPluginId() (line 65 of core/lib/Drupal/Core/Entity/EntityReferenceSelection/SelectionPluginManager.php).
Warning: end() expects parameter 1 to be array, null given in Drupal\Core\Entity\EntityReferenceSelection\SelectionPluginManager->getPluginId() (line 66 of core/lib/Drupal/Core/Entity/EntityReferenceSelection/SelectionPluginManager.php).
Warning: key() expects parameter 1 to be array, null given in Drupal\Core\Entity\EntityReferenceSelection\SelectionPluginManager->getPluginId() (line 67 of core/lib/Drupal/Core/Entity/EntityReferenceSelection/SelectionPluginManager.php).

Answer: As commented, you should not need to provide a deriver for a single entity reference selection plugin. A random plugin ID like extra_my_entity should work. The only condition is that you define the (in this case
irrelevant) group property with the same value:
/**
 * Provides an entity reference selection for my_entity.
 *
 * @EntityReferenceSelection(
 *   id = "extra_my_entity",
 *   label = "...",
 *   entity_types = {
 *     "my_entity"
 *   },
 *   group = "extra_my_entity",
 *   weight = 1
 * )
 */
class MyEntityExtraSelection extends DefaultSelection {

See Entity reference selection plugins break when not following a weird ID pattern.
When you extend DefaultSelection then also extend the schema:
config/schema/mymodule.schema.yml
entity_reference_selection.extra_my_entity
  type: entity_reference_selection.default
  label: '...'

Starting a new group
A group in contrast consists of multiple plugin classes. A base class that derives the installed entity types using for example the base plugin ID extra. On installation Drupal will scan the entity types and create for each entity a plugin ID: extra:[entity_type]. You can override the base class by using this plugin ID syntax and the group extra. These group members then don't need to define a deriver, like the core plugins you've seen overriding default:*.
It's not a good idea to combine base and group member in one class, because then deriving the plugin ID as base ends up in a:b:b and other unpredicted things can happen.
Comment: I can see that it *shouldn't* but it unfortunately *does*. At least right now for me, I tried all your suggestions, and the only one that doesn't lead to the error is what I described. Deriver included. As your link is about 5 years old, something might have happened since...
Comment: I mean, yes, I can name both id and group the same (actually, if I don't, if I use `a:b` for the id and `a` for the group, the core function will assemble `a:b:b` at some point) but 1. Deriver 2. the key named label are both necessary.
Comment: Incidentally, this is how I found out. I started to print out the variables in the plugin manager and suddenly realized that all other plugins have the deriver set but mine. When I added it, it no longer gave the error but it still didn't run my selection code. Then I saw that it still used `PhpSelector`. Then, finally, I saw the source code comment saying that `label` is required. :-)
Comment: You can read in the issue what happened in the last 5 years. They didn't find a solution yet, but they documented the quirks. When using the deriver syntax `a:b` you normally want to override derived plugins. If this is not your intention then don't use this syntax and you shouldn't need to worry about the deriver class. You can solve this naming pattern problem without deriver.
Comment: Sorry, that's what I say. No matter what happened during these 5 years, right now, in front of me, if I remove the deriver, it blows up. If I include it, it works. That's how it is, even if it shouldn't. :-) (Yes, I ended up using the non-colon version. Still. D9.0.7, just for reference.)
Comment: OK, I've added the schema and now my answer contains all details of what is working on my computer as a custom entity reference selection plugin, in contrast to your solution based on core plugins deriving installed entity types. So we have two different working solutions now :-)
Answer: Update
I needed it again, this time already in Drupal 10. The old tricks are no longer necessary, it works without the deriver and the extra key now.
Earlier
Finally, after some investigation, two required items never documented:

unlike the core EntityReferenceSelection plugins that, for some reason, get away without it, you have to provide

deriver = "Drupal\Core\Entity\Plugin\Derivative\DefaultSelectionDeriver"

in the plugin annotation.

It might be completely unnecessary in your case but you have to make sure your custom entity type has an entity_key named label. If it doesn't, core will use PhpSelector instead of your selector, forcedly.
Comment: @Clive, generating the plugin via drush works because it follows this weird plugin/group naming scheme described here https://www.drupal.org/project/drupal/issues/2649712
Comment: It might be that the core plugins you've seen override existing default plugins derived from installed entity types. The question is whether you need a derived plugin at all. Try to not use the `:`  syntax which separates base plugin ID and derivative ID.
Comment: @4k4 From experience that doesn't work - you need the namespace or whatever it'd be called to make the plugin work
Comment: @Clive for `default:*` or a custom plugin ID?
Comment: Pretty sure for custom @4k4 - OP's problem sounds identical to one I vaguely remember having last year and coming to the same conclusion
Comment: @Clive, can't confirm that, for testing I've created a plugin with `drush gen`, which suggests `mymodule_advanced_myentity_selection` as plugin ID, and the plugin seems to work.
Comment: Interesting, thanks for the link @4k4


How do I solve this? java.io.IOException: Stream Closed

Question: Please help me. I'm working with my stop word code, using FileInputStream but I got an error that says java.io.IOException: Stream Closed. I was following a tutorial in YouTube: https://www.youtube.com/watch?v=ckQUlI7x7hI and his code run without error.
Here is the code:
    import java.io.FileInputStream;
    import java.util.ArrayList;

    public class DataCleaning {

    public static void main(String[] args) {

        ArrayList sw = new ArrayList<>();

        try{
            FileInputStream x = new FileInputStream("/Users/Dan/Desktop/DATA/stopwords.txt");

            byte b[] = new byte[x.available()];
            x.read(b);
                x.close();

                String data[] = new String(b).split("\n");

            for(int i = 0; i < data.length; i++)
            {
                sw.add(data[i].trim());
            }
             FileInputStream xx = new FileInputStream("/Users/Dan/Desktop/DATA/cleandata.txt");

            byte bb[] = new byte[x.available()];
            xx.read(bb);
                xx.close();

                String dataa[] = new String(bb).split("\n");

                for(int i = 0; i < dataa.length; i++)

            {
                String file = "";
                String s[] = dataa[i].split("\\s");
                for(int j = 0; j < s.length; i++)
                {
                    if(sw.contains(s[j].trim().toLowerCase()))
                    {
                        file=file + s[j] + " ";
                    }

                }
                System.err.println(file + "\n");
            }

        } catch(Exception a){
            a.printStackTrace();
        }

    }

}

and this is the error when i run the code:
java.io.IOException: Stream Closed
at java.io.FileInputStream.available(Native Method)
at datacleaning.DataCleaning.main(DataCleaning.java:28)

Comment: How is your code different from his code? How is your data different from his data?
Comment: Hint: `x.available()` <-- is `x` open at that point?
Answer: You must fix your bb initialization:
byte bb[] = new byte[xx.available()];

xx.available() instead of x.available()


yii-user-management profile 404 error

Question: I have finally got to the admin area of yii user management but now I click on the profile link
profile/profile/view/id/1 and there is a 404 error
Once again any help appreciated.
Answer: Placing this in the config/main.php resolved the issue.
<code>'modules'=>array(
    'registration' => array(),
    'avatar' => array(),
    'role' => array(),
    'messages' => array(),
    'usergroup' => array(),
    'membership' => array(),
    'profile' => array(),
    'friendship' => array(),
    'user' => array()
     ),
</code>
This activates the module parts.(I am new at yii)

yii-user-management profile 404 error


Passando um valor do body de um modal para uma função PHP

Question: Boa noite,
Estou com o seguinte problema, tenho um modal dentro de um sistema, o que eu preciso fazer e não estou conseguindo é passar os valores que eu leio no javascript para uma função do PHP para no caso "deletar" o que eu necessito, se alguém puder por favor me ajudar, eu sou novo em desenvolvimento e estou lutando para conseguir continuar aprendendo, muito obrigado mesmo, segue os códigos que estou utilizando:
Aqui é a minha função:
<?php

    function paraProd($id,$maquina){

            $id = $_POST ['id'];
            $maquina = $_POST ['maquina'];

            //  Declara os valores de sessão globais a uma variável!
            $local = $_SESSION['hostname'];
            $user = $_SESSION['idUsuario'];

            //  Chama função de conexão com banco de dados!

            $conn = DBConnect();

            //  Faz as alterações de UPDATE nas tabelas do banco de dados!

            $sql = "DELETE FROM supervisorio.producao_inj WHERE maquina = '$maquina'";

            if (mysqli_query($conn, $sql)) {
                  echo "Record deleted successfully";
                } else {
                  echo "Error deleting record: " . mysqli_error($conn);
                }

    }

Aqui é o modal da onde eu quero enviar os dados para a função do PHP:
function modalAceita(id,maquina,lote,produto){

            $.ajax({
            url:"functions.php",
            type:'POST',
            data: {id:id,maquina:maquina,lote:lote,produto:produto},
            beforeSend:function(){
                $('#modal4').find('.modal-body').html('Carregando...');
                $('#modal4').modal('show');
            },
            success:function() {
                $('#modal').modal('hide');
                $('#modal4').find('.modal-title').html("INJETORA "+id+"");
                $('#modal4').find('.modal-body').html('
Tem certeza de parar a Produção?

Maquina: '+maquina+'
Produto: '+produto+'
Lote: '+lote+'

<button type="button" class="btn btn-secondary" data-dismiss="modal">Fechar</button>  <button type="button" class="btn btn-primary" onclick="<?php paraProd('+id+','+maquina+');?>" data-dismiss="modal">Salvar mudanças</button>
');
                $('#modal4').modal('show');
            }
        });

}

Tenho certeza que estou fazendo da forma errada, porém não encontrei em lugar algum uma solução, me desculpem se postei da maneira errada tb minha pergunta, porém sou novo nessa jornada, muito obrigado desde já a quem puder me ajudar!
Answer: Único problema que eu vejo é que sua função paraProd() não esta sendo chamada, se é para remover um registro de determinada tabela, ao invés de fazer isso dentro do functions.php você poderia criar um arquivo exclusivo para deletar os registro desta tabela.
ex:
cria um arquivo chamado delete_table.php (ai chama esse arquivo no ajax)
no incio do arquivo faz uma validação de isset
if(isset($_POST['id])){
// aqui vc faz a rotina de deletar o registro ou então chama sua função paraProd()
}


Criar e/ou editar imagem com PHP

Question: É possível editar imagens com PHP?
Por exemplo, colocar marcas d'água, ou até mesmo fazer um "paint" (com outras linguagens juntas tbm, sem ser só PHP).
OBS: gostaria de uma solução sem uso de frameworks.
Comment: Pesquise por [PHP GD](https://pt.stackoverflow.com/search?q=gd+php) e [PHP ImageMagick](https://pt.stackoverflow.com/search?q=imagemagick+php) para mais exemplos.
Answer: Sim, é possível.
Há funções que recortam e redimensionam imagens:
http://php.net/manual/pt_BR/function.imagecrop.php
http://php.net/manual/pt_BR/function.imagecopyresized.php
Mas para tarefas mais específicas, há a biblioteca GD:
http://php.net/manual/pt_BR/ref.image.php
Veja o exemplo da aplicação de marca d`água em uma imagem com GD: http://php.net/manual/en/image.examples.merged-watermark.php
Instalação do GD no seu PHP: http://php.net/manual/en/image.installation.php

O PHP não está limitado a criar apenas saída em HTML. Ele também pode
  ser usado para criar e manipular arquivos de imagem em uma diversidade
  de formatos, incluindo gif, png, jpg, wbmp, e xpm. E ainda mais
  convenietemente, o PHP pode enviar streams de saída de imagem
  diretamente para o browser. Você precisará compilar o PHP com a
  biblioteca GD de imagens de funções para isto funcionar. O PHP e GD
  também podem requerer outras bibliotecas, dependendo dos formatos de
  imagens com os quais você queira trabalhar.
  (Manual do PHP em PT-BR)

Espero ter ajudado.
Comment: Vlw, realmente é oque precisava
Comment: Por favor, marque a resposta como "aceita", @MatheusLopesMarques
Comment: opa, esqueci :P colocado

Criar e/ou editar imagem com PHP


How many data points is statistically significant to determine the probability of an outcome?

Question: With regards to the stock market, I currently have an 82.76% win rate over almost 500 samples. At what point is it enough to give a probability measure? Assuming that I don't change the strategy or selection criteria?
Answer: I'm not sure what you mean by a 'probability measure'. With a random sample of any size $n,$ you can get a 95% confidence interval that is likely to include your
true win rate. The interval gets 'tighter' (shorter) as the sample size increases.
For reasonably large $n$ the confidence interval is of the form
$$\hat p \pm 1.96 \sqrt{\frac{\hat p(1-\hat p)}{n}},$$
where $\hat p$ is the observed win rate (number of wins divided by $n).$
The assumptions for this interval are that the stock purchases are
made independently of each other and using a population and a method of selection that remain essentially the same
throughout the 500 purchases.
For the figures you quote, I get the interval $(0.7945, 0.8607),$ which has
$\hat p = 0.8276$ as its center. It is up to you to decide whether $n = 500$ is enough purchases for this
interval to be short enough for your purposes.


Delphi - TStack Capacity confusion

Question: I have been working with TStack to try and implement a simple Undo/Redo feature in my program. The thought behind this is that as an action is performed the current state of the program is saved - i.e. pushed to the stack. When the user clicks undo the last state of the program is reloaded - i.e. popped from the stack.
The flaw in this idea is that the stack cannot go on growing forever meaning that after a capacity value is reached, the oldest items (those at the bottom of the stack) should be removed as new items are pushed on top.
The TStack object in Delphi contains a Capacity property which I assumed would automatically perform this 'clean-up' but when I overload the stack (e.g. push 11 items to one with capcity 10) the capacity updates to accomodate for more items.
Can anyone offer me any advice on how to use TStack more effectively in this instance? I understand that an alternative would be to use an array structure but I like the prospective ease of using stacks.
Regards
Comment: Perhaps easier to use a queue and an indicator where the last added item in the queue is. That way you'll have redo option to.
Comment: Stack is not going to work for you. Give it up. It's the wrong data structure. You are looking for a deque perhaps. Or just create your own using a fixed length array. Use circular indexing when the array gets full.
Comment: Sorry to say, but the `Capacity` property is, as you found out, automatically increased. his is the same with all `TOrderedList` derived collection objects. There is also no setting to force it not to grow. You may be able to use the `OnNotify` event to check if your own limit is reached, and if so change the content as needed.
Comment: @TomBrunberg  A stack doesn't lend itself to removing from the bottom, so how would you go about enforcing a limit?
Comment: @DavidHeffernan You are right. Better build it from scratch on basis of an array as you suggested.
Comment: Consider using `TList` instead of `TStack`.  `TList` will let you add and remove items from anywhere in the list.
Comment: @Remy going to be inefficient though to be constantly moving the entries array. Circular buffer better.
Comment: Thanks for the suggestions.
Answer: In reality the TStack is powered by a dynamic array.
If you really wanted to you could abuse this fact to have the stack remove items from the bottom, but now you'd be fighting the stack.
I think it's a better idea just to use a circular list.
A simple design might work like this.
type
  TCircularList<T> = class(TObject);
  private
    FStorage: TList<T>;
    FCapacity: cardinal;  //duplication for performance reasons
    FCurrentIndex: cardinal;
  protected
    function GetItem(index: cardinal): T;
    procedure SetItem(index: cardinal; const Value: T);
  public
    constructor Create(Size: cardinal = 10);
    destructor Destroy; override;
    procedure Add(const Item: T);
    property Items[index: cardinal]: T read GetItem write SetItem; default;
  end;

constructor TCircularList<T>.Create(Size: cardinal = 10);
begin
  inherited Create;
  Assert(Size >= 2);
  FStorage:= TList<T>.Create;
  FCapacity:= Size;
  FStorage.Capacity:= Size;
end;

destructor TCircularList<T>.Destroy;
begin
  FStorage.Free;
  inherited;
end;

procedure TCircularList<T>.Add(const Item: T);
begin
  FCurrentIndex:= (FCurrentIndex + 1) mod FCapacity;
  FStorage[FCurrentIndex]:= Item;
end;

function TCircularList<T>.GetItem(index: cardinal): T;
var
  cIndex: cardinal;
begin
  cIndex:= Index mod FCapacity;
  Result:= FStorage[index];
end;

procedure TCircularList<T>.SetItem(index: cardinal; const Value: T);
var
  cIndex: cardinal;
begin
  cIndex:= index mod FCapacity;
  FStorage[index]:= Value;
end;

Obviously you'd need a few more methods like a last and delete method, but I leave that up to you, you should be able to extrapolate from here.
Usability remarks
I have to say that from a UX perspective I think the idea of an undo/redo function sucks.
Why not have a list of snapshots, you that you can go backwards and forwards in time, much like the situation would be if you saved a number of backup files on disk.
The undo function requires you to memorize exactly what you've done the last x steps which does not scale very well.
I also don't understand why there must be a limit, why not allow as much undo/snapshots as memory/disk space permits?

Delphi - TStack Capacity confusion


Logitech g hub script stop as soon as i release

Question: Is it possible to make the code stop running as soon as I release mouse button 1 instead of having to to wait until the loop is finished?
EnablePrimaryMouseButtonEvents(true);
function OnEvent(event, arg)
  if IsKeyLockOn("capslock")then
    if IsMouseButtonPressed(1) then
      repeat
        MoveMouseRelative(-69,99)
        Sleep(133)
        MoveMouseRelative(11,91)
        Sleep(133)
        MoveMouseRelative(-109,84)
        Sleep(133)
        MoveMouseRelative(-86,75)
        Sleep(133)
        MoveMouseRelative(1,64)
        Sleep(133)
        MoveMouseRelative(33,56)
        Sleep(133)
        MoveMouseRelative(58,47)
        Sleep(133)
        MoveMouseRelative(75,39)
        Sleep(133)
        MoveMouseRelative(84,29)
        Sleep(133)
        MoveMouseRelative(83,18)
        Sleep(133)
        MoveMouseRelative(75,20)
        Sleep(133)
        MoveMouseRelative(60,36)
        Sleep(133)
        MoveMouseRelative(33,49)
        Sleep(133)
        MoveMouseRelative(3,55)
        Sleep(133)
        MoveMouseRelative(-32,69)
        Sleep(133)
        MoveMouseRelative(-55,64)
        Sleep(133)
      until not IsMouseButtonPressed(1)
    end
  end
end

so even if i click left mouse I have to wait until the loop finishes so im wondering if theres a way for the program to stop the moment i let go of left mouse
Answer: For a more responsive script you need to tighten the loop.
You are repeating the same functions(MoveMouseRelative and Sleep) a lot in the loop body. if you simplify the loop body you can have it check the release condition after each Sleep
EnablePrimaryMouseButtonEvents(true);
function OnEvent(event, arg)
  if IsKeyLockOn("capslock")then
    if IsMouseButtonPressed(1) then
      local positions = {             -- Move `MoveMouseRelative` args to an 2d array.
          {-69,99},
          {11,91},
          {-109,84},
          {-86,75},
          {1,64},
          {33,56},
          {58,47},
          {75,39},
          {84,29},
          {83,18},
          {75,20},
          {60,36},
          {33,49},
          {3,55},
          {-32,69},
          {-55,64},
      }
      local index = 1
      repeat
        MoveMouseRelative(positions[index][1], positions[index][2])
        Sleep(133)
        index = (index % #positions) + 1 -- loop index when it reaches the array length.
      until not IsMouseButtonPressed(1)
    end
  end
end


Is it possible to distinguish if a melody is in C Dorian or in D Phrygian?

Question: (This is my first post in this community, I tried to search an answer about that basic question but it's not easy, so sorry if it is a duplicate)
Since the C Dorian scale contains the following notes:
C  D  D# F  G  A  A#
And the D Phrygian contains:
 D  D# F  G  A  A# C
And thus bacially the same notes. How is it possible to say about a track that is has been written in C Dorian or in D Phrygian ? More generally, how is it possible to say about a track it is in written in a particular mode without naming any key.
I ask that question because on this Wikipedia page you can find a sentence like:

Björk's "Army of Me" is a rare example of a pop song whose verse is
written in the Locrian mode.

And I don't understand how it has been determined.
Comment: D# needs to be called Eb, and A# needs to be called Bb. That way, there's *one* of each letter name - a convention nearly as old as written music.
Comment: Pretty sure something largely equivalent has been asked before.
Comment: Hmm, I don't hear Army of Me in C Locrian; I hear it in Bb minor, with a lot of emphasis on the 2nd degree.
Comment: Personal example: I wrote a song a few months ago that I originally thought was in E dorian, but looking at it afterwards, I realised that it was more accurate to say that it was in B minor. The 'b' tone sounds like 'home' whereas the 'e' sounds like 'going away from home'. To distinguish between two modes that use the same notes, one has to establish what sounds like 'home', or in musical terms, the tonic.
Answer:
How is it possible to say about a track that is has been written in C
Dorian or in D Phrygian

You are the judge! If after hearing it you feel that C is the home note, then for you it is in C Dorian. If you feel that D is the home note, then for you it is in D Phrygian. You feel it, you don't calculate it.
Saying that something is "written in" a mode gives the impression that as long as you use the right tool, you're guaranteed to succeed and produce the result that was printed on the tool's packaging. But it is entirely possible to use the notes of the D Phrygian mode in such a way that G ends up being felt as the tonic, for example. And then it would be in G Aeolian from the perspective of those listeners. It's not what you use, it's how you use it.
You can often move the tonic and thus change the mode by simply playing a different, loud, bass note. Rhythmic placement of "one" can affect the interpretation of notes as well. In the right circumstances, even a drummer can change the mode! See this answer:
Why do modes sound so different, although they are basically the same as a mode of another scale?
Answer: A piece in Dorian will emphasize the sixth and seventh notes of the scale, because these are what distinguish it from other modes.
A piece in Phrygian will emphasize the second note of the scale, because that is what distinguishes it from other modes.
In general, a mode has a characteristic sound, which is determined by a set of intervals that differentiate it from other, otherwise similar modes. Locrian, for example, will emphasize its fifth note, which forms a unique interval (against the key note) not occurring in other modes.
So recognizing that unique, characteristic sound is how one knows the mode (or by analyzing a score).
The mode is independent of the key. The key just indicates the pitch considered to be the "resting point" of the music.
THUS:
C Dorian sounds different from D Phygian, because Dorian will emphasize the sound of the A-Bb part of the scale; whereas D Phrygian will emphasize the D-Eb part of the scale.
In the Bjork sound, Locrian is recognized because, given its "resting pitch", the other notes used form a Locrian scale.
Comment: @snoobdogg the notes being emphasized are a secondary consideration.  The primary consideration is the home note.  It's entirely possible to have a piece in C Dorian that emphasizes E flat, and it's entirely possible to have a piece in D Phrygian that emphasizes A and and B flat.
Comment: allright, could you develop a bit more that notion of "emphase" of those notes. This is because they are more present in regards to the other notes of the scale or because they are used on the strong beat of the bar? (I'm a french native speaker, not sure if I use the right terms)
Comment: @snoobdogg You have the right idea. Those notes will be used frequently, in prominent places in the music. That could be on strong beats, but it could also be at important emotional moments — any part of the music that might call attention to their unique sound.
Comment: I feel like this is put backwards. Emphasizing characteristic tones is a possible technique to establish the feeling of given scale or mode, but to know what feeling we have about the tonality we need to... feel it. So you answered a question about some of the techniques that Bjork has used to achieve given result, not how do we recognize what the result is.
Answer: I think this is one of the places where you could actually argue that music theory is just theory, because you can decide how you choose to analyze it, and there's no way to prove that either method is better. You could look at, "Which chord is the root of the chord progression in this music," but then you might find a song like Viva La Vida, where I personally feel it isn't the first chord of the progression, but there isn't any way to "prove" that.
The hard part is that people will feel the music in a certain way. They will subconsciously analyze it in a more advanced, organic way than we ever could. So I would argue that some songs are definitively one, and not the other, because they feel like they are one, and not the other. An easy way to check this is by playing one of the scales (to set a context in your head) and then listening to the song. Does the song seem to fit more in one context than the other?
TL;DR Mechanically, you can't prove any difference between the two, but when people hear the music, their subconscious will likely interpret it as being in a certain scale, simply because the song "feels" that way in a way that we can't definitely define.
Comment: I don't think your points here hold up. There's nothing in music theory to suggest that the first chord of a progression is, or should be, the root chord. Further, the whole point of music theory is to explain why people tend to hear music in a certain way.