Find all subsets of a list

Question: I have a list and I need to output each subset of the list
for example a b c d e
would output to
 a
 b
 c
 d
 e
 ab
 ac
 ad
 ae

 abc
 abd
 abe
 bcd
 bce
 ....
 abcde

I believe the correct term is combination no element should be duplicated on the same line
I was going to attempt this with a series of  loops but im not even sure wehre to start
any suggestions?
Comment: `aaaaa` is not a **subset** of `a b c d e`. What is the actual definition of the result you're looking for?  Apparently, elements from your original list can be repeated, but how many times?
Comment: duplicated of ?? http://stackoverflow.com/questions/756055/listing-all-permutations-of-a-string-integer
Comment: Agreed with @vlad, if your 2-letter sequences had gone `ae` `ba` `bb` `bc` `...` `ee` it would have been a little more clear that you're going for all sequences of these chars, but you sorta skipped that.
Comment: Agree with Ron, would probably phrase it as words of maximum length 5 that can be formed from the alphabet { a, b, c, d, e }
Comment: It appears that he wants all sets of sizes 1 to N that can be formed using any number of items from the original set.
Comment: @vlad sorry you are correct aaaa is not a subset I did it by hand
Comment: I updated the question to reflect
Comment: @vaquito no its not that appears to be a permutation answer I would never need any one element more than once
Comment: I have an answer that solves your original question... I deleted it to avoid downvotes after you changed your answer. You definitely want subsets,right?
Comment: @Sapph yes ( I never down vote unless its completely off topic) i updated the question again to clarify more
Comment: Why the hate with the down vote? its a valid question!
Comment: @Crash893 it looks to me like it's still slightly misleading.  if all you want are subsets, then no elements should appear in the results twice (unless they appear in the original list twice), so `aab` and `acc` should not be part of the results list.  Also, if this is the case, you are looking for permutations of a collection of elements, and @vaquito is correct that this is a duplicate question.
Comment: I updated the question 11min ago
Comment: No i don't need permutations Just combinations
Comment: I'm heading home ill check back in an hour or so
Comment: Possible duplicate of [How to get all subsets of an array?](https://stackoverflow.com/questions/999050/how-to-get-all-subsets-of-an-array)
Comment: Wow!  you went wayyyyyyyyyy back to find that match
Answer: This will generate the set you want, but in a different order (I sort by alphabet at the end, you'd want to sort by length as well).
You'll end up with:
a
  ab
  abc
  abcd
  abcde
  abce
  ...
  d
  de
  e
So, every possible subset (aside from the empty string), while maintaining the order of the original list.
The idea is to add each element to to a growing list. With every new element, add it first, and then add it to all existing elements.
So, start with 'a'.
Go on to 'b'. Add it to the list. We now have {'a', 'b'}.
Add it to existing elements, so we have 'ab'. Now we have {'a', 'b', 'ab'}.
Then 'c', and add it to existing elements to get 'ac', 'bc', 'abc': {'a', 'b', 'ab', 'c', 'ac', 'bc', abc'}. So forth until we're done.
        string set = "abcde";

        // Init list
        List<string> subsets = new List<string>();

        // Loop over individual elements
        for (int i = 1; i < set.Length; i++)
        {
            subsets.Add(set[i - 1].ToString());

            List<string> newSubsets = new List<string>();

            // Loop over existing subsets
            for (int j = 0; j < subsets.Count; j++)
            {
                string newSubset = subsets[j] + set[i];
                newSubsets.Add(newSubset);
            }

            subsets.AddRange(newSubsets);
        }

        // Add in the last element
        subsets.Add(set[set.Length - 1].ToString());
        subsets.Sort();

        Console.WriteLine(string.Join(Environment.NewLine, subsets));

Comment: this looks like its working, I have to modify it slightly but this is a huge help
Answer: if all you need are combinations of the elements in your original list, you can transform the problem into the following: you have a bit array of size N, and you want to find all possible choices for the elements of the array.  For example, if your original list is
a b c d e
then your array can be
0 1 0 0 0
which results in an output of
b
or the array can be
1 0 1 1 0
which returns
acd
this is a simple recursion problem that can be solved in an O(2^n) time
edit adding pseudo-code for recursion algorithm:
CreateResultSet(List<int> currentResult, int step)
{
    if (the step number is greater than the length of the original list)
    {
        add currentResult to list of all results
        return
    }
    else
    {
        add 0 at the end of currentResult
        call CreateResultSet(currentResult, step+1)

        add 1 at the end of currentResult
        call CreateResultSet(currentResult, step+1)
    }
}

for every item in the list of all results
display the result associated to it (i.e. from 1 0 1 1 0 display acd)

Comment: This is right and i was thinking orginaly of some sort of binary switch to turn on each combo but im not sure how to go about coding it
Answer: This will work with any collection. I modified @Sapp's answer a little
    static List<List<T>> GetSubsets<T>(IEnumerable<T> Set)
    {
        var set = Set.ToList<T>();

        // Init list
        List<List<T>> subsets = new List<List<T>>();

        subsets.Add(new List<T>()); // add the empty set

        // Loop over individual elements
        for (int i = 1; i < set.Count; i++)
        {
            subsets.Add(new List<T>(){set[i - 1]});

            List<List<T>> newSubsets = new List<List<T>>();

            // Loop over existing subsets
            for (int j = 0; j < subsets.Count; j++)
            {
                var newSubset = new List<T>();
                foreach(var temp in subsets[j])
                    newSubset.Add(temp);

                newSubset.Add(set[i]);

                newSubsets.Add(newSubset);
            }

            subsets.AddRange(newSubsets);
        }

        // Add in the last element
        subsets.Add(new List<T>(){set[set.Count - 1]});
        //subsets.Sort();

        return subsets;
    }

**And then if I have a set of strings I will use it as:
Answer: Here is some code I made. It constructs a list of all possible strings from an alphabet, of lengths 1 to maxLength: (in other words, we are calculating the powers of the alphabet)
  static class StringBuilder<T>
  {
    public static List<List<T>> CreateStrings(List<T> alphabet, int maxLength)
    {
      // This will hold all the strings which we create
      List<List<T>> strings = new List<List<T>>();

      // This will hold the string which we created the previous time through
      // the loop (they will all have length i in the loop)
      List<List<T>> lastStrings = new List<List<T>>();
      foreach (T t in alphabet)
      {
        // Populate it with the string of length 1 read directly from alphabet
        lastStrings.Add(new List<T>(new T[] { t }));
      }

      // This holds the string we make by appending each element from the
      // alphabet to the strings in lastStrings
      List<List<T>> newStrings;

      // Here we make string2 for each length 2 to maxLength
      for (int i = 0; i < maxLength; ++i)
      {
        newStrings = new List<List<T>>();
        foreach (List<T> s in lastStrings)
        {
          newStrings.AddRange(AppendElements(s, alphabet));
        }
        strings.AddRange(lastStrings);
        lastStrings = newStrings;
      }

      return strings;
    }

    public static List<List<T>> AppendElements(List<T> list, List<T> alphabet)
    {
      // Here we just append an each element in the alphabet to the given list,
      // creating a list of new string which are one element longer.
      List<List<T>> newList = new List<List<T>>();
      List<T> temp = new List<T>(list);
      foreach (T t in alphabet)
      {
        // Append the element
        temp.Add(t);

        // Add our new string to the collection
        newList.Add(new List<T>(temp));

        // Remove the element so we can make another string using
        // the next element of the alphabet
        temp.RemoveAt(temp.Count-1);
      }
      return newList;
    }
  }

Comment: I had similar code in my original answer, but it turns out the asker wasn't clear originally and this is not the solution he needs.
Answer: something on the lines of an extended while loop :
<?

$testarray[0] = "a";
$testarray[1] = "b";
$testarray[2] = "c";
$testarray[3] = "d";
$testarray[4] = "e";

$x=0;
$y = 0;
while($x<=4) {

$subsetOne[$x] .= $testarray[$y];
$subsetOne[$x] .= $testarray[$x];

$subsetTwo[$x] .= $testarray[$y];
$subsetTwo[$x] .= $subsetOne[$x];

$subsetThree[$x] = str_replace("aa","ab",$subsetTwo[$x]);

$x++;
}

?>

Find all subsets of a list


Cliente Rest em Java recebendo um LocalDate

Question: Estou fazendo um cliente teste em java.
Minha classe livro é assim:
public class Livro {

    private Long id;
    private String nome;

    @JsonFormat(shape = JsonFormat.Shape.STRING,pattern="dd/MM/yyyy")
    private LocalDate publicacao;

    private String editora;
    private String resumo;
    private List<Comentario> comentarios;
    private Autor autor;

   // get and sets
}

Recebo o seginte json.
[
  {
    "id": 1,
    "nome": "Livro de teste 2",
    "publicacao": "20/05/2014",
    "editora": "teste",
    "resumo": "teste de resumo"
  }
]

Se utilizo o campo publicacao como Date funciona perfeitamente.
Mas gostaria de utilizar como Localdate como esta definido na Clase
Contudo da o seguinte erro.

Caused by: java.time.format.DateTimeParseException: Text '20/05/2014'
  could not be parsed at index 0    at
  java.time.format.DateTimeFormatter.parseResolved0(DateTimeFormatter.java:1949)
    at
  java.time.format.DateTimeFormatter.parse(DateTimeFormatter.java:1851)
    at java.time.LocalDate.parse(LocalDate.java:400)    at
  java.time.LocalDate.parse(LocalDate.java:385)     at
  com.fasterxml.jackson.datatype.jsr310.deser.LocalDateDeserializer.deserialize(LocalDateDeserializer.java:67)
    at
  com.fasterxml.jackson.datatype.jsr310.deser.LocalDateDeserializer.deserialize(LocalDateDeserializer.java:32)
    at
  com.fasterxml.jackson.databind.deser.SettableBeanProperty.deserialize(SettableBeanProperty.java:490)
    at
  com.fasterxml.jackson.databind.deser.impl.MethodProperty.deserializeAndSet(MethodProperty.java:95)
    at
  com.fasterxml.jackson.databind.deser.BeanDeserializer.deserializeFromObject(BeanDeserializer.java:341)
    ... 14 more

Ou seja como faço o parse de um campo json "publicacao": "20/05/2014",
para um campo Localdate ?
Para fazer o client estou utilizando as seguintes dependencias no maven.
<dependencies>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-web</artifactId>
            <version>4.2.5.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.7.2</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.datatype</groupId>
            <artifactId>jackson-datatype-jsr310</artifactId>
            <version>2.4.0</version>
        </dependency>
</dependencies>

Answer: Opa!
Atualmente na minha aplicação estou fazendo da seguinte maneira:
@JsonFormat(pattern = "dd/MM/yyyy", shape = JsonFormat.Shape.STRING)
@JsonDeserialize(using = LocalDateDeserializer.class)
@JsonSerialize(using = LocalDateSerializer.class)
@Column(name = "data_vencimento")
private LocalDate dataVencimento;

Espero ter ajudado!
Answer: Mude a versão da dependência jackson-datatype-jsr310 para a mesma versão da dependência jackson-databind:
<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.7.2</version>
</dependency>
<dependency>
    <groupId>com.fasterxml.jackson.datatype</groupId>
    <artifactId>jackson-datatype-jsr310</artifactId>
    <version>2.7.2</version>
</dependency>

E registre o módulo JavaTimeModule ao invés do módulo JSR310Module. Exemplo:
public static void main(String[] args) throws IOException {
    ObjectMapper mapper = new ObjectMapper();
    mapper.registerModule(new JavaTimeModule());

    Livro livro = mapper.readValue("{\"id\": 1,"
                                + "\"nome\": \"Livro de teste 2\", "
                                + "\"publicacao\": \"20/05/2014\","
                                + "\"editora\": \"teste\","
                                + "\"resumo\": "
                                + "\"teste de resumo\"}", Livro.class);
}


Put form fields next to accordion

Question: may someone tell me why the form fields don't get displayed on the right of the screen? Even when using col-6?
Code pen:
https://codepen.io/ogonzales/pen/abjgabQ
As is:

Expected:
Answer: You have forgot to close .col-6 div  on the line number 64:
Please check the below code:

          <button class="accordion-button" type="button" data-bs-toggle="collapse" data-bs-target="#collapseOne" aria-expanded="true" aria-controls="collapseOne"> Requisitos </button>

            Ser mayor de 10 años y contar con una computadora (o laptop) y conexión a internet. Debido a que las clases serán online, el estudiante necesita contar con una computadora para unirse. En su defecto, puede el estudiante podrá unirse desde un dispositivo móvil (celular). .accordion-body, though the transition does limit overflow.

          <button class="accordion-button collapsed" type="button" data-bs-toggle="collapse" data-bs-target="#collapseTwo" aria-expanded="false" aria-controls="collapseTwo"> Características y disctado del curso </button>

            ¿Cómo será el dictado de clases bajo esta modalidad? Deberás conectarte con tu profesor y compañeros a través de la Plataforma de Videoconferencia Zoom, en el horario y frecuencia de clase que elegiste para el presente ciclo. En esta modalidad, el docente te acompañará siempre en tiempo real, durante los días y horario de clases, facilitando tu aprendizaje. Por ello, ¡El logro de tus metas no se detiene!

          <button class="accordion-button collapsed" type="button" data-bs-toggle="collapse" data-bs-target="#collapseThree" aria-expanded="false" aria-controls="collapseThree"> Niveles, ciclos y horarios </button>

                  a
                  b
                  c
                  d

                  row 1, column 1
                  row 1, column 2
                  row 1, column 3
                  row 1, column 4

                  row 2, column 1
                  row 2, column 2
                  row 2, column 3
                  row 2, column 4

                  row 3, column 1
                  row 3, column 2
                  row 3, column 3
                  row 3, column 4

Get In Touch

If success is a process with a number of defined steps, then it is just like any other process. So, what is the first step in any process?

              <form class="row fill-form mb-4 mb-md-0 form-flat-style">

                  Name
                  <input type="text" class="form-control" placeholder="">

                  Email
                  <input type="email" class="form-control" placeholder="">

                  Subject
                  <input type="text" class="form-control" placeholder="">

                  Phone
                  <input type="text" class="form-control" placeholder="">

                  Message
                  <textarea class="form-control" id="exampleFormControlTextarea1" rows="5"></textarea>

                  <button type="submit" class="btn btn-primary">Send us</button>

              </form>

Contact Detail

6580 Allison Turnpike Creminfort, AL 32808-4509

                Call us: +123 4567 8910

                Mail us: firstname.lastname@example.com

Put form fields next to accordion


Group in which every nonidentity element is of order 2

Question: I'm working on the following problem in Algebra:

Let $G$ be a group in which every nonidentity element is of order $2$. Show that every subgroup $H$ of $G$ has the property that $G/H$ is isomorphic to a subgroup of $G$.

Here's my progress so far:
First, I've shown that any group $G$ such that every nonidentity element is of order $2$ is abelian. That part is easy. Then, this means that every subgroup $H$ of $G$ is then normal, as every subgroup of an abelian group is normal ($\forall$ x $\in$ G & $\forall$ $h \in H$, $xhx^{-1} = xx^{-1}h = h \in H$ ).
Now, we recall that if $\phi:G \longrightarrow H$ is a group homomorphism, then $G/\ker(\phi) \cong \phi(G)$, where $\ker(\phi)$ is normal in $G$ by the First Isomorphism Theorem. Since every subgroup $H$ of $G$ is normal, & every normal subgroup is the kernel of a group homomorphism $\phi: G \longrightarrow G/H$, $G/H \cong \phi(G)$.
It's left to show that $\phi(G)$, the image of $\phi$, is isomorphic to a subgroup of $G$, where $\phi:G \longrightarrow G/H$ is a homomorphism for a normal subgroup $H$ of $G$. This is the last piece of the proof that I'm stuck on. Is my logic up to this point sound? If so, how can I show this last piece of the proof?
Thanks!
Comment: Why the downvote? There's ample context!
Answer: Such a group is abelian : if $(ab)^2=1$, then $ab ab=1$ but $a=a^{-1}, b=b^{-1}$, hence $aba^{-1}b^{-1}=1$, or$ab=ba$.
SO we can note the multiplication by a plus sign $(a+b)$ instead of $ab$, and $2.a=0$ for all $a$.
With this notation one sees that the group is in fact a $Z/2Z$ vector space, therefore isomorphic to $(Z/2Z)^d$, and a subgroup is isomorphic to $(Z/2Z)^e$.
I assumed that the dimension is finite, but using the existence of bases one can prove the same for infinite dimensional vector spaces. Namely if $V$ is a vector space and $W$ a subspace choosing a base of $V/W$ enable one to prove that  it is isomorphic tp a subspace of $V$.
Comment: Hi Thomas. I believe you're using the fact that if every nonidentity element of $G$ is of order $2$. then $G$ is isomorphic to a product of $Z/2Z$'s correct? And from here, you conclude that our subgroup $H$ of $G$ must then also be a product of $Z/2Z$'s? Thus, the quotient $G/H$ is again a product of $Z/2Z$'s? My only question is, how do we know that the number of $Z/2Z$'s showing up in the product corresponding to $G/H$ is equal to the number of $Z/2Z$'s showing up in the product corresponding to $H$?
Comment: I transformed a question into a  linear algebra problem, and the answer is : a quotient of a vector space is isomorphic to a subspace.


Group Theory and Divisors

Question: Here is the problem I'm working at:

Find a divisor $d$ of $6! = 720$ such that $S_6$ does not have a subgroup of order $d$.

Initial Approach:
So I factored the number $720$ and here are the divisors that I came up with:
$1, 2, 3, 4, 5, 6, 8, 9, 10, 12, 15, 16, 18, 20, 24, 30, 36, 40, 45, 48, 60, 72, 80, 90, 120, 144, 180, 240, 360, 720$
So there are a total of 30 divisors for the number $720$. I believe it would be helpful to know how many total subgroups are there in $S_6$. I did find this link, not sure if it would help out or not.
Update
So after doing some further research, I found out that $S_6$ has a total of $1455$ subgroups, but a proof is not given as to why this is true. But why is this true? Well the divisors of $1455$ are given as follows:
$1, 3, 5, 15, 97, 291, 485, 1455$
Comment: You can show that $S_6$ has subgroups of order $2,3,4,5,6,12,24,60,120,360,720$ by using the fact that every symmetric group has an alternating group inside, and using Cauchy.
Comment: I doubt the total number of subgroups will help. Perhaps you could try going in the other direction -- can you make a list of divisors of $720$ that *do* show up as orders of subgroups $S_6$? Symmetric groups, alternating groups, cyclic groups, etc. I personally suspect *large* orders (like $720/3 = 240$) are less likely to show up.
Comment: Ah well, in that case, I believe this calls for [Lagrange's Theorem](https://en.wikipedia.org/wiki/Lagrange%27s_theorem_(group_theory)) then. Right?
Answer: I don't see how knowing the number of subgroups in $S_{6}$ really helps, but here is an argument which may help, provided you know the classification of groups of order $pq$ for distinct primes $p, q$. Note that any group of order $15$ must be cyclic, since $15$ is the product of the distinct primes $3$ and $5$, and $5$ is not congruent to $1$ mod $3$. Hence, if $S_{6}$ had a subgroup of order $15$, it must have an element of order $15$. But this cannot be, since the order of any element of $S_{6}$ is the least common multiple of the lengths of the cycles in its disjoint cycle decomposition.
Comment: @pjs36: thanks! I had no idea what else to try, but happily this approach worked.
Comment: *Much* simpler than I was thinking. Well done!
Comment: Yes I just got done reading the proof. Definitely a (+1).

Group Theory and Divisors


Jquery loop: iterate siblings by four, then re-start from beginning

Question: Q: How do I create a loop to show four div at time, that are children of #reviewswidget? Once slideshow hits end of children, it needs to return to the first four divs.

title 1 goes here

rating 1 goes here

 review 1 goes here

author 1 goes here

title 2 goes here

rating 2 goes here

 review 2 goes here

author 2 goes here

My Attempt:
jQuery(function () {
        jQuery('#reviewswidget div').hide().slice(0, 4).show();
        setInterval(function () {
            jQuery('#reviewswidget div').filter(':visible').fadeOut(function () {
                self.setSliceIteration(4);
                self.setSliceTotal(jQuery('#reviewswidget div').length);
                if (self.getSlice() === 0 && self.getSlice() === '') {
                    jQuery('#reviewswidget div').hide().nextAll().slice(self.getSlice()).show();
                    self.setSlice(self.getSliceIteration() + self.getSlice());
                }
                if (self.getSlice() < self.getSliceTotal()) {
                    $(this).nextAll().slice(self.getSlice()).show();
                    self.setSlice(self.getSliceIteration() + self.getSlice());
                }
                if (self.getSlice() < self.getSliceTotal()) {
                }
            });
        }, 3000);
    });

Full Code: http://jsfiddle.net/Q3jaf/1/
Comment: Why not put 4 divs into a parent div?
Answer: Try
var $chidlren = $('#reviewswidget').children().slice(4).hide();
setInterval(function(){
    $('#reviewswidget').children().slice(0, 4).hide().appendTo('#reviewswidget')
    $('#reviewswidget').children().slice(0, 4).show()
}, 1000)

Demo: Fiddle
Comment: How would I implement a single fadein and fadeout transition? Appendto just shifts it down. http://jsfiddle.net/Q3jaf/2/
Comment: If I wanted to add a delay for x amount of seconds after fade in, then perform the fade out how would I do it in this example?
Comment: @DavidEugenePeterson try http://jsfiddle.net/QHe3t/3/ - increase the `setInterval()` delay


mysql: How to get the last value of a column, and the first value of another coumn in the same table?

Question: how can I only retrieve the following data from the table below with one query

MIN(SamplingStart) -
First StartAddress // [WHERE StartAddress = MIN(SamplingStart)] -
Last StartAddress   // [WHERE StartAddress = MAX(SamplingStart)]

This is the code I have so far. The problem is with number 3 above. How can I get no 3 to work while 1,2 must still work.
**The result must look like this.**

+-----------+--------------------+----------------+
| StartTime | StartAddress       | StopAddress    |
+-----------+--------------------+----------------+
| 08:00:00  | 26 Riverside Drive | Paterson       |
+-----------+--------------------+----------------

**Existing Code to modify.**

SELECT

MIN(SamplingStart) AS StartTime,
StartAddress AS StartAddress,
StopAddress AS StopAddress

FROM table1;

****table1****
+---------------+--------------------+--------------------+
| SamplingStart | StartAddress       | StopAddress        |
+---------------+--------------------+--------------------+
| 08:00:00      | 26 Riverside Drive | 70 Piet Retief     |
| 09:00:00      | 10 Glen Drive      | 16 Olga Street     |
| 10:00:00      | 66 Bremerhof       | 26 Bluewater Drive |
| 11:00:00      | 7 New Street       | Walker Drive       |
| 13:00:00      | Goodwood Street    | Blouberg           |
| 15:00:00      | Marine Drive       | William Moffet     |
| 18:00:00      | Jumanji            | Paterson           |
+---------------+--------------------+--------------------

Comment: I would go for subquery for stopadress. But you asked for one query?
Comment: Ok. I'm very new to mysql. I googled subquery, and to me it looks like it might work. I'm going to play around with it and let you know if I need more help:-) Thanks!!
Comment: No problem. You are very welcome. See my answer below for an idea.
Answer: You can use conditional aggregation:
SELECT MIN(SamplingStart) AS StartTime,
       MAX(CASE WHEN SamplingStart = StartTime THEN StartAddress END) AS StartAddress,
       MAX(CASE WHEN SamplingStart = EndTime THEN StopAddress END) AS StopAddress
FROM table1 t1 CROSS JOIN
     (SELECT MIN(SamplingStart) AS StartTime, MAX(SamplingStart) AS ENDTime
      FROM table1
     ) tt

Answer: I would do this(I know it is not really just one query but...):
SELECT
MIN(SamplingStart) AS StartTime,
StartAddress AS StartAddress,
(select StopAddress from table1 order by SamplingStart desc limit 0,1) as StopAddress

FROM table1 ;


How to add conflicts in D8 info.yml?

Question: I want to know how to add conflicts in D8 info.yml.
I tried like this in D8 .info.yml:
name: Example
type: module
description: some example.
core: 8.x
package: Other
dependencies:
  - menu_ui
conflicts:
  - module1
  - module2

and in .install file
<?php
/**
 * Implements hook_requirements().
 */
function example_requirements($phase) {
  $requirements = [];

  switch ($phase) {
    // Called while the module is installed.
    case 'install':
    if (\Drupal::moduleHandler()->moduleExists('module1')) {
        $requirements[] = [
          'title' => t('Module 1'),
          'value' => t('Module 1'),
          'description' => t('Module 1 conflicts with example.'),
          'severity' => REQUIREMENT_ERROR,
        ];
      }
      break;
  }

  return $requirements;
}

But in D7 it is working:
name = Example
description = some example.
core = 7.x
dependencies[] = menu
package = Other
conflicts[] = module1
conflicts[] = module2

While enabling my example module it is not showing any conflict error in D8.

Installation Order:
1) Fresh Drupal installation.
2) Module 1
3) Module 2
4) Example module(here i need to show module1 and 2 are present while
  installing)
Comment: It seems that this is not yet implemented. See [this](https://www.drupal.org/node/92233) issue.
Comment: ty for your comment, it saved my time.
Answer: It seems that this is not implemented yet. Related issue is here.
An alternative would be to use hook_requirements() in your module's .install file. You can check here if the conflicting module is present during the installation process and prevent the system from installing the module.
Here's example code that would go in your module's .install file:
/**
 * Implements hook_requirements().
 */
function YOUR_MODULE_requirements($phase) {
  $requirements = [];

  switch ($phase) {
    // Called while the module is installed.
    case 'install':
    // Called during regular use of the website.
    case 'runtime':
    // Called while the update.php is being executed.
    case 'update':
      // Do not allow administrators to install the module if conflicting module
      // is already installed.
      //
      // You can move this code to any other phase as well.
      if (\Drupal::moduleHandler()->moduleExists('ARCH_ENEMY_OF_YOUR_MODULE')) {
        $requirements[] = [
          'title' => t('Name of your module'),
          'value' => t('Arch enemy module'),
          'description' => t('Explain that administrators need to uninstall the module before proceeding.'),
          'severity' => REQUIREMENT_ERROR,
        ];
      }
      break;
  }

  return $requirements;
}

You can see a working example of hook_requirements() in my Drupal 8 boilerplate repo on Github.
Hope this helps.
Comment: No luck, still not throwing any error while installing even though my module1 and 2 are installed.
Comment: Will have a look at it shortly
Comment: Just tested this - it's working properly and prevents you from installing the module if the conflicting module is already installed. Post your code if it doesn't work for you.
Comment: `moduleExists('module1')) {
        $requirements[] = [
          'title' => t('Module 1'),
          'value' => t('Module 1'),
          'description' => t('Module 1 conflicts with example.'),
          'severity' => REQUIREMENT_ERROR,
        ];
      }
      break;
  }

  return $requirements;
}`
Comment: Code is not formatted properly in comments so it's better to post it to the question itself. However your code seems to be fine - are you sure that the machine name of the other module is `module1`?
Comment: Updated in question..
yes the other module name is **module1**
Comment: Something else is not right; I suggest doing this on a clean install. Also, just to clarify: when you add `hook_requirements()` to the `example` module, the system will prevent Example module from being installed. Can you write the order in which you are installing the modules?
Comment: Added installation order in question
Comment: Strange; I tested the code I posted and it works properly. I suggest trying this on another clean installation and seeing if other parts of your setup cause the problem. Here's what I would do: (1) remove any conditions and just prevent the module from installing; if this works fine, install Devel and check what is returned when you run this code: `\Drupal::moduleHandler()->moduleExists('module1')`.

How to add conflicts in D8 info.yml?


how resolve PHP class defined in another folder

Question: how does PHP find a class when the class is defined in a sibling folder of the running .php file?  The php file I am running is located in the ./examples folder. The class file is found in ./src/Fedex.
The use statement that ./examples/address-validation.php uses to set the path to a class
use FedEx\AddressValidationService\Request;
use FedEx\AddressValidationService\ComplexType;
use FedEx\AddressValidationService\SimpleType;

$addressValidationRequest = new ComplexType\AddressValidationRequest();

when I run the .php file I get this not found error:
Fatal error: Uncaught Error: Class 'FedEx\AddressValidationService\ComplexType\AddressValidationRequest'
not found in C:\xampp\htdocs\php-fedex-api-wrapper\examples\address-validation.php

The location of the class is in the ./src/FedEx/AddressValidationService folder.  Where both the ./src and ./examples folders are in the same parent folder.
Comment: Automatic resolution of classes and loading of files is done via a mechanism called autoload. You have to register things with autoload, and then you can just use them. Composer does a great job of helping you produce a registry, and offers various methodologies for mapping namespaces/classes to the file system.
Comment: You should make use of `$_SERVER['DOCUMENT_ROOT']` to exactly counter this sort of issue.
Comment: @JAAulde is right. you have to register the classes with autoload at first. If you have problem with local addresses, use dirname(\_\_FILE\_\_) to define correct location.
Comment: `use` statements only set a short alias so you don't need to type the full namespace every time; they don't have anything to do with class or file loading. To load code from other files you need to [include](https://php.net/include) them, or use a tool that includes them for you (such as Composer's auto-loader).
Comment: Do you used this API with Composer autoloader?
Answer: You should define a path to that class in the composer autoloader if you have one or if you have a custome loader you should teach that loader of to resolve class which are inside of the Namespace FedEx\AddressValidationService\Request
If you have define a composer.json file at the ROOT directory of your project you can define a PSR-4 autloader like this
{
    "autoload": {
        "psr-4": {"FedEx\\": "./src/FedEx/"}
    }
}

after that you must execute composer dump-autoload

Lear more about Composer

If you want to create a custom autoloader and you don't want to use Composer which I highly recommand you can learn more about spl-autoload-register
Comment: In the original example file the autoloader (bootstrap.php) is included:
https://github.com/JeremyDunn/php-fedex-api-wrapper/blob/master/examples/address-validation.php
Comment: have you try to run `composer dump-autoload`


Counting free trees from rooted trees.

Question: The number of free trees on n vertices is given in Sloane's OEIS A000055.  the number of rooted trees is A000081.  If t(x) is the ordinary generating function (o.g.f.) for free trees and T(x) is the o.g.f. for rooted trees then:
t(x) = 1 + T(x) - (T(x)^2 - T(x^2))/2.
I am trying to understand the equation in terms of the symbolic method of derivation of generating functions as described in Flajolet and Sedgewick, Analytic Combinatorics.  I recognize (T(x)^2 - T(x^2))/2 as the o.g.f. for the number of unordered distinct pairs of rooted trees.  I do not understand how subtracting this from T(x) gives us the o.g.f. for free trees.  I know that every tree is centered or bi-centered and I think this might have something to do with the explanation.
Comment: What is the definition of a free tree?
Comment: The proof is on pages 55 to 57 of the book "Graphical Enumeration" by Harary and Palmer (which I highly recommend you read because of its extremely straightforward presentation of Polya counting).
Comment: "A tree which is not rooted is sometimes called a free tree, although the unqualified term "tree" generally refers to a free tree."   From Weisstein's Math World "Rooted Tree".
Answer: Here we show OPs formula using the dissimilarity theorem for trees. In the following we also give some basic information around this theorem to ease reading.

We denote with

$\mathcal{U}$ the class of unrooted unlabelled non-plane trees. With the corresponding generating function $U(z)$ (see A000055).

\begin{align*}
U(z)&=z+z^2+z^3+2z^4+3z^5+6z^6+11z^7+23z^8+47z^9\\
&\qquad+106z^{10}+235z^{11}+551z^{12}+1301z^{13}+3159z^{14}
\end{align*}

$\mathcal{R}$ the class of rooted unlabelled non-plane trees. With the generating function $R(z)$ (see A000081).
  \begin{align*}
R(z)&=z+z^2+2z^3+4z^4+9z^5+20z^6+48z^7+115z^8+286z^9\\
&\qquad+719z^{10}+1842z^{11}+4766z^{12}+12486z^{13}+32973z^{14}
\end{align*}

Unrooted trees are also called sometimes free trees (see e.g. Analytic Combinatorics VII.25, p.480 by P. Flajolet and R. Sedgewick).
Note that contrary to OEIS $U(z)$ does not contain the empty unrooted tree. This is in accordance with the formula we show below and which is stated this way quite often in the literature.

Otter's formula
The following is valid
  \begin{align*}
U(z)=R(z)-\frac{1}{2}\left(R(z)^2-R(z^2)\right)\tag{1}
\end{align*}
This formula named after R. Otter was presented in The number of trees (1948).

The following  proof is according to Analytic Combinatorics VII.26  by P. Flajolet  and  R. Sedgewick. The authors refer in  their proof to Combinatorial  Species  and Tree-like Structures by F. Bergeron, G. Labelle and P. Leroux. Otter's formula is stated there as Theorem 1 in section 4.1. The Dissymmetry Theorem for trees.

Preliminaries
Let $\mathcal{U}^\bullet$ (and  $\mathcal{U}^{\bullet-\bullet}$) be the class of unrooted trees  with  one  vertex (respectively,  one edge) distinguished. We have
  \begin{align*}
\mathcal{U}^\bullet\cong\mathcal{R}\qquad\text{ and }\qquad\mathcal{U}^{\bullet-\bullet}\cong \operatorname{SET}_2(\mathcal{R})\tag{2}
\end{align*}
The equivalence relation $\mathcal{U}^\bullet\cong\mathcal{R}$ is obvious. We can associate to each unrooted tree with a distinguished edge in $\mathcal{U}^{\bullet-\bullet}$ an unordered not necessarily distinct pair of elements of $\mathcal{R}$ by breaking the tree at the edge, giving the right hand side of (2).
A class of unordered pairs of elements $\operatorname{SET}_2(\mathcal{B})$ fulfills the combinatorial isomorphism
  \begin{align*}
\operatorname{SET}_2(\mathcal{B})+\operatorname{SET}_2(\mathcal{B})-\Delta(\mathcal{B}\times\mathcal{B})\cong
\mathcal{B}\times\mathcal{B}\tag{3}
\end{align*}
  (we may think of lower triangle + upper triangle - diagonal is equal the square). If $B(z)$ is the generating function of the class $\mathcal{B}$, then  since
  \begin{align*}
\Delta(\mathcal{B}\times\mathcal{B}):=\{(\beta,\beta)|\beta\in\mathcal{B}\}
\end{align*}
  we obtain
  \begin{align*}
\Delta_B(z)=\sum_{(\beta,\beta)\in\mathcal{B}}z^{2|\beta|}=B(z^2)
\end{align*}
  If we set $\mathcal{A}\equiv \operatorname{SET}_2(\mathcal{B})$ we obtain according to (3)
  \begin{align*}
A(z)&=\frac{1}{2}\left(B(z)^2+B(z^2)\right)
\end{align*}

Otter's formula can be shown via the following combinatorial isomorphism

Dissimilarity theorem for trees
The dissimilarity theorem for trees states the validity of
  \begin{align*}
\mathcal{U}^\bullet+\mathcal{U}^{\bullet-\bullet}\cong\mathcal{U}+\left(\mathcal{U}^\bullet\times\mathcal{U}^\bullet\right)\tag{4}
\end{align*}
In order to prove this theorem, we recall a diameter of an unrooted tree is a simple path of maximal length. If the length of any diameter is even, call centre its mid-point, otherwise, call bi-centre its mid-edge. Note for each tree there is either one centre or one bi-centre.
The left-hand side of (4) corresponds to trees that are pointed either at a vertex ($\mathcal{U}^\bullet$) or an edge ($\mathcal{U}^{\bullet-\bullet}$).
The term $\mathcal{U}$ on the right-hand side corresponds to cases where the pointing happens to coincide with the canonical centre or bicentre.
If there is no coincidence, then, an ordered pair of trees results from a suitable surgery of the pointed tree.

If the tree is pointed at a vertex $s$ different from the center, let $p$ be the vertex adjacent to $s$, in the direction of the center (if the center is an edge to which $s$ belongs, $p$ is the other vertex of this edge). By cutting the edge joining $s$ and $p$, one obtains an ordered pair of rooted trees, the left one with root $s$ and the right one with root $p$.
If the tree is pointed at an edge, different from the center, let $p$ be the vertex of the distinguished edge nearest to the center. Then cut the edge and place on the left the rooted tree with root $p$, and on the right the other part.

Note:

There is a typo in P. Flajolet's book regarding the dissimilarity theorem for trees (4). The right-hand side of the formula there is incorrectly stated as $\mathcal{U}+\left(\mathcal{U}\times\mathcal{U}\right)$ instead of $\mathcal{U}+\left(\mathcal{U}^\bullet\times\mathcal{U}^\bullet\right)$ (see formula (59) at page 481).
The surgery argument is from Theorem 1 in F. Bergeron's book.

Putting all together:
  Using the preliminaries together with the dissimilarity theorem we obtain
  \begin{align*}
\mathcal{U}^\bullet+\mathcal{U}^{\bullet-\bullet}\cong\mathcal{U}+\left(\mathcal{U}^\bullet\times\mathcal{U}^\bullet\right)&\qquad\qquad \text{this is }(4)\\
\mathcal{R}+ \operatorname{SET}_2(\mathcal{R})\cong\mathcal{U}+\left(\mathcal{R}\times\mathcal{R}\right)&\qquad\qquad \text{due to }(2)
\end{align*}
  and since the generating function of the class $\operatorname{SET}_2(\mathcal{R})$ is according to (3)
  \begin{align*}
\frac{1}{2}\left(R(z)^2+R(z^2)\right)
\end{align*}
  we finally get Otter's formula
  \begin{align*}
R(z)+\frac{1}{2}\left(R(z)^2+R(z^2)\right)&=U(z)+R(z)^2\\
U(z)&=R(z)-\frac{1}{2}\left(R(z)^2-R(z^2)\right)
\end{align*}
  and the claim follows.
Comment: @GeoffreyCritzer: You're welcome! ... and you're right in both aspects of your comment. Formulation corrected, thanks.
Comment: The fourth sentence in Preliminaries  reads:  We can associate each rooted tree with a distinguished edge in U^^ with an unordered pair of distinct elements of R...    Should it say instead  .. each UNROOTED tree...    with an unordered (NOT NECESSARILY DISTINCT) pair of elements of R.  ?
Comment: Otherwise, I understand the argument.  Thank you for making it so clear.
Comment: It has just now occurred to me that we can make the same argument for LABELED trees.  Let U(z) be the e.g.f for labeled unrooted trees and R(z) be the e.g.f. for rooted labeled trees.  We reach the result: U(z) = R(z) - R(z)^2/2 given on page 132 of Flajolet and Sedgewick, Analytic Combinatorics.

Counting free trees from rooted trees.


ARIMA -- Residual autocorrelation is non-significant upto lag 6 and significant beyond lag 6

Question: I tried to fit an AR(1) model and was examining the estimates of the model. I had a question on the output (ran in SAS - Proc ARIMA):
The residual auto-correlation up to lag 6 was non-significant (in other words - there is no auto-correlation); however, after lag 6 it is significant.

What does that imply?
Does that mean the model needs improvement?
Also, why would it be significant after lag 6?

<code>Autocorrelation Check of Residuals  (Highlighted values are the auto-correlation
    values and significant values are italicized)
[To Lag] [Chi-Square]  [DF] [Pr > ChiSq]    [Autocorrelations]
  6          9.46       5     0.0922     ** 0.023 0.146  0.092 -0.01   0.089  0.127**
 12         24.68      11    *0.0101*    ** 0.17  0.178 -0.095 -0.042 -0.056 -0.103**
 18         34.42      17    *0.0074*    ** 0.126 0.105  0.05  -0.014 -0.151 -0.005**
 24         38.86      23    *0.0206*    **-0.046 0.042  0.133 -0.008 -0.029 -0.017**
 30         51.21      29    *0.0067*    **-0.067 0.094  0.104  0.183  0.054  0.015**
</code>
Comment: Would those be a series of Ljung-Box tests on the residuals, each from lag 1 up to `[To lag]`?
Answer: The Ljung-Box statistic is not significant calculated over lags one to six lag six simply because you have no particularly large autocorrelations until lags seven & eight.  Plot & examine the auto-correlation function of the residuals. There's some evidence for lack of fit, so perhaps you can come up with a better model:  higher autocorrelations seem to repeat at intervals of seven without dropping off, suggesting seasonal differencing with a period of seven might be worth a try; possibly a seasonal moving average term.  All the same, with about 150 observations your current model doesn't look awful.
Answer: try fitting a seasonal ARIMA, with a seasonal difference of 6.
Your model has significant autocorrellations at lags in multiples of 6.  It's just a guess on my end, but I'd think the seasonal ARIMA with difference of 6 would help.
Comment: Correlations at lags 6, 12, 18, 24, 30:
0.127, -0.103, -0.005, -0.017, & 0.015.

Correlations at lags 7, 14, 21, 28:
0.17, 0.105,  0.133, 0.183.

Which are bigger?
Comment: Oh, I see, I wasn't reading the results right. (never done arima in SAS, only R.  results look different.)
Comment: Yes, too many stars all over the place.


Colocar legendas em baixo dos ícones de redes sociais

Question: Bom dia senhores, peço ajuda a algum Deus do Css, preciso fazer em css puro, colocar estas legendas alinhadas as bolinhas dos icones sociais, elas ja estao alinhadas e já aparecem, porém não consigo fazer com que elas 'desçam' mais a baixo das bolinhas... na imagem mostra como deveria ficar, HELP
COMO DEVERIA FICAR:

Está online em: https://diretivagestao.com/cv/index.html
<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, viewport-fit=cover" />
    <link href="img/favicon.ico" rel="icon">
    <link href="img/favicon.ico" rel="apple-touch-icon">
    <title>Cartão de Visita Digital | Líder Tratores - Cachoeira do Sul</title>

    <link rel='stylesheet' href='css/style.css' media='all' />

    <link rel='stylesheet' href='css/frontend.css' media='all' />

    <link rel='stylesheet' href='css/main.css' media='all' />

    <link rel='stylesheet' href='css/fontawesome/css/all.css' media='all' />

JULIANA JAEGER BECKEL

Diretora Administrativa

                                                    Celular

                                                    Celular

                                                    Celular

                                                    Celular

                                                    Celular

                                                    Celular

                                                    Celular

                                                    Celular

O erro seria nessa linha:
Celular

Comment: Você esta usando algum framework para UI como o Bootstrap?
Me parece que o código está um pouco fora do padrão para se aportar na responsividade.
Se usar o bootstrap pode ganhar funções para alinhar tudo em cols.
Comment: Boa tarde, desculpa demora pelo retorno sou iniciante em CSS e por aqui também. Ainda estou com o problema, mas tive grande avanço, só falta agora eu descobrir como deixar as legendas mais a baixo dos ícones, o projeto utilizava Boostrap pelo o que me foi passado, porém estou em um desafio e consegui tudo, mas estas legendas estão me quebrando... não consigo deixar elas mais a baixo dos icones com css puro...
Answer: CONSEGUI!!!
RESOLVIDO COM 3 ATRIBUTOS, 1 LINHA:
margin-left: -75px;
position: absolute;
margin-top: 54px !important;

Muito obrigado a todos que tentaram me ajudar de qualquer maneira, que tenham uma ótima semana.


How to check if node is being rendered inside view?

Question: I need to check inside node template if its contents are being rendered through view or not. What is the best approach to do it?
Answer: You can check to see if $view is set and is an object in the template file; if it does, it means the node is being rendered in a View. From there you can even check that the View is the correct one if you need to.
if (isset($view) && is_object($view)) :
  // Do something
endif;

Answer: I am unaware of a good way to do this.  However, the proper Drupal way is to not have one part of a template rely on where it is being used.  If something needs to be different, then render it out in a different manner.
For nodes in views, you can accomplish this with custom node view modes.  Essentially, you implement hook_entity_info_alter, and create new view modes (ones inaddition to Full and Teaser).  You can then use the Manage Display tab on the content type page to set up how you want the new mode to work, and then set up your view to use Node style: Row with your new display mode.  Also look at @Andy's answer on How to add additional display(view mode) for node? for some options that make this easier to do just from the UI.
Comment: Thanks, first link was very useful. I've implemented a new custom display type for node and crated template for it.


Drupal Services Bad request

Question: I have a drupal7 Site, in which I activated the services module to expose a SOAP service.
The problem is that I set up everything, the endpoints, the handling of the request, load the WSDL and set the class to get th efunctions, but I always get an error
function tigoapi_server() {

require_once 'ServicePort.php';
global $HTTP_RAW_POST_DATA;
$server = new SoapServer(drupal_get_path('module', 'tigoapi') . '/wsdl/TigoAPIService_1.wsdl');
ini_set("soap.wsdl_cache_enabled", "0"); // disabling WSDL after the server is initiated
$server->setClass('ServicePort');

error_log(print_r($server->getFunctions(),true),3,"/var/www/sites/tigo/sites/all/modules/services/tigoapi/tigoapi.log");
$server->handle($HTTP_RAW_POST_DATA);

I always get:
curl http://server/tigoapi?wsdl
<?xml version="1.0" encoding="UTF-8"?>
<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/"><SOAP-ENV:Body><SOAP-ENV:Fault><faultcode>SOAP-ENV:Client</faultcode><faultstring>Bad     Request</faultstring></SOAP-ENV:Fault></SOAP-ENV:Body></SOAP-ENV:Envelope

Now, if I try it , same server, same WSDL, same ServicePort class, just not going throug the Drupal router it works:
    require_once 'ServicePort.php';
global $HTTP_RAW_POST_DATA;
//$server = new SoapServer(drupal_get_path('module', 'tigoapi') . '\wsdl\TigoAPIService_1.wsdl',array('encoding'=>'UTF-8'));
$server = new SoapServer('wsdl/TigoAPIService_1.wsdl');
ini_set("soap.wsdl_cache_enabled", "0"); // disabling WSDL after the server is initiated
    $server->setClass('ServicePort');

    error_log(print_r($server->getFunctions(),true),3,"/var/www/sites/tigo/sites/all/modules/services/tigoapi/tigoapi.log");
//$server->handle();
$server->handle($HTTP_RAW_POST_DATA);

This works perfectly.
I'm using nginx and php-fpm, it would seem that the difference is in the way the requests gets here as with drupal I have a $_GET variable called 'q'
any ideas on this?
Answer: Ok it seems I'm implementing it wrong.
The SoapServer::handle() source code shows why:
 if (SG(request_info).request_method &&
        strcmp(SG(request_info).request_method, "GET") == 0 &&
        SG(request_info).query_string &&stricmp(SG(request_info).query_string, "wsdl") == 0) {.....

the Get parameter must be wsdl, which Drupal rewrites.
Also in essence using the SoapServer drupal module you get around this.
references to implement this properly:
example
More info
Soap server module

Drupal Services Bad request


I am looking for a methodology for categorizing keywords

Question: I.e. I want to put in Baseball and get out Sports & Outdoors.
Answer: Try WordNet.
The relation beween Baseball and Sports is called hypernym.
Here is a snippet out of WordNet's baseball hypernym hierarchy:

S: (n) baseball, baseball game, ball (a ball game played with a bat
  and ball between two teams of nine players; teams take turns at bat
  trying to score runs) "he played baseball in high school"; "there was
  a baseball game on every empty lot"; "there was a desire for National
  League ball in the area"; "play ball!" direct hyponym / full hyponym
  domain term category direct hypernym / inherited hypernym / sister
  term S: (n) ball game, ballgame (a field game played with a ball
  (especially baseball)) S: (n) field game (an outdoor game played on a
  field of specified dimensions) S: (n) outdoor game (an athletic game
  that is played outdoors) S: (n) athletic game (a game involving
  athletic activity) S: (n) sport, athletics (an active diversion
  requiring physical exertion and competition) S: (n) diversion,
  recreation (an activity that diverts or amuses or stimulates) "scuba
  diving is provided as a diversion for tourists"; "for recreation he
  wrote poetry and solved crossword puzzles"; "drug abuse is often
  regarded as a form of recreation" S: (n) activity (any specific
  behavior) "they avoided all recreational activity" S: (n) act, deed,
  human action, human activity (something that people do or cause to
  happen) S: (n) event (something that happens at a given place and
  time) S: (n) psychological feature (a feature of the mental life of a
  living organism) S: (n) abstraction, abstract entity (a  ...


Como Fazer a seguinte função em javascript puro?

Question: Eu gostaria de fazer o seguinte cálculo:
pegar o valor de valor a pagar,pegar o valor dos dias de atraso e que ao clicar no botão confirmar faça o seguinte calculo: valor_a_pagar*(atraso*2)/100, tentei isso mas não deu certo
html:

   Pagamento De Janeiro

  {% for s in students %}
  Valor a pagar {{s.fee}}
<form>

 Dias de atraso<input type="search" placeholder=""
           name="atraso" id="atraso" value="0">
        <button class="btn btn-light" type="submit" onclick="calc()">confirmar</button>
  {%endfor%}
  {% render_field form.jan_pay class="form-control" %}

Comment: mas esse código já é js puro
Comment: então precisa fazer debug e descobrir o que acontece, olhar no console e ver se tem erros
Comment: mas ele não funciona
Answer: O problema é que você está pegando o valor atraso.value fora da função calc. Então esse valor é carregado apenas uma vez, quando a página é carregada, e nunca mais é atualizado.
Se a ideia é pegar o que foi preenchido, pegue o valor dentro da função:

// os elementos podem ser pegos fora da função mesmo
var pag = document.getElementById("pag_jan");
var atraso = document.getElementById("atraso");

function calc(e) {
  e.preventDefault();
  // pegue os valores dentro da função
  var result = pag.innerText;
  var result_atraso = atraso.value;

  if (result_atraso <= 0) {
    return;
  } else {
    var resultado =  result * (result_atraso * 2) / 100;
    console.log(resultado);
  }
}

// associar o evento de clique à função calc
document.getElementById("botao").addEventListener('click', calc);
 Pagamento De Janeiro

Valor a pagar 100
  <form>
    Dias de atraso
    <input type="search" name="atraso" id="atraso" value="0">
    <button id="botao">confirmar</button>
  </form>

E no JavaScript também coloquei ponto-e-vírgula no final das linhas. Pode parecer "frescura", e sei que o JavaScript "aceita" o código sem ponto e vírgula e "funciona", mas isso evita algumas situações bizarras que podem ocorrer se você não usá-los, como essa e essa (veja mais sobre isso aqui).
Comment: Obrigado amigo funcionou, eu já tinha ouvido falar sobre os ponto e virgulas mas como eu programo muito em python acabo esquecendo


Is this a travel under Euroleague basketball rules?

Question: In basketball's Euroleague, a player who is stationary receives the ball. A few seconds after receiving the ball he steps back and after both of his feet touch the ground he shoots. Is this a travel?
Answer: Euroleague plays under FIBA Rules; in that rulebook, travelling is defined thusly:

Establishing a pivot foot by a player who catches a live ball on the playing court:

• A player who catches the ball while standing with both feet on the floor:

▬ The moment one foot is lifted, the other foot becomes the pivot foot.
▬ To start a dribble, the pivot foot may not be lifted before the ball is released
      from the hand(s).
▬ To pass or shoot for a field goal, the player may jump off a pivot foot, but
      neither foot may be returned to the floor before the ball is released from the
      hand(s).

Thus, if a player is stationary and receives the ball, they may pick up one foot and replace it, or may pick up both feet and replace neither foot (passing or shooting in the air), but may not pick up both feet and replace both.


(OG) Example function to detect User's roles?

Question: Using Open Atrium 6.x-1.2 (Organic Groups 6.x-2.3 inc it's access control.mod), would someone be as kind to provide an example function that would detect the current user's role? It's my understanding OG overrides the standard Drupal permissions page. My end goal is to allow certain roles access to groups they don't specifically have membership (eg: Executive) for a custom OA/OG access control policy/module.
Would some implementation of Rules be possible here?
My skill level: no PHP but just started studying module dev
Answer: To test whether the currently-logged-in User has a specific Role, you can do this:
<code>global $user;
if (in_array('Executive', $user->roles)) {
  drupal_set_message("I have the 'Executive' role.");
}
</code>
Comment: Wow. Seems I was thinking things would be more complicated by the nature of OG ignoring the standard Drupal perms. Brilliant & my thanks to you, good sir.
Comment: @TheDoctor Please don't change the title if the question becomes solved, simply mark the answer as accepted as stated in [ask]


Show that $ trace(AB) = (\sum_{i=1}^{n} a_{i}b_{i})^2 $

Question: With $a,b \in \mathbb{K}^n, \ A:=(a_{i}a_{j})_{i,j = 1,...,n} \in \mathbb{K}^{n x n} $ and $ B:=(b_{i}b_{j})_{i,j = 1,...,n} \in \mathbb{K}^{n x n} $ (where $\mathbb{K}$ is a field)
I want to show that
$$ trace(AB) = (\sum_{i=1}^{n} a_{i}b_{i})^2 $$
I am fairly new to matrices and especially traces, so any hint as to where I begin here would be greatly appreciated!
Comment: There's a formula for the multiplication and a formula for the trace...
Comment: @Randall These are very special matrices since the $(i,j)$ entry is the product $a_ia_j$ or $b_ib_j$. These cannot be diagonal unless they are the zero matrix.
Comment: Also, if I'm reading your matrices right, shouldn't the square be on the inside?  That, or it's just wrong.
Comment: Maybe that is a mistake in my textbook, there it is stated with the square outside the bracket.
Comment: Well I cannot get it to work even for diagonal matrices.  Maybe someone else can chime in on what's going on here.
Answer: The $(i,i)$-entry of $AB$ is given by
$$\sum_{k=1}^n A_{i,k}B_{k,i} = \sum_{k=1}^n a_ia_kb_kb_i = a_ib_i \sum_{k=1}^n a_kb_k.$$
Thus the the trace of $AB$ is
$$\sum_{i=1}^n \left( a_ib_i \sum_{k=1}^n a_kb_k \right).$$
Can you show that is equal to $\left(\sum_{i=1}^n a_ib_i\right)^2$?
Comment: I'm not sure what you mean by "per associativity," but yes you can write that.
Comment: Ah i see now. Thanks.
Comment: I mean, it wasn't my question anyway but I still appreciate learning something.
Comment: Can I write: $\left( \sum_{i=1}^n  a_ib_i \right) \left( \sum_{k=1}^n a_kb_k \right) = \left(\sum_{i=1}^n a_ib_i\right)^2$ per associativity?


Why can't I see all of the client certificates available when I visit my web site locally on Windows 7 IIS 7?

Question: My team has recently moved to Windows 7 for our developer machines. We are attempting to configure IIS for application testing. Our application requires SSL and client certificates in order to authenticate.
What I've done:

I have configured IIS to require SSL and require (and tried accept) certificates under SSL Settings.
I have created the https binding and set it to the proper server certificate.
I've installed all the root and intermediate chain certificates for the soft certificates properly in current user and local machine stores.

The problem
When I browse to the web site, the SSL connection is established and I am prompted to choose a certificate. The issue is that the certificate is one that is created by my company that would be invalid for use in the application. I am not given the soft certificates that I have installed using MMC and IE.
We are able to utilize the soft certs from our development machines to our Windows 2008 servers that host the application.
What I did:

I have attempted to copy the Root CA to every folder location for the Current User and Location Machine account stores that the company certificate's root is in.

My questions:

Could I be mishandling the certs anywhere else?
Could there be a local/group policy that could be blocking the other certs from use?
What (if anything) should have to be done differently on Windows 7 from 2008 in regards to IIS?

Thanks for your help.
Comment: I dont have an answer, but I would like all the drive by,  shit question asking folks to take note of how it should be done.
Comment: @Jay. This is a great question. Thanks for adding good content to the community here.
Answer: The problem is due to some external security policies that renew each week. Recreated the above process with a PC not on the network and it worked fine. Thanks overzealous security administrators!


How to insert values from multiple tables into another table?

Question: I'm new to databases. I have 4 tables in total: 3 tables are populated automatically when the user logs on to Facebook. I want the values of the primary keys form those tables to be populated into the 4th table. How do I do this... I need help soon!
This is how the tables look:
table:attributes
fb_user : fb_uid, birhtday, gender, email.
company_master : com_id, com_name.
position_master : pos_id, pos_name.

And the 4th table goes like this:
[table]:[attributes]
work_history : work_id, fb_uid, com_id, pos_id.

fb_uid, pos_id and com_id are primary keys.
How to perform this using less database operations? Is there any way to use triggers for this to optimize?
Answer: Firstly what type of database are you using?  Secondly, this seems to be a database design issue.  You really should use a single unique primary key across all tables instead of using different primaries and mapping them.  Since your using Facebook it would make sense to use their Facebook id as the primary for all tables then store the other ids as unique fields.  This would also allow you to easily use useful features like joins to retrieve data from multiple tables at once.  If this isn't practical, since for example, your using multiple logins (Facebook Google, etc) for the same user, you would then want to have a lookup table like you suggest as the driving table then use it to help populated the others.  Ideally you want to minimize redundant data as much as possible to reduce the risk of data inconsistencies.  If you are new to databases you should do some reading on database design and database normalization.  A good design will help with scalability and prevent a lot of headaches and frustration.
Comment: i'm using mysql DB.. i'm still a beginner.. thanks anyways. but is there no way to do it with these tables, without making a field common in all the tables??


Flutter chamar um dialog dentro de um onTap()

Question: Estou com um problema em um desenvolvimento de APP no flutter, estou tentando chamar um metodo dentro de um onTap(); porem esta apresentando o seguinte erro:

"The return type 'void' isn't a 'Widget', as defined by anonymous
  closure."

Mesmo quanto uso o metodo como um Widget não da certo.
Segue codigo:
import '*';
import 'descanso.dart';
import 'jornada.dart';

class Menu extends StatefulWidget {
  @override
  _MenuState createState() => _MenuState();
}

class _MenuState extends State<Menu> {
  void _dismissDialog() {
    Navigator.pop(context);
  }

  void _showMaterialDialog() { -----> Estou tentando chamar esse metodo.
    showDialog(
        context: context,
        builder: (context) {
          return AlertDialog(
            title: Text('Material Dialog'),
            content: Text('This is the content of the material dialog'),
            actions: <Widget>[
              FlatButton(
                  onPressed: () {
                    _dismissDialog();
                  },
                  child: Text('Close')),
              FlatButton(
                onPressed: () {
                  print('HelloWorld!');
                  _dismissDialog();
                },
                child: Text('Print HelloWorld!'),
              )
            ],
          );
        });
  }

  @override
  Widget build(BuildContext context) {
    List<String> itemNames = [
      'Simulador',
      'Simulador',
      'Regras',
      'Pesquisa',
    ];

    List<Color> tileColors = [
      null,
      null,
      null,
      null,
    ];

    List<Color> splashColors = [
      invertColorsMaterial(context),
      MaterialColors.blue,
      MyColors.accentColor,
      MyColors.accentColor,
    ];

    return Scaffold(
      backgroundColor: Colors.white,
      body: Column(
        children: <Widget>[
          Expanded(
            flex: 5,
            child: Container(
              child: Image.asset("assets/img_emb.jpeg"),
            ),
          ),
          Expanded(
            flex: 8,
            child: Container(
              child: Padding(
                padding: EdgeInsets.only(top: 0.0),
                child: Scaffold(
                  backgroundColor: Colors.white,
                  body: Container(
                    child: Column(
                      children: <Widget>[
                        Padding(
                          padding: EdgeInsets.only(
                            left: 20.0,
                            bottom: 10.0,
                          ),
                          child: Row(
                            mainAxisAlignment: MainAxisAlignment.start,
                            children: <Widget>[
                              Text(
                                "versao 0.01",
                                style: TextStyle(
                                  color: Colors.black,
                                  fontWeight: FontWeight.bold,
                                ),
                              ),
                            ],
                          ),
                        ),
                        Expanded(
                          child: GridView.count(
                            crossAxisCount: 1,
                            childAspectRatio: 2.5,
                            children: List.generate(
                              itemNames.length,
                              (index) {
                                return Hero(
                                  tag: 'titulo$index',
                                  child: Titulos(
                                    context,
                                    tileColors[index],
                                    splashColors[index],
                                    Row(
                                      mainAxisAlignment:
                                          MainAxisAlignment.center,
                                      crossAxisAlignment:
                                          CrossAxisAlignment.center,
                                      children: <Widget>[
                                        Text(
                                          "${itemNames[index]}",
                                          style: TextStyle(
                                            fontWeight: FontWeight.w700,
                                            fontSize: 20.0,
                                            color: Color(0xFF1E3C96),
                                          ),
                                          softWrap: true,
                                          overflow: TextOverflow.fade,
                                          maxLines: 1,
                                        ),
                                      ],
                                    ),
                                    onTap: () {
                                      Navigator.push(
                                        context,
                                        CupertinoPageRoute(
                                          builder: (context) {
                                            if (index == 0) {
                                              return Jornada();
                                            } else if (index == 1) {
                                              return Descanso();
                                            } else if (index == 2) {

                                              return _showMaterialDialog(); -------> Onde o erro esta aparecendo.

                                            } else if (index == 3) {
                                              return new Scaffold(
                                                backgroundColor: Colors.white,
                                                body: new MyReviewPage(),
                                              );
                                            } else {
                                              return null;
                                            }
                                          },
                                        ),
                                      );
                                    },
                                  ),
                                );
                              },
                            ),
                          ),
                        ),
                      ],
                    ),
                  ),
                ),
              ),
            ),
          ),
        ],
      ),
    );
  }
}

Answer: O seu erro é estar passando uma showDialog para um Navigator...
Modifique o bloco do OnTap() da seguinte forma:
[...]

onTap: () {
  if (index == 2)
    _showMaterialDialog();
  else {
      Navigator.push(
        context,
        CupertinoPageRoute(
          builder: (context) {
            if (index == 0) {
              return Jornada();
            } else if (index == 1) {
              return Descanso();
            }  if (index == 3) {
              return Scaffold(
                backgroundColor: Colors.white,
                body: MyReviewPage(),
              );
            } else
              return null;
          },
        ),
      );
  }

},

[...]

Utilize return somente para quando a sua função for, por exemplo no seu caso, Widget MontarTela(){}.


can the product of 2 non-square matrices be invertible (without rank)

Question: If I have 2 matrices $A$ and $B$, such that $A$ is of dimensions $n$ x $m$ ($n$ lines/rows and $m$ columns ) and $B$ is $m$ x $n$, when $m>n$. Is it possible for $AB$ or $BA$ to be invertible? I know how to prove this using rank, but I would like an explanations that does not use rank.
Comment: By considering its echelon form, a short fat matrix $A$ will annihilate a nonzero column vector $v$ and therefore $CBAv=0$ for all matrices $B$ and $C$. So $CBA\ne I$.
Comment: It's possible for $AB$ to be invertible.
Comment: @LordSharktheUnknown i said i know the solution, i just want to see a proof without the use of ranks
Comment: A demonstration that something is *possible* can be accomplished by giving an example.  In your Question we might give an example of $A,B $ that give $AB=I$, and I'd expect you to be satisfied this product is invertible "without (mentioning) rank".
Comment: You can do the $AB$ part just by writing down examples.
Comment: the more difficult part for me is to prove that $BA$ is singular (without rank of course)
Comment: @DonatPants Are you happy with the notions of Gaussian elimination, and echelon forms, or are they too redolent of ranks for you?
Comment: @LordSharktheUnknown I understand these two concepts, and would be happy with a proof that uses them.
Comment: @LordSharktheUnknown this was the kind of answer I was looking for, feel free to post this as an answer and I will accept it
Answer: It is possible for $AB$ to be invertible. For instance take $A = \left(\begin{array}{rrr} 1 & 0 & 0 \\ 0 & 1 & 0 \end{array}\right)$ and $B = \left(\begin{array}{rr} 1 & 0 \\ 0 & 1 \\ 0 & 0 \end{array}\right)$. The product $AB$ is the $2\times 2$ identity matrix (clearly invertible).
It is not possible for $BA$ to be invertible. I'll explain the "moral" reason for this, then I'll give a more concrete proof. The two matrices $A$ and $B$ represent linear transformations between vector spaces. $A$ represents a linear transformation from a larger vector space to a smaller one, and $B$ represents a linear transformation from a smaller space to a larger one. Thus, the product $BA$ represents a linear transformation from the large space to the large space that goes through a smaller space (we read the linear transformations from right to left). Imagine vector spaces as cotton candy. You can easily squish cotton candy, but once it's been squished, you cannot get it to expand again. You start with a big box of cotton candy. $A$ puts the cotton candy in a small box, and in doing so, it must squish the cotton candy. Then $B$ puts the cotton candy back into the big box. There is no way for it to expand to fill the big box again.
For a formal proof, recall a portion of the invertible matrix theorem: a square matrix is invertible if and only if its null space is $\left\{\vec{0}\right\}$. Since $A$ is $n\times m$ ($m > n$), the null space of $A$ is nontrivial, i.e., there is a nonzero vector $\vec{v}$ such that $A\vec{v} = \vec{0}$. But now $BA\vec{v} = B\vec{0} = \vec{0}$ so $\vec{v}$ is in the null space of $BA$. Thus, $\mathrm{Null}(BA)\neq \left\{\vec{0}\right\}$ so $BA$ is not invertible.
Answer: With $n = 1$, and $m = 2$ we have:
$$(1, 0) \times \left(\matrix{ 1 \\ 0 }\right) = 1$$
Geometrically, the matrix representation of any embedding of $\Bbb{R}^n$ into $\Bbb{R}^m$ composed with a projection back on to $\Bbb{R}^n$ gives an example. The above example corresponds to the embedding of the $x$-axis into the plane and the orthogonal projection onto the $x$-axis.
Answer: I assume that a $n\times m$ matrix has $n$ lines and $m$ columns
$AB$ can be invertible (find an example) but not $BA$ since $A$ represents a linear map from $\mathbb{R}^m$ to $\mathbb{R}^n$ whose kernel is not trivial.


jQuery slideUp to show the element and not hide

Question: jQuery's slideUp effect hides the element by sliding it up, while slideDown shows the element. I want to show my div using slideUp. can anyone guide me ? thanks
Answer: $("div").click(function () {
      $(this).hide("slide", { direction: "down" }, 1000);
});

http://docs.jquery.com/UI/Effects/Slide
Comment: no I didnt, I dont want jQuery UI. I want to do this with jQuery only!
Comment: If you want it, do it. There was an answer before(has been deleted now) using animate, that should be the right way. But you have to do something more on your own than only tell us what you want to have.
Comment: these arguments are not even documented. dont work at all, even the same code using hide
Comment: Umair, I have not tried this, but you could try to change the "hide" to "show" and change the direction to which ever direction you want.
Comment: Should not be so hard to find out the opposite `show()` if you don't want to hide it.
Comment: This is documented, just follow the link provided by Jason, Demo: http://jsfiddle.net/doktormolle/AGtG8/
Comment: You'll need to include jquerUI too, did you?
Answer: It's a little more complex than just saying slideUpShow() or something, but you can still do it. This is a pretty simple example, so you might find some edge-cases that need adressing.
$("#show-animate-up").on("click", function () {
    var div = $("div:not(:visible)");

    var height = div.css({
        display: "block"
    }).height();

    div.css({
        overflow: "hidden",
        marginTop: height,
        height: 0
    }).animate({
        marginTop: 0,
        height: height
    }, 500, function () {
        $(this).css({
            display: "",
            overflow: "",
            height: "",
            marginTop: ""
        });
    });
});

Here's a fiddle showing the slideUp/slideDown methods, the same effects using animate, and a modified version using animate that goes in reverse: http://jsfiddle.net/sd7zsyhe/1/
Since animate is a built-in jQuery function, you don't need to include jQuery UI.
Comment: This should be the answer if the OP doesn't want to use the jQuery UI library
Comment: +1 This works very well and you have a great jsfiddle example. I don't know why this hasn't been chosen as the correct answer
Answer: To get the opposite of slideUp and slideDown. Add these two functions to jQuery.
$.fn.riseUp = function()   { $(this).show("slide", { direction: "down" }, 1000); }
$.fn.riseDown = function() { $(this).hide("slide", { direction: "down" }, 1000); }

Comment: For this you need to use the jQueryUI library, [link](https://developers.google.com/speed/libraries/devguide#jquery)
Comment: This is effectively the same answer that @jason gave earlier only somewhat more obtuse due to namespacing.
Comment: It is essentially the same answer, though this in shortcut-form, that may be more readable to some.
Comment: This is a much better answer because it is easily re-usable.
Comment: may be you want try `slideToggle()` it's up and down show hide functionality. Slow down the movement by give it a value like this `slideToggle(500)` or `slideToggle('slow')`.
Answer: I found a tricky way...
you can set div with css style bottom:0px,
add call
$("#div).slideDown();
will show with the slideUp-to-show effect you want.
Comment: This works, but only as long as the #div in question can also be set to position: absolute; When the #div in question needs to be positioned relative, it does not.
Answer: Jquery toggle
This toggle effect is only for up and down. Jquery UI is for every other direction
Comment: how to use toggle for up and down ?
Answer: Despite the name, slideDown can actually slide your element both ways. Use absolute position if it is required to animate inside the parent element:

#slideup {
  position:fixed;
  bottom:0;
  background:#0243c9;
  color:#fafefa;
  width:100%;
  display:none;
  padding: 20px;
}
#littleslideup {
  position:absolute;
  bottom:0;
  background:#000;
  color:#fff;
  display:none;
  padding:10px;
  z-index:100;
}
#slidedown {
  position:fixed;
  top:0;
  background:#c94333;
  color:#fafefa;
  width:100%;
  display:none;
  padding: 20px;
}
button {
  display:inline-block;
  font-size:16px;
  padding:10px;
}

This amounts to 70% of the total timber stand area of the region (not including the dwarf pine and shrubby alder) and is more than the total area of all other stone birch forests growing in the Magadan, Khabarovsk, Primorye and Sakhalin regions and other areas of its distribution.

Absolute-positioned element

Click >>

<button onclick="jQuery('#slideup').slideDown(1500);"      >"Slideup"</button>
<button onclick="jQuery('#slidedown').slideDown(1500);"    >"Slidedown"</button>
<button onclick="jQuery('#littleslideup').slideDown(1500);">"Slideup" inside element</button>

Finally, closing the subject of volcanic activity, it must be said that the stone birch stands by its functional reaction quite adequately in order to re ect the character and intensity of the physical, chemical and thermic processes, stipulated by volcanism as well as the in uence upon biota and ecosystems.

Could be a bottom cookie warning bar

Could be a top cookie warning bar

Answer: For those who don´t use the Jquery UI but want to add the function to Jquery Library:
jQuery.fn.slideUpShow = function (time,callback) {
    if (!time)
        time = 200;
    var o = $(this[0]) // It's your element

    if (o.is(':hidden'))
    {
        var height = o.css({
            display: "block"
        }).height();

        o.css({
            overflow: "hidden",
            marginTop: height,
            height: 0
        }).animate({
            marginTop: 0,
            height: height
        }, time, function () {
            $(this).css({
                display: "",
                overflow: "",
                height: "",
                marginTop: ""
            });
            if (callback)
                callback();
        });
    }

    return this; // This is needed so others can keep chaining off of this
};

jQuery.fn.slideDownHide = function (time,callback) {
    if (!time)
        time = 200;
    var o = $(this[0]) // It's your element
    if (o.is(':visible')) {
        var height = o.height();

        o.css({
            overflow: "hidden",
            marginTop: 0,
            height: height
        }).animate({
            marginTop: height,
            height: 0
        }, time, function () {
            $(this).css({
                display: "none",
                overflow: "",
                height: "",
                marginTop: ""
            });
            if (callback)
                callback();
        });
    }

    return this;
}

Credits: @redbmk answer
Answer: I've got some downvotes so I checked my answer and indeed I didn't answered correctly the OP question, sorry. So I'm gonna try to fix that.
First, the slideUp() method in JQuery is intended to hide the element rather than reveal it. It is basically the opposite of slideDown() which shows your element by sliding it down.
By knowing that I think we agree that there is no magic function right there to do a slide up effect to show an element (in JQuery).
So we need to do a little bit of work to get what we need: slid up reveal effect. I found out some solutions and here is one I think simple to implement:
https://coderwall.com/p/9dsvia/jquery-slideup-to-reveal
The solution above works with the hover event, for the click event try this modified code:
http://jsfiddle.net/D7uT9/250/
The answer given by @redbmk is also a working solution.
Sorry for my misunderstanding the first time.

OLD ANSWER
It's an old post, but if someone is looking for a solution here is my recommandation.
We can, now, use slideToggle() to achieve this effect (without the need of jQuery UI).
$(".btn").click(function () {
      $("div").slideToggle();
});

Documentation: http://api.jquery.com/slidetoggle/
Comment: It would be very useful if the downvoting is accompanied by a comment. Thank you
Answer: Having encountered this with a student looking to "slide up always hide" an error container, I advised he simply use CSS transitions:
.slide-up {
  transition: 1s ease-out;
  transform: scale(1);
}

.slide-up[aria-hidden="true"] {
  transform: scale(0);
  height: 0;
}

jQuery(document).ready(function($) {
  const $submitButton = $(".btn");
  const $someDivs = $("div");
  const $animatedSlidingTargets = $(".slide-up");
  $someDivs.on("click", function() {
    $animatedSlidingTargets.attr("aria-hidden", true);
  });
});

Answer: For @Jason's answer, whether slide-up to show and slide-down to hide, you still need to use the { direction: "down" } option in jQuery:
$(".btnAbout").on("click", function () {
    // Slide-up to show
    $("#divFooter").show("slide", { direction: "down" }, 1000);
});

$("#btnCloseFooter").on("click", function () {
    // Slide-down to hide
    $("#divFooter").hide("slide", { direction: "down" }, 1000);
});

But this requires jquery-ui, or else you'll hit the TypeError: something.easing[this.easing] is not a function error:


chef-server stuck ruby_block[supervise_rabbitmq_sleep] action run on Docker container

Question: I have an ubuntu host running docker1.2. On top of it I have created a centos6 container which is running great! When I tried to install chef-server-11.x version it gets stuck here:
  * file[/opt/chef-server/sv/rabbitmq/down] action delete (up to date)
  * link[/opt/chef-server/init/rabbitmq] action create (up to date)
  * link[/opt/chef-server/service/rabbitmq] action create (up to date)
  * ruby_block[supervise_rabbitmq_sleep] action run

After Googling, I found we need to specify platform here in /opt/chef-server/embedded/cookbooks/runit/recipes/default.rb, which I did see following file contains, but it's still not working:
when "centos"
  include_recipe "runit::upstart"

Do I need to specify something else for docker running centos?
Answer: I have solved above issue:
Because Docker replaces the default /sbin/init with its own, there's no way to run the Upstart init inside a Docker container. However this causes some problems: some Debian packages try to communicate with Upstart, and will fail to install.
Solution:
$sudo dpkg-divert --local --rename --add /sbin/initctl
$sudo ln -s /bin/true /sbin/initctl


Alpine linux on AWS / EC2 : how to login with my public key?

Question: I'm trying to install Alpine Linux (v.3.6) on Amazon AWS EC2 via a standard community AMI. I provided my valid ssh key, which does work with all other instances (Amazon Linux) in the same VPC. However, I can't login to the instance. What is the default username for Alpine AWS?
Should my public SSH key be uploaded automatically into the instance like in case of Amazon Linux, Ubuntu, etc. - or is Alpine Linux AMI for some special installations only, so I should use Packer or smth. to create a new user and put my public key there?
Where can I find any documentation about AWS Alpine Comunity AMI?
Answer: If anyone's still scratching their heads on this one:
I just launched the latest Alpine-3.7-r2-Hardened-EC2 instance with
ssh -i .ssh/KEY.pem alpine@host

Just guessed it followed the ubuntu@host pattern of the ubuntu instances.
Comment: using the `Alpine-3.7-r2-Hardened-EC2` AMI you can become `root` with `sudo -s` after logging in as `alpine`
Comment: how'd you manage to do it? it seems nothing is listening there: ssh: connect to host x.x.x.x port 22: Operation timed out. I tried `root` and `alpine`, neither worked
Comment: never mind, figured it out, it was configuration - I created another and yes, it works. would help if they had it documented somewhere :/
Answer: As far as I can see the community AMI (ami-23475747) is undocumented.  The standard installation uses root and no password for login.  I have tested the AMI with my public key loaded and the server rejects the key.
Comment: I can't login via ssh into the server as a root user without a password.
Answer: If you're using PuTTY on Windows, upgrade to version 0.76 or newer.
I ran into this same problem when trying to connect using PuTTY and Pageant 0.73 on Windows. I knew my key worked, since I had just used it for several other test machines. Per the other solutions on this post, I tried connecting on the command line using the ssh binary and manually specifying my SSH key as a .pem file, which curiously worked correctly. I assume this is because this version of SSH had installed had been updated more recently. This led me to try an upgrade of PuTTY, which connected properly immediately.


Using index position to filter an array by values in another array - javascript

Question: I'm working with an extremely large data cube that I need to manipulate for data visualization purposes. I have a multidimensional array contains arrays of every possible combination of objects, with the final object of each array being an associated value.
I'm using multiple inputs (each with id's enumerated based off of the value's index in data) to allow users to filter the results by each object within the array, except for the last object that is displayed as "total available". From those inputs I'm aggregating selections into a variable so that the index of the selections corresponds to the index position of the associated value in data.
var selections = [];
var data = [[val0, val1, val2, 5121231], [val0, val1, val2, 2242], [val0, val1, val2, 72356], [val0, val1, val2, 24122], [val0, val1, val2, 75632]];

$('#fields').change(function(){
    for (var i = 0; i < data[0].length; i ++){
        selections[i] = $('select#field' + i).val();
    }
});

This will create a multidimensional array that looks like this:
selections = [[data[0][0], data[1][0], data[2][0], data[3][0], data[4][0]], [data[0][1], data[1][1], data[2][1], data[3][1], data[4][1]], [data[0][2], data[1][2], data[2][2], data[3][2], data[4][2]], [data[0][3], data[1][3], data[2][3], data[3][3], data[4][3]]]

What I'm attempting to do is filter data such that for ALL selections made, if data[x][i] === any value in selections[i], data[x] is populated into a new array.
Any thoughts?
*****UPDATE*****
A HUGE thanks to Dave for his help! We were able to set up dependent dropdown filters that manipulates a keyless multidimensional array (data cube). If you're working with large data sets in-browser, take a look at the solution. Here's what he/we came up with:
https://jsfiddle.net/JSnoobDC16/yteu6cbb/28/
Answer: Since you're using jQuery, this can easily be solved using $.grep() combined with Array.some().
var newArray = $.grep(data, function(item) {
  return selections.some(function(selectedValue, i) {
    return selectedValue.indexOf(item[i]) >= 0;
  });
});

There's a full snippet below and an updated fiddle here: https://jsfiddle.net/gh8fzxLh/

//function to initialize the materialize dropdowns
function pageReady() {
  $(document).ready(function() {
    $('select').material_select();
  });
}

//function to get the sum of object elements
function sum( obj ) {
  var sums = 0;
  for( var el in obj ) {
    if( obj.hasOwnProperty( el ) ) {
      sums += parseFloat( obj[el] );
    }
  }
  return sums;
}

//function to return array of all values at a certain index positon
function getFields(matrix, index){
  var fields = [];
  for (var i = 1; i<matrix.length; i++ ){
    fields.push(matrix[i][index]);
  }
  return fields;
}

//function to return only unique values from array
function unique(arr) {
  var hash = {}, uniqueArr = [];
  for ( var i = 0, l = arr.length; i < l; ++i ) {
    if ( !hash.hasOwnProperty(arr[i]) ) {
      hash[ arr[i] ] = true;
      uniqueArr.push(arr[i]);
    }
  }
  return uniqueArr;
}

//importing data set
var data = [
  ["state", "gender", "martial staus", "ethnicity"],
  ["GA", "null", "null", "Caucasian", 5086317],
  ["FL", "", "null", "null", 4338099],
  ["IN", "M", "null", "African-American", 72238],
  ["GA", "", "married", "Caucasian", 390578],
  ["MO", "null", "null", "Caucasian", 4165871],
  ["MO", "", "married", "Caucasian", 344501],
  ["NY", "null", "null", "African-American", 1204504],     ["AR", "M", "single", "Caucasian", 164311],
  ["CO", "null", "married", "null", 551192],
  ["OH", "null", "married", "Caucasian", 1017924],
  ["LA", "M", "null", "East Asian", 3229],
  ["AZ", "F", "single", "Uncoded", 21302],
  ["AR", "", "married", "Middle Eastern", 187]
];

var selections = []; //variable to hold all selected values
var valCombos = data[0].length; //establishing number of dropdown selection objects

/* Adding multiselection dropboxes (and soon to be other data inputs)
for each field. */
for (var i = 0; i < valCombos; i ++){
  var options = unique(getFields(data, i)).sort();
  $('#selectBar').append('

<select class="fields" id="field' + i + '" multiple><option value="" disabled selected>Select Values</option></select>' + data[0][i] + '

');
  $.each(options, function (index, value) {
    $('#field' + i).append('<option value="' + value + '">' + value + '</option>');
  });
}

pageReady();

/*Updating "selections" array as user makes selections.
"Selections" will be used to filter the cube for visualizations. */
$('.fields').change(function(){
  for (var i = 0; i < valCombos; i ++) {
    selections[i] = $('select#field' + i).val();
  }
  console.log(selections);

  var selectedData = getSelectedData(data, selections);

  console.log(selectedData);
  $("#count").text(sumData(selectedData));

});

function getSelectedData(data, selections) {
  return $.grep(data, function(item) {
    return selections.some(function(value, i) {
      return value.indexOf(item[i]) >= 0;
    });
  });
}

function sumData(selectedData) {
  return selectedData.reduce(function(prev, current) {
    return prev + current[current.length - 1];
  }, 0);
}

<link href="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.6/css/materialize.min.css" rel="stylesheet"/>

  Sum of lastIndexOf values displays here

Comment: I dug into the JQuery documentation around $.grep(), but I don't think I'm implementing your suggested snippet correctly. The problem mainly stems from the fact that the various arrays in "selections" can have equal values. So, if I'm returning any item in data that matches some value in selections without specifying *which* item matches from which value (ex: `data[i][x] == selections[x][y] !== selections[y][y]`), then I'll get a lot of false positives.
Comment: Maybe a fiddle is the best way to share, since there are a number of dependencies I'm working with. https://jsfiddle.net/JSnoobDC16/yteu6cbb/12/
Comment: Ah, I think I get it. My syntax was slightly off and I had a small bug in it. See the updated answer and updated fiddle. Is this what you are looking for?
Comment: So close! I need dependency between the filters. So essentially, if you make a selection in the "State" filter, then any selection you make thereafter will satisfy both the "State" selection AND the new selection. For instance:

"State = AR" returns two arrays. If I were then to select "Gender = M", selections would now only contain the array where "State = AR && Gender = M".
Comment: I got it! Solution in the updated post. Thanks so much for your help, Dave!
Comment: I'm glad I could help. I should mention that if you only want the sum, this can be simplified so you aren't iterating the array twice. Originally I thought you actually needed the array output. You could do an `$.each()` instead of a `$.grep()`


Custom alert dialog not dismiss

Question: I want to implement dismiss to R.id.textSizeA button, but it's not working. Anyone can help? The custom alert dialog has lots of radio buttons for its settings. When I press the radio button it should close the dialog, but I don't know how to do.
 final LinearLayout textSizeBtn = (LinearLayout) findViewById(R.id.text_size_btn);
    textSizeBtn.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(final View view) {

            final AlertDialog.Builder alertDialog = new AlertDialog.Builder(view.getContext());

            final LayoutInflater layoutInflater = LayoutInflater.from(view.getContext());
            final View view1 = layoutInflater.inflate(R.layout.font_size_dialog, null);
            alertDialog.setView(view1);

            RadioGroup radioGroup = (RadioGroup) view1.findViewById(R.id.textSizeChanGroup);
            radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
                @Override
                public void onCheckedChanged(RadioGroup radioGroup, int checkedId) {

                    TextView sampleText = (TextView) view1.findViewById(R.id.texSize_sampleText);

                    if (checkedId == R.id.textSizeA) {
                        String size = String.valueOf(12);
                        sampleText.setTextSize(Float.parseFloat(size));
                        textSizeHint.setText(size);
                        SharedPreferences.Editor editor = view.getContext().getSharedPreferences(String.valueOf(R.string.textSizePref), MODE_PRIVATE).edit();
                        editor.putString("textSizeA", size);
                        editor.clear();
                        editor.apply();

                    } else if (checkedId == R.id.textSizeB) {
                        String size = String.valueOf(13);
                        sampleText.setTextSize(Float.parseFloat(size));
                        textSizeHint.setText(size);
                        SharedPreferences.Editor editor = view.getContext().getSharedPreferences(String.valueOf(R.string.textSizePref), MODE_PRIVATE).edit();
                        editor.putString("textSizeA", size);
                        editor.clear();
                        editor.apply();

                    }
                }
            });
            alertDialog.create().show();

        }
          });

Comment: You are not even dismissing the dialog. Use alertDialog.dismiss() where you want to close it.
Comment: i want to dismiss when the radio button is checked, how to implement?
Answer: Try this
Change
alertDialog.create().show();

to
AlertDialog alert = alertDialog.create();
alert.show();

now use alert to dismiss the alert like below
if (checkedId == R.id.textSizeA) {
    String size = String.valueOf(12);
    ...
    ...
    editor.apply();
    alert.dismiss(); // add this
} else if
...
...

Comment: Sorry my bad. It was my mistake. Please try now.
Answer: Replace this line
final AlertDialog.Builder alertDialog = new AlertDialog.Builder(view.getContext());
with
final AlertDialog alertDialog = new AlertDialog.Builder(view.getContext());
And this
alertDialog.create().show();
with
alertDialog.show();
and call alertDialog.dismiss(); whenever you want to dismiss alert dialog

Custom alert dialog not dismiss


How should event and fact data be combined in modelling a prediction?

Question: I am attempting to predict whether an individual is likely to complete an action given a set of input data about their actions on an ecommerce website.
Some of that data could be considered "factual". For instance, their name, how much they've spent in total, products they've bought, time since they last purchased.
Some of the data however could be considered "event" based. For instance, the time between two purchases, or the amount of time passed since the last action, or the offers on sale right now, or product they've bought.
I believe that in some cases the factual data will influence the action rate (e.g. someone has previously bought a lot, suggesting loyalty to the site) and in other cases the event data will influence it (e.g. today there is a 20% off sale site wide, suggesting more users are likely to ).
Is it better to learn off the event data (where each event is considered in isolation, and you potentially lose some of the aggregated data) or the aggregate data (where you potentially lose some of the nuance between events).

UserID,Timestamp,ThisOrderValue,TotalOrderValueEver,Offers,TimesActionPerformed
User1,Time0,£100,£100,20%,0
User1,Time1,£40,£140,15%,1
User1,Time2,£30,£170,15%,1
User1,Time3,£100,£270,NULL,2
User2,Time0,£10,£10,15%,0
User2,Time1,£100,£110,NULL,0

Or should I go for something that aggregates everything together, like this:

UserID,FirstSeen,LastSeen,FirstOrderValue,LastOrderValue,TotalOrderValueEver,OffersSeen,TimesPerformedAction
User1,Time0,Time2,£100,£30,£270,20%;15%,2
User2,Time0,Time1,£10,£100,£110,15%,0

My assumption would be that the second is correct to learn from, but throws away possible relevant data (such as the connection between the 20% off and the first purchase, or that they didn't perform the action until their second purchase).
Which makes more sense?
Comment: What makes you think using the raw event data causes you to "lose some of the aggregated data"?
Comment: Possibly a misguided hunch! I'm worried that if each event is considered in isolation (e.g. Event1,Order1=£10,Event2,Order2=£20,etc) that I'd lose something that the aggregate includes, such as the fact that Event2 triggered the Action I want because the first order (Order1) had some property to it.
Comment: If I understand correctly, your concern is that there could be lagged effects among the events: that is, features of one event could influence the outcome of a later event. Is that correct? Because I understand why you might have trouble seeing how to estimate a lagged effect with the event data, but not how the aggregate data would help.
Comment: Yes, I think that's what I mean - I believe that events affect later events. I believe the aggregate data would help because someone who has high purchase frequency or high average order volume is more likely to complete the action. And so I wonder if event data is best, enriched with aggregate data?
Answer: It sounds like your best bet is to use the event data, but supplement it with lagged covariates. For example, if you want to investigate the effect of the previous order value on some characteristic of the current order, then add a column PreviousOrderValue. Or you could add a column for the total order value over all the subject's orders in the previous 30 days. There's a lot of possibilities here; books on the analysis of longitudinal data or time series are good places to get an overview.