If a joint cdf is increasing in each argument, then the pdf is strictly positive a.s.?

Question: Let $F:\mathbb{R}^d \to [0,1]$ be an absolutely continuous joint cdf and let it be strictly increasing in each argument. Does it imply that its pdf $f$ is strictly positive a.s. (with respect to the Lebesgue measure on $\mathbb{R^d}$)? I would be very thankful for a reference to a book.
My idea was to show that $F$ being strictly increasing implies that $\int_A f d\lambda > 0$ for any $A = (a_1,b_1) \times \ldots \times (a_d, b_d)$, where $(a_i, b_i)$ are open intervals in $\mathbb{R}$ and $\lambda$ is the Lebesgue measure on $\mathbb{R}^d$. This would in turn imply that $f > 0$. However, I didn't manage to show any of these implications.
Comment: No, in the one-dimensional case for example it implies only that $f \geq 0$. There can be points where $f=0$.
Comment: @Karl I meant strictly positive a.s. I corrected the formulation.
Answer: No, this is not true. We construct a counterexample in the plane. To make computations easy, we restrict ourselves to the unit square $U=[0,1]\times[0,1]$, but you will see that the idea extends to the entire plane easily. Define the set $N=[1/3,2/3]\times[1/3,2/3]$.
Consider the probability density function
$f(x,y)=\begin{cases} 0&(x,y)\not\in U,\\
0&(x,y)\in N,\\
9/8&(x,y)\in U \setminus N.
\end{cases}$
The associated marginal distribution functions are strictly increasing for arguments inside the unit interval. The idea easily extends to the whole space. For example, take a standard normally distributed vector in $\mathbb{R}^d$, set its density to zero for arguments in the unit ball and renormalize to get a density function again.
Comment: Thanks, you're right. I guess one needs continuity of $f$ to obtain that it is strictly positive...
Comment: Glad I could help. By the way, continuity of $f$ is not relevant. You can also let $f$ go down from $U$ to the null set $N$ in a continuous way. The problem is that the marginal distributions do not "feel" the sets where $f$ is null because they integrate it out.


Probability of the second product to be a failure if the first was success from two boxes

Question: There are two boxes with products. We know that the the products in the first box are perfect, but the products in the second are $\dfrac{1}{4}$ of them a failure. We choose a random box and a random product and we see that it is a success and we put it back in the box. What is the probability a second product from the same box will be a failure?
I don't know how to approach this problem.
Answer: Hint: This is a conditional probability problem. Calculate the probability that the first product is from the non-perfect box. If you have that, multiply that by $\frac14$ to know the probability that the product from the same box is a failure.


Pegar input pela view

Question: tenho um formulario com os inputs: email, nome e sobrenome. O email sempre terá um formato definido, então quero pegar os elementos e fazer com que preencha automaticamente nos outros campos, exemplo:
Usuário digita o email
Email: firstname.lastname@example.com (os emails sempre terão esse formato), então quero que o form preencha nos outros campos:
Nome: carina
Sobrenome: joao
views.py
def cadastro(request):
    if request.method == 'POST':
        return create(request)
    else:
        return new(request)

def new(request):
    return render(request, 'cadastro1.html',
                {'form': CadastroForm()})

def create(request):
    form = CadastroForm(request.POST)
    ponto = form.email.index(".")
    arroba = form.email.index("@")
    first = form.email[0:ponto]
    second = form.email[ponto + 1:arroba]

    obj = form.save()
    if not form.is_valid():
      return render(request, 'cadastro1.html',
                    {'form': form})

    return HttpResponseRedirect('/cadastro/%d/' % obj.pk)

Aqui já tenho o código para percorrer, porém não estou sabendo jogar nos campos
Comment: Vc quer que as informaçãoes apareçam no form enquanto o usuário digita ou basta o usuario digitar o email e vc salva diretamente no banco, sem a necessidade dos campos (nome e sobrenome) aparecerem dinamicamente para o ususário?
Comment: Aparecendo dinamicamente
Comment: Então vc vai ter que usar javascript, veja que vc não deve fazer isso no lado servidor (a view ) e  sim no lado cliente (na rendereização da template). Crie um script e carregue-o junto com a template então manipule o evento `onchange` do elemento de input do email para preencher os campos que vc deseja. Se quiser um exemplo completo, faça um clone [desse repositorio no github](https://github.com/Sidon/drd/), para reproduzi-lo passo a passo com instrucoes em portugues, veja [essa resposta.](https://pt.stackoverflow.com/a/190406/7412)
Comment: Ok, vou fazer isso, obrigada
Answer: Vc pode capturar o campo de email e quebrar a string:
getEmail = request.POST['email'] #Pega o email
email = getEmail.split('@') #Quebra a string antes dps do @
nomes = email[0].split('.') #Quebra a string antes e dps do .
nome = nomes[0] #Aqui vc tem o primeiro nome
sobrenome = nomes[1] #Aqui vc tem o sobrenome

Agora você salva:
user = User()
user.email = getEmail
user.nome = nome
user.sobrenome = sobrenome
user.save()

Mas como disseram, a melhor opção é fazer no front com js e preencher automaticamente o form e já mandar pro back pronto.
Comment: Oi Flávio - você teve muito trabalho para tentar arrumar seu código, e acabou com ele pior.

Para blocos de código, simplesmente cole o código na interface, selecione ele todo, e use o botao `{ } `.  As aspas contrárias são apenas para expressões "inline".
Comment: Mas eu não tinha o código, fui digitando aqui direto baseado em algo q já tinha feito antes. kkkkkk
Mas vllw.

Pegar input pela view


Update and delete queries not working in play-slick

Question: Iam trying to write a simple CRUD application for play-slick. I can Insert into the database and display all users, but I cannot update or delete users. My entire code is below
package models

import javax.inject.{ Inject, Singleton }
import play.api.db.slick.DatabaseConfigProvider
import slick.jdbc.JdbcProfile

import scala.concurrent.{ Future, ExecutionContext }

/**
 * A repository for people.
 *
 * @param dbConfigProvider The Play db config provider. Play will inject this for you.
 */
@Singleton
class PersonRepository @Inject() (dbConfigProvider: DatabaseConfigProvider)(implicit ec: ExecutionContext) {
  // We want the JdbcProfile for this provider
  private val dbConfig = dbConfigProvider.get[JdbcProfile]

  // These imports are important, the first one brings db into scope, which will let you do the actual db operations.
  // The second one brings the Slick DSL into scope, which lets you define the table and other queries.
  import dbConfig._
  import profile.api._

  /**
   * Here we define the table. It will have a name of people
   */
  private class PeopleTable(tag: Tag) extends Table[Person](tag, "people") {

    /** The ID column, which is the primary key, and auto incremented */
    def id = column[Long]("id", O.PrimaryKey, O.AutoInc)

    /** The name column */
    def name = column[String]("name")

    /** The age column */
    def age = column[Int]("age")

    /**
     * This is the tables default "projection".
     *
     * It defines how the columns are converted to and from the Person object.
     *
     * In this case, we are simply passing the id, name and page parameters to the Person case classes
     * apply and unapply methods.
     */
    def * = (id, name, age) <> ((Person.apply _).tupled, Person.unapply)
  }

  /**
   * The starting point for all queries on the people table.
   */
  private val people = TableQuery[PeopleTable]

  /**
   * Create a person with the given name and age.
   *
   * This is an asynchronous operation, it will return a future of the created person, which can be used to obtain the
   * id for that person.
   */
  def create(name: String, age: Int): Future[Person] = db.run {
    // We create a projection of just the name and age columns, since we're not inserting a value for the id column
    (people.map(p => (p.name, p.age))
      // Now define it to return the id, because we want to know what id was generated for the person
      returning people.map(_.id)
      // And we define a transformation for the returned value, which combines our original parameters with the
      // returned id
      into ((nameAge, id) => Person(id, nameAge._1, nameAge._2))
    // And finally, insert the person into the database
    ) += (name, age)
  }

  /**
   * List all the people in the database.
   */
  def list(): Future[Seq[Person]] = db.run {
    people.result
  }

  def del(id: Int) : Future[Seq[Person]] = db.run {
   people.filter(_.id === id).delete

  }

  def update (id: Int, name: String) : Future[Seq[Person]] = {
    db.run(people.filter(_.id === id).update("john"))

  }
}

It might also be possible that I have excluded some imports, so please check to see if i need to import anything.
I also get this error and I don't know what it means:

type mismatch; found :
  UserData.this.dbConfig.profile.ProfileAction[Int,slick.dbio.NoStream,slick.dbio.Effect.Write]
  (which expands to)
  slick.sql.FixedSqlAction[Int,slick.dbio.NoStream,slick.dbio.Effect.Write]
  required:
  slick.dbio.DBIOAction[Seq[models.User],slick.dbio.NoStream,Nothing]
Comment: Please specify the line throwing errors
Comment: @prms ,  def update (id: Int, name: String) : Future[Seq[Person]] = {
    db.run(people.filter(_.id === id).update("john"))

  }
Answer: I think you are having a problem with the return types when you delete or update.
AFAIK they return the number of rows that have been modified.
Try this:
def del(id: Int) : Future[Int] = db.run {
  people.filter(_.id === id).delete
}

def update (id: Int, name: String) : Future[Int] = {
  db.run(people.filter(_.id === id).update("john"))
}


Django filter by two fields rangement

Question: I have a model with two fields: min_age, max_age. And I need to filter it with Django Filters by range of two fields. How can I do that?
# models.py

class AdvertisementModelMixin(models.Model):
    min_age = models.PositiveSmallIntegerField(
        blank=True,
        null=True,
        validators=[
            MaxValueValidator(80)
        ]
    )
    max_age = models.PositiveSmallIntegerField(
        blank=True,
        null=True,
        validators=[
            MaxValueValidator(80)
        ]
    )

Comment: So exactly what are the inputs of the filter, and how would the filter work?
Comment: @willem-van-onsem I'm sending get request like `/?user_age=16`, and it will send me models whose age range is 16 years. For example, it should send model with `min_age=12`, `max_age=18`
Answer: You can create a custom filter with:
from django_filters import FilterSet, NumberFilter

class MyFilterSet(FilterSet):
    user_age = NumberFilter(field_name='user_age', method='filter_user_age')

    def filter_user_age(self, queryset, name, value):
        return queryset.objects.filter(min_age__lte=value, max_age__gte=value)
or for nullable's:
from django.db.models import Q
from django_filters import FilterSet, NumberFilter

class MyFilterSet(FilterSet):
    user_age = NumberFilter(field_name='user_age', method='filter_user_age')

    def filter_user_age(self, queryset, name, value):
        return queryset.objects.filter(
            Q(min_age=None) | Q(min_age__lte=value),
            Q(max_age=None) | Q(max_age__gte=value),
        )
Comment: And what if fields are nullable? for example, `min_age=12`, `max_age=None` it should send me models with `min_age=12`, and `max_age` is unlimited

Django filter by two fields rangement


access field data in template.php and create variable for header image in page.tpl.php

Question: I am trying to allow the user to set a custom image to display in the header on node pages that have a header_image field and to display a default header image on all other pages (including system and module generated pages).
I thought I could do this by creating a "Header Image" view and using a contextual filter to get the header_image field on the displayed node. This works okay when displaying a node that has the header_image field but not on a page that doesn't have that field. Because this view is a block the contextual filter uses the default value of "Content ID from URL" and I can't use a fixed default value.
I am guessing I have to use the preprocess_page function and field_has_data or perhaps the Entity API Module to check if the node has data in the header_image field. If there is no header_image field or it has no value I would like to use the default image for that field. Is there anyway to specify using the default image that was set by the user? other wise I would use the default image at file_stream_wrapper_get_instance_by_uri('public://')->getDirectoryPath().'/default_images/default_header.jpg'
There must be a common solution to this problem.. Actually I just had a thought.. what if there are multiple nodes on a page? Any suggestions what I should do to accomplish this?
Answer: I recently tried to do this but stumbled then over the Header Image Module which does this perfectly. It allows you to create a block which holds any content (for example a custom content type) and ads it to a block. You can specify on each content where it should be displayed (nid, path, term etc.).


Is $BAB'$ (with positive definite $A$ and full-row rank$(B) = k$) itself of rank $k$?

Question: Here's the setup:
A matrix $B$ with dimensions $k \times p$ with $k \leq p$ and rank$(B) = k$.
A matrix $A$ with dimensions $p \times p$ is positive definite (not necessarily symmetric).
Question: Is the square matrix $BAB'$ (which will have dimensions $k \times k$) a full-rank matrix?
I know that the rank is at most $k$, but if the rank can be shown to equal $k$, that will make things very easy for what I need to do.
Note: $B'$ is the notation I use for the transpose of matrix $B$, partially because I suck at HTML.
Thank you in advance.
Comment: Maybe you'll find this formatting guide helpful for future questions: http://meta.math.stackexchange.com/questions/5020/tex-latex-mathjax-basic-tutorial-and-quick-reference. Also, you can write $A^T$ for transpose matrices by typing "A^T"
Answer: Hint: motivate the following steps to prove your statement
$BAB^Tx=0$ $\Rightarrow$ $x^TBAB^Tx=0$ $\Rightarrow$ $y^TAy=0$ $\Rightarrow$ $y=B^Tx=0$ $\Rightarrow$ $x=0$.


Test for empty string in Mongoose regular expression

Question: Everything I've found indicates that an empty string can be matched in a regular expression by /^$/. However, that expression is not working in my Mongoose Validator for zipcode.
I want to set zipcode if one of two states is true - either it is empty or it is a valid, five digit number.
ZIP_REGEX: /^$|^[0-9]{5}$/
zip: {
    type: Number,
    validate: [ ZIP_REGEX, 'ValidationError']
},

This validator fails each time I attempt to store an empty string. The result is I can set valid zipcode, but never unset them. Is Mongoose also trying to verify that the empty string is a Number? Is the regular expression wrong?
Comment: Can an empty number even exist?  How can you store an empty string in a numeric type?  How can you validate an empty string against a numeric type?
Comment: One thing I've discovered is that if the type is String, this works fine. Not a great solution, however.
Comment: Practically speaking, yes, an empty number can exist. It's equivalent to a user saying, "I do not wish to share my zipcode with this service."
Answer: Use a custom validation function for anything a bit unusual like this.  Assuming you want to support both numbers and strings as input:
function validator(v) {
    return (!v && v !== 0) || /^[0-9]{5}$/.test(v.toString());
};

zip: {
    type: Number,
    validate: [validator, 'ValidationError']
},


Chosen library not working

Question: I installed chosen module and the library v1.8.3.
Jquery update is 1.10
Libraries is installed and enabled as well.
I get this error on the console when I try to use a select list with chosen:
Uncaught TypeError: this.selected_item.off is not a function

Does anyone know how to solve this?
Answer: I guess the Chosen library version 1.8.3 (released Jan on 22 2018) is a little bit too far ahead of the Chosen module version 7.x-2.1 (released on Mar 23 2017).
Replace the library by an older release (preferably version 1.1.0) and it should work.

From the Chosen module's README.txt:

-- INSTALLATION --

  1. Download the Chosen jQuery plugin
  (http://harvesthq.github.io/chosen/ version 1.1.0 is recommended)
  and extract the file under sites/all/libraries.
  2. ...

Comment: Hi. Tried with version 1.1.0
Still doesn't work, same console error. Tried to install chosen module again but nothing...
Comment: @Drii7 – Please ensure to flush all caches (Drupal, Browser) multiple times.
Comment: Funny - tried with safari and it works. Maybe is the chrome cache! Thank you! :)
Comment: @Drii7 – Disable Chrome cache https://stackoverflow.com/questions/5690269/disabling-chrome-cache-for-website-development

Chosen library not working


Updating specific part of Arraylist string?

Question: I am making a program where the person inputs multiple values and the Arraylist stores it as a single string with option 1. Option two allows you to change a specific part of that string from "Complete" to "Incomplete" and vice-versa but only if the status part of the String is one of the two. I am getting the warning "Result of 'String.replace()' is ignored" and the part of the string isn't updating. Any help would be appreciated!
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Array listObj = new Array();
        Scanner userinput = new Scanner(System.in);
        int arraysize = (listObj.list.size());

        int power = 1;
        while (power < 2) {
            System.out.println("To-Do List / What would you like to do?");
            System.out.println("1 = Add Task / 2 = Mark Task as Done / 3 = Remove Task / 4 = Edit Task / 5 = Display Tasks / 6 = Exit");
            int selection = userinput.nextInt();

            if (selection == 1) {
                for (int i = 0; i <= arraysize; i++) {
                    String title;
                    String date;
                    String status;
                    String description;
                    String id;

                    System.out.print("Enter Title: ");
                    title = userinput.next();
                    System.out.print("Enter Due Date: ");
                    date = userinput.next();
                    System.out.print("Enter Status (Complete or Incomplete): ");
                    status = userinput.next();
                    System.out.print("Enter Description: ");
                    description = userinput.next();
                    listObj.list.add(title + " " + date + " " + status + " " + description);
                    System.out.println();
                    listObj.list.forEach(System.out::println);
                    System.out.println();
                }
            }
            if (selection == 2) {
                int idinput;
                System.out.println("Enter Project ID to Toggle Complete/Incomplete: ");
                idinput = (userinput.nextInt()-1);
                System.out.println();
                System.out.println(listObj.list.get(idinput));
                System.out.println();
                System.out.println("What is the status of this assignment?: ");
                String toggleselect = userinput.next();
                if (toggleselect.equals("Incomplete")) {
                    listObj.list.get(idinput).replace("Incomplete", "Complete");
                } else if (toggleselect.equals("Complete")) {
                    listObj.list.get(idinput).replace("Complete", "Incomplete");
                } else {
                    System.out.println("Status is not Complete/Incomplete");
                }
                System.out.println();
                listObj.list.forEach(System.out::println);
                System.out.println();
            }
        }
    }
}

import java.util.ArrayList;
public class Array {
    ArrayList<String> list = new ArrayList<String>();

    public ArrayList<String> getList() {
        return list;
    }
}`your text`

Comment: The end of your quoted code looks like a copy/paste accident?: _"}`your text`"_
Answer: public String replace(char searchChar, char newChar)

demands a String to output to, as you can see by the return type. In this case use
public E set(int index, E element)

from the ArrayList library,
with E return type being your ArrayList,
and E element being your call
listObj.list.get(idinput).replace("Complete", "Incomplete");

So,
listObj.list.get(idinput).replace("Complete", "Incomplete");

becomes
listObj.list.set(idinput, listObj.list.get(idinput).replace("Complete", "Incomplete"));

Also, why are you creating a class called Array that just encapsulates an ArrayList in it?


Why are these NO counterexamples for Baire's Theorem?

Question: Baire's Theorem states: Let $X$ be a complete metric space and let $U_n \subset X$ be open and dense ($n \in \mathbb{N}$). Then $\bigcap_{n=1}^\infty U_n\subset X$ is dense.
In the lectures, we discussed the well-known counterexample of the rational numbers. We got two more examples that are NO counterexamples:

$X=\mathbb{N}\subset \mathbb{R}$ with subspace topology, $U_n:=\mathbb{N}\setminus \{n\}$
$X=\{\frac{1}{n} \mid n\in \mathbb{N}\} \cup \{0\}, U_0:=X\setminus \{0\}, U_n:= X\setminus \{\frac{1}{n}\}$

My problem is that I don't see any difference between the counterexample of the rationals and these two examples, e.g. $\mathbb{N}$ is complete, $\mathbb{N}\setminus \{n\}$ is open since singletons are closed and the closure of $\mathbb{N}\setminus \{n\}\subset \mathbb{N}$ is $\mathbb{N}$ (imo).
Where's my mistake in thinking?
Comment: What makes you think that the closure of $\mathbb{N}\setminus\{n\}$ in $\mathbb{N}$ is $\mathbb{N}$?
Comment: Can you see why $U_n$ is not dense in the first example?
Comment: What's your sequence in $U_n$ with limit outside of $U_n$? @SafariPark
Comment: @AsafKaragila No, I can't. I can choose a sequence in $U_n$ whose limit is either in $U_n$ or in $\mathbb{N}$ and that's the definition of being dense, isn't it?
Comment: @AlessandroCodenotti Good point! If I remove e.g. 0, I can only choose sequences that either end in 1, -1 or fluctuate between 1 and -1, hence reaching 0 with arbitrary precision is impossible
Comment: @user3482749 combining your comment with the one from Alessando, $\mathbb{N}$  is not the closure of $\mathbb{N}\backslash \{ n \}$ as I cannot find a seq in my $U_n$'s that converge to the missing $n$ (which I would have to reach arbitrary precisely for being a closure)?
Comment: @SafariPark Precisely, yes.
Comment: @user3482749 Great, thanks a lot. Then both examples have the same explanation for why they are no counterexamples!
Comment: @SafariPark : Proper notation is $\mathbb N \setminus \{n\}$ or $\mathbb N \smallsetminus\{n\}$ or $\mathbb N-\{n\},$ not $\mathbb N\backslash\{n\}.$
Comment: The only dense subset of $\Bbb N$ is $\Bbb N$. The only dense subsets of $X$ are $X$ and $X\setminus \{0\}$.
Answer: $\mathbb N \smallsetminus\{n\}$ is not dense, since no sequence of points in that set approaches $n$ as a limit.


Looking for updated SSG for Amazon Linux 2 and Amazon Linux 2023

Question: Are there any new data stream and xccdf checklist available for Amazon Linux 2 and Amazon Linux 2023?
I am able to install the scap-security-guide on an Amazon Linux 2 server, but the data stream xml file and xccdf xml file are from 2019 with an extremely outdated DISA STIG RHEL7 profile.
What is the method to build a new profile based on DISA's STIG releases?
Comment: Amazon Linux 2 *is* RHEL 7 under the hood
Answer: You can contribute in the Upstream for scap-security-guide package: https://github.com/ComplianceAsCode/content
So far, currently there is no contributors working on profiles for Amazon Linux. New contributors are welcome.


How can I translate the field group description?

Question: I have created two field groups on the manage form display tab for a content type. I have added some description also.
On the interface translation, I can translate the field group labels but there I can't translate the description of a field group. As when I search the description there I can't find any results.
I also checked it in the config translation but field group is not present on that page.
Is there any way I can translate the field group translation?
Answer: As far as I know there is no proper UI for this yet, but field groups are config, so you should be able to translate all strings by creating/editing translated versions of those config files.
First, export your current config, e.g. drush config:export
Then, in your config/sync directory look for files like core.entity_form_display.ENTITY.BUNDLE.FORMMODE.yml. In those files you will see a structure like
langcode: ISO2CODE
status: true
depenencies:
  config:
    - ...
third_party_settings:
  field_group:
    GROUP_ID:
      children:
        - field_foo
        - field_bar
      label: MY_GROUP_LABEL
      format_settings:
        description: 'MY DESCRIPTION'
...some more stuff...

The third_party_settings/field_group contains your group labels in your primary language. To translate a label, create a file language/LANGCODE/core.entity_form_display.ENTITY.BUNDLE.FORMMODE.yml below your config/sync directory.
This file must contain the same structure as the one in the main config file, but remove everything that is not translateable:
third_party_settings:
  field_group:
    GROUP_ID:
      label: MY_TRANSLATED_LABEL
      format_settings:
        description: 'MY TRANSLATED DESCRIPTION'

Finally, reimport the config with the translated labels, e.g. drush config:import


Iphone Adhoc distirbution profile update

Question: I have an AdHoc profile, now I want to add device for that profile, do I need to update certificate also ?
Answer: No, you don't. Just add device to the list, click Edit profile, choose newly added device and click Save. After several seconds your profile will be available for downloading.
Answer: No, you just need to add the device to the ad-hoc profile.


Construct a condition in Azure DevOps using 'each'

Question: In Azure DevOps (YAML pipeline), we have a stages that should be run only after another set of stages have been skipped.
In the example below, the parameter copyStages_UAT can be amended by users when triggering a manual run, meaning it's impossible to hard-code the dependsOn and condition properties, so necessitating the use of the directive each.
- template: ../Stages/stage--code--depoly-to-environment.yml
  parameters:
    name: Deploy_PRD_UKS
    displayName: Deploy PRD - UK South
    dependsOn:
    - ${{ each uatStage in parameters.copyStages_UAT }}:
      - Roll_Back_${{ uatStage.name }}
    variables:
    - template: ../Variables/variables--code--global.yml
    - template: ../Variables/variables--code--prd.yml
    environment: PRD

This stage above works in a pipeline, however because a successful run results in stages defined in dependsOn being skipped, sadly then Azure DevOps will also skip this stage.
To counter this, I'm trying to add a condition to check whether or not the previous stages were all skipped.
condition: >-
  and(replace(
    ${{ each uatStage in parameters.copyStages_UAT }}:
      eq(dependencies.Roll_Back_${{ uatStage.name }}.result, 'Skipped'),
  ), ', )', ' )')

Unfortunately though, it seems as though I cannot use the directive each in this context -

The directive 'each' is not allowed in this context. Directives are not supported for expressions that are embedded within a string. Directives are only supported when the entire value is an expression.

As condition can only be a string, how can I leverage expressions and/or directives to construct my desired condition?
Example of desired YAML
Assuming the following value was given for the parameter copyStages_UAT -
- name: UAT_UKS
  displayName: UAT - UK South
- name: UAT_UKW
  displayName: UAT - UK West

This is how the YAML should be compiled. I'm not worried out the format of the condition, as long as the relevant checks are included.
- template: ../Stages/stage--code--depoly-to-environment.yml
  parameters:
    name: Deploy_PRD_UKS
    displayName: Deploy PRD - UK South
    dependsOn:
    - Roll_Back_UAT_UKS
    - Roll_Back_UAT_UKW
    condition: >-
      and(
        eq(dependencies.Roll_Back_UAT_UKS.result, 'Skipped'),
        eq(dependencies.Roll_Back_UAT_UKW.result, 'Skipped')
      )
    variables:
    - template: ../Variables/variables--code--global.yml
    - template: ../Variables/variables--code--prd.yml
    environment: PRD

Answer: Azure DevOps Pipelines does not have a particularly good way for solving this. However, and(...),
join(delimiter, ...) and 'Filtered Arrays' can be used to hackily accomplish this.

Observe that the following condition could be rearranged:
and(
  eq(dependencies.Roll_Back_UAT_UKW.result, 'Skipped'),
  eq(dependencies.Roll_Back_UAT_UKX.result, 'Skipped'),
  eq(dependencies.Roll_Back_UAT_UKY.result, 'Skipped'),
  eq(dependencies.Roll_Back_UAT_UKZ.result, 'Skipped')
)

and(
  eq(dependencies.Roll_Back_
  UAT_UKW
  .result, 'Skipped'), eq(dependencies.Roll_Back_
  UAT_UKX
  .result, 'Skipped'), eq(dependencies.Roll_Back_
  UAT_UKY
  .result, 'Skipped'), eq(dependencies.Roll_Back_
  UAT_UKZ
  .result, 'Skipped')
)

Or more abstractly, where PREFIX=eq(dependencies.Roll_Back_ and SUFFIX=.result, 'Skipped'):
and(
  <PREFIX>
  UAT_UKW
  <SUFFIX>, <PREFIX>
  UAT_UKX
  <SUFFIX>, <PREFIX>
  UAT_UKY
  <SUFFIX>, <PREFIX>
  UAT_UKZ
  <SUFFIX>
)

With filtered arrays (NAMES=parameters.parameterName.*.name) to extract the name, an aggregation could then be written:
and(<PREFIX>${{ join('<PREFIX>, <SUFFIX>', <NAMES>) }}<SUFFIX>)

Thus:
condition: |
  and(
    ne(dependencies.Roll_Back_${{ join('.result, ''Skipped''), ne(dependencies.Roll_Back_', parameters.copyStages_UAT.*.name) }}.result, 'Skipped')
  )

But there are some obvious caveats with this:

If there is 0 elements in parameters.copyStages_UAT, then the expression would evaluate to and(dependencies.Roll_Back_.result, 'Skipped') which could be non-sensical.

and(...) requires a minimum of 2 arguments, so this could potentially fail if there is only 0 or 1 expression(s). To circumvent this, True can be supplied as the first and second argument such that the expression is always valid. If your logic instead requires or(...), then use False instead of True to keep the meaning consistent.

Therefore, you may need to protect against these scenarios occurring with a modified check:
${{ if eq(length(parameters.copyStages_UAT), 0) }}:
  condition: false
${{ else }}:
  condition: |
    and(
      True,
      ne(dependencies.Roll_Back_${{ join('.result, ''Skipped''), ne(dependencies.Roll_Back_', parameters.copyStages_UAT.*.name) }}.result, 'Skipped')
    )

Answer: Updated:
To summary your demand, you are looking for a expression that you can use it in condition while the dependsOn value are dynamic. And this stage should run only after another set of dependent stages are all skipped.
As far as I know and tested, this can not be achieved via each.
For further confirmation, I discussed this scenario with our pipeline PM who is more familiar with each and YAML pipeline.
Same as me, he also think this isn't possible to achieve. Because ${{ each }} expects to be the outermost part of a mapping key or value, so you can't nest it into a condition string.

Work around:
You could fake it by having a hard-coded stage which depends on the dynamic list, figures out if they were all skipped, and sets an output variable. Then the real final job would only depend on that "decider" job, and its condition would depend on the contents of the output variable.
Figuring out that all upstream dependencies were skipped is something of an exercise for you. You might be able to dynamically construct one step per stage. Those steps map the stage's status to a variable with a known name scheme. Then the final (hardcoded) step iterates the environment variables of the known name scheme and decides whether the next stage should proceed.
And... yes, I am aware how ugly that sounds ☹
Comment: @DavidGard, appreciate for this detailed explanation. Got that. That is clear for me now. Would share you suggestions once I have update here.
Comment: Thanks for your reply. In this case, I only want to run one stage if the stages it depends upon have been skipped. So using your examples above, both images are correct. However, I cannot use `always()` because that would mean that the `DeployEurope` stage would always be run, even if `avaiableazure` and `merlinazure` had been run, and as mentioned it should only be run if those stages it depends on are skipped. I have updated my question to (hopefully) make it clearer.
Comment: @DavidGard, As far as I know, this is not possible to use each directly in condition. To avoid misleading you, I discussed this with our program manager who are most familiar with the function of **each** for further confirmation. Same result, we are all think as of now, you need achieve that by using work around. See my update answer.
Comment: Thanks for the confirmation. That is not ideal, and I'm not sure that the workaround is going to be feasible. As far as I am aware, you can only share output variables either between tasks in a job, or between jobs in a stage (using `isOutput=true`) - indeed the [documentation](https://learn.microsoft.com/en-us/azure/devops/pipelines/process/variables?view=azure-devops&tabs=yaml%2Cbatch#set-variables-in-scripts) specifically says "Multi-job output variables only work for jobs in the same stage."
Comment: @DavidGard Ah, we have released a new feature in sprint 168, so that users can access output variable across stages. See this feature timeline doc: https://learn.microsoft.com/en-us/azure/devops/release-notes/2020/sprint-168-update#jobs-can-access-output-variables-from-previous-stages
Comment: Ah, OK. I'm still not convinced it's the right thing to do here so I'm exploring other options. But this will absolutely help with another issue I have - I was on the verge of implementing a solution to output to a file and publish an artefact from one stage for consumption by the next, but hoepfully that will no longer be necessary.


Does $f_n(x)=n(x^{\frac{1}{n}}-1)$ converge uniformly in $(0,\infty)$ and in $[0,10]$?

Question: I'd like your help with the deciding whether the following function uniformly converges in two intervals.
$$f_n(x)=n \left(x^{\frac{1}{n}}-1 \right) .$$
In $(0,10]$, with l'Hôpital, I showed that for every $x$ the limit of the function is $\ln x$, so with a help from Dini's theorem, I am able that the function is monotone and the limit is continuous so the function uniformly converges.
I'm not sure what should I do with the other interval. I tried to evaluate the limit of $|f_n(x)-f(x)|$, I didn't come to any smart conclusion.
Answer: The sequence does converge uniformly to $\ln x$ on any compact subset of $(0,\infty)$, but the convergence is not uniform in $(0,a\,]$ for any $a>0$. If the convergence were uniform, there would exist an $n_0$ such that for all $n\ge n_0$
$$
|f_n(x)-\ln x|\le1\quad\forall x\in(0,a\,].
$$
But
$$
|f_n(2^{-n})-\ln(2^{-n})|=\Bigl(\ln2-\frac12\Bigr)n
$$
is not bounded.
Observe that $(0,a\,]$ is not compact and Dini's theorem does not apply.
Answer: As pointed out by Julian, the sequence does not converge uniformly on $(0,a]$ for any $a>0$; but it does converge uniformly on any compact subset of $\Bbb R$.
For sets of the form $[a,\infty)$:
Using L'Hopital, you can show the pointwise limit is $f(x)=\ln x$ on $[a,\infty)$.
Now take $x_n=2^n$. Then
$$
|f_n(x_n)-\ln(x_n)|= |n(2-1) -  n\ln 2|=n(1-\ln2)\quad
\buildrel{n\rightarrow\infty}\over\longrightarrow\quad\infty.
$$
Thus, there is no $N$ so that $|f_n(x)-\ln x|<1$ for all $n\ge N$ and all $x\in [a,\infty)$.
Thus, the convergence is not uniform on $[a,\infty)$.


how long a ftp/sftp session can be opened?

Question: I wonder how long an ftp or sftp session can remain open? The reason I'm asking is I have some legacy code which opens an ftp session using WinSCPnet.dll then calls db to create a file and dump it in a location to do sftp.
This is about trying to open a session:

SessionOptions Class
TimeSpan Timeout  Server response timeout. Defaults to 15 seconds.

But how long does it stay open?
Comment: How many months do you need it to stay open?
Comment: @MichaelHampton do u know how long? 1 hr? 1 day? 1 month?...
Comment: On a clean network connection with no interference and defaults all around, an ssh session will stay open indefinitely.
Answer: This may depend on several factors:

timeout limit on the SSH host
timeout limit on an intermediate firewall or NAT router (aging)
timeout limit on your client

The earliest timeout defines how long the session can be open.


Proving $H$ Is A Subgroup Of $G$

Question:
Let $G=\mathbb{R}^2$ with vectors addition, Prove: $H=\{x,0:x\in \mathbb{R}\}$ is a sub group

I am trying to understand the combined condition to prove it is a sub group, I need to take $a,b\in H$ and show that $ab^{-1}\in H$
So If I take $a=(a,0),b=(b,0)$ I need to show that $(a,0)+(-b,0)=(a-b,0)\in H$ but $b^{-1}=(-b,0)$ is in $H$ is it fine or I must take $b^{-1}\in G$ that is not in $H$?
Comment: For all $b\in H$ you must show that $b^{-1}\in H$.
Answer: The one and only requirement on $b$ is that $b\in H$ (and similarily, we need $a\in H$). You then have to show that $ab^{-1}\in H$. This includes the case where you pick $a = e$, which means that $b^{-1}\in H$ is part of what you need to check for any $b\in H$. However, it happens automatically since we pick arbitrary $a$. Separately making sure that $b^{-1}\in H$ before checking that $ab^{-1}\in H$ is unnecessary, and looking for $b^{-1}\in G\setminus H$ to use in the test is entirely irrelevant.
Personally, I prefer to use the full three-property test for subgroups:

$e\in H$
for any $a\in H$, we have $a^{-1}\in H$
for any $a, b\in H$, we have $ab\in H$

The last two points may be condensed into the single test that you are using, but unless everything is completely clear to you, I strongly suggest you use this test instead. There are fewer confusions that way, and it usually takes the same amount of time and space anyways.
Comment: @gbox Yes. If you've also established that $H$ is non-empty.
Comment: Just to close the issue $(a-b,0)\in H$ and therefore $H$ is a subgroup?

Proving $H$ Is A Subgroup Of $G$


How to characterize pairs $(a,b) \in \mathbb N^2$ which satisfy this curious equation $\text{lcm}(a,b)-\text{gcd}(a,b)=\varphi(a \cdot b)$?

Question: If $p$ is a prime then: $\text{lcm}(1,p)-\text{gcd}(1,p)=p-1=\varphi(1 \cdot p)$
How to characterize pairs $(a,b) \in \mathbb{N} \times \mathbb{N}$ which satisfy this curious equation?
This equation I posed by some investigation not much related to anything other than curiosity.
$\varphi$ is the totient-function.
Comment: A good start would be to collect solutions. With which range are you content ?
Comment: WLOG we can assume $a\le b$. It seems that there are only solutions for $a\le 2$.
Comment: Another infinite family of solutions if $(2,2p)$ , where $p$ is an odd prime.
Comment: @Peter $1 \leq a,b \leq 1000$ would be a nice start.
Comment: @Peter Which pairs did you find with $a=2$?
Comment: @Peter So this equation, basically, characterizes the prime numbers?
Comment: Let us [continue this discussion in chat](https://chat.stackexchange.com/rooms/105512/discussion-between-peter-and-ante).
Comment: Please do not use titles consisting only of math expressions; these are discouraged for technical reasons -- see [Guidelines for good use of $\LaTeX$ in question titles](http://meta.math.stackexchange.com/a/9730).
Answer: Assume that for some prime $p$, we have $p^2 \mid a$. Then, it is clear that $p^2 \mid ab \implies p \mid \varphi(ab)$. It is also clear from definition that $p \mid \text{lcm}(a,b)$. This shows:
$$p \mid (\text{lcm}(a,b)-\varphi(ab)) \implies p \mid \gcd(a,b) \implies p \mid b$$
We have prime $p$ dividing both $a$ and $b$. Then:
$$\nu_p(\text{lcm}(a,b)-\gcd(a,b))=\nu_p(\gcd(a,b))=\min(\nu_p(a),\nu_p(b)) $$
$$\nu_p(\varphi(ab))=\nu_p(\varphi(p^{\nu_p(a)+\nu_p(b)}s)) \geqslant \nu_p(a)+\nu_p(b)-1$$
from the canonical formula for the Euler Totient Function. This forces:
$$\min(\nu_p(a),\nu_p(b)) \geqslant \nu_p(a)+\nu_p(b)-1$$
But we know that $\nu_p(a) \geqslant 2$. This shows:
$$\nu_p(a)+\nu_p(b)-1>\nu_p(b)\geqslant \min(\nu_p(a),\nu_p(b))$$
which is a contradiction. This means that our initial assumption about the existence of $p$ such that $p^2 \mid a $ is false. This shows that $a$ is square-free. Similarly, we also have $b$ to be square-free.
Now, let $\{p_i \mid 1 \leqslant i \leqslant I\}$ be the set of primes dividing both $a$ and $b$, $\{q_j \mid 1 \leqslant j \leqslant J\}$ be the set of primes dividing $a$ alone, and $\{r_k \mid 1 \leqslant k \leqslant K\}$ be the set of primes dividing $b$ alone. These three sets have no primes in common with each other (pairwise intersection is $\varnothing$). Then:
$$a=\prod p_i \prod q_j \quad ; \quad b=\prod p_i \prod r_k$$
$$\text{lcm}(a,b)-\gcd(a,b)=\prod p_i \prod q_j \prod r_k - \prod p_i = \prod p_i \bigg( \bigg( \prod q_j \prod r_k \bigg) -1\bigg)$$
$$\varphi(ab)=\varphi \bigg(\prod p_i^2 \prod q_j \prod r_k \bigg) = \prod p_i \prod (p_i-1) \prod (q_j-1) \prod (r_k-1)$$
Equating, we have:
$$\text{lcm}(a,b)-\gcd(a,b)=\varphi(ab)$$
$$\prod p_i \bigg( \bigg( \prod q_j \prod r_k \bigg) -1\bigg)=\prod p_i \prod (p_i-1) \prod (q_j-1) \prod (r_k-1)$$
$$\bigg(\prod q_j \prod r_k \bigg) -1 = \prod (p_i-1) \prod (q_j-1) \prod (r_k-1)$$
Note that you have:
$$x=\bigg(\prod q_j \prod r_k \bigg) \implies \varphi(x)=\prod (q_j-1) \prod (r_k-1)$$
This shows:
$$x-1=\varphi(x) \cdot \prod (p_i-1) \implies \varphi(x) \mid (x-1)$$
Note that $\varphi(x) \mid (x-1)$ is Lehmer's Totient Problem. It is unknown whether there are any solutions except prime $x$. Knowing that the quotient is expressable as $\prod (p_i-1)$ doesn't help.
Let us assume that the only solutions to Lehmer's Totient Problem are prime $x$. Then:
$$\phi(x)=x-1 \implies \prod (p_i-1)=1$$
This is only possible when there is only one prime in the product ($I=1$) which must be $2$, or when there are no primes in the product ($I=0$), which gives null product as $1$. This corresponds to the solutions $(1,p)$ for all primes $p$ and $(2,2q)$ for odd primes $q$. Hence, assuming that Lehmer's Totient Problem has only prime solutions, these are the only possible pairs of solutions:
$$(a,b)=(1,p),(p,1),(2,2q),(2q,2) \quad ( p,q \in \mathbb{P} \space ; \space q \neq 2)$$
Lehmer's Totient Problem: https://mathworld.wolfram.com/LehmersTotientProblem.html


Forecasting with log transformed data and then taking the exponential of my predictions

Question: I am aware a similar question was asked here Interpreting forecast predictions of log transformed data.
But I would like a deeper comment/answer.
I have a time series and want to make forecast. I found that taking the log of my series (all positive values), helps with my increasing variance over time. If my first difference series is stationary, when I make a forecast with ARIMA(p,1,q), is it safe to take the exponential of my predictions, so to get my predictions back in levels? What problems are there with this procedure?
Comment: Here are two excellent treatments of the matter by Dave Giles: [Forecasting From Log-Linear Regressions](https://davegiles.blogspot.com/2013/08/forecasting-from-log-linear-regressions.html) and [More on Prediction From Log-Linear Regressions](https://davegiles.blogspot.com/2014/12/s.html). [This thread](https://stats.stackexchange.com/questions/140713) may also be relevant.
Answer: If you are making a point forecast of the median, then simply get the exponent. If you are forecasting the mean then there are roughly two ways of getting back to original units: simple exponent and the one with variance adjustment:
$$\hat y_t=\hat y_{t-1}e^{\hat\Delta_t}$$
$$\hat y_t=\hat y_{t-1}e^{\hat\Delta_t+\hat\sigma_{\Delta}^2/2}$$
where $\Delta_t=\ln y_t-\ln y_{t-1}$
The variance adjustment comes from the equation for the mean of the lognormal distribution $\xi\sim\mathcal{logN}(0,\sigma^2)$ where $E[\xi]=e^{\sigma^2/2}$. So, strictly, you shouldn't be using it unless your  errors are normal. Since you mentioned ARIMA it's likely that you already assume normal errors because that's what standard packages do unless told otherwise.
If you knew the true variance $\sigma_{\Delta}^2$ of the process then the latter would have been the only option. Unfortunately, you don't know the true variance. So, you have to pick one of the above options.
Some practitioners think that it is better to use the former because variance adjustment is not worth the trouble with estimated variance $\hat\sigma_{\Delta}^2$: it introduces its own error. Fortunately, the variance is usually not large enough to matter and you get about the same answers in both options.
To me the whole problem can be avoided by not making a point forecast, and instead proceed with the distribution forecast. In other words don't give your users one number, give them a distribution of the projections. If you are using the standard ARIMA packages then the simplest way to do this is to use their standard facilities, e.g. filter function does it MATLAB, where you supply random disturbances and get back the random paths, from which you can construct neat fan charts, like the ones used by BOE's inflation report.
Comment: to obtain distribution it is easiest to generate a bunch of paths, let's say 100, and that will allow you to show quantiles of the forecast
Comment: Thank you! Do you have any references on how to make a distribution of the projection (maybe in python)?
Comment: +1, although I'm not all that sure about "the variance is usually not large enough to matter"...
Comment: The variance adjustment you have included only works under an assumption of normality. Consider making that explicit. For more information, see links I have included under the OP.
Comment: @RichardHardy, I agree, but OP uses ARIMA, which are always with normal errors by default in software
Comment: @Aksakal, the update looks good, thank you.
Comment: @Aksakal. I have a question. To obtain the distribution of my projections, I guess the first step is to transform my estimated with the exponential ŷ_t (which are in logs), so to get back to units, and then obtain the distribution of my projections?
Comment: @Aksakal and, is it possible to obtain the distribution of my six periods ahead projections?


How to pass variable to html emails sent from Python

Question: I have this python script:
import time
from email.message import EmailMessage

user_age = "12"
user_name="John"

msg = EmailMessage()
msg['Subject'] = "Test Subject"
msg['From'] = 'firstname.lastname@example.com'
msg['To'] = 'email@example.com'
msg.set_content("Test Mesage")

html_message = open('test.html').read()
msg.add_alternative(html_message, subtype='html')

while True:
    with smtplib.SMTP_SSL('smtp.gmail.com', 465) as smtp:
        smtp.login("firstname.lastname@example.com", "pass")
        smtp.send_message(msg)

    time.sleep(500)

I want to pass a variable like first_name, age, links from this python script to html template (test.html), access and format them into html.
Something like:

     ....

        Hei user {{user_name}} we recieved your age confirmation! {{user_age}} is it right?

Answer: Just replace your placeholders with the variables:
html_message = html_message.replace('{{user_name}}',user_name).replace('{{user_age}}',user_age)

Comment: Ooh god! Thank you very much!
Answer: import time
from email.message import EmailMessage

html_message = html_message.replace('{{user_name}}',user_name).replace('{{user_age}}',user_age)

msg = EmailMessage()
msg['Subject'] = "Test Subject"
msg['From'] = 'firstname.lastname@example.com'
msg['To'] = 'firstname.lastname@example.com'
msg.set_content("Test Mesage")

html_message = open('test.html').read()
msg.add_alternative(html_message, subtype='html')

while True:
    with smtplib.SMTP_SSL('smtp.gmail.com', 465) as smtp:
        smtp.login("firstname.lastname@example.com", "pass")
        smtp.send_message(msg)

    time.sleep(500)


Shell script to enumerate the (already existing) LDAP group called "VPN Users"

Question: I am new to LDAP and learning about the ldapsearch and ldap in general. Would like to write a shell script that enumerate the (already existing) LDAP group "VPN Users", then get all user "samaccountname" (e.g.joe.smith). Can someone please help? I've tried to do it but seems like my ldapsearch has errors:
ldapsearch -h 127.0.0.1 -x -b (&(objectCategory=group)(cn=VPN Users))

Edit - Sorry about that. I made some progress and now at least cat get some data from the LDAP server by running something like this:
echo -n 'password' |
ldapsearch -y pass.txt -h [IP here] -b "ou=x,dc=x,dc=x,dc=x" -x `
 -D "cn=user,ou=test,ou=x,ou=x,dc=x,dc=x,dc=xx" `
 -W "(&(objectClass=person)(objectClass=user)(sAMAccountName=*) (memberOf=cn=VPN Users,ou=test,ou=x,ou=x,dc=x,dc=x,dc=xx))" `
 -y /dev/fd/0

But I would like it to:

enumerate the (already existing) LDAP group "VPN Users"
get all user "samaccountname" (e.g. joe.smith, etc.)

Thanks
Comment: `... seems like my ldapsearch has errors:` - Including the errors would make it a lot easier to actually tell you what the problem is.  The answer is often found in the error.
Comment: Or this ldapsearch -h [remote IP here] -x -b "ou=test dc=unit,dc=dev,dc=net" "(&(objectCategory=group))"
Comment: Please also provide the error you are encountering.
Comment: Sorry about that. I made some progress and now at least cat get some data from the LDAP server by running something like this:
echo -n 'password' | ldapsearch -y pass.txt -h [IP here] -b "ou=x,dc=x,dc=x,dc=x" -x -D "cn=user,ou=test,ou=x,ou=x,dc=x,dc=x,dc=xx" -W "(&(objectClass=person)(objectClass=user)(sAMAccountName=*) (memberOf=cn=VPN Users,ou=test,ou=x,ou=x,dc=x,dc=x,dc=xx))" -y /dev/fd/0

But I would like it to:

# enumerate the (already existing) LDAP group "VPN Users"
## get all user "samaccountname" (e.g. joe.smith, etc.)
Comment: Please edit provided information into your question.
Comment: I did!
Edit - Sorry about that. I made some progress and now at least cat get some data from the LDAP server by running something like this: echo -n 'password' | ldapsearch -y pass.txt -h [IP here] -b "ou=x,dc=x,dc=x,dc=x" -x -D "cn=user,ou=test,ou=x,ou=x,dc=x,dc=x,dc=xx" -W "(&(objectClass=person)(objectClass=user)(sAMAccountName=*) (memberOf=cn=VPN Users,ou=test,ou=x,ou=x,dc=x,dc=x,dc=xx))" -y /dev/fd/0 But I would like it to: # enumerate the (already existing) LDAP group "VPN Users" ## get all user "samaccountname" (e.g. joe.smith, etc.)
Comment: Please refactor your question to something readable by a human.
Answer: The expression to use in your query would be something like this:
(&(objectClass=user)(memberOf="VPN Users")) attrs=sAMAccountName

Finally:
ldapsearch -y pass.txt -h [IP here] -b "ou=x,dc=x,dc=x,dc=x"
 -D "cn=user,ou=test,ou=x,ou=x,dc=x,dc=x,dc=xx" `
 -W "(&(objectClass=user)(memberOf="VPN Users")) attrs=sAMAccountName -y /dev/fd/0

Answer: If you have something maintaining the memberOf attribute (e.g. slapd-memberOf):
ldapsearch -h ldap.example.com -b ou=groups,dc=example,dc=com \
    -D  cn=user,ou=accounts,dc=example,dc=com -W  -y password.txt \
    "(&(memberOf=cn=VPN Users,ou=groups,dc=example,dc=com)(sAMAccountName=*))" \
    sAMAccountName

You can pipe the output through sed if your interested in just the values, e.g.
| sed -n 's/^sAMAccountName: //p'

-y needs the password to be exact. Most text editors including vim will insert a trailing newline (\n). This must be removed, e.g. truncate -s -1 password.txt.


Is storing object instances in file in Java a good idea?

Question: I have a project where I would like to create minimal instances of a class across the whole project (in Java). Is it a good idea to serialize and deserialize the object and store it in a file? I will be using the class heavily across the whole project so I am not sure if that is a good solution.
Are there any other methods to achieve this?
P.S. - I have this class as a singleton class
Comment: Well... If you can create more than a single instance it's **not** a Singleton.
Comment: A "singleton" class is not singleton across requests.
Comment: Are you redefining what Singleton is?
Comment: You can use a bean and inject it into the places you'll be needing this instance.
Comment: if it's a singleton, then you are subverting its singletonness when you deserialize it all over the place. not clear what you are trying to accomplish here.
Comment: @NathanHughes - I am trying to get one instance across all the different processes running in the project. This is easy to achieve when the project is a web application. I am not sure how to exactly do this when it is not.
Comment: @d_void what is your definition of "project". Your last comment seems to imply that there are multiple "processes" in your "project". And, you want a single instance of your class-instance across all processes, is that right?
Comment: @StvnBrkdll - yes exactly. Sorry for the ambiguous question.
Comment: What is the data that your "class" manages? Typical ways to manage shared state across processes would be to store the state in a shared database, or use something like a distribute cache or a distributed key-value store (ehcache, redis, etc).
Comment: @StvnBrkdll - It basically just logs information depending upon different parameters provided
Answer: No, it is not a good idea and it should be self-explanatory why.
If you want to get into detail as to why you shouldn't use the approach you suggested, then have a look at @Joachim Sauer's answer here.
Without knowing what you intend to do with the class you want to re-use, it sounds like you need something like a static instance.
So, instead of confusing yourself with what the singleton design pattern is, just create an instance of that class, in (preferably) your main class like this:
<code>public static ClassIWantToStore reusable = new ClassIWantToStore();
</code>
Or if you want a different instance of the class each time:
<code>//THIS IS NOT SINGLETON
public static ClassIWantToStore getNewInstance(){
  //Modify functionality if you want something more
  //before returning the class instance.
  return new ClassIWantToStore();
}
</code>
I recommend you read what the static keyword does in Java, which could prove useful to situations like the one you're in now; but it should also be used carefully, because it can help you shoot yourself in the leg when misused.
This is a good and simple explanation of the static keyword.


Theory containing all sentences of the language

Question: According to Enderton, the theory which consists of all sentences of the language is the only unsatisfiable theory. Why is this true? In particular, this implies that there exists at most one sentence which cannot be satisfied with all the others, and I don't understand why that must be the case.
Comment: How does it imply "that there exists at most one sentence which cannot be satisfied with all the others"?
Comment: "there exists at most one sentence which cannot be satisfied with all the others" - I don't understand the meaning of this sentence. What does it mean that a sentence satisfies another sentence?
Answer: Note that a theory is not just an arbitrary subset of all sentences of a language. Rather, it must be closed under logical implication. Therefore, a theory cannot be all sentences but one: If only one of $p$, $\neg p$, $q$, $\neg q$ is missing, we still have one sentce and its negation; so if e.g. $q$ is missing, we still have $p$ and $\neg p$, from which we get $p\land \neg p$ and then with $(p\land \neg p)\to q$ we resurrect $q$.
Comment: Not every definition of a theory requires it to be closed under implication. Actually, most definitions I have encountered take a theory to be just an arbitrary set of sentences in some language (or sequents, or something like that).
Answer: Presumably, Enderton defines a theory to be a set of sentences which is closed under logical entailment. That is, if $T$ is a theory and $T\models \varphi$, then $\varphi\in T$. Note that the statement is not true if a theory is just an arbitrary set of sentences: For any sentence $\varphi$, the theory $\{\varphi\land \lnot \varphi\}$ is unsatisfiable, but this singleton set is not the set of all sentences in the langauge.
Suppose $T$ is unsatisfiable. Then for any sentence $\varphi$, we have that for any model $M\models T$, also $M\models \varphi$ (vacuously: there are no models of $T$). So $T\models \varphi$, and hence $\varphi\in T$, since $T$ is a theory. So $T$ is the set of all sentences in the language.
If instead you define a theory to be deductively closed (if $T$ is a theory and $T\vdash \varphi$, then $\varphi\in T$), then you need to get the completeness theorem involved. The completeness theorem says that $T\vdash \varphi$ if and only if $T\models \varphi$, so you can just use the previous argument and appeal to completeness.


Show $P, Q \vdash P \wedge Q$

Question: I'm asked to show that $p, q \vdash p \wedge q$. Technically what must be shown is that $p, q \vdash \sim (p\rightarrow \sim q)$, since $\sim$ and $\rightarrow$ are taken as primitives. As axioms, I'm allowed to use all substitution instances of:
$$p \rightarrow (q\rightarrow p)$$
$$(p\rightarrow (q\rightarrow r))\rightarrow ((p\rightarrow q)\rightarrow (p\rightarrow r))$$
$$(\sim p \rightarrow \sim q)\rightarrow((\sim p \rightarrow q)\rightarrow p)$$
and only Modus Ponens as a rule of inference.
However I'm also allowed to use the Deduction Theorem, as well as $$p\rightarrow q, q\rightarrow r \vdash p\rightarrow r$$
$$p, \sim p \vdash q$$
$$\sim p \rightarrow \sim q \vdash q\rightarrow p$$
$$p \rightarrow q \vdash \sim q \rightarrow \sim p$$
$$\sim (p\rightarrow q)\vdash p$$
$$\sim (p\rightarrow q)\vdash \sim q$$
$$p\rightarrow q, \sim p \rightarrow q \vdash q$$
(I'm being somewhat informal in writing $\{a, b\} \vdash c$ as $a, b \vdash c$.)

I've been stuck on this exercise for more than an hour now and would appreciate any help.
Answer: I know from your previous question that you have shown $\neg \neg p \vdash p$
So, since you can easily show that $p, p \to \neg q \vdash \neg q$, you can use the fact that $\neg \neg p \vdash p$ to show that $p, \neg \neg (p \to \neg q) \vdash \neg q$. Thus, by the Deduction Theorem, you have $p \vdash \neg \neg (p \to \neg q) \to \neg q$.
Likewise, since it is trivial to show that $q, p \to \neg q \vdash q$, we also know that $q, \neg \neg (p \to \neg q) \vdash q$, and use the Deduction Theorem to obtain $q \vdash \neg \neg (p \to \neg q) \to q$.
So, starting with both $p$ and $q$, we can obtain both $\neg \neg (p \to \neg q) \to \neg q$ as well as $\neg \neg (p \to \neg q) \to q$, and then combine that with the following instance of Axiom 3:
$(\neg \neg (p \to \neg q) \to \neg q) \to ((\neg \neg (p \to \neg q) \to q) \to \neg (p \to \neg q)$
to obtain:
$\neg (p \to \neg q)$

Show $P, Q \vdash P \wedge Q$


Espaçamento entre grids e imagem colada na card

Question:
Como faço para dar um espaçamento entre o texto e o accordion:

Segue o codigo: https://codepen.io/ludieverson/pen/vMqVXv
<link rel="stylesheet" type="text/css" media="screen" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" />
<link rel="stylesheet" type="text/css" media="screen" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" />

  Anim pariatur cliche reprehenderit, enim eiusmod high life accusamus terry richardson ad squid. 3 wolf moon officia aute, non cupidatat skateboard dolor brunch. Food truck quinoa nesciunt laborum eiusmod. Brunch 3 wolf moon tempor, sunt aliqua put a bird on it squid single-origin coffee nulla assumenda shoreditch et. Nihil anim keffiyeh helvetica, craft beer labore wes anderson cred nesciunt sapiente ea proident. Ad vegan excepteur butcher vice lomo. Leggings occaecat craft beer farm-to-table, raw denim aesthetic synth nesciunt you probably haven't heard of them accusamus labore sustainable VHS.

            <button class="btn btn-link "  data-toggle="collapse" data-target="#collapseOne" aria-expanded="true" aria-controls="collapseOne">
              Collapsible Group Item #1
            </button>

            Anim pariatur cliche reprehenderit, enim eiusmod high life accusamus terry richardson ad squid. 3 wolf moon officia aute, non cupidatat skateboard dolor brunch. Food truck quinoa nesciunt laborum eiusmod. Brunch 3 wolf moon tempor, sunt aliqua put a bird on it squid single-origin coffee nulla assumenda shoreditch et. Nihil anim keffiyeh helvetica, craft beer labore wes anderson cred nesciunt sapiente ea proident. Ad vegan excepteur butcher vice lomo. Leggings occaecat craft beer farm-to-table, raw denim aesthetic synth nesciunt you probably haven't heard of them accusamus labore sustainable VHS.

            <button class="btn btn-link collapsed" data-toggle="collapse" data-target="#collapseTwo" aria-expanded="false" aria-controls="collapseTwo">
              Collapsible Group Item #1
            </button>

            Anim pariatur cliche reprehenderit, enim eiusmod high life accusamus terry richardson ad squid. 3 wolf moon officia aute, non cupidatat skateboard dolor brunch. Food truck quinoa nesciunt laborum eiusmod. Brunch 3 wolf moon tempor, sunt aliqua put a bird on it squid single-origin coffee nulla assumenda shoreditch et. Nihil anim keffiyeh helvetica, craft beer labore wes anderson cred nesciunt sapiente ea proident. Ad vegan excepteur butcher vice lomo. Leggings occaecat craft beer farm-to-table, raw denim aesthetic synth nesciunt you probably haven't heard of them accusamus labore sustainable VHS.

            <button class="btn btn-link collapsed" data-toggle="collapse" data-target="#collapseThree" aria-expanded="false" aria-controls="collapseThree">
              Collapsible Group Item #1
            </button>

            Anim pariatur cliche reprehenderit, enim eiusmod high life accusamus terry richardson ad squid. 3 wolf moon officia aute, non cupidatat skateboard dolor brunch. Food truck quinoa nesciunt laborum eiusmod. Brunch 3 wolf moon tempor, sunt aliqua put a bird on it squid single-origin coffee nulla assumenda shoreditch et. Nihil anim keffiyeh helvetica, craft beer labore wes anderson cred nesciunt sapiente ea proident. Ad vegan excepteur butcher vice lomo. Leggings occaecat craft beer farm-to-table, raw denim aesthetic synth nesciunt you probably haven't heard of them accusamus labore sustainable VHS.

            <button class="btn btn-link collapsed" data-toggle="collapse" data-target="#collapseFour" aria-expanded="false" aria-controls="collapseFour">
              Collapsible Group Item #1
            </button>

            Anim pariatur cliche reprehenderit, enim eiusmod high life accusamus terry richardson ad squid. 3 wolf moon officia aute, non cupidatat skateboard dolor brunch. Food truck quinoa nesciunt laborum eiusmod. Brunch 3 wolf moon tempor, sunt aliqua put a bird on it squid single-origin coffee nulla assumenda shoreditch et. Nihil anim keffiyeh helvetica, craft beer labore wes anderson cred nesciunt sapiente ea proident. Ad vegan excepteur butcher vice lomo. Leggings occaecat craft beer farm-to-table, raw denim aesthetic synth nesciunt you probably haven't heard of them accusamus labore sustainable VHS.

            <button class="btn btn-link collapsed" data-toggle="collapse" data-target="#collapseFive" aria-expanded="false" aria-controls="collapseFour">
              Collapsible Group Item #1
            </button>

            Anim pariatur cliche reprehenderit, enim eiusmod high life accusamus terry richardson ad squid. 3 wolf moon officia aute, non cupidatat skateboard dolor brunch. Food truck quinoa nesciunt laborum eiusmod. Brunch 3 wolf moon tempor, sunt aliqua put a bird on it squid single-origin coffee nulla assumenda shoreditch et. Nihil anim keffiyeh helvetica, craft beer labore wes anderson cred nesciunt sapiente ea proident. Ad vegan excepteur butcher vice lomo. Leggings occaecat craft beer farm-to-table, raw denim aesthetic synth nesciunt you probably haven't heard of them accusamus labore sustainable VHS.

            <button class="btn btn-link collapsed" data-toggle="collapse" data-target="#collapseSix" aria-expanded="false" aria-controls="collapseFour">
              Collapsible Group Item #1
            </button>

            Anim pariatur cliche reprehenderit, enim eiusmod high life accusamus terry richardson ad squid. 3 wolf moon officia aute, non cupidatat skateboard dolor brunch. Food truck quinoa nesciunt laborum eiusmod. Brunch 3 wolf moon tempor, sunt aliqua put a bird on it squid single-origin coffee nulla assumenda shoreditch et. Nihil anim keffiyeh helvetica, craft beer labore wes anderson cred nesciunt sapiente ea proident. Ad vegan excepteur butcher vice lomo. Leggings occaecat craft beer farm-to-table, raw denim aesthetic synth nesciunt you probably haven't heard of them accusamus labore sustainable VHS.

            <button class="btn btn-link collapsed" data-toggle="collapse" data-target="#collapseSeven" aria-expanded="false" aria-controls="collapseFour">
              Collapsible Group Item #1
            </button>

            Anim pariatur cliche reprehenderit, enim eiusmod high life accusamus terry richardson ad squid. 3 wolf moon officia aute, non cupidatat skateboard dolor brunch. Food truck quinoa nesciunt laborum eiusmod. Brunch 3 wolf moon tempor, sunt aliqua put a bird on it squid single-origin coffee nulla assumenda shoreditch et. Nihil anim keffiyeh helvetica, craft beer labore wes anderson cred nesciunt sapiente ea proident. Ad vegan excepteur butcher vice lomo. Leggings occaecat craft beer farm-to-table, raw denim aesthetic synth nesciunt you probably haven't heard of them accusamus labore sustainable VHS.

    This is some text within a card body.

    This is some text within a card body.

Answer: No Bootstrap a maneira mas prátia é usando os utilities de espaçamento vc pode conferir a lista completa aqui https://getbootstrap.com/docs/4.0/utilities/spacing/
Mas basicamente M é para margin e P é para padding, sendo que os valores vão de 1 a 5, tipo m-1 é uma margem pequena no elemento, e p-5 seria um padding grande no elemento. Sendo que vc mode ainda aplicar apenas no mt- = margin-top, ou mb- = margin-bottom, o mesmo vale para o P. Se quiser os eixo X ou Y igual use mx- para a horizontal e my- para a vertical.
Então no seu caso eu apenas criei um espaçamento entre as ROWs, colocando my-3 nelas e ficou conforme a imagem

<!DOCTYPE html>

    <meta charset="utf-8" />
    <title>Page Title</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" type="text/css" media="screen"
        href="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css" />
    <link rel="stylesheet" type="text/css" media="screen"
        href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" />

                Anim pariatur cliche reprehenderit, enim eiusmod high life accusamus terry richardson ad squid. 3 wolf
                moon officia aute, non cupidatat skateboard dolor brunch. Food truck quinoa nesciunt laborum eiusmod.
                Brunch 3 wolf moon tempor, sunt aliqua put a bird on it squid single-origin coffee nulla assumenda
                shoreditch et. Nihil anim keffiyeh helvetica, craft beer labore wes anderson cred nesciunt sapiente ea
                proident. Ad vegan excepteur butcher vice lomo. Leggings occaecat craft beer farm-to-table, raw denim
                aesthetic synth nesciunt you probably haven't heard of them accusamus labore sustainable VHS.

                                <button class="btn btn-link " data-toggle="collapse" data-target="#collapseOne"
                                    aria-expanded="true" aria-controls="collapseOne">
                                    Collapsible Group Item #1
                                </button>

                                Anim pariatur cliche reprehenderit, enim eiusmod high life accusamus terry richardson ad
                                squid. 3 wolf moon officia aute, non cupidatat skateboard dolor brunch. Food truck
                                quinoa nesciunt laborum eiusmod. Brunch 3 wolf moon tempor, sunt aliqua put a bird on it
                                squid single-origin coffee nulla assumenda shoreditch et. Nihil anim keffiyeh helvetica,
                                craft beer labore wes anderson cred nesciunt sapiente ea proident. Ad vegan excepteur
                                butcher vice lomo. Leggings occaecat craft beer farm-to-table, raw denim aesthetic synth
                                nesciunt you probably haven't heard of them accusamus labore sustainable VHS.

                                <button class="btn btn-link collapsed" data-toggle="collapse" data-target="#collapseTwo"
                                    aria-expanded="false" aria-controls="collapseTwo">
                                    Collapsible Group Item #1
                                </button>

                                Anim pariatur cliche reprehenderit, enim eiusmod high life accusamus terry richardson ad
                                squid. 3 wolf moon officia aute, non cupidatat skateboard dolor brunch. Food truck
                                quinoa nesciunt laborum eiusmod. Brunch 3 wolf moon tempor, sunt aliqua put a bird on it
                                squid single-origin coffee nulla assumenda shoreditch et. Nihil anim keffiyeh helvetica,
                                craft beer labore wes anderson cred nesciunt sapiente ea proident. Ad vegan excepteur
                                butcher vice lomo. Leggings occaecat craft beer farm-to-table, raw denim aesthetic synth
                                nesciunt you probably haven't heard of them accusamus labore sustainable VHS.

                                <button class="btn btn-link collapsed" data-toggle="collapse"
                                    data-target="#collapseThree" aria-expanded="false" aria-controls="collapseThree">
                                    Collapsible Group Item #1
                                </button>

                                Anim pariatur cliche reprehenderit, enim eiusmod high life accusamus terry richardson ad
                                squid. 3 wolf moon officia aute, non cupidatat skateboard dolor brunch. Food truck
                                quinoa nesciunt laborum eiusmod. Brunch 3 wolf moon tempor, sunt aliqua put a bird on it
                                squid single-origin coffee nulla assumenda shoreditch et. Nihil anim keffiyeh helvetica,
                                craft beer labore wes anderson cred nesciunt sapiente ea proident. Ad vegan excepteur
                                butcher vice lomo. Leggings occaecat craft beer farm-to-table, raw denim aesthetic synth
                                nesciunt you probably haven't heard of them accusamus labore sustainable VHS.

                                <button class="btn btn-link collapsed" data-toggle="collapse"
                                    data-target="#collapseFour" aria-expanded="false" aria-controls="collapseFour">
                                    Collapsible Group Item #1
                                </button>

                                Anim pariatur cliche reprehenderit, enim eiusmod high life accusamus terry richardson ad
                                squid. 3 wolf moon officia aute, non cupidatat skateboard dolor brunch. Food truck
                                quinoa nesciunt laborum eiusmod. Brunch 3 wolf moon tempor, sunt aliqua put a bird on it
                                squid single-origin coffee nulla assumenda shoreditch et. Nihil anim keffiyeh helvetica,
                                craft beer labore wes anderson cred nesciunt sapiente ea proident. Ad vegan excepteur
                                butcher vice lomo. Leggings occaecat craft beer farm-to-table, raw denim aesthetic synth
                                nesciunt you probably haven't heard of them accusamus labore sustainable VHS.

                                <button class="btn btn-link collapsed" data-toggle="collapse"
                                    data-target="#collapseFive" aria-expanded="false" aria-controls="collapseFour">
                                    Collapsible Group Item #1
                                </button>

                                Anim pariatur cliche reprehenderit, enim eiusmod high life accusamus terry richardson ad
                                squid. 3 wolf moon officia aute, non cupidatat skateboard dolor brunch. Food truck
                                quinoa nesciunt laborum eiusmod. Brunch 3 wolf moon tempor, sunt aliqua put a bird on it
                                squid single-origin coffee nulla assumenda shoreditch et. Nihil anim keffiyeh helvetica,
                                craft beer labore wes anderson cred nesciunt sapiente ea proident. Ad vegan excepteur
                                butcher vice lomo. Leggings occaecat craft beer farm-to-table, raw denim aesthetic synth
                                nesciunt you probably haven't heard of them accusamus labore sustainable VHS.

                                <button class="btn btn-link collapsed" data-toggle="collapse" data-target="#collapseSix"
                                    aria-expanded="false" aria-controls="collapseFour">
                                    Collapsible Group Item #1
                                </button>

                                Anim pariatur cliche reprehenderit, enim eiusmod high life accusamus terry richardson ad
                                squid. 3 wolf moon officia aute, non cupidatat skateboard dolor brunch. Food truck
                                quinoa nesciunt laborum eiusmod. Brunch 3 wolf moon tempor, sunt aliqua put a bird on it
                                squid single-origin coffee nulla assumenda shoreditch et. Nihil anim keffiyeh helvetica,
                                craft beer labore wes anderson cred nesciunt sapiente ea proident. Ad vegan excepteur
                                butcher vice lomo. Leggings occaecat craft beer farm-to-table, raw denim aesthetic synth
                                nesciunt you probably haven't heard of them accusamus labore sustainable VHS.

                                <button class="btn btn-link collapsed" data-toggle="collapse"
                                    data-target="#collapseSeven" aria-expanded="false" aria-controls="collapseFour">
                                    Collapsible Group Item #1
                                </button>

                                Anim pariatur cliche reprehenderit, enim eiusmod high life accusamus terry richardson ad
                                squid. 3 wolf moon officia aute, non cupidatat skateboard dolor brunch. Food truck
                                quinoa nesciunt laborum eiusmod. Brunch 3 wolf moon tempor, sunt aliqua put a bird on it
                                squid single-origin coffee nulla assumenda shoreditch et. Nihil anim keffiyeh helvetica,
                                craft beer labore wes anderson cred nesciunt sapiente ea proident. Ad vegan excepteur
                                butcher vice lomo. Leggings occaecat craft beer farm-to-table, raw denim aesthetic synth
                                nesciunt you probably haven't heard of them accusamus labore sustainable VHS.

                        This is some text within a card body.

                        This is some text within a card body.


How to subtract timestamps from two seperate columns, then enter this data into the table

Question: I am attempting to create a sign-in, sign-out program using python and mysql on a raspberry pi. I have so far successfully created a system for registering, signing in, and signing out, but am having trouble with the final component. I am trying to subtract the two separate time-stamps (signin, signout) using TIMESTAMPDIFF, and then entering this value into a separate column in the table. However, the statement I am using is not working.
Code:
employee_id = raw_input("Please enter your ID number")

minutes_calc = "INSERT INTO attendance (minutes) WHERE id = %s VALUES (TIMESTAMPDIFF(MINUTE, signin, signout))"

try:

    curs.execute(minutes_calc, (employee_id))
    db.commit()
except:

    db.rollback()
    print "Error"

Table Structure so far (apologies for formatting):
name    |    id    |    signin           |    signout          |    minutes    |

Dr_Kerbal      123     2016-08-21 22:57:25   2016-08-21 22:59:58    NULL

Please Note that I am in need of a statement that can subtract the timestamps regardless of their value instead of a statement that focuses on the specific timestamps in the example.
Additionally the datatype for the column minutes is decimal (10,0) as I initially intended for it to be in seconds (that was when I encountered other issues which have been solved since), its null status is set to YES, and the default value is NULL.
Thank You for your Assistance
Answer: You need an update query not INSERT
UPDATE attendance
SET `minutes` = TIMESTAMPDIFF(MINUTE, signin, signout);

Comment: Thanks, it worked except for one small tweak. I had to remove the single quotes around minutes to get the command to work.


What is the distribution function of a random variable X which has a constant fixed value of 2?

Question: I remember reading somewhere that it is not possible for a continuous variable to take on an exact value so would the answer be 0?
Answer: Find the CDF $F$ of $X$:
$$F(x) = \text{Pr}(X \le x)$$

If $x < 2$, then $F(x) = \text{Pr}(\varnothing) = 0$.
If $x \ge 2$, then $F(x) = 1$.

The PDF $f$ of $X$ is $$f(x) = \frac{d}{dx} F(x)$$
wherever defined.
Which is $0$ everywhere obviously.
Answer: You can construe such a variable as either continuous or discrete. The probability density would not be a function but a measure, the Dirac Delta $\delta(x-2)$. Alternatively, the probability mass function is a Kronecker Delta, $\delta_{x2}$. See here
Comment: To get the distribution how exactly would you integrate the Dirac Delta?
Comment: @chloeloughan The cdf  is $\int_{-\infty}^x\delta (y-2)dy=\Theta (x-2)$, a Heaviside step function.


save Python script with formatting - special characters

Question: I use pygmentize to save my Python script as rtf file (with propoer colors depends on keywords in syntax).
Unfortunatelly program substitute special characters (ą,ę,ź,ć,ó) with strange symbols.
Is there any option to set proper code page?
Alternatively - is there any other tool which can proceed this operation properly?
If answer for both question is no - how I should automatically remove all special characters from Python script?
Answer: Did you use the encoding option so pygmentize will use the actual encoding of your source file? If you don't, it defaults to latin-1 which doesn't contain the characters you quoted.
Comment: But you did --- although maybe not explicitly. Check the encoding settings of your editor and use that.
Comment: Thanks for fast answer - you wrote "encoding of source code". I didn't set encoding in my source code (well, I must admit that I use pygmentize to color also R! scripts, so i suppose that even if I set it, it will doesn't work properly).
Comment: @Mateusz: The safest bet (generally) would be to use `utf-8` as your source encoding (which you need to tell your editor and (unless you're on Python 3) also your Python interpreter by inserting the line `# -*- coding: utf-8 -*-` at the top of your script). A decent editor can change the encoding of a source file for you. If you use `utf-8`, you're future-proof.


Como fazer uma conexão com banco de dados utilizando o padrão de projeto Singleton

Question: Bom eu faço muitas aplicações web, onde todas elas eu utilizo banco de dados, e toda vez que vou  fazer um novo projeto, eu crio um arquivo responsável por fazer as consultas com o banco de dados(CRUD).
Só que eu quero mudar isso, quero fazer um arquivo onde tenho todas essa consultas com o banco de dados, e queria utilizar o padrão de projetos Singleton.
E queria uma ajuda de como montar esse arquivo.
Comment: Recomendo esta questão como leitura adicional: http://pt.stackoverflow.com/questions/18860/por-que-n%C3%A3o-devemos-usar-singleton/18933#18933
Comment: Vídeo falando sobre Singleton em PHP: https://www.youtube.com/watch?v=hHKOLn0Lx7A
Answer: O pattern Singleton consiste em sempre retornar a mesma instância de determinada classe a qualquer ponto da aplicação.
Isso é feito limitado o acesso ao método construtor e retornando a instância através de um método estático, ou seja, um método que você pode chamar sem instanciar a classe.
Segue uma implementação rápida:
class BancoDeDados
{
    // Instância da classe
    private static $instance = null;
    private $conn;

    // Construtor privado: só a própria classe pode invocá-lo
    private function __construct()
    {
        $host = "localhost";
        $user = "root";
        $pswd = "root";
        $db = "banco";

        try {
            $this->conn = mysqli_connect($host, $user, $pswd, $db);
            $this->conn->set_charset('utf8');
        } catch (Exception $e) {
            die("Erro na conexão com MySQL! " . $e->getMessage());
        }
    }

    // método estático
    static function getInstance()
    {
        // Já existe uma instância?
        if (self::$instance == NULL)
            self::$instance = new BancoDeDados();   // Não existe, cria a instância
        return self::$instance;                     // Já existe, simplesmente retorna
    }

    // Previne o uso de clone
    private function __clone() {}
}

// Usando a classe
$db = BancoDeDados::getInstance();

// Você não poderá fazer isso por causa do construtor privado:
$db = new BancoDeDados();

A partir dai, desenvolva os métodos para acesso a sua classe de banco.
Comment: Não, essas operações você cria normalmente em métodos públicos.
Comment: Esse código me ajudou bastante, mas como mencionei, quero fazer operações CRUD. Eu devo fazer essas funções estáticas também? Ex: static function updateDb().....
Answer:
Singleton
Intenção:
Garantir uma única instância e prover um ponto de acesso global
  a ela durante todo o ciclo de uso da aplicação

Primeiro, singleton não é para uso de banco de dados. Se precisar usar múltiplas bases de dados, o que acontece? Singleton se torna um problema. Se precisa de um pattern para database, procure por DAO (por exemplo). E caso não use ainda, procure trabalhar com PDO no PHP, pois é muito mais seguro, flexível e atende bem.
Segundo, singleton no PHP é inviável. O motivo? A cada requisição http feita o PHP destrói automaticamente todas as instâncias. Seja qual for a linguagem ou tecnologia usada, qualquer situação em que a resposta destrua a instância o singleton deixa de fazer sentido, pois é gerada uma nova instância a cada requisição.
Ao usar um pattern você precisa entender bem a qual problema ele se propõe a resolver, se ele se encaixa na resolução do seu problema e se o ambiente em que você irá aplicá-lo permitirá que esse propósito seja cumprido. Qualquer coisa diferente disso você deve evitar o uso, pois ao invés de solucionar o seu problema ele acabará criando muitos outros.
Comment: Dalton, por favor, confira o guia [Como devemos formatar perguntas e respostas?](http://meta.pt.stackoverflow.com/q/1084/201), pois seu uso da formatação de código é equivocado. Valeu!
Comment: É benéfico quando bem aplicado. Singleton na maioria das vezes não é usado corretamente. Em PHP seria viável com o uso de um web socket onde a instância não seria destruída, assim você teria de fato uma única instância durante todo o ciclo de uso da aplicação. Singleton perde o sentido se a instância for destruída. É importante frisar que escrever um singleton corretamente é totalmente diferente de implementá-lo corretamente, por isso é muito importante que se conheça bem a motivação dos patterns e seus casos de uso.
Comment: Dalton, singleton realmente não é o melhor pattern para isso. Porém não esqueça que cada caso é um caso e cabe ao expertise do programador avaliar o seu uso.  Como você disse, o objetivo do pattern é eliminar o problema de múltiplas instâncias. se você tem esse problema numa aplicação (criação de varias instâncias de um mesmo objeto, mesmo numa mesma requisição php) seu uso é sim benéfico.
Comment: Um caso de uso que ocorreu comigo. Tenho um código legado que estou trabalhando. Sua migração completa demorará alguns meses e o ambiente de prod estava sofrendo com grande consumo de memoria entre as requisições. Precisava fazer algo. Analisando alguns trechos de código descobri que a classe do banco era instanciada até 8 vezes por requisição! Nesse caso o singleton foi minha solução. O apliquei na classe do banco, dei um replace all nas instancias da classe e resolvi o problema do consumo de memoria em menos de 15 minutos. Fiz algo de errado em aplicar singleton ?
Comment: Sobre o seu caso de uso, acredito que o pattern Registry seria o ideal.
Comment: http://avedo.net/101/the-registry-pattern-and-php/ - pelo que entendi o resgistry é uma coleção de instancias, que retorna sempre a mesma instancia de um objeto. Você está sugerindo que eu crie mais uma classe em um código legado para garantir que eu vá receber sempre a mesma instancia de um único objeto?
Comment: Registry é como uma caixa que guarda instâncias e usa a instância específica que você guardou quando requisitada. Lembre-se que fazer funcionar é diferente de usar corretamente, singleton funcionou e sabemos que não é a melhor solução para esse caso de uso. O que sugiro é refatorar o código legado e usar os patterns corretamente. Se não for possível, ainda que ache que terá um pouco mais de trabalho com o Registry, é o que recomendo, afinal quanto mais bed smells forem adicionados, pior a aplicação ficará, ainda que pareça uma solução eficiente no momento.
Comment: Já estou migrando o código legado em outro projeto. Irei utilizar data mapper para abstração com banco. Devo perder mais tempo com o código legado se o singleton resolve o problema?
Comment: A decisão é sua, se você precisar utilizar mais um banco no código legado você terá mais uma dor de cabeça com a utilização do singleton.
Comment: Não é o caso. O código legado não sofrerá novas melhorias.
Comment: Ok, outra coisa: Sem o private function __clone() você não garantirá que o seu singleton possua uma única instância durante a execução do fluxo, pois ele poderá ser clonado.
Comment: Realmente esqueci do clone. Editei a resposta, Obrigado!


How to synchronise web application database with a windows application database

Question: I am having two databases for  the same application , one in windows and the other is web based.Since web based one have  few functionalities I can't opt for a single database.At the same time I want to share Both databases to be updated with other's data so as to work error free with my module of appointment fixing.If anyone have a nice solution to this problem please help me with your advise,Thanks.......
Comment: You need to clarify your question.  What are you looking for?  Is the "windows" db hosted on user desktops or on a central server?  Is the "web based" db hosted on a server in the same facility or off site?  How will users be accessing the web interface?  The "windows" db?
Comment: windows db is on a central server.Web db is hosted on a offsite server.
Answer: Can you clarify the statement, "Since web based one have few functionalities"? The best option is to use one database for both apps.
Edit:
If the web db only has a minimal set of tables, it should be easy to roll that schema into the other database and then host onh the offsite server. Problem solved...
Comment: It means web based db is only a small part of the other(only meant for appointment module)
Answer: Go for a single database no matter how much wrangling it takes. Two way DB synchronization is not for the faint of heart and I find it hard to believe that you can't find a way to use a single DB.
Even if one of the databases is not feature rich enough ("have few functionalities") use the OTHER one as your single DB.
UPDATE: Here's another thought. It is not unheard of for an application to access two separate databases to do its job. Why not keep both and have the apps query whichever is needed?
Comment: That's nice,but my DBs are in different servers and are at different places.so even if I use a single database how could I update it in each server.
Comment: If you had a DB in a single place you wouldn't NEED to update it on each server. That's kind of my point.


Capturar Nível de Qualidade de Compressão da Imagem PHP

Question: Preciso capturar o nível de qualidade de uma imagem, achei algo relativo no [Imagick][1]
Tentativa de uso:
    $img = new Imagick();
    $img->readImage( $local_da_imagem );
    print_r( $img->getCompressionQuality() );

mas, este retorno sempre é 0
Answer: Resolvido
$img = new Imagick();
$img->readImage( $local_da_imagem );
echo $img->getImageCompressionQuality() ;

Assim é retornado o nível de qualidade da imagem, indo de 0 a 100, quanto mais alto, melhor a qualidade.


How to override form id of Webform?

Question: I want to override form_id of webform in Drupal 7. Example my webform form id is webform_141 and I want to override it to webform_en or webform_uk.
Is it possible?
Note: I need to override it for multilingual site.
Comment: What is the reason to override the form ID?
Comment: @JimmyKo I need to override it for multilingual site.
Comment: I think changing form ID is discouraged and there is no safe way to do that. You have never know how other module manipulates the form ID. If you change it to ease the development. I would suggest you to store the form ID into a constant or inside the $conf array in settings.php
Answer: You can simply do following way, using hook_form_alter, paste following code in your template.php file, save and clear cache. Change the THEME with your themeName in code or if you are doing with costume module then with module name.
In your case the code will be,
function THEME_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'webform_141') {
    $form['#id'] = 'webform_en';
  }
}

Answer: You can use hook_form_alter.
E.g:

/**
 * Implement hook_from_alter
 *
 * @param type $form
 * @param type $form_state
 * @param type $form_id
 */
function MYMODULE_form_alter(&$form, &$form_state, $form_id) {
   $form['#form_id']='webform_en';
}

Comment: When you see the form in console then id will be the same(its default one).
Answer: /**
 * Implement hook_from_alter
 *
 * @param type $form
 * @param type $form_state
 * @param type $form_id`enter code here`
 */
function MYMODULE_form_alter(&$form, &$form_state, $form_id) {
   if($form_id == 'webform_141'){
    $form['#form_id'] = 'webform_en';
    $form['#form_id'] = 'webform-en';
    $form['form_id']['#value'] = 'webform_en';
    $form['form_id']['#id'] = 'webform_en';
   }
}

Comment: You probably should add an if statement checking the form ID as shown in [this answer](http://drupal.stackexchange.com/questions/222449/how-to-override-form-id-of-webform-in-drupal-7#answer-222459), other wise, **all** of your forms will be affected.

How to override form id of Webform?


Nginx with node and lingering_close keeping connections open for 5 seconds

Question: We have a collection of servers set up to use our new shiny API, which will replace our old API written in an arcane language.
The new application is a cluster of servers using node, just behind NGINX.
This is the same type clustered set up for the old API.
There is another server sitting in font of these two clusters, using NGINX to route traffic to one or the other.
Right now the new cluster is getting much less than 1% of the traffic, while the old cluster is receiving much more than 99% of the traffic.
Logs indicate that the client (the client sitting in front of the NGINX router) is always receiving responses in a timely manner (regardless of which cluster processes the request)
Logs also indicate that node is responding to it's local NGINX in a timely manner.
The old NGINX/API is working well.
However, the LOCAL NGINXs for the node cluster are logging that each request is taking the time it takes for node to respond... plus an extra 5 seconds.
A little investigation proves that this is due to a configuration setting called lingering_close... which is set to 5 seconds. According to the documentation, lingering close uses 'Heuristics' to decide when to stay open.
http://nginx.org/en/docs/http/ngx_http_core_module.html#lingering_close
That's more than a little vague.
We know that the connection only stays open for 5 seconds when responses are smaller than 1.1k. I know that's weird... but 'Heuristics'
If we turn lingering_close off... the connections close without the impact of Heuristics.
This never seems to happen on the OLD cluster.
Does anyone have any clearer information on what Heuristics might be keeping the connection open, and possibly some advice on how to proceed.
my biggest worry is that all traffic is moved to the second cluster, and all of these open connections start to cause a performance issue.
Comment: To make this a little simpler... what does heuristics mean in the link above.
Answer: It's all about indication that there can be more data left in the socket. E.g. the lingering close is enabled if not complete request body has been read during processing, or if there are some more data left in the buffer, or if the socket in active state.
You may be interested in this change, which significantly reduces probability of lingering close on Linux: http://hg.nginx.org/nginx/rev/f7849bfb6d21
Comment: Thanks... but since node responding with the full payload, why would NGINX keep the connection lingering? Is there something missing in the header? or the payload?
Comment: @Nicholas Lingering close isn't related to your nodejs backends. It only works on the client side.
Comment: My worry is that we will have performance issues when the traffic is ramped up to hundreds of requests per second. Right now it would seem the proxy is keeping the connection open. Is this something I should be concerned about?>
Comment: I'd suggest you to upgrade nginx to the latest mainline version (lingering close heuristics on Linux was improved in nginx 1.11.0), or just turn off lingering close.


How to associate a node with a menu without adding it to the menu

Question: Since menus drive the breadcrumbs by default in Drupal, is there a way to associate a node with a menu without actually adding it to the menu?  I am trying to maintain a concise menu that nodes can be associated with on the node edit page, without having every node that I associate with the menu then becoming yet another item in an ever growing menu tree.
Answer: I am not exactly sure of what you are trying to accomplish here, but it sounds like you are trying to use menus to alter the breadcrumb behavior
If that's the case, you should try the menu breadcrumb module - http://drupal.org/project/menu_breadcrumb or the custom breadcrumb module - http://drupal.org/project/custom_breadcrumbs
Hope this helps


Input disable não é encontrado no serialize

Question: Se o form que eu tenho é validado, eu desabilito o form, desta maneira:
 $("#Editar :input").prop("disabled", true);

Porém eu tenho uma function que serialize, e se eu estou com os forms desabilitados, eles não encontram o valor. Tem alguma forma de desabilitar os campos, mas que eles ainda sejam encontrados ?
Esta é a função que utilizo, ele compara o form quando é carregado, e o form na hora da ação, e como estão desabilitados, ele não encontra valores.
   $(function () {
        var init_form = $('#Editar').serialize();
    $(':submit').click(function () { window.onbeforeunload = null; }); window.onbeforeunload = function () { var check_form = $('#Editar').serialize(); console.log(check_form); console.log(init_form); if (check_form === init_form) return null; return 'Os dados do formulário não foram salvos, deseja permanecer nesta página?'; };
 });

No console, o que aparece em branco é o var check_form = $('#Editar').serialize(); o outro não, como corrigir?
Answer: A propriedade disable realmente não é lida no serialize, tente trocar a propriedade do campo para readonly.
$('#inputId').prop('readonly', true);

Isso deve resolver seu problema.
Comment: Deu certinho, obrigado.