General summation formula for...

Question: I'm looking for a general summation formula for $\left((1-\lambda)\lambda^0+(1-\lambda)\lambda^1\right)R^{(2)} + \left((1-\lambda)\lambda^2+(1-\lambda)\lambda^3\right)R^{(4)} + \left((1-\lambda)\lambda^4+(1-\lambda)\lambda^5\right)R^{(6)} + \ldots$
Comment: What is $R^{(n)}$ ? Why do you keep all these $(1-\lambda)$ factors ?
Comment: $R^n$ ignore the parenthesis.
Comment: to ensure that the weights sum to 1.
Comment: They sum to $1+\lambda$, not to $1$. but the question was why don't you leave them in evidence.
Comment: no they really sum to 1.
Comment: use excel and see yourself. but $\lambda < 1$
Comment: @Yves Daoust You are doing it in the wrong way, let say for $\lambda=0.9$ and $R=1$. $\left((1-0.9)*0.9^0 + (1-0.9)*0.9^1 + (1-0.9)*0.9^2 + \ldots\right)=1$
Comment: You are right, sorry. There is a closed formula for the sum.
Answer: You mean something like this?
$$\sum _{i=0}^{\infty} (1-\lambda)({\lambda}^{2i}+{\lambda}^{2i+1})R^{(2i+2)}$$
As pointed out in the comments, you could factor the $(1-\lambda)$ term out of the sum as:
$$(1-\lambda)\sum _{i=0}^{\infty} ({\lambda}^{2i}+{\lambda}^{2i+1})R^{(2i+2)}$$
Comment: Yes thanks. But the right would be $\sum_{i=0}^\infty(1-\lambda^{3i})\lambda^{3i}R^{3i+3}$.
Comment: and what if $\left((1-\lambda)\lambda^0+(1-\lambda)\lambda^1+(1-\lambda)\lambda^2)\right)R^{(3)} + \left((1-\lambda)\lambda^3+(1-\lambda)\lambda^4+(1-\lambda)\lambda^5\right)R^{(6)} + \left((1-\lambda)\lambda^6+(1-\lambda)\lambda^7+(1-\lambda)\lambda^8\right)R^{(9)} + \ldots$ Is there how get a general formula. @GaussTheBauss
Comment: Is there another way without adding more terms to the summation?
Comment: @Davi $(1-\lambda)\sum _{i=0}^{\infty} ({\lambda}^{3i}+{\lambda}^{3i+1}+{\lambda}^{3i+2})R^{(3i+3)}$
Comment: no, I'm sorry. The number is 9.
Comment: Yes there is a cancellation, the where the sum is 1. But there is something about R that I don't tell you, I'm sorry. R is another summation and the power is the number of sum.
Answer: This sum can be written
$$(1-\lambda^2)\sum_{k=0}^\infty \lambda^{2k}R^{(2k+2)}.$$
If $R^{(n)}$ is to be understood as $R^n$, this geometric series converges to
$$\frac{(1-\lambda^2)R^2}{1-\lambda^2R^2}$$ when $|\lambda R|<1$.
Comment: Shocking downvote.
Comment: and what if $\left((1-\lambda)\lambda^0+(1-\lambda)\lambda^1+(1-\lambda)\lambda^2)\right)R^{(3)} + \left((1-\lambda)\lambda^3+(1-\lambda)\lambda^4+(1-\lambda)\lambda^5\right)R^{(4)} + \left((1-\lambda)\lambda^6+(1-\lambda)\lambda^7+(1-\lambda)\lambda^8\right)R^{(6)} + \ldots$ Is there how get a general formula. @Yves Daoust
Comment: @davi: first fix the exponents of $R$.
Comment: @davi: $(1-\lambda^3)R^3/(1-\lambda^3R^3)$.
Comment: @GaussTheBauss Let's remove those comments then.
Comment: @GaussTheBauss: done. :)

General summation formula for...


Simple/Basic steganography algorithms and methods

Question: What are the basic and simpliest steganography algorithms and methods?
I mean the steganography applied to images.
How does a simple program that hides data to images work? What are the main techniques used? How does the program recognize the encrypted message in image without the source image?
Comment: recognize the encrypted message in image without the source image? - checksum I guess. BTW, you should differ computer steganography and real-world. They usually use different techniques.
Answer:
What are the basic and simpliest steganography algorithms and methods?  I mean the steganography applied to images.

I have written a library for this in the past a long time ago so I can describe the process.
Basically if you have a file format, let's say the 24-bit BMP format.  First you need a way to read and write pixels into that file format. Either you can use a library or write your own once you learnt what the file format is.
An image can be looked at as a series of pixels.  Consider a 4x4 pixel image:

x x x x
  x x x x
  x x x x
  x x x x

Number these pixels from 1 to 16:

01  02 03 04
  05  06 07 08
  09  10 11 12
  13 14 15 16

Each pixel that is numbered above has a red component, a green component and a blue component.  Each of those components are 1 byte each and so each component can be looked at as a value of 0 to 255.  (24-bit = 8bits for red, 8 bits for green, 8 bits for blue).  So each of the numbers above have 3 sets of values from 0 to 255.
So in the above example with a 4x4 image you have a total of 16pixels*3color_components = 48 bytes of data in your image.  Typically what you will do is use only the least significant bit of each color component to encode your image.  In which case you would have 48 bits bits of data available for you = 6 bytes available to you to encode any 6 byte message you want.
To make this easier though let's just look at encoding a simple 3 bit message into a single pixel. And let's assume we are only using 1 bit per color component.
Let's say we want to encode the 3 bit message: 111
Here is an example of the value pixel 1 above has before you encode the data:
R: 10101011
G: 11111010
B: 00011010
What you do is change only the least significant bit to the new data:
R: 1010101 1
G: 1111101 1
B: 0001101 1
The pixel will look the same to the human eye, but now you are using the least significant bit to represent the data you wanted to encode.
If you want to encode more than 3 bits of data into a single pixel you can also do that.  What happens is that you will encode more than just the least significant bit, you can use the least 2 significant bits, or the least 3, etc. The more bits you use, you will start to notice a little bit of a difference in the image quality.  You can use up to 7 bits though and your image will still look recognizable.
Typically you will have a lot more than 3 bits of data you want to encode though.  The more data you want to encode, you will have to either have more pixels, or use more bits per pixel to encode the data.  Let's say you have 9 bits of data you want to encode, well if you are only using the least significant bit, then you need 3 pixels to encode that information.  If you want to only use 1 pixel though you can do that by using the 3 least significant bits per color component to encode that data.
To do this type of work you'll probably want to create some functions for easily working with bits of data that abstract away the complexities of dealing constantly with bitwise operators.
The technique will vary for different file formats, but the concept is the same.  Steganography can also refer just to hiding the data for example in a GIF extension block even.  Typically you hide it by varying the pixels of the image though, or in some file formats the color lookup table.
Some images have a color lookup table in the header, and then the pixels are indexes into those color lookup tables.  What you can do is re-order the color lookup table so the most similar colors are close together, then you can encode data both into the color lookup table itself and into the indexes of the pixels.  Because it won't matter if the index slightly changes because the lookup table is ordered according to being similar.
You really do need to have an understanding of the file formats to do this type of work though.  Or at least be using a library that can manipulate the file format and file data for you.  If you are really interested in this topic I suggest to start with a simple file format like BMP and to learn it.  You can always find file format specifications on sites like www.wotsit.org.

How does the program recognize the encrypted message in image without the source image?

You are correct.  The program that decodes the information does not need the source image.
How this works is that it simply does the reverse, the program will need to know how many bits of data you enoded using and use the same to decode.  It will simply iterate over each pixel and combine the bits into bytes and write those bytes out to a file.
Comment: Very elaborate answer, great description of the "least significant bit change" method. Thanks.
Comment: For palette-based formats you can decrease amount of real colors to free some indexes and then fill them with RGB of the most popular color. That will allow to avoid noise in the picture. Encoding of message will be a bit different from just slicing bits and replacing them in an image. That's because you can allocate 3 indexes and if there 2 places in the image you'll have 3**2 = 9 different messages.
Comment: Ya basically there are no hard fact rules of what steganography is defined to be, if you understand the file format and are creative then you can accomplish it.
Answer: Modifying least significant bits of bitmap pixels.
For a nice overview, see this page
Answer: There are literally infinite ways to hide information in images.
One simple way is to notice that changing the least significant bit of each RGB value doesn't make a noticeable difference, so setting the least-significant bit of every byte in the image gives us <code>(#-bits-in-image / 8)</code> bits to store hidden data in.


About convert Image to byte[] and reverse in Java

Question: i have one problem when i convert image to byte[] and reverse:
I have 2 function convert image to byte[] as follow
public byte[] extractBytes2 (String ImageName) throws IOException {
    File imgPath = new File(ImageName);
    BufferedImage bufferedImage = ImageIO.read(imgPath);
    WritableRaster raster = bufferedImage .getRaster();
    DataBufferByte data   = (DataBufferByte) raster.getDataBuffer();
    return ( data.getData() );
}

and
public byte[] extractBytes (String ImageName) throws IOException
{
    Path path = Paths.get(ImageName);
    byte[] data = Files.readAllBytes(path);
    return data;
}

I will have byte[] byteArray
byteArray = extractBytes2("image/pikachu.png");

or
byteArray = extractBytes("image/pikachu.png");

when i convert byte[] to Image i use
Graphics g = panelMain.getGraphics();
    Graphics2D g2D = (Graphics2D) g;
    try {
        InputStream in = new ByteArrayInputStream(byteArray);
        BufferedImage image = ImageIO.read(in);
        g2D.drawImage(image, 0, 0, GiaoDienChinh.this);
        g2D.setPaint(Color.BLACK);
        panelMain.setOpaque(true);
        panelMain.paintComponents(g2D);
    }
    catch ( Exception e ) {
    }
    finally {
    }

but i only draw with byteArray use function "extractBytes" not with "extractBytes2" !!!
Anyone can explain me how i can draw image with byteArray which got from "extractByte2"?
Thanks for all support!
Comment: I actually don't understand the problem: is method `extractBytes2` not working or not called or does `byteArray` always holds the result of `extractBytes` when you paint the image?
Answer: Let's start with the paint code.
ImageIO.read(in) is expecting a valid image format that one of it's pluggable service provides knows how to read and convert to a BufferedImage.
When you pass the byes from extractBytes, you're simply passing back an array of bytes that represents the actual image file.  I'd be the same as saying Image.read(new File("image/pikachu.png"))
However, the data buffer returned from your extractBytes2 is returning a internal representation of the image data, which may not be "readable" by ImageIO.
UPDATED

A BufferedImage is an accessible buffer of image data, essentially
  pixels, and their RGB colors. The BufferedImage provides a powerful
  way to manipulate the Image data. A BufferedImage object is made up of
  two parts a ColorModel object and a Raster object.

Referenced from here
UPDATED
I had this wacky idea on the way home of how to convert a BufferedImage to a byte array...
The basic idea is to use ImageIO.write to write out the BufferedImage to a ByteOutputStream...
public static byte[] extractBytes2(String ImageName) throws IOException {
    File imgPath = new File(ImageName);
    BufferedImage bufferedImage = ImageIO.read(imgPath);

    ByteOutputStream bos = null;
    try {
        bos = new ByteOutputStream();
        ImageIO.write(bufferedImage, "png", bos);
    } finally {
        try {
            bos.close();
        } catch (Exception e) {
        }
    }

    return bos == null ? null : bos.getBytes();

}

Here's my test...

public class TestByteImage {

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

    public static byte[] extractBytes2(String ImageName) throws IOException {
        File imgPath = new File(ImageName);
        BufferedImage bufferedImage = ImageIO.read(imgPath);

        ByteOutputStream bos = null;
        try {
            bos = new ByteOutputStream();
            ImageIO.write(bufferedImage, "png", bos);
        } finally {
            try {
                bos.close();
            } catch (Exception e) {
            }
        }

        return bos == null ? null : bos.getBytes();

    }

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

                JFrame frame = new JFrame("Test");
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.setLayout(new BorderLayout());
                frame.add(new ImagePane());
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }

    public class ImagePane extends JPanel {

        private BufferedImage original;
        private byte[] byteData;
        private BufferedImage fromBytes;

        public ImagePane() {
            String name = "/path/to/your/image";
            try {
                original = ImageIO.read(new File(name));
                byteData = extractBytes2(name);
            } catch (IOException ex) {
                ex.printStackTrace();
            }

            setFont(UIManager.getFont("Label.font").deriveFont(Font.BOLD, 48f));

        }

        @Override
        public Dimension getPreferredSize() {
            return original == null ? super.getPreferredSize() : new Dimension(original.getWidth() * 2, original.getHeight());
        }

        protected void drawText(Graphics2D g2d, String text, int x, int width) {
            BufferedImage img = new BufferedImage(width, getHeight(), BufferedImage.TYPE_INT_ARGB);
            Graphics2D tmpg = img.createGraphics();
            tmpg.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
            tmpg.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
            tmpg.setFont(g2d.getFont());
            tmpg.setColor(Color.RED);
            FontMetrics fm = tmpg.getFontMetrics();
            int xPos = ((width - fm.stringWidth(text)) / 2);
            int yPos = ((getHeight() - fm.getHeight()) / 2) + fm.getAscent();
            tmpg.drawString(text, xPos, yPos);
            tmpg.dispose();

            AffineTransform transform = g2d.getTransform();
            g2d.setTransform(AffineTransform.getRotateInstance(Math.toRadians(-10), x + (x + width) / 2, getHeight() / 2));
            g2d.drawImage(img, x, 0, this);
            g2d.setTransform(transform);
        }

        @Override
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);
            if (original != null) {
                g.drawImage(original, 0, 0, this);
                drawText((Graphics2D) g, "Original", 0, original.getWidth());
            }
            if (byteData != null && fromBytes == null) {
                try {
                    fromBytes = ImageIO.read(new ByteInputStream(byteData, byteData.length));
                } catch (IOException exp) {
                    exp.printStackTrace();
                }
            }
            if (fromBytes != null) {
                g.drawImage(fromBytes, getWidth() - fromBytes.getWidth(), 0, this);
                drawText((Graphics2D) g, "From Bytes", getWidth() - fromBytes.getWidth(), fromBytes.getWidth());
            }
        }
    }
}

Comment: thanks i see. But have any way i can use byteArray from `extractBytes2` to draw image?
Answer: Use ImageIo to write bufferedImage into ByteArrayOutputStream, then invoke the toByteArray method of the stream.


Laravel 4: How to add more data to Auth::user() without extra queries?

Question: I'm rather new to Laravel 4 and can't seem to find the right answer, maybe you can help:
A User in our application can have many Accounts and all data is related to an Account, not a User. The account the User is currently logged into is defined by a subdomain, i.e. accountname.mydomain.com.
We added a method account() to our User model:
/**
 * Get the account the user is currently logged in to
 */
public function account()
{
    $server = explode('.', Request::server('HTTP_HOST'));
    $subdomain = $server[0];
    return Account::where('subdomain', $subdomain)->first();
}

The problem is that there is always an extra query when we now use something like this in our view or controller:
Auth::user()->account()->accountname

When we want to get "Products" related to the account, we could use:
$products = Product::where('account_id', Auth::user()->account()->id)->get();

And yet again an extra query...
Somehow we need to extend the Auth::user() object, so that the account data is always in there... or perhaps we could create a new Auth::account() object, and get the data there..
What's the best solution for this?
Thanks in advance
Comment: How about storing your model into a session
Comment: That was our first thought as well, but I think it's ugly if we have to use Session::get('account_id') everywhere. Plus the user can change the subdomain to another account, so the session has to be checked/updated on every request.
Comment: From what you write, account() method has no relation with User, so you should not put it in User model, you can add it at the end of bootstrap/start.php and call `account()->id` ( It's not the best practices, just try and let us know if it works)
Answer: Just set it to a session variable.  This way, you can check that session variable before you make the database call to see if you already have it available.
Or instead of using ->get(), you can use ->remember($minutes) where $minutes is the amount of time you wish to keep the results of the query cached.
Answer: You should take a look at Eloquent relationships : http://laravel.com/docs/eloquent#relationships
It provides simple ways to get the account of a user and his products. You said that a user can have many accounts but you used a first() in your function I used a hasOne here.
Using Eloquent relationships you can write in your User model:
<?php
public function account()
{
    // I assume here 'username' is the local key for your User model
    return $this->hasOne('Account', 'subdomain', 'username');
}

public function products()
{
    // You should really have a user_id in your User Model
    // so that you will not have to use information from the
    // user's account
    return $this->hasMany('Product', 'account_id', 'user_id');
}

You should define the belongsTo in your Account model and Product model.
With Eager Loading you will not run a lot of SQL queries : http://laravel.com/docs/eloquent#eager-loading
You will be able to use something like
$users = User::with('account', 'products')->get();

To get all users with their account and products.
Comment: I can't use hasOne, since the user can have many accounts.. There is a users_accounts table to connect users to their accounts and viceversa. We have a belongsToMany relationship that gets all the accounts the user has access to, but the problem is the account the user is currently viewing (only defined by the subdomain). We need that information available in the Auth::user() object without performing DB queries.
Answer: I think this is a good example for the purpose of Repositories.
You shouldn't query the (involved) models directly but wrap them up into a ProductRepository (or Repositories in general) that handles all the queries.
For instance:
<?php

class ProductRepository
{
    protected $accountId;

    public function __construct($accountId)
    {
         $this->accountId = $accountId;
    }

    public function all()
    {
        return Product::where('account_id', $this->accountId)->get();
    }
}

//now bind it to the app container to make it globaly available
App::bind('ProductRepository', function() {
    return new ProductRepository(Auth::user()->account()->id);
});

// and whenever you need it:
$productRepository = App::make('ProductRepository');
$userProducts = $productRepository->all();

You could group the relevant routes and apply a filter on them in order to bind it on each request so the account-id would be queried only once per repository instance and not on every single query.
Scopes could also be interesting in this scenario:
// app/models/Product.php
public function scopeCurrentAccount($query)
{
    return $query->where('account_id', Auth::user()->account()->id);
}

Now you could simply call
$products = Product::currentAccount()->get();


Is it possible to filter by taxonomy field?

Question: Is it possible to filter by taxonomy field in a view, using Drupal 7?
I will try to explain the problem with a silly example: let's say I have a list of countries that are a taxonomy term and each country has a field "Language".
I also have a list of items each linked to a specific country.
I would like to be able to filter by language, getting only those items that have a country where e.g Spanish is spoken.
Answer: Absolutely. When creating a new View, be sure to show "Taxonomy Terms" rather than Content. Change "of type" to be Countries.

After that, you should be able to add a Filter for the language field.


CSS Junk files in the css folder

Question: What are all those junk CSS files in site/files/css with names like css_ZFCUUB6IIfaVQ-erWDr0M0Na1JbxEsU-8zjQrWAtrbU.css? There are hundreds of them.
How do these get generated over time? What do they do?
Answer: They aren't junk files, they are aggregated files are generated when you have CSS aggregation turned on. They make your page load times faster, as multiple files are aggregated into a single file, meaning less files have to be downloaded to the browser.
Answer: Yes @Jaypan is right. You need to check on admin/config/development/performance. In the Bandwidth optimization section there is an option for Aggregate and compress CSS files. Deselect that option and save, if you want to remove them.
Clear the cache and check.

CSS Junk files in the css folder


Smallest number such that the sum of digits and the product of digits is $2000$

Question: Find the smallest number such that the sum of the digits and the product of the digits is $2000$.
I came across the following question on the internet and I am unable to solve this.
Which mathematical tools are used to solve such kind of questions? Can anyone please explain in detail?
Comment: I reckon your number is gonna contain lots of 1s but not any 0s. DUCY?
Comment: So the digits' sum is $2000$, and the digits' product is also $2000$?
Comment: Well, I would first note that $2000 = 2^4\cdot 5^3$.  Maybe you can combine some of those $2$'s into $4$'s instead if you like, maybe even an $8$ if you so wish.
Comment: @AdamRubinson Probably yes
Comment: Ok, so given that there's lots of 1s, what are your next thoughts for how to arrange the 1s, 2s (or 4s or 8s), and 5s in order to make your number as small as possible?
Comment: Hint to answer Adam's question: $73>37$.
Answer: Hint: The prime factorization of $2000$ is $2^4\cdot 5^3$

 This implies that among the possible digits in our number, we could have any number of $1$'s, we must have exactly three $5$'s, and we must have either four $2$'s or two $2$'s and a $4$ or one $2$ and an $8$ or two $4$'s.

Taking note of the possibilities remaining due to the restriction on the product of the digits being what they are, we then try to use the fewest number of digits and have the smallest leading string of digits possible.

 We use a $2$ and an $8$ rather than the other options for how to distribute the factors of two as this leaves us with our factors of two only occupying two slots and leaves us with a smallest possible leading digit

Arranging the digits then our final number is:

 $\underbrace{11111\cdots 11}_{1975~\text{ones}}25558$
Comment: Thanks for the explanation!
Comment: Not intending to confuse the OP, but this number is even smaller when read in base 9. Then if changing bases is OK, wouldn't it be a better bet to replace the 8 with 222 and read the number in base 6? (considering that the 2000 is still base 10)
Comment: @LaurentLARIZZA haha, sure then, so long as we had clarified that the number $2000$ we were interested in was specifically the base $10$ interpretation.  As soon as you start changing bases though, you open up a can of worms in terms of changing how $2000$ is meant to be interpreted as well.
Comment: @JMoravitz: Fair enough. The remark was just for fun :) Note that the OP did not specify that the number had to be positive... (No, really, your answer is perfectly correct)
Comment: @LaurentLARIZZA the OP didn't specify that the number has to be an integer either. So $1\,.\,\underbrace{1111\cdots 11}_{1974~\text{ones}}25558$ is then an improvement?


Connection pool and File handles

Question: We use Retrofit/OkHttp3 for all network traffic from our Android application. So far everything seems to run quite smoothly.
However, we have now occasionally had our app/process run out of file handles.

Android allows for a max of 1024 file handles per process
OkHttp will create a new thread for each async call
Each thread created this way will (from our observation) be responsible for 3 new file handles (2 pipes and one socket).

We were able to debug this exactly, where each dispached async call using .enqueue() will lead to an increase of open file handles of 3.

The problem is, that the ConnectionPool in OkHttp seems to be keeping the connection threads around for much longer than they are actually needed. (This post talks of five minutes, though I haven't seen this specified anywhere.)

That means if you are quickly dispatching request, the connection pool will grow in size, and so will the number of file handles - until you reach 1024 where the app crashes.

I've seen that it is possible to limit the number of parallel calls with Dispatcher.setMaxRequests()(although it seems unclear whether this actually works, see here) - but that still doesn't quite address the issue with the open threads and file handles piling up.
How could we prevent OkHttp from creating too many file handles?
Answer: I am answering my own question here to document this issue we had. It took us a while to figure this out and I think others might encounter this too and might be glad for this answer.

Our problem was that we created one OkHttpClient per request, as we used it's builder/interceptor API to configure some per-request parameters like HTTP headers or timeouts.
By default each OkHttpClient comes with its own connection pool, which of course blows up the number of connections/threads/file handles and prevents proper reuse in the pool.
Our solution
We solved the problem by manually creating a global ConnectionPool in a singleton, and then passing that to the OkHttpClient.Builder object which builds the actual OkHttpClient.

This still allows for per-request configuration using the OkHttpClient.Builder
Makes sure all OkHttpClient instances are still using a common connection pool.

We were then able to properly size the global connection pool.

Connection pool and File handles


Pointwise or Uniform convergence?

Question: Consider the functions $f_n:[-1,1]\to\mathbb{R}$ defined by
$$f_n(x):= \frac{x}{\sqrt{x^2 + \tfrac 1n}}$$ and determine whether the convergence is uniform or pointwise.
Answer: We have that

If a sequence of functions $(f_n)_{n\geq 1}$ converges pointwise to a
  function $f$ and uniformly to a function $g$, then $f=g$.

and

If a sequence of continuous functions $(f_n)_{n\geq 1}$ converges uniformly to a
  function $f$, then $f$ is continuous.

Prove convergence pointwise to the function $f\colon[-1,1]\mapsto \operatorname{sign}(x)$ as you started: fix $x_0\in[-1,1]$ arbitrarily, and consider the  limit of the sequence of real numbers $(f_n(x_0))_{n\geq 1}$. (You may want to consider separately the case $x_0<0$, $x_0=0$ and $x_0>0$.)
Then, for uniform convergence... see how to apply the two statements above.
Comment: A trick to avoid one distinction of case (but that's really not necessary, and the "optimization of time" is marginal): all the $f_n$'s is odd, so you can restrict yourself to the study on $[0,1]$.
Comment: Fix for instance $x_0 \in(0,1]$. Then
$$
\frac{x}{\sqrt{x^2+\frac{1}{n}}} = \frac{x}{\lvert x\rvert}\cdot\frac{1}{\sqrt{1+\frac{1}{nx_0}}} = 1\cdot  \frac{1}{\sqrt{1+\frac{1}{nx_0}}}.
$$
Since $nx_0 \xrightarrow[n\to\infty]{} \infty$, the RHS converges to $1$. You do not need $\varepsilon-\delta$-proofs here: if you have a continuous function  $\phi$ and a sequence $a_n\to \ell$, then $\phi(a_n) \to \phi(\ell)$.
Comment: Sorry, in the comment above the $x$'s should be $x_0$'s. (Typing $\LaTeX$ in comments is a bit painful.)
Comment: Fix $\varepsilon> 0$. We can write $$
\left\lvert \frac{1}{\sqrt{1+\frac{1}{nx_0}}} - 1\right\rvert
=
\left\lvert \frac{1-\sqrt{1+\frac{1}{nx_0}}}{\sqrt{1+\frac{1}{nx_0}}}\right\rvert
=
\frac{\sqrt{1+\frac{1}{nx_0}}-1}{\sqrt{1+\frac{1}{nx_0}}}
\leq \sqrt{1+\frac{1}{nx_0}}-1
$$
Having the RHS less than $\varepsilon$ is equivalent to having
$$
\sqrt{1+\frac{1}{nx_0}} \leq 1+\varepsilon
$$
which, reorganizing and massaging a bit, is equivalent to having
$$
\frac{1}{n} \leq x_0\left( (1+\varepsilon)^2-1 \right).
$$
Comment: So picking $N = \left\lceil \frac{1}{x_0\left( (1+\varepsilon)^2-1 \right)} \right\rceil$ ensures that, for $n\geq N$, the RHS is less than $\varepsilon.$ (Having checked carefully the derivation, but that's the gist of it.)
Comment: It is $x_0$, I believe. Try to go through the derivation step by step?

Pointwise or Uniform convergence?


Assumptions in Artin's primitive root conjecture

Question: I'm having a little trouble, understanding the necessity of the assumptions in Artin's Conjecture.
Artin's primitive root conjecture states, that:
for any $$a\in \mathbb{Z}\setminus \{-1\}$$ and $$a \neq b^2$$ There are infinitely many primes $p$ , such that $a$ is a primitive root modulo $p$.
Can anybody explain why these restrictions are necessary?
Answer: The hypothesis is that $a$ is not a square, not merely that it is squarefree.
Suppose $a=b^2$.
If the order of $b$ is even, then the order of $a$ is half the order of $b$ and so $a$ cannot have the maximum order.
If the order of $b$ is odd, then the order of $a$ is equal to the order of $b$ and so $a$ cannot have the maximum order because the maximal order is $p-1$, which is even.
Here is a uniform argument (not distinguishing between $b \bmod p$ having even or odd order).  For odd primes $p$, $a^{(p-1)/2} = b^{p-1} \equiv 1 \bmod p$ by Fermat's little theorem, so the order of $a \bmod p$ is a factor of $(p-1)/2$. Thus a perfect square is never a primitive root modulo an odd prime $p$.


VotingApi function takes time to update the database

Question: I have added a menu item that calls a function that calls votingapi_set_votes and delete votes. This function works locally fine but when uploaded to the hosting and when i call the function it takes like 5 minutes to update the database with the votingapi_set_votes function.
Menu_item's callback calls a function that contains votingapi_set_votes.
Locally: i call the menu item with the node id as parameter and the a vote is added to the node.
On Hosting: When i call the menu_item i need to wait five minutes or so to see the node vote updated.
Answer: I hope this code may work for you Try this code in your theme's js file:
Drupal.behaviors.Your-Theme-Name = {

 attach: function (context, settings) {

//add your class in click function

    jQuery('.view-id-top_users.view-display-id-page .views-field-php .flag-link-toggle').click(function(){

        jQuery(document).ajaxComplete(function() {

         location.reload();

        });

    });

  }

    };

Comment: I am going to try it vikram, i think it's going to take some time to test as i can't upload any thing for a while. However the solution seems legit. Thanks.


Java: JPanel background not scaling

Question: I am trying to draw an image to a JPanel in java and I have that down, good. My problem now is I am attemping to make it scale to the full size of the window, but it is not doing so. I have tried methods, and they either make the image disappear, or there is no graphical change at all.
The code I am currently working with:
class ImagePanel extends JPanel {
    private static final long serialVersionUID = 1L;

    private Image img;

    public ImagePanel(String img) {
        this(new ImageIcon(img).getImage());
    }

    public ImagePanel(Image img) {
        this.img = img;
        Dimension size = new Dimension(img.getWidth(null), img.getHeight(null));
        setPreferredSize(size);
        setMinimumSize(size);
        setMaximumSize(size);
        setSize(size);
        setLayout(null);
    }

    public void paintComponent(Graphics g) {
        g.drawImage(img, 0, 0, null);
    }
}

Full class at: http://pastebin.com/CpcBt2j8
I have tried adding in code such at img = img.getScaledInstance(440, 440, Image.SCALE_SMOOTH) and that has no effect whatsoever. I have also tried making a new image called scaledImg and setting img's getScaledInstance value to that, and that completely removes the image from display.
How can I get the image to be scaled to the full size I want?
Answer: I guess the "simplest" approach would be to do something like...
@Override
public void paintComponent(Graphics g) {

    super.paintComponent(g);
    Image scaled = img.getScaledInstance(getWidth(), getHeight(), Image.SCALE_SMOOTH);
    g.drawImage(scaled, 0, 0, null);

}

This is inefficient, costly and may not produce the desired results
To start with, take a look at The Perils of Image.getScaledInstance()
You could also take a look at Java: maintaining aspect ratio of JPanel background image for more details about maintaining the aspect ratio of the image and scale to fit vs scale to fill.
I would also buffer the result, so that you are not repeatedly scaling the image within the paintComponent method which might be caught often...
Updated with working example
This works fine for me...
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.HeadlessException;
import java.awt.Image;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

public class TestImagePane {

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

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

                try {
                    Image img = null;
                    img = ImageIO.read(new File("/path/to/image"));

                    JFrame frame = new JFrame("Testing");
                    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                    frame.setLayout(new BorderLayout());
                    frame.add(new ImagePanel(img));
                    frame.pack();
                    frame.setLocationRelativeTo(null);
                    frame.setVisible(true);
                } catch (IOException | HeadlessException exp) {
                    exp.printStackTrace();
                }
            }
        });
    }

    class ImagePanel extends JPanel {

        private static final long serialVersionUID = 1L;

        private Image img;
        private Image scaled;

        public ImagePanel(String img) {
            this(new ImageIcon(img).getImage());
        }

        public ImagePanel(Image img) {
            this.img = img;
        }

        @Override
        public void invalidate() {
            super.invalidate();
            int width = getWidth();
            int height = getHeight();

            if (width > 0 && height > 0) {
                scaled = img.getScaledInstance(getWidth(), getHeight(), Image.SCALE_SMOOTH);
            }
        }

        @Override
        public Dimension getPreferredSize() {
            return img == null ? new Dimension(200, 200) : new Dimension(img.getWidth(this), img.getHeight(this));
        }

        @Override
        public void paintComponent(Graphics g) {
            super.paintComponent(g);
            g.drawImage(scaled, 0, 0, null);
        }
    }

}

Comment: This is not producing a result at all, as I said I have tried this. The graphics are completely removed.
Comment: What do you mean by *"The graphics are completely removed"*? Apart from the fact that you weren't calling `super.paintComponent`
Comment: Sorry, I didn't put down what I mean. I meant that the image that was drawn was completely removed from view, it just leaves the panels.
Answer: To dynamically scale an image you use:
//g.drawImage(img, 0, 0, null);
g.drawImage(image, 0, 0, getWidth(), getHeight(), null);

See Background Panel for a complete implementation along with a tiling feature.

Java: JPanel background not scaling


Manipulating $\int_{x_{0}}^{\infty} \frac{1}{x} \, \cos (x t) \, \text{e}^{-x^{2}} \, dx$

Question: Is there a way to express the integral
$I(x_{0}, t) = \int_{x_{0}}^{\infty} \frac{1}{x} \, \cos (x t) \, \text{e}^{-x^{2}} \, dx$,
where $x_{0} \neq 0$ and $t \ge 0$, in terms of more well-known functions? In particular, I am interested in a form where $t$ appears in the limits and not in the integrand, analogous to how something like the integral of $sin (x t) \, \text{e}^{-x^{2}}$ may be expressed in terms of error functions. My attempts thus far have only yielded
$I(x_{0}, t) = \text{e}^{-t^{2} / 4} \Big(\int_{x_{0} - i t/2}^{\infty} \frac{\text{e}^{-x^{2}} (z - i t / 2)}{z^{2} + t^{2} / 4} \, dz + \int_{x_{0} + i t/2}^{\infty} \frac{\text{e}^{-x^{2}} (z + i t / 2)}{z^{2} + t^{2} / 4} \, dz \Big)$,
from which I cannot find a way to proceed further. My next step would be to split the limits, introducing integrals to and from $0$, although this introduces singularities which naturally cancel but are nonetheless undesirable.
Any analyses of the integral are welcome.
For completeness (although not relevant to the actual question itself), I have an incrementally increasing variable $t$ with fixed $x_{0}$, for which I intend to compute this integral. For large $t$, it becomes highly oscillatory.
Comment: is it $\cos(xt)$ or $\cos(x)t$?
Comment: @tired Could you elaborate? Wouldn't the integrand be undefined at $x = 0$ if $x_{0} = 0$?
Answer: This is a partial answer. By using the definition of the $\operatorname{Ei}$ exponential integral function we can get for all $a>0$:
$$
I(a,0)=-\frac{\operatorname{Ei}(-a^2)}{2}.
$$
Comment: @Bronshtein Yes, and I've given a closed-form for $x_0 = a >0$ and for $t=0$. What is the comment for?
Comment: Immediately after the integral is given, the conditions for $x_{0}$ and $t$ are stated.
Answer: OP here - I hadn't logged on StackExchange in a while and forgot I had an account when I originally posted.
I've since discovered one way to get $t$ out of the integrand, and that's by differentiating under the integral sign:
$\frac{d I}{d t} = - \int_{x_{0}}^{\infty} \sin (x t) \, \text{e}^{-x^{2}} \, dx = - \frac{1}{2 i} \, \text{e}^{-t^{2}/4} \int_{x_{0} - i t / 2}^{x_{0} + i t / 2} \text{e}^{-z^{2}} \, dz$,
$I (x_{0}, t) = \frac{1}{2} \int_{x_{0}^{2}}^{\infty} \frac{1}{x} \, \text{e}^{-x} \, d x - \frac{1}{2} \int_{0}^{t} \text{e}^{-x^{2} / 4} \, \Big(\int_{0}^{x / 2 - i x_{0}} \, \text{e}^{z^{2}} \, d z + \int_{0}^{x / 2 + i x_{0}} \, \text{e}^{z^{2}} \, d z \Big) \,d x$.
I would still be interested whether there is a better way, though.


When is a 2-form invertible?

Question: We are on a manifold $M$, and we have a 2 form $\omega: T M \times T M \rightarrow \mathbb R$. We can also think of $\omega$ as $\omega: TM \rightarrow (TM \rightarrow \mathbb R$) where $\omega$ is now a linear function from the tangent bundle $TM$ to the space of linear functions $TM \rightarrow \mathbb R$. But this is just the space of linear functionals, so we can write it as $\omega: TM \rightarrow T^*M$.
Now, on being given a function $H: M \rightarrow \mathbb R$, we know that $dH \in T^* M$. Hence, we can try to find a vector field $X_H : M \rightarrow TM$ such that $\omega (X_H) = dH$. This is the question posed by symplectic geometry, where $\omega$ is the symplectic data, and $H$ is the hamiltonian.
But I can also write this as $X_H = \omega^{-1} dH$. Question: when is $\omega$ invertible?
$\omega$ is a linear function from $TM$ to $T^*M$. So $\omega$ is invertible when it gives us a bijection from $TM$ to $T^* M$.  Over $\mathbb R^n$ this is easy to check: pick a basis write a matrix, compute determinant. What about in the abstract on a manifold? I am hoping that the condition works out to be $d \omega = 0$, thereby justifying this condition on a symplectic form.
Comment: Hm, so you can always calculate the determinant of the arising matrices that come from writing the form in local coordinates, and check if all those are nonequal to zero. But I don't think you're going to get anything simpler than this. Closedness will, in any case, not be what you're looking for: for example, the zero-form $\omega = 0$ is obviously non-invertible, but closed. If you have any specific goal in mind, perhaps it is better to ask in what kind of data you'd rather want to express the invertibility question?
Comment: [this page](http://math.mit.edu/~cohn/Thoughts/symplectic.html) does a good job of explaining why $d\omega=0$.
Answer: Condition is that $\omega$ is non-degenerate. By definition, a two form is non-degenerate when the mapping $TM \to T^*M$ is invertible. On a symplectic manifold $(M, \omega)$, $\omega$ is assumed to be non-degenerate. It has nothing to do with the closed-ness of $\omega$.
In a local coordinate, write
$$ \omega = \omega_{ij} dx^i \wedge dx^j, $$
then the mapping $TM \to TM^*$ you defined send $\frac{\partial }{\partial x^i}$ to
$$ \sum_j \omega_{ij} dx^j.$$
So the matrix representation of the mapping $TM\to T^*M$ with respect to the basis
$$\left\{ \frac{\partial }{\partial x^1} , \cdots, \frac{\partial }{\partial x^n}\right\}, \ \ \ \{ dx^1, \cdots, dx^n\}$$
is given by $(\omega_{ij})$. So the mapping is non-degenerate if and only if the matrix $(\omega_{ij})$ is invertible.
Comment: In the setting of mechanics, they are always considering the cotangent bundle $T^*M$ with the form $\omega = d\alpha$, it is exact and in particular closed. @SiddharthBhat
Comment: That's the tautological one form, @SiddharthBhat see [this](https://math.stackexchange.com/questions/252180/tautological-1-form-on-the-cotangent-bundle)
Comment: Thank you. I continue to search for a better explanation of why $\omega$ ought to be closed :D
Comment: What is $\alpha$ @ArcticChar?
Answer: Maybe this answer is a little besides the point, since Arctic Char's answer correctly addresses that there's not really much you can do except go to local coordinates. There is one fancy equivalence that says if $M$ is $2n$-dimensional, then a 2-form $\omega$ is non-degenerate if and only if $\omega \wedge \dots \wedge \omega \neq 0$ for the $n$-fold wedge product of the form with itself (see here for the proof of this on vector spaces, from which the statement for differential forms follows straightforwardly by doing this at every point).
However, since you conclude your question by saying that you'd like to justify this condition on symplectic manifolds, let me make two remarks:
The reason why one requires closedness of $\omega$ on a symplectic manifold $M$ is because that way, it induces a Poisson bracket on the space of smooth functions $C^\infty(M)$. This is then important for doing all kinds of physics-shenanigans related to Hamiltonian mechanics, which is, from my experience, the main motivation for considering symplectic manifolds at all.
Additionally, perhaps it's interesting to you that there is a very similar concept where one does not require any non-degeneracy of anything, namely Poisson manifolds.
They are a little different in the sense that you don't require the existence of a closed 2-form, but you just require the existence of a Poisson bracket on the space of smooth functions $C^\infty(M)$. This comes down to the existence of a Poisson bivector $\pi \in \Gamma(\Lambda^2 TM)$ which fulfils an analogue of the closedness condition of symplectic forms, necessary for the Leibniz rule of the Poisson bracket. So, rather than a 2-form, you need to work with 2-vectors, and it turns out that this generalization is very often a whole lot more complicated. Turns out having an isomorphism $TM \to T^*M$ is an extremely handy tool!
Hence, from this perspective, I'd see the non-degeneracy in the symplectic setting as a kind gift you're allowed to use that makes a lot of questions simpler, but which is not philosophically required if you just want to do emulate Hamiltonian mechanics on your manifold.
Comment: Nice, thanks a lot. So it is possible to write classical mechanics on top of a Poisson manifold as well? Without needing a symplectic form?
Comment: Yes, I'd say so, since all you really need to do mechanics is a notion of functions $C^\infty(M)$ (for your observables and Hamiltonians) and a Poisson bracket $\{\cdot,\cdot\}$ on $C^\infty(M)$. In standard examples, you will a posteriori notice that you are in the symplectic setting anyway ($e.g. M = \mathbb{R}^{2n}$ or $M$ a cotangent bundle), but once you start doing more freaky things, like quotienting out symmetries, you may very well end up in a situation where you don't have a symplectic form anymore, but still want to do mechanics. Then Poisson manifolds come into play.

When is a 2-form invertible?


Multilevel Poisson Regression

Question: I have some data with individual level variables (like satisfaction) and these individuals are nested within buildings (there are 12 different buildings) and I have a continuous variable that is measured at the building level. I'm trying to use this to predict an outcome that is count data. Should I be running a sort of multilevel model here? If so, what could this model say about my data differently than if I just combined all these factors into a linear model?
Answer: If you simply fitted a linear regression model with your covariates, without taking account of clustering, you my obtain biased results. This is because your data are clustered within buildings. This leads to observations that are more similar to others in the same building than to those in other buildings. That is, there is intra-class correlation. Failure to adequately adjust for this can lead to biased fixed effects.
One popular and principled approach is to use a generalized linear mixed effects model, where you would specify random intercepts for buildings.
This would be a 2-level multilevel model with individuals are level 1 and buildings at level 2.
If you simply fitted a (generalized) linear model, the parameter estimates could be biased. Therefore you should definitely fit a model that adjusts for the clustering. Personally I would use a mixed effects model (also known as a mixed model and also known as multilevel model in this case), although there are alternatives, such as a linear model were the building ID is also fixed effect (no random effects) or generalized estimating equations.
One of the advantages of the mixed model framework is that you can easily incorporate random slopes for the fixed effects, if warranted.
Comment: Can the continuous variable that only applies to buildings (at level 2) be included in the model even though there are just 12 buildings?
Comment: @762 Yes ! ! A mixed effects model will handle this automatically. If you use `R` then take a look at the `lme4` package
Comment: Excellent! Can the `lme4` package also handle discrete outcomes and predictors (like number of people in building)
Comment: @762 Yes, for the dependent variable,  depending on the numbers you may want to fit a Poisson model (which would be a GLMM), though if the numbers are large and well approximated by a normal distribution, a LMM may be adequate, If you refer to independent variables, they should be handled automatically. Take a look at the 2 references I gave to my answer [here](https://stats.stackexchange.com/questions/386474/what-is-the-joint-density-function-of-a-three-level-mixed-effects-model) which are both  by the authors of the `lme4` package

Multilevel Poisson Regression


OpenAPI3 json nested object complex query parameters

Question: I am trying to build complex query API.
Using open API to auto generate model classes and controller.
In open api 3 there is a support for complex object in query parameters.
https://swagger.io/docs/specification/describing-parameters/#schema-vs-content. I wish the doc had some examples..
My open Api:
parameters:
  - in: query
    name: filter
    content:
      application/json:
        schema:
          schema:
           $ref: "#/components/schemas/ComplexFilter"
 components:
     schemas:
       ComplexFilter:
           type: object
           properties:
             name:
               type: string
             lastname:
               type: string
             userName:
               type: string

Generated controller:
 @RequestMapping(method = RequestMethod.GET, value = "/users")
        @ResponseBody
        public List<User> search( @Parameter(name = "page") @RequestParam(value = "page") Integer page,
         @Parameter(name = "size") @RequestParam(value = "size") Integer size,
        @Parameter(name = "filter") ComplexFilter filter
            return service.filter(page,size,filter);
        }

The client application, in my case it's type script app, auto generated by OpenAPI Generator using generator version 6.1.0 looks like
public listUsers(page?: number, size?: number, filter?: ComplexFilter, options?: AxiosRequestConfig) {
        return UsersApiFp(this.configuration).listUsers(page, size, filter, options).then((request) => request(this.axios, this.basePath));
    }

Now is the problem: when I generate request it looks like
http://localhost:8085/api/v1/users?page=0&size=5&filter.name=test

but spring boot(server) expect query parameter without "filter." prefix
http://localhost:8085/api/v1/users?page=0&size=5&name=test

tried to set deepObject type in open api .. no luck
parameters:
  - in: query
    name: filter
    content:
      application/json:
        schema:
          schema:
           $ref: "#/components/schemas/ComplexFilter"
          style: deepObject
          explode: true

Answer: You don't need the content keyword here, it's typically only used when the parameter value is a JSON string e.g. filter={"key1":"value1","key2":"value2"}.
Instead, add the schema directly to the parameter and use style: form + explode: true as the serialization method:
parameters:
  - in: query
    name: filter
    schema:
      $ref: "#/components/schemas/ComplexFilter"

    # Exploded form is the default serialization method for query params,
    # so these keywords can be omitted
    style: form
    explode: true

Comment: this is not true style: form + explode: true used only with primitives https://swagger.io/docs/specification/serialization/
Comment: These keywords are used with objects and arrays too. Check the examples in the table in the "Query parameters" section.


Show that the matrix is a generator matrix of a MDS code

Question: Let $a_1,\dots,a_n$ be pairwise distinct elements of $\mathbb{F}_q$ and $k ≤ n$. I have to show that

the matrix $\begin{bmatrix}1&\dots&1&0\\a_1&\dots&a_n&0\\a_1^2&\dots&a_n^2&0\\\vdots&&\vdots&0\\a_1^{k-1}&\dots&a_n^{k-1}&1\end{bmatrix}$ is a generator matrix of an $[n+1,k,n−k+2]$ MDS code.

if q is a power of 2, then the matrix $\begin{bmatrix}1&\dots&1&0&0\\a_1&\dots&a_q&1&0\\a_1^2&\dots&a_q^2&0&1\end{bmatrix}$ is a generator matrix of an $[q + 2, 3, q]$ MDS code.

I don't even know where to start, the things we covered in the lecture are not so many, but what I thought could be useful, but don't know how to apply are:

Theorem: Let $C$ be an $[n,k]$ code with generator matrix $G$ and parity check matrix $H$. The following are equivalent:

$C$ is MDS
All $(n-k)\times(n-k)$ full size minors of $H$ are invertible
All $k\times k$ full size minors og G are invertible

Maybe I could use this theorem, part (3), but I'm not sure how to show that all the minors og G are invertible.
Should I maybe, from definition of MDS, show that the distance is indeed $d(C)=n-k+2$, and then conclude that the code is MDS? But aren't the elements arbitrary?
Should I maybe look for a parity check matrix $H$ and do something?
Please any hint is appreciated.
Comment: There is a typo in your first matrix (zero column cannot be right...)
Comment: @azimut you are right, I edited it, thank you a lot!
Answer: Hint
Use characterization (3) of your theorem and remember the formula for the determinant of a Vandermonde matrix!
Hint (2)
Come up with different cases for the $k\times k$ minor, depending on the number of the involved "special" columns (the 1 or 2 rightmost columns of the generator matrix). Then, you can either directly apply Vandermonde or you have to do some transformation first.
For the second case of the $[q+2,3]$ MDS code, there are cases without Vandermonde. But here, the minors are of fixed size $3\times 3$, so just approach those cases by a direct computation of the determinant.
Comment: Thank you very much for your hint! I can see it a bit clearly for my first $(n+1)\times k$ matrix. Do you think I could use it also for the $(q+2)\times 3$ matrix? Because this time it seems a different case..
Comment: @Dada I've added a second hint.


add tls/ssl for postfix with multiple domains and multiples ips

Question: I am working on a postfix server. This server is sending mail through multiple IPs for multiple domains. Some domains have a dedicated IP address. Other are on the same IP.
Everything works fine.
Now, i want to enable SSL and TLS. I know what to do for a postfix server which has a single IP address and a single domain:
cd /etc/postfix
openssl req -nodes -new -x509 -keyout dsfc.key -out dsfc.crt

Then i have to add this in /etc/postfix/main.cf:
smtpd_use_tls = yes
smtpd_tls_key_file = /etc/postfix/dsfc.key
smtpd_tls_cert_file = /etc/postfix/dsfc.crt
smtpd_tls_ask_ccert = yes
smtpd_tls_req_ccert = yes
smtpd_tls_security_level = encrypt
smtpd_tls_auth_only = yes
smtpd_tls_ccert_verifydepth = 1
smtpd_tls_session_cache_database = btree:/var/lib/postfix/smtpd_scache
smtpd_tls_session_cache_timeout = 86400

But i am not sure it will work in my case. Should i have one certificate per domain or per ip ? Or one certificate will do the job for all the domains ?
Thanks
Answer: The SSL/TLS cert and key are for the mail servers domain/IP which all other domains go through so the secure mail server covers all domains that use it, dedicated IPs are of no consequence. For best results and maximum security use the configuration options that are available to you.
If you plan on using smtpd_tls_security_level=encrypt realize some mail servers will not accept connection because they do not accept TLS only connections. If you insist on encrypt check your mail log and see if there are any hosts rejecting for this reason. You can create /etc/postfix/tls_policy and add the hosts there and designate may so mail will be delivered IE:
smtp_tls_policy_maps = hash:/etc/postfix/tls_policy

In that file you can add hosts like below
live.co.uk             may
live.com               may
charter.net            may
mx.west.cox.net        may
bigpond.com            may
cox.net                may

Yes live.com will reject if TLS is forced
Dont forget to run postmap after edits to file
Example:
# TLS parameters
# ---------------------------------

# The default snakeoil certificate. Comment if using a purchased
# SSL certificate.
#smtpd_tls_cert_file = /etc/ssl/certs/postfix.pem
#smtpd_tls_key_file = /etc/ssl/private/postfix.pem

# Uncomment if using a custom SSL certificate.
smtpd_tls_cert_file=/path/to/ssl/example.com/cert.pem
smtpd_tls_key_file=/path/to/ssl/example.com/key.pem

# The snakeoil self-signed certificate has no need for a CA file. But
# if you are using your own SSL certificate, then you probably have
# a CA certificate bundle from your provider. The path to that goes here.
smtp_tls_CAfile=/path/to/ssl/example.com/chain.pem
smtpd_tls_CAfile=/path/to/ssl/example.com/chain.pem

# trusted CA path, where your server has the trust store of commercial certs
smtp_tls_CApath = /etc/ssl/certs
smtpd_tls_CApath = /etc/ssl/certs

smtpd_use_tls = yes
smtp_use_tls = yes
#enable ECDH
smtpd_tls_eecdh_grade = strong
#enabled SSL protocols, don't allow SSLv2 and SSLv3
smtpd_tls_protocols= !SSLv2, !SSLv3
smtpd_tls_mandatory_protocols= !SSLv2, !SSLv3
#allowed ciphers for smtpd_tls_security_level=encrypt
smtpd_tls_mandatory_ciphers = high
#allowed ciphers for smtpd_tls_security_level=may
smtpd_tls_ciphers = high
#enforce the server cipher preference
tls_preempt_cipherlist = yes
#disable following ciphers for smtpd_tls_security_level=encrypt
smtpd_tls_mandatory_exclude_ciphers = aNULL, MD5 , DES, ADH, RC4, PSD, SRP, 3DES, eNULL
#disable following ciphers for smtpd_tls_security_level=may
smtpd_tls_exclude_ciphers = aNULL, eNULL, EXPORT, DES, RC4, MD5, PSK, aECDH, EDH-DSS-DES-CBC3-SHA, EDH-RSA-DES-CBC3-SHA, KRB5-DES, CBC3-SHA
#enable TLS logging to see the ciphers for inbound connections
smtpd_tls_loglevel = 1
#enable TLS logging to see the ciphers for outbound connections
smtp_tls_loglevel = 1
smtp_tls_note_starttls_offer = yes
smtpd_tls_received_header = yes
smtpd_tls_session_cache_timeout = 3600s
tls_random_source = dev:/dev/urandom
smtpd_tls_dh1024_param_file = /etc/ssl/certs/dhparam.pem

# Note that forcing use of TLS is going to cause breakage - most mail servers
# don't offer it and so delivery will fail, both incoming and outgoing. This is
# unfortunate given what various governmental agencies are up to these days.
#

# For MTAs that reject based on encrypt TLS setting, lets do 'may' to get the mail delivered
#smtp_tls_policy_maps = hash:/etc/postfix/tls_policy

# AUTH only must be enabled when using smtpd encrypt
smtpd_tls_auth_only = yes
# Enable and force all incoming smtpd connections to use TLS.
#smtpd_tls_security_level = encrypt
# Enable and force all outgoing smtp connections to use TLS.
#smtp_tls_security_level = encrypt
# Enable (but don't force all incoming smtpd connections to use TLS.
smtpd_tls_security_level = may
# Enable (but don't force) all outgoing smtp connections to use TLS.
smtp_tls_security_level = may

# See /usr/share/doc/postfix/TLS_README.gz in the postfix-doc package for
# information on enabling SSL in the smtp client.

Comment: Bob if thats the case use 'may' instead of 'encrypt' no need to know remote domains postfix will handle that. [Read Postfix TLS](http://www.postfix.org/TLS_README.html). Using encrypt on a public mail server is not a wise decision if you want mail flowing without TLS issues.
Comment: In fact what i want to do is to send mails with TLS if remote server accepts TLS and if not send mail in classical way. But i do not know all destination domains.... Thanks


Central limit theorem for the variance

Question: The central limit theorem establishes that the average of $n$ i.i.d. random variables tends to a normal law, with parameters $\mu$ and $\sigma^2/n$.
The average is a non-biaised estimator of the mean of the distribution. If we turn to the case of the non-biased estimator of the distribution variance, $s^2$, the central limit theorem can also be used as $s^2$ is the difference of

the average of $n$ i.i.d. random variables ($\overline{x^2}$),
the square of a normally distributed variable (${\overline x}^2$).

Anyway the computation is uneasy as these two variables aren't independent.
As $s^2$ is unbiaised, its mean is $\sigma^2$. But what is the variance of $s^2$ ? And is its distribution normal in the limit ?
Comment: You are considering $$\bar x=\frac1n\sum_{i=1}^nx_i\qquad s^2=\frac1n\left(\sum_{i=1}^nx_i^2\right)-\bar x^2$$ then $$E(s^2)=\frac{n-1}n\sigma^2$$ hence $s^2$ is a biased estimator of the variance $\sigma^2=\mathrm{var}(x_i^2)$.
Comment: Then correct your post. And what prevents you to compute $E(s^4)$?
Comment: @Did: I am unsure about the notation and I want to refer to the unbiaised estimator. Anyway, this distinction is not essential as they are proportional to each other.
Comment: @Did: no idea of the relation between $E(s^4)$, presumably drawn from the moments of the original distribution, and the variance of the limit distribution of $s^2$ (which I don't know).
Comment: I disagree with the downvote.
Answer: Let
$s^2=\frac{n}{n-1}\left(\overline{x^2}-\left(\overline x\right)^2\right)=\frac{1}{n-1}\sum_{i=1}^n \left(x_i-\overline x\right)^2$. Define centered r.v.'s $y_i=x_i-\mathbb Ex_1$ and rewrite sample variance in terms of this r.v.'s:
$$
s^2=\frac{1}{n-1}\sum_{i=1}^n \left(y_i-\overline y\right)^2 = \frac{n}{n-1}\left(\overline{y^2}-\left(\overline y\right)^2\right)=\overline{y^2}-\left(\overline y\right)^2+\frac{s^2}{n}.
$$
Note that $\sigma^2=\text{Var}(x_1)=\mathbb E[y_1^2]$.
Find the limiting distribution of $\sqrt{n}\left(s^2-\sigma^2\right)$:
$$\tag{1}\label{1}
\sqrt{n}\left(s^2-\sigma^2\right) = \sqrt{n}\left(\overline{y^2}-\left(\overline y\right)^2+\frac{s^2}{n} -\sigma^2 \right)=\sqrt{n}\left(\overline{y^2}-\sigma^2 \right) -\sqrt{n}\left(\overline y\right)^2+\sqrt{n}\frac{s^2}{n} .
$$
Next prove that $\sqrt{n}\left(\overline y\right)^2 \xrightarrow{p} 0$ and $\sqrt{n}\,\dfrac{s^2}{n}=\dfrac{s^2}{\sqrt{n}}\xrightarrow{p} 0$ as $n\to\infty$. Indeed, by Slutsky's theorem,
$$\sqrt{n}\left(\overline y\right)^2 = \underbrace{\overline y}_{\begin{array}$\downarrow p \cr 0\end{array}} \cdot \underbrace{\sqrt{n}\left(\overline y\right)}_{\begin{array}$\downarrow d \cr N(0,1)\end{array}}\xrightarrow{d} 0\cdot N(0,1)=0$$
The convergence in distribution to zero implies the convergence in probability.
Next,
$$
\dfrac{s^2}{\sqrt{n}} = s^2\cdot \frac{1}{\sqrt{n}}\xrightarrow{p} \sigma^2\cdot 0=0.$$
We obtain that the second and third terms in r.h.s. of (\ref{1}) tends to zero in probability. Consider the first term:
$$
\sqrt{n}\left(\overline{y^2}-\sigma^2 \right) = \sqrt{n}\left(\overline{y^2}-\mathbb E\left[y_1^2\right] \right) \xrightarrow{d} N(0,\text{Var}(y_1^2))=N(0,\mathbb E\left[y_1^4\right]-\sigma^4).
$$
By Slutsky's theorem,
$$\tag{2}\label{2}
\sqrt{n}(s^2-\sigma^2)\xrightarrow{d}N(0,\mathbb E\left[y_1^4\right]-\sigma^4)= N(0,{\mathbb E}\left[(x_1-\mathbb Ex_1)^4\right]-\sigma^4).
$$
So, you can say that the limiting distribution of $s^2$ is normal with mean $\sigma^2$ and variance $$\dfrac{{\mathbb E}\left[(x_1-\mathbb Ex_1)^4\right]-\sigma^4}{n}.$$ But this words are extremely non-rigorous. The rigorous statement is (\ref{2}).

Central limit theorem for the variance


Getting EditText name to array variable android

Question: I am developing an application which randomly chooses a string from the arrays.xml file. Every string has 3 variables (%1$s, %2$s, %3$s). The first is taken from EditText, the second from Spinner (gets from array) and the third from an EditText.
I tried to use String.format but it didn't work, the logcat gives NullPointerException.
<string-array name="blabla">
<item>Blabla %1$s blabla %2$s blablabla %3$s.</item>
<item>blablabla %1$s blablabla %3$s blabl %2$s.</item>
</string-array>

and the Java code:
public void invia(View v){
    Spinner eta = (Spinner) findViewById(R.id.etaspin);
    String etastring = eta.getSelectedItem().toString().trim();

    EditText nome = (EditText) findViewById(R.id.nomeins);
    String nomestring = nome.getText().toString();

    EditText citta = (EditText) findViewById(R.id.cittains);
    String cittastring = citta.getText().toString();
    Resources res = getResources();

    String tot = res.getString(R.array.blabla, etastring, nomestring, cittastring);

    tot = myString[rgenerator.nextInt(myString.length)];
     TextView stiusatxt = (TextView) findViewById(R.id.stiusa);
     stiusatxt.setText(tot);
}

As per now the only thing that works is the random string display but none of the variables work.
Comment: the last line throw the NullPointerException, right?
Comment: No, the NPE was thrown when I was using the String.format from Android Developers website
Comment: Android Developers website ?? This line `res.getString(R.array.blabla, etastring, nomestring, cittastring);` is to getString, but u r using string-array
Comment: Exactly, that's my problem
Answer: Try doing it this way
int random = new Random().nextInt(2);
String tot = String.format(res.getStringArray(R.array.blabla)[random], etastring, nomestring, cittastring);

Your code is giving problems because you are trying to read a string from an array using getString() instead of getStringArray()


Which is the best book to learn meta-analysis?

Question: I have somewhat extensive experience in meta-analysis, but remain an avid reader on this topic.
I am thus wondering, which is the best book to learn meta-analysis in general?
And which books are the best for selected topics, e.g. diagnostic meta-analysis, individual patient data meta-analysis, Bayesian meta-analysis, and network meta-analysis, just to name a few?
This is not a banal question, as a simple Amazon search returns more than 900 results.
Interestingly, Amazon suggests as most relevant Introduction to Meta-Analysis by Borenstein and Hedges, whilst the first for feedback is The Handbook of Research Synthesis and Meta-Analysis by Cooper and Hedges. Google Books instead lists first Meta-Analysis in Social Research by Glass, McGaw, and Smith, whereas Google Scholar clearly establishes the Cochrane Handbook for Systematic Reviews of Interventions by Higgins and Green as the most quoted one.
Answer: My favorite is: Introduction to Meta-Analysis 1st Edition
by Michael Borenstein (Author), Larry V. Hedges  (Author), Julian P. T. Higgins (Author), Hannah R. Rothstein (Author). ISBN-13: 978-0470057247
Answer: For theory the classic book by Olkin and Hedges is my favorite.  The practical book by Bornstein, Hedges et al. is really a good applied book that introduces and explains their software.
Larry V. Hedges and Ingram Olkin. "Statistical Methods for Meta-Analysis"
Academic Press, 2014
Borenstein, Michael, et al. "Introduction to Meta-Analysis". John Wiley & Sons, Ltd, 2009.
Comment: Giving full bibliographic references would enhance this answer.


Como fazer uma consulta no banco de dados 10 dias pra frente e 10 dias pra trás da data atual?

Question: Hoje já consigo fazer a consulta de 10 dias atrás como mostra a consulta abaixo, só não estou conseguindo implantar os 10 dias a frente da data atual.

<code>SELECT
  `vw_saldobancario`.`contaApelido`,
  `vw_saldobancario`.`tipoMovimento`,
  `vw_saldobancario`.`historico`,
  (
    vw_saldobancario.debitosPendentes + vw_saldobancario.debitos
  ) AS debitos,
  (
    vw_saldobancario.creditosPendentes + vw_saldobancario.creditos
  ) AS creditos,
  `vw_saldobancario`.`dataMovimento`,
  `vw_saldobancario`.`conta_bancaria_id`,
  IF (
    creditosPendentes > 0
    OR debitosPendentes > 0,
    'SIM',
    'NAO'
  ) AS Pendentes
FROM
  `vw_saldobancario`
WHERE `dataMovimento`  BETWEEN DATE_ADD(CURRENT_DATE(), INTERVAL -10 DAY) AND CURRENT_DATE()
  AND `conta_bancaria_id` = 3
GROUP BY `idHistorico`</code>
Answer: Se você pensa incluir data atual mais 10 a função é DATE_ADD(date, INTERVAL value addunit). Não precisa incluir o sinal: DATE_ADD(CURRENT_DATE(), INTERVAL 10 DAY)
Comment: Sim, mas essa não e a questão amigo e como eu faço pra ter além de 10 a frente também ter 10 atrás ??
Comment: WHERE `dataMovimento`  BETWEEN DATE_ADD(CURRENT_DATE(), INTERVAL -10 DAY) AND DATE_ADD(CURRENT_DATE(), INTERVAL 10 DAY)
Comment: Era isso mesmo man, Obrigado!!
Comment: Que bom que te ajudei man!


Comparação de retorno de query com status "N"

Question: Preciso de ajuda para comparação no "if" c# de um retorno de banco de dados dataTable.
Abaixo o trecho do código:
public class ArcerarDto
{
    public DataTable SelectArcerarContract()
    {
        ArcerarDal arcerarObj = new ArcerarDal();
        DataTable arcerarDt = arcerarObj.SelectArcerar();

        if (arcerarDt.Rows[0][2].ToString() = 'N') ///// erro aqui
        {
            //logFile "ERRO", "Contrato do xxx está Inativo."
            //aborta processamento
        }

Comment: E qual é a dúvida?
Comment: Nem pode comparar string com char faça...  `== "N"`
Comment: Bom não sei ainda se é a melhor forma de comparar mais um sinal de igual é atribuição e dois sinal de igual juntos é comparação, então o seu código pode ser somente erro de digitação.
Comment: obrigada Virgilio!
Comment: Muito obrigada pela ajuda! Deu certo
Answer: if (arcerarDt.Rows[0][2].ToString() = 'N')// erro

Operador de igualdade em C#: ==.
A utilização do "=" é quando você vai setar algum valor a variável ou propriedade.
No caso de IF / ELSE utiliza-se operando "==" (operador de igualdade).
if (arcerarDt.Rows[0][2].ToString() == "N")// correto

Answer: Verificar se não faltou um "=" no trecho abaixo:
if (arcerarDt.Rows[0][2].ToString() **==** 'N')


Finding MSBuild using vswhere in invoke-build on an ADO pipeline

Question: On my local machine I can use MSBuild pretty easily. But when I try to use the same PowerShell script as I do on my local machine on an ADO Pipeline, I get complaints that MSBuild is a not a cmdlet. This leads me to believe that I need to use vswhere to find MSBuild on the agent machine and then use that to build my slns. I've looked around on the web without any luck, so I thought I'd ask here just in case anyone has dealt with something like this before.
Answer: I assume you are using the "Invoke-build" powershell module and that is how you are calling your scripts in your ADO pipeline (i.e. you are running Invoke-Build from powershell in a directory with a *.build.ps1 script containing the tasks that call your build scripts)
If so it comes with a built-in helper command called "Resolve-MSBuild" which does exactly what you want.
If you add the statement:
<code>Set-Alias MSBuild (Resolve-MSBuild)
</code>
at the top of your .build.ps1 script (prior to any task statements) this should create a command alias that will run the actual msbuild whenever called.


Call a custom module's function from template file

Question: In the same context that this question, I want to add a link to a function in my custom module from a template file.
Something like this:
In my template file: Action
In my custom module
function my_function($id){
//update data base
}
Answer: a function doesn't have a url unless you set up a callback url for it first with hook_menu. Then you can point your link to it and process the data. So in your case it'd look something roughly like that:
In your custom module:
function mymodule_menu() {
  $items['some_url/%'] = array(
    'page callback' => 'mymodule_myfunction',
    'page arguments' => array(
      1,
    ),
  );
  return $items;
}

function mymodule_myfunction($id) {
 // update database
}

Then in your template use l() as Kevin mentioned (you should adjust to fit your variables etc):
print l('Action', 'abc/20');

This is very simplified. You'd want to probably enable some access limitations on that new url (abc/%) etc and you can read more about that in the hook_menu docs I linked to above.
Comment: You should also generate these links with `l()` function too, not raw anchor tags.
Comment: You may also want to check out the [Examples for Developers](https://www.drupal.org/project/examples) module which has an example [menu_example](https://cgit.drupalcode.org/examples/tree/menu_example?h=7.x-1.x) sub-module. It will give you an overall idea how to accomplish the task in hand.
Comment: good catch, edited
Comment: But how can I read my parameters $id in mymodule_myfunction? **print l(t('Action'), 'my_link', array('attributes' => array('id' => array('26'))));**
Comment: it should be like **print l(t('Action'), 'my_link/'.$id);** Thank you


Correlations between variables based on gender in R

Question: I have a data set in which female is coded as 0 and male as 1 and then I have different testing scores; writing, reading, math. I want to determine whether the correlation between math and writing scores significantly differs between the male and female populations. How would I code this in R? Note: My sample sizes for females is greater than males.
Comment: The coefficient d can be significantly different from 0 while the correlations are the same. This can happen when the genders do not have the same variance in scores of math or writing.
Comment: Essentially you could frame it as a hypothesis, with the null that the there is no interaction between gender and math in predicting writing scores. Then fit the regression E[Writing | Gender, Math] = a + b Writing + c Math + d Writing Math. If the coefficient d is statistically significantly different from 0, you can reject the null.
Answer: To show how you could approach this problem with a Monte Carlo simulation (as suggested in Sextus Empiricus's answer)...
You could either do it with a permutation test (AKA randomisation test) or with bootstrapping. I have chosen the latter.
First, I created some fake data that should look somewhat like yours:
library(tidyverse)

set.seed(123)

SAMPLE_SIZE <- 1000
MALE_PROP <- 0.4
n_males <- SAMPLE_SIZE * MALE_PROP
n_females <- SAMPLE_SIZE * (1 - MALE_PROP)

males <- data.frame(
  gender = rep(1, n_males),
  writing = rnorm(n = n_males, mean = 60, sd = 10)
) %>%
  mutate(math = writing * 0.80 + rnorm(n = n_males, mean = 5, sd = 5))

females <- data.frame(
  gender = rep(0, n_females),
  writing = rnorm(n = n_females, mean = 60, sd = 10)
) %>%
  mutate(math = writing * 0.65 + rnorm(n = n_females, mean = 5, sd = 5))

df <- males %>%
  bind_rows(females)

We have 1,000 individuals, 40% of whom are males. Here is a sample of 5 rows:

gender
writing
math

0
56.47547
46.80284

1
62.11980
50.17477

0
65.14230
51.73375

0
66.81830
55.42685

1
64.26464
55.45913

And this is what the correlations between writing and math scores look like for the two genders:
df %>%
  ggplot(aes(x = writing, y = math, colour = factor(gender))) +
  geom_point() +
  geom_smooth(method = 'lm', colour = 'black') +
  facet_wrap(~ gender) +
  labs(colour = 'gender')

Note that you can calculate the actual sample correlations by doing:
cor(males$writing, males$math)
# [1] 0.8460947
cor(females$writing, females$math)
# [1] 0.8002061

so we see that males have a slightly higher correlation. But is this difference statistically significant?

Now, here is where the magic happens. We draw 10,000 bootstrap resamples (with replacement) for each gender, calculate the respective correlations, and store the differences between male and female correlations:
male_rows <- df %>%
    filter(gender == 1) %>%
    select(writing, math)

female_rows <- df %>%
    filter(gender == 0) %>%
    select(writing, math)

N_BOOT <- 10000

corr_deltas <- numeric(N_BOOT)

for (i in 1:N_BOOT) {
  male_boot <- male_rows %>%
    slice_sample(prop = 1, replace = TRUE)

  female_boot <- female_rows %>%
    slice_sample(prop = 1, replace = TRUE)

  male_corr <- cor(male_boot$writing, male_boot$math)
  female_corr <- cor(female_boot$writing, female_boot$math)

  corr_delta <- male_corr - female_corr

  corr_deltas[i] <- corr_delta
}

Now we have all we need. We can plot a histogram of the correlation differences together with their 95% confidence interval:
lower_bound_95ci <- quantile(corr_deltas, 0.025)
upper_bound_95ci <- quantile(corr_deltas, 0.975)

ggplot() +
  geom_histogram(aes(x = corr_deltas)) +
  geom_vline(aes(xintercept = lower_bound_95ci), linetype = 'dashed') +
  geom_vline(aes(xintercept = upper_bound_95ci), linetype = 'dashed') +
  labs(title = paste(
    'The 95% CI for the difference in correlations is (',
    round(lower_bound_95ci, 3), ',', round(upper_bound_95ci, 3), ')'),
    subtitle = 'Therefore, males have a higher correlation than women.',
    x = 'correlation delta')

Since the 95% CI does not include 0 in this case, we would conclude that the correlation between writing and math scores was significantly higher for males than for females.
Answer: If your population is approximately normal distributed then you can approximate the distribution of a correlation coefficient by a normal distribution after applying a Fisher transformation.
$$z = 0.5 \log \frac{1+r}{1-r} \sim N\left(\mu,\sigma^2\right)$$
where $\mu = 0.5 \log \frac{1+\rho}{1-\rho}$ and $\sigma = \frac{1}{\sqrt{N-3}}$ where $\rho$ is the true correlation of the population and $N$ is the sample size.
Then you can take the difference of the two $z$ scores (based on your two correlations) and given the hypothesis that you have the same correlation the difference should be normal distributed with zero mean and standard deviation $\sqrt{\frac{1}{N_1-3}+\frac{1}{N_2-3}}$.

If your population is not approximately normal distributed, then you could approximate the distribution with a Monte Carlo method like resampling and observing the variation that occurs among the different samples. This works better if you have a large sample size.


Notating three simultaneous notes of different durations for piano

Question: On the same staff, how do I notate three simultaneous notes of different duration?  For example, half notes on middle C and the C above and four eighth notes on the G inbetween
Answer: Welcome to MP&T.
You can do it like either of these:
Comment: Thanks.  I had tried the first, but I like the second better.
Comment: I used to do this with a common vertical line.
Comment: @Joshua You naughty person, you :-)
Answer: From what you say it sounds like you need two voices.  The middle Cs plus the octave can be joined as one voice, and the Gs would be a second voice.  You would have one stem going down and the other going up.
Comment: Jomiddnz's answer is the same as mine. (+1) As (s)he says, you need two voices.
Comment: Thanks.  I was trying to avoid the stems up running into the stems down. Looks like I can get close.


why does spring's spel have rootObject?

Question: in spel ,if a variable is not prefixed with #, spel will look it in the rootObject.
otherwise, spel look it in the context.
why does spring's spel have rootObject ?
can rootObject be treated as a common variable?
is it just for convenience?
Comment: Please provide enough code so others can better understand or reproduce the problem.
Answer: The context usually is the same for all the evaluation of that expression.
The root object is volatile. Think about it as an HTTP request body, where context could be a session for that user. So, root object cannot be as a part of the context since and it cannot be treated as a common variable since. It lives just in a scope of the current expression evaluation.

why does spring's spel have rootObject?


Can we use $|A|=|B|$ to prove $|A| \le|B|$ and $|B| \le|A|$ directly in the set theory?

Question: Recently, when I self-learned Discrete Mathematics and Its Applications 8th by Kenneth Rosen, I did only the even-numbered exercises which the author offers the detailed description than the odd ones because the odd ones and the corresponding even ones are very similar. I was stuck at exercise 2.5-14.
The problem is

Show that if A and B are sets with the same cardinality,
then $|A| \le|B|$ and $|B| \le|A|$

The book solution uses "one-to-one" and "onto" of $A\to B$ definition to prove $|A| \le|B|$ and $|B| \le|A|$ respectively.
Q:
Maybe the solution by the book takes the uncountably infinite set in account and since comparing $\infty$ is nonsense, so it use the basic definition to prove the inequalities, is it that case? If not, can we use the arithmetic property to prove $\le$ directly from $=$ which applied here will give the converse statement of the SCHRODER-BERNSTEIN THEOREM?
Comment: Please combine your questions into one
Comment: Thanks for the comment, modified already.
Answer: Proof. Suppose that $A$ and $B$ are sets with the same cardinality. I.e., $\vert A \vert = \vert B \vert$. By definition, there is a bijective mapping $f$ from $A$ to $B$. Since $f : A \to B$ is bijective, $f^{-1} : B \to A$ is also bijective. Since $f$ is bijective, it is also injective. Hence, $\vert A \vert \le \vert B \vert$. Furthermore, since $f^{-1}$ is bijective it is also injective. Therefore, $\vert B \vert \le \vert A \vert$. Our conclusion has been reached. $\blacksquare$
As for your question, I believe that your text uses the definition of cardinality to make the comparison $\vert A \vert \le \vert B \vert$. If you wish to use the arithmetic property $a = b \Leftrightarrow a \le b \text{ and } b \le a$, your conclusion would be restricted to natural numbers. In this context, you would be limited to finite sets. But, the given statement is actually stronger. It allows you to say something about the ordering of sets of arbitrary size. That, if you can construct a bijection from $A$ to $B$ and $\vert A \vert = \aleph_{100}$, then you automatically know that $\vert B \vert = \aleph_{100}$ and $\aleph_{100} \le \aleph_{100}$.
Comment: 1. Your answer is also very helpful and similar to the accepted one, but only one answer can be chosen as accepted. 2. To answer "I believe that your text uses the definition of cardinality to make the comparison $|A|\le|B|$", the textbook states "If there is a one-to-one function from A to B, the cardinality of A is less than or the same as the cardinality of B and we write $|A|\le|B|$" as you said.
Answer: This has to do with how cardinality is defined for infinite sets. If $A$ and $B$ or finite, this is trivial.
When working with infinite sets there is very little reason to think that any coherent notion of "size" exists in the first place.
If you fix a particular notion of cardinality, so that each set has a cardinality and the set of cardinals less than the cardinality of a given set is ordered, then you can use the arithmetic definition $a=b\iff(a\le b\land b\le a)$. Typically this is done by defining $\lvert X\rvert$ to be the smallest ordinal $\alpha$ such that there exists a bijection $f:\alpha\to X$, and each such ordinal is regarded as a cardinal.
However, in the general setting, we may or may not have ordinals, or any way of assigning sets specific cardinalities. What we do have is a notion of "equipotence." Two sets $A$ and $B$ are said to be equipotent if and only if there exists a bijection from $A$ to $B$. Thus, regardless of what "$\lvert A\rvert$" and "$\lvert B\rvert$" "actually" mean (if they mean anything at all), we can always take $\lvert A\rvert=\lvert B\rvert$ to mean "there exists a bijection from $A$ to $B$". Similarly, we can interpret $\lvert A\rvert\le\lvert B\rvert$ as "there exists an injection from $A$ to $B$." This makes sense: obviously $\lvert A\rvert=\lvert f(A)\rvert$, and $f(A)\subseteq B$, so there should be at most $B$-many elements in $A$.
What this all leads to is the Schröder–Bernstein theorem. What the theorem actually states is that for any pair of sets $A$ and $B$, if there exist injections $f:A\to B$ and $g:B\to A$, then there exists a bijection from $A$ to $B$. In other words: $(\lvert A\rvert\le\lvert B\rvert\land\lvert B\rvert\le\lvert A\rvert)\implies\lvert A\rvert=\lvert B\rvert$.
What you are trying to prove is the converse of the Schröder–Bernstein theorem:
Suppose there is a bijection from $A$ to $B$. Prove that there exist injections from $A$ to $B$ and from $B$ to $A$.

For a quick 'n' dirty introduction to ordinals and cardinals, I would recommend Vsauce's How to count past infinity
Comment: Thanks. I have understood what you said. With your answer "there is very little reason to think that any coherent notion of "size" exists in the first place.", "equipotence" is necessary for comparing two uncountably infinite sets.


Rejection threshold of the Benjamini-Hochberg procedure

Question: Is there a possibility to calculate or estimate the overall rejection threshold of the Benjamini–Hochberg procedure (BH)?
For the correction of the FWER using the Bonferroni method, the significance threshold is adjusted to the number of evaluated hypotheses $m$ as follows $\bar{\alpha}= \frac{\alpha}{m}$. But since the BH-procedure produces an individual $q$-value for each independent hypothesis that is compared to an apriori defined FDR, I am not sure how this can be done.
Answer: As you sense, there is no fixed p-value cutoff for the Benjamini-Hochberg control of false discovery rate. The cutoff depends on the specific distribution of p-values among the $m$ hypotheses that you are evaluating together. You put them in increasing order and count up in $k$ from the lowest p-value $(k=1)$. You agree to  "reject the null hypothesis" for hypotheses up through this value of $k$:

For a given $\alpha$, find the largest $k$ such that $P_{(k)} \leq \frac{k}{m} \alpha.$

If the null hypotheses all hold so there is a uniform distribution of p-values in [0,1], the p-value cutoff will be close to $\alpha$. How much below that you go if some null hypotheses don't hold depends on how non-uniform the distribution of p-values is.
Comment: Did you mean *"the q-value cutoff will be close to α"*?
Comment: @SextusEmpiricus the terminology gets so confusing on this. I intended that to be the cutoff among the hypothesis p-values to achieve the desired q-value for FDR. The q-value is called $\alpha$ in the quote from Wikipedia on the method.
Comment: but this cutoff will be $\frac{k}{m} \alpha$, right?
Comment: @SextusEmpiricus yes. So does one call the original hypothesis p-values "q-values" when you put them in order to do the B-H FDR control? Or is the "q-value" the FDR? Or is the "q-value" $\frac{k}{m} \alpha$? I don't know if there is a universally accepted terminology for this, would appreciate a reference if there is.
Comment: I am actually not sure what the OP means by overall rejection threshold. I don't believe it applies to this situation because there is no single threshold according to which each hypothesis is treated independently. This confuses me about your statement "the p-value cutoff will be...".
Comment: @SextusEmpiricus Yes, I agree that overall rejection threshold is a misnomer in the context of the BH-procedure. I had this idea came when I was reading a paper about finding an adequate significance threshold for an Illumina Methylation Array (doi: 10.1186/s12864-019-5761-7). Since I am using BH to correct for multiple comparison, I wanted to check how far apart my cut-off is from their customized Bonferroni approach. Maybe this R function might bring some clarification (https://www.rdocumentation.org/packages/IHW/versions/1.0.2/topics/get_bh_threshold). I'll tell you if I find anything
Answer: I'm not certain of the formal validity of this approach, but you could calculate the corresponding FWER as given by the Hochberg method.
The Benjamini-Hochberg procedure for controlling the False Discovery Rate is (I'm going to quote Wikipedia)

... we have $H_1 \ldots H_m$ null hypotheses tested and $P_1 \ldots P_m$ their corresponding p-values. We list these p-values in ascending order and denote them by $P_{(1)} \ldots P_{(m)}$.
...

For a given $\alpha$, find the largest $k$ such that $P_{(k)} \leq \frac{k}{m} \alpha.$
Reject the null hypothesis (i.e., declare discoveries) for all $H_{(i)}$ for $i = 1, \ldots, k$.

That method sets the FDR at $\alpha$, i.e., out of the rejected hypotheses, we expect the fraction of Type I Errors to be $\alpha$.
The Family-Wise Error Rate, on the other hand, is the probability of at least one Type I Error in the set of rejected hypotheses.  The Hochberg method accomplishes this with a calculation similar to the BH FDR method (again, quoting Wikipedia),

Start by ordering the p-values (from lowest to highest) $P_{(1)} \ldots P_{(m)}$ and let the associated hypotheses be  $H_{(1)} \ldots H_{(m)}$
For a given $\alpha$, let $R$ be the largest $k$ such that $P_{(k)} \leq \frac{\alpha}{m-k+1}$
Reject the null hypotheses $H_{(1)} \ldots H_{(R)}$

You could put these together to 1) define an FDR $\alpha$, 2) determine the largest rejected p-value $p^*$ and the number of rejected hypotheses $k$ out of total $m$, 3) calculate the corresponding Hochberg FWER $\tilde{\alpha}$ as
$$ \tilde{\alpha} = p^* \times(m-k+1) $$
Comment: I am not sure about Wikipedia or myself, but when I try to simulate and compute the FDR  and FWER of the Benjamini-Hochberg procedure then I get that it is the FWER that is equal to $\alpha$. Do you know anything about that https://stats.stackexchange.com/questions/495211/proof-derivation-for-false-discovery-rate-in-benjamini-hochberg-procedure ?
Answer: After some thought, I believe that the unadjusted p-value of the last (rank-wise) significant test after the BH-procedure comes closest to a significance threshold.
An example:
Do the BH-procedure:

Some p-values: $0.0001,0.0234,0.3354,0.0021,0.5211,0.9123,0.0008,0.0293,0.0500, 1.000$

Order them: $0.0001, 0.0008, 0.0021, 0.0234, 0.0293, 0.0500, 0.3354, 0.5211, 0.9123, 1.0000$

Compute q-values for all 10 ranks: $q_i = \frac{i}{m}\cdot \alpha$, for $i=1,2,..,m$.

Find the largest ranked p-value that is smaller than its corresponding q-value.

Results:
$$\begin{array}{}
\textbf{Rank} & \textbf{q-value} & \textbf{p-value} & \textbf{Significance (BH)} \\ \hline
1                & 0.005            & 0.0001           & True                       \\ \hline
2                & 0.01             & 0.0008           & True                       \\ \hline
3                & 0.015            & 0.0021           & True                       \\ \hline
4                & 0.02             & 0.0234           & False                      \\ \hline
5                & 0.025            & 0.0293           & False                      \\ \hline
6                & 0.03             & 0.05             & False                      \\ \hline
7                & 0.035            & 0.3354           & False                      \\ \hline
8                & 0.04             & 0.5211           & False                      \\ \hline
9                & 0.045            & 0.9123           & False                      \\ \hline
10               & 0.05             & 1                & False                      \\ \hline
\end{array}$$
On the table, we can see that all tests above Rank 3 are non-significant, thus we can conclude that 0.0021 acts as our significance threshold.
In comparison, the Bonferroni correction has a threshold of $\frac{\alpha}{m}=0.005$.
Here is the R-code I used for this example:
<code># generate p-values
pValues <- c(0.0001,0.0234,0.3354,0.0021,0.5211,0.9123,0.0008,0.0293,0.0500, 1)

# order the p-values
pValues <- sort(pValues)

# BH-procedure
alpha <- 0.05
m <- length(pValues)
qValues <- c()

for (i in 1:m){
  qV <- (i/m)*alpha
  qValues <- append(qValues, qV)
}

# find the largest p-value that satisfies p_i < q_i
BH_test <- qValues > pValues

# largest k is 3, thus threshold is 0.0021
threshold <- pValues[sum(BH_test)];threshold
</code>


What type of regression for two groups of data?

Question: I have data from 500 school children who took a test. 250 of the children have a certain type of disability (group A). Each child in group A was matched to a child on the basis of age, gender to a child without a disability (group b). In total there are 500 children. I have other characteristics measured too.
We need to do some sort of regression where the dependent variable is the test score and the independent variables are the other things we measured (age, gender, socioeconomic family status, reading scores, empathy scores), but I don't know how to account for the groups.
Regular multiple regression looks like Y = beta + beta(x) +...+ error
but I don't know how to account for the matching in this equation.
Secondly, it isn't clear if I should include age and gender in the regression because they were matching criteria, although many of the other posts say they should be included but not analyzed. What is the rule?
Comment: Is 500 the number of children you started with, or the number you ended up with after matching (by dropping Group A and/or B individuals for whom there was not an adequate match found)?  Or are those two numbers the same?  In your matching, did you allow for the same child in Group B to be used as a match for more than one child in Group A?  And did you match on both age and gender via exact matching?
Comment: There are 500 children that we have in total now after matching. We have 250 of the children with disability and for each we found a 'control' without the disability (matched on age, gender). In total there are 500 children whose test scores we have to analyze.
Comment: Thanks, please see my updated answer below.
Answer:
Regular multiple regression looks like Y = beta + beta(x) +...+ error but I don't know how to account for the matching in this equation.

In general, you don't need to account for matching in the outcome regression equation beyond just using the matched samples (which in most cases will be smaller than the samples you started with because you discarded individuals from the treatment and/or control groups for whom there was not an adequate match found).
If you had applied "matching with replacement", allowing for a child in Group B to be used as a match for more than one child in Group A, then you would have needed to account for this in the model, for example, by including a Group B member in the regression as many times as he/she was used for a match (or assigning frequency weights).  But in your case, with as many Group B children as Group A children, it is not needed.

Secondly, it isn't clear if I should include age and gender in the regression because they were matching criteria, although many of the other posts say they should be included but not analyzed. What is the rule?

The main purpose of including variables in a causal-effect regression model is to eliminate confounding (estimated association between exposure and outcome being distorted/biased because exposure is also correlated with another risk factor that is also associated with the outcome).
Matching is also used to reduce or eliminate the impact of a confounding variable because by creating similar distributions of that variable in the two groups we essentially eliminate any differences in the association between the treatment/exposure variable and the outcome that are due to differences in the confounding variable.
Your end goal is to get an unbiased estimate of the effect of having a disability on test scores.  If your matching did what it needed to do in terms of removing confounding, then including or not including those age and gender variables in the regression should not have an effect on the estimate of the disability variable.  What is possible though is that if you are treating age as a continuous variable (rather than discrete, like gender), then there may be some interaction effects between disability and age that were not captured by matching.  In that case, you could see a difference in results, but that would be due to the variables you are working with, not due to some inherent difference between controlling or not controlling for matching variables.
Also FYI, mathematically, if there are no other covariates besides the variables you exactly matched on, then "regression adjustment after exact one-to-one exact matching gives the identical answer as a simple, unadjusted difference in means" (see https://r.iq.harvard.edu/docs/matchit/2.4-15/Examples2.html)


I deleted my local directory in tf. How to re-get it?

Question: I am on linux, command line tf.
I delete my local directory. Now the tf get does not retrieve the files -
How do I get it back from tfs???
Comment: Do you mean you deleted it from the repo or from your actual filesystem?
Answer: You need to use the following command:
tf get /force

You could also use /all. But I prefer /force to resync a working copy with the server, just so that nothing is missed.
From MSDN:

/all
  Forces all files to be retrieved, not just those that are
  out-of-date.
/overwrite
  Overwrites writable files that are not checked out.
/force
  Implies /all and /overwrite.


Relation between embeddings in $\mathcal{C}([0,1])$ and the the compactness of the unit ball

Question: Assume that a Banach space of functions on $[0,1]$, $\mathcal{B}([0,1])$, with norm $||\cdot||_{B}$ can be embedded in the space of continuous functions, $\mathcal{C}([0,1])$, with the sup-norm $||\cdot||_{\infty}$. In other words, $\mathcal{B}([0,1]) \subset \mathcal{C}([0,1])$ and there exists a $C>0$ such that
$$ ||f||_{\infty} \leq C ||f||_{\mathcal{B}}, \quad f \in \mathcal{B}([0,1]). $$
My question is whether in that case the unit ball $\{f \in \mathcal{B}:||f||_{B} \leq 1 \}$ is necessarily compact in the topology of the sup-norm. For some of these spaces the Arzela-Ascoli theorem can be applied to show compactness but I am not sure if there is a more general result in that direction.
Thank you.
Comment: Take $\mathcal B [0,1]=C[0,1]$ for an obviosu counter-example.
Comment: @KaviRamaMurthy You are right! Are there any additional conditions on $\mathcal{B}([0,1])$ that would make this work?
Answer: $C[0,1]$ is a "universal space" in the class of separble Banach spaces. This means any separable Banach space can be isometrically embedded in $C[0,1]$. (Ref. Geometric Functional Analysis by Holmes]. Take any infinite dimensional Banach space, embed it in $C[0,1]$ isometrically and you get an example where the ball is not compact in the sup norm.
Comment: Thanks a lot for your valuable input.