What operations can I do to simplify calculations of determinant?

Question: My question is simple. Given an $n \times n$ matrix $A$, what operations can we do to the rows and columns of $A$ to make the calculation of its determinant easier?
I know we can put it into row echelon form, then the determinant is simply $\operatorname{trace}(A)$. Another question is, like operations in an augmented matrix $(A \mid b)$, can we swap rows? Would it affect the determinant?
Comment: @alkabary : In your attempted edit you had \space|\space.  I changed that to \mid.  I think that's better than inserting spaces manually because the spacing conventions that apply to it are different in different contexts and the software knows how the conventions vary with the context.
Comment: @MatGomes check this link here

http://www.math.vanderbilt.edu/~msapir/msapir/proofdet1.html
Comment: The determinant of a matrix in row echelon form is **not** the trace. (It's the *product* of the diagonal elements, not the *sum*.)
Comment: Every time you swap two rows, you change the sign of the determinant and so you have to keep track of  the numbers of row swapping , Even number of row swapping wouldn't affect, but odd number of row swapping will be negative the determinant
Comment: @MichaelHardy sounds good
Comment: @alkabary Ah alright, thanks! Also, can you do the same thing to columns, does it change anything? I've noticed that my lecturer often took a multiple of a column from another column. It's not something I've done with augmented matrices so is it always valid to do that when calculating determinants?
Comment: @alkabary This is perfect, really helped thanks!
Comment: @MatGomes You are very welcome !
Comment: Don't forget that some kinds of matrices allow for further simplifications. For example, if $A$ is block diagonal then its determinant is the product of the determinants of the blocks.
Answer: The determinant of an $n\times n$ matrix $A$ is a multilinear, antisymmetric function on the columns of $A$.
Let $$A = \begin{bmatrix} a_{11} & a_{12} & \cdots & a_{1n} \\ a_{21} & a_{22} & \cdots & a_{2n} \\ \vdots & \vdots & & \vdots \\ a_{n1} & a_{n2} & \cdots & a_{nn}\end{bmatrix}$$
Now let $\mathbf a_i$ be the $i^{th}$ column of $A$.  Thus $\mathbf a_2 = \begin{bmatrix} a_{12} \\ a_{22} \\ \vdots \\ a_{n2}\end{bmatrix}$, for instance.
Then $\det(A) = \det(\mathbf a_1, \mathbf a_2, \cdots, \mathbf a_n)$.

Multilinearity
OK.  Now what does multilinear mean?  It means that $\det$ is linear in each of its arguments. Thus if you have something like $\det(3\mathbf a_1 + 4\mathbf b_1, \mathbf a_2, \cdots, \mathbf a_n)$, then this is exactly the same as $3\det(\mathbf a_1, \mathbf a_2, \cdots, \mathbf a_n) + 4\det(\mathbf b_1, \mathbf a_2, \cdots, \mathbf a_n)$.  Also:
$$\begin{align}\det(\mathbf a_1, -\mathbf a_2 + 5\mathbf b_2, \mathbf a_3, 6\mathbf a_4 + 2\mathbf b_4) &= -\det(\mathbf a_1, \mathbf a_2, \mathbf a_3, 6\mathbf a_4 + 2\mathbf b_4) + 5\det(\mathbf a_1, \mathbf b_2, \mathbf a_3, 6\mathbf a_4 + 2\mathbf b_4) \\ &= -[6\det(\mathbf a_1, \mathbf a_2, \mathbf a_3, \mathbf a_4) + 2\det(\mathbf a_1, \mathbf a_2, \mathbf a_3, \mathbf b_4)] \\ &\ \ \ \ + 5[6\det(\mathbf a_1, \mathbf b_2, \mathbf a_3, \mathbf a_4) + 2\det(\mathbf a_1, \mathbf b_2, \mathbf a_3, \mathbf b_4)] \\ &= -6\det(\mathbf a_1, \mathbf a_2, \mathbf a_3, \mathbf a_4) - 2\det(\mathbf a_1, \mathbf a_2, \mathbf a_3, \mathbf b_4) \\ &\ \ \ \ + 30\det(\mathbf a_1, \mathbf b_2, \mathbf a_3, \mathbf a_4) + 10\det(\mathbf a_1, \mathbf b_2, \mathbf a_3, \mathbf b_4)\end{align}$$

Antisymmetry
The fact that $\det$ is antisymmetric means that if you swap any two arguments of $\det$, you'll negate the sign. Thus $$\det(\mathbf a_1, \mathbf a_2) = -\det(\mathbf a_2, \mathbf a_1)$$
Likewise
$$\begin{align}\det(\mathbf a_1, \mathbf a_2, \mathbf a_3, \mathbf a_4) &= -\det(\mathbf a_1, \mathbf a_4, \mathbf a_3, \mathbf a_2) \\ &= \det(\mathbf a_4, \mathbf a_1, \mathbf a_3, \mathbf a_2)\end{align}$$
So swapping an even number of columns doesn't change the sign, but swapping an odd number will produce a negative sign.
One consequence of this antisymmetry is that if two columns are scalar multiples of each other, then the determinant must be zero.  This is because after pulling the constant multiple out front the two columns will be the same.  Then if you swap those two columns, the determinant will look the same -- but it'll have a minus sign out front.  And thus the determinant will equal its negative.  But the only number that equals its negative is zero. Thus the determinant is zero.
Thus $\det(\mathbf a_1, k\mathbf a_1) = 0$.

So knowing these properties of the determinant, what operations can we do on the columns of a matrix?  We can do $3$ things:

We can switch any two columns.  This will have the effect of negating the determinant.
We can pull any constant times a column out of the determinant: i.e. $\det(\mathbf a_1, 2\mathbf a_2) = 2\det(\mathbf a_1, \mathbf a_2)$.
We can add a scalar multiple of one of the columns to another column.  This will not change the value of the determinant at all.  That is $\det(\mathbf a_1, \mathbf a_2) = \det(\mathbf a_1, \mathbf a_2 + k\mathbf a_1)$.

Now you should try to prove each of the above by using the properties of the determinant that I gave above (there's only two of them, so it shouldn't be too hard).

One last thing before moving on to an example: the determinant of the transpose of a matrix is equal to the determinant of the matrix.  That is $\det(A^T) =\det(A)$.  This implies that everything that we did with columns above, we could equally well have done to the rows of a matrix.  This is provable by showing the $A$ and $A^T$ share the same characteristic polynomial.

Now we'll look at an example.
Let $$A = \begin{bmatrix} 2 & 2 & 3 \\ 1 & 3 & 5 \\ 1 & 4 & 7\end{bmatrix}$$
The way we'll solve this is basically the same way we'd do a Gaussian elimination problem -- except we'll be do column operations instead of row operations.  We could do row operations, but I flipped a coin and it landed column-side up. :)
$$\begin{align}\det(A) &= \det\left(\begin{bmatrix} 2 \\ 1 \\ 1\end{bmatrix}, \begin{bmatrix} 2 \\ 3 \\ 4\end{bmatrix}, \begin{bmatrix} 3 \\ 5 \\ 7\end{bmatrix} \right) \\ &= \det\left(\begin{bmatrix} 2 \\ 1 \\ 1\end{bmatrix}, \begin{bmatrix} 2 \\ 3 \\ 4\end{bmatrix} - \begin{bmatrix} 2 \\ 1 \\ 1\end{bmatrix}, \begin{bmatrix} 3 \\ 5 \\ 7\end{bmatrix} - \frac 32\begin{bmatrix} 2 \\ 1 \\ 1\end{bmatrix}\right) \\ &= \det\left(\begin{bmatrix} 2 \\ 1 \\ 1\end{bmatrix}, \begin{bmatrix} 0 \\ 2 \\ 3\end{bmatrix}, \begin{bmatrix} 0 \\ \frac 72 \\ \frac {11}2\end{bmatrix}\right) \\ &= \frac 12\det\left(\begin{bmatrix} 2 \\ 1 \\ 1\end{bmatrix}, \begin{bmatrix} 0 \\ 2 \\ 3\end{bmatrix}, \begin{bmatrix} 0 \\ 7 \\ 11\end{bmatrix}\right) \\ &= \frac 12\det\left(\begin{bmatrix} 2 \\ 1 \\ 1\end{bmatrix}, \begin{bmatrix} 0 \\ 2 \\ 3\end{bmatrix}, \begin{bmatrix} 0 \\ 7 \\ 11\end{bmatrix} - 3\begin{bmatrix} 0 \\ 2 \\ 3\end{bmatrix}\right) \\ &= \frac 12\det\left(\begin{bmatrix} 2 \\ 1 \\ 1\end{bmatrix}, \begin{bmatrix} 0 \\ 2 \\ 3\end{bmatrix}, \begin{bmatrix} 0 \\ 1 \\ 2\end{bmatrix}\right) \\ &= -\frac 12\det\left(\begin{bmatrix} 2 \\ 1 \\ 1\end{bmatrix}, \begin{bmatrix} 0 \\ 1 \\ 2\end{bmatrix}, \begin{bmatrix} 0 \\ 2 \\ 3\end{bmatrix}\right) \\ &= -\frac {1}{2}\det\left(\begin{bmatrix} 2 \\ 1 \\ 1\end{bmatrix}, \begin{bmatrix} 0 \\ 1 \\ 2\end{bmatrix}, \begin{bmatrix} 0 \\ 2 \\ 3\end{bmatrix} - 2\begin{bmatrix} 0 \\ 1 \\ 2\end{bmatrix}\right) \\ &= -\frac 12\det\left(\begin{bmatrix} 2 \\ 1 \\ 1\end{bmatrix}, \begin{bmatrix} 0 \\ 1 \\ 2\end{bmatrix}, \begin{bmatrix} 0 \\ 0 \\ -1\end{bmatrix}\right)\end{align}$$
At this point we just have to remember that the determinant of a triangular matrix is the product of the diagonal elements.  Thus $\det(A) = -\frac12(2)(1)(-1) = 1$.
Notice also that I did a couple of steps that I didn't really need to because I wanted to demonstrate all three operations to you.


Why cannot add row to jtable?

Question: I need some help with addrow to jTable.
I have 2 jFrames, first one has jTable1 and second one has jTextfields. I would like to add data (string) from second frame to jTable1 in first frame. I tried many versions and watch many tutorials..but no success.
in first frame where i have jTable1 i have SwingWorker and i wrote:
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
         jButton1.setEnabled(false);
         jButton2.setEnabled(true);
         Boolean praznaMapa = false;
         worker = new SwingWorker<Void, String>(){
            @Override
            protected Void doInBackground() throws Exception {

                if(isCancelled())
                {
                    return null;
                }
                AddRowToTable(new Object[]
                {
                    PrviStolpec,DrugiStolpec,TretjiStolpec,timeStamp,
                });
}}
worker.execute();}

     public static void AddRowToTable (Object [] data)
    {

        DefaultTableModel tblmodel = (DefaultTableModel)jTable1.getModel();
        tblmodel.insertRow(0, data);
    }

and in the second frame where i have textfields i wrote:
String PrviStolpec = FIRSTFRAME_Okno.withoutExtension;
String DrugiStolpec = "OK";
String TretjiStolpec = FIRSTFRAME_Okno.stSledenja;
String timeStamp = new SimpleDateFormat ("yyyy-MM-dd HH:mm:ss").format(Calendar.getInstance().getTime());
                FIRSTFRAME_Okno.AddRowToTable(new Object[]
                {
                    PrviStolpec,DrugiStolpec,TretjiStolpec,timeStamp,
                });
                FIRSTFRAME_Okno.jTable1.setSelectionBackground(Color.green);

but when i run program, nothing happen. No error and no data in jTable1 :(
Any suggestion?
Thank you!
Comment: 1) Method names should NOT start with an upper case character. 2) Variable names should not start with an upper case character. Learn and follow Java conventions. 3) An application should only have a single JFrame. If you need child windows then you can use a `JDialog`. 4) You should NOT be using code like: `FIRSTFRAME_Okno.jTable1` to access variables of another class. If you want to update the table then you pass the "table" as a parameter to your child dialog. If the child dialog has a reference to the visible table, then the above code should work.
Comment: Not answering your question, I recommend you don't use `SimpleDateFormat` and `Calendar`. Those classes are poorly designed and long outdated, the former in particular notoriously troublesome. Instead for getting the current time as a string use `ZonedDateTime.now(ZoneId.systemDefault()).format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"))` using classes from [java.time, the modern Java date and time API](https://docs.oracle.com/javase/tutorial/datetime/).
Comment: @OleV.V. tnx for the note!
Comment: Can you please provide a [mre]?
Comment: @camickr thank you for answer! I updated my question. I think i have problem with SwingWorker which i have in first jframe.
Answer: I found solution!
It is really stupid one, but anyway...
I have in second class:
FIRSTFRAME_Okno = new FIRSTFRAME_Okno();

Because of that jTable1 was not updated.
Every function which i call from second class i use:
FIRSTFRAME_Okno.functionName();

Tnx!

Why cannot add row to jtable?


How can I add an article to a region?

Question: How can I add a content (let's say content of Article type)' to ANY region (not only in content region), or how to add a region to a node view page?
Comment: welcome to drupal, please learn how to ask question, you question is not clear.
http://drupal.stackexchange.com/help/how-to-ask
Comment: I wonder how I can add an Article to ANY region (not only in content region) ??
Answer: By default drupal don't let you do this , you should achieve it with this two solution

use nodeblock

This module allows you to specify content type(s) as being a block.
  This allows the content managers of the site to edit the block text
  and title without having to access the block administration page.
  Users only need edit access to that node in order to edit it.
We advice you to use this module together with Node Level Blocks or
  Block Reference module.
It is very handy to create a simple block content type and enable this
  content type for blocks and use these in place of the normal 'add
  block' functionality.

Achieve it by views block,I mean create a view, get result of it with what you want ,then save it as block ( I mean create block view), then put the block in the region you want.
Comment: Views would be better, honestly.

How can I add an article to a region?


AVPlayerLayer animates frame changes

Question: Whenever I change the frame of my AVPlayerLayer, the video is not resized immediately, but animated to the new size.
For example: I change the frame from (0, 0, 100, 100) to (0, 0, 400, 400), the view's frame is changed immediately, but the video's size is animated to the new size.
Has anyone encountered this issue? And if yes does someone know a way to disable the default animation?
Thanks!
Comment: Funny, I have the opposite issue: I can't get animations to work on AVPlayerLayer!
Answer: You can try disabling implicit actions and using zero length animations:
CALayer *videolayer = <# AVPlayerLayer #>
[CATransaction begin];
[CATransaction setAnimationDuration:0];
[CATransaction setDisableActions:YES];
CGRect rect = videolayer.bounds;
rect.size.width /= 3;
rect.size.height /= 3;
videolayer.bounds = rect;
[CATransaction commit];

Comment: Yes, seems to work fine. Cheers. A note to others: this requires the QuartzCore.framework to use CATransaction
Answer: This is what I used:
AVPlayerLayer * playerLayer = <# AVPlayerLayer #>;
playerLayer.frame = <# CGRect #>;
[playerLayer removeAllAnimations];

I hope this helps. I don't know if its best practices, but it works for me.
It seems that whenever ".frame" or "setFrame" is used, it adds animation to the layer.
Comment: Tried this (in swift) but placed the playerLayer.removeAllAnimations() in the wrong place. You need to call this directly after every time you change the frame, not when you create the layer.
Answer: The easiest and cleanest way to deal with this is to create a UIView subclass that has AVPlayerLayer as its layerClass. When doing this the AVPlayerLayer will behave just like a regular UIView layer. You can change the frame of the view instead of the layer and no implicit animations will happen.
AVPlayerLayerView.h
#import <UIKit/UIKit.h>
#import <AVFoundation/AVFoundation.h>

@interface AVPlayerLayerView : UIView

@property (nonatomic, readonly) AVPlayerLayer *playerLayer;

@end

AVPlayerLayerView.m
#import "AVPlayerLayerView.h"

@implementation AVPlayerLayerView

+ (Class)layerClass {
    return [AVPlayerLayer class];
}

- (AVPlayerLayer *)playerLayer {
    return (AVPlayerLayer *)self.layer;
}

@end

You can now do this:
playerLayerView.frame = CGRectMake(0, 0, 400, 400);

To associate the AVPlayerLayer with an AVPlayer simply do this:
playerLayerView.playerLayer.player = player;

Answer: Do you use ?:
- (void)setPlayer:(AVPlayer *)player {
    [(AVPlayerLayer *)[self layer] setPlayer:player];
    [(AVPlayerLayer *)[self layer] setVideoGravity:AVLayerVideoGravityResize];
}

Answer: Here is what I do in Swift right after changing the playerLayer's frame:
playerLayer.removeAllAnimations()

Answer: I got this working in Swift 4 via the following:
    var videoLayer = AVPlayerLayer()
    CATransaction.begin()
    CATransaction.setAnimationDuration(0)
    CATransaction.setDisableActions(true)
    var rect = videoLayer.bounds
    rect.size.width /= 3
    rect.size.height /= 3
    videoLayer.bounds = rect
    CATransaction.commit()

Answer: Probably this, what will help in some cases:
adding custom 'setFrame:' setter in view that holds the player layer
- (void)setFrame:(CGRect)frame {
    [super setFrame:frame];

    self.playerLayer.frame = CGRectMake(0.0f, 0.0f, frame.size.width, frame.size.height);
}

AVPlayerLayer animates frame changes


Cooperative Multitasking system

Question: I'm trying to get around the concept of cooperative multitasking system and exactly how it works in a single threaded application.
My understanding is that this is a "form of multitasking in which multiple tasks execute by voluntarily ceding control to other tasks at programmer-defined points within each task."
So if you have a list of tasks and one task is executing, how do you determine to pass execution to another task? And when you give execution back to a previous task, how do resume from where you were previously?
I find this a bit confusing because I don't understand how this can be achieve without a multithreaded application.
Any advice would be very helpeful :)
Thanks
Comment: Single-threaded, bare metal (without an OS) cooperative multi-tasking is done all the time on embedded systems such as microcontrollers. Here is one interruptless example I wrote that uses time-stamps and state machines as a way to let multiple tasks do certain things when it is time and/or at fixed time intervals, all in a single main loop. https://stackoverflow.com/a/50032992/4561887
Answer: In your specific scenario where a single process (or thread of execution) uses cooperative multitasking, you can use something like Windows' fibers or POSIX setcontext family of functions. I will use the term fiber here.
Basically when one fiber is finished executing a chunk of work and wants to voluntarily allow other fibers to run (hence the "cooperative" term), it either manually switches to the other fiber's context or more typically it performs some kind of yield() or scheduler() call that jumps into the scheduler's context, then the scheduler finds a new fiber to run and switches to that fiber's context.
What do we mean by context here? Basically the stack and registers. There is nothing magic about the stack, it's just a block of memory the stack pointer happens to point to. There is also nothing magic about the program counter, it just points to the next instruction to execute. Switching contexts simply saves the current registers somewhere, changes the stack pointer to a different chunk of memory, updates the program counter to a different stream of instructions, copies that context's saved registers into the CPU, then does a jump. Bam, you're now executing different instructions with a different stack. Often the context switch code is written in assembly that is invoked in a way that doesn't modify the current stack or it backs out the changes, in either case it leaves no traces on the stack or in registers so when code resumes execution it has no idea anything happened. (Again, the theme: we assume that method calls fiddle with registers, push arguments to the stack, move the stack pointer, etc but that is just the C calling convention. Nothing requires you to maintain a stack at all or to have any particular method call leave any traces of itself on the stack).
Since each stack is separate, you don't have some continuous chain of seemingly random method calls eventually overflowing the stack (which might be the result if you naively tried to implement this scheme using standard C methods that continuously called each other). You could implement this manually with a state machine where each fiber kept a state machine of where it was in its work, periodically returning to the calling dispatcher's method, but why bother when actual fiber/co-routine support is widely available?
Also remember that cooperative multitasking is orthogonal to processes, protected memory, address spaces, etc. Witness Mac OS 9 or Windows 3.x. They supported the idea of separate processes. But when you yielded, the context was changed to the OS context, allowing the OS scheduler to run, which then potentially selected another process to switch to. In theory you could have a full protected virtual memory OS that still used cooperative multitasking. In those systems, if a errant process never yielded, the OS scheduler never ran, so all other processes in the system were frozen. **
The next natural question is what makes something pre-emptive... The answer is that the OS schedules an interrupt timer with the CPU to stop the currently executing task and switch back to the OS scheduler's context regardless of whether the current task cares to release the CPU or not, thus "pre-empting" it.
If the OS uses CPU privilege levels, the (kernel configured) timer is not cancelable by lower level (user mode) code, though in theory if the OS didn't use such protections an errant task could mask off or cancel the interrupt timer and hijack the CPU. There are some other scenarios like IO calls where the scheduler can be invoked outside the timer, and the scheduler may decide no other process has higher priority and return control to the same process without a switch... And in reality most OSes don't do a real context switch here because that's expensive, the scheduler code runs inside the context of whatever process was executing, so it has to be very careful not to step on the stack, to save register states, etc.
** You might ask why not just fire a timer if yield isn't called within a certain period of time. The answer lies in multi-threaded synchronization. In a cooperative system, you don't have to bother taking locks, worry about re-entrance, etc because you only yield when things are in a known good state. If this mythical timer fires, you have now potentially corrupted the state of the program that was interrupted. If programs have to be written to handle this, congrats... You now have a half-assed pre-emptive multitasking system. Might as well just do it right! And if you are changing things anyway, may as well add threads, protected memory, etc. That's pretty much the history of the major OSes right there.
Answer: The basic idea behind cooperative multitasking is trust - that each subtask will relinquish control, of its own accord, in a timely fashion, to avoid starving other tasks of processor time. This is why tasks in a cooperative multitasking system need to be tested extremely thoroughly, and in some cases certified for use.
I don't claim to be an expert, but I imagine cooperative tasks could be implemented as state machines, where passing control to the task would cause it to run for the absolute minimal amount of time it needs to make any kind of progress. For example, a file reader might read the next few bytes of a file, a parser might parse the next line of a document, or a sensor controller might take a single reading, before returning control back to a cooperative scheduler, which would check for task completion.
Each task would have to keep its internal state on the heap (at object level), rather than on the stack frame (at function level) like a conventional blocking function or thread.
And unlike conventional multitasking, which relies on a hardware timer to trigger a context switch, cooperative multitasking relies on the code to be written in such a way that each step of each long-running task is guaranteed to finish in an acceptably small amount of time.
Comment: In Windows 3.1 (a cooperative multi-tasking operating system), the Sleep API can be used to relinquish control to the operating system. With its help, it is possible that the application keep the data on the stack frame. Note that this doesn't work with the message queue processing model described in most text books, so the program needs to actively get messages from the message queue and process them if we want to write it this way (a loop of: Sleep-Process-Get message-Dispatch message). Otherwise the UI will freeze.
Answer: The tasks will execute an explicit wait or pause or yield operation which makes the call to the dispatcher. There may be different operations for waiting on IO to complete or explicitly yielding in a heavy computation. In an application task's main loop, it could have a *wait_for_event* call instead of busy polling. This would suspend the task until it has input to process.
There may also be a time-out mechanism for catching runaway tasks, but it is not the primary means of switching (or else it wouldn't be cooperative).
Answer: One way to think of cooperative multitasking is to split a task into steps (or states). Each task keeps track of the next step it needs to execute. When it's the task's turn, it executes only that one step and returns. That way, in the main loop of your program you are simply calling each task in order, and because each task only takes up a small amount of time to complete a single step, we end up with a system which allows all of the tasks to share cpu time (ie. cooperate).

Cooperative Multitasking system


Create Tag Synonyms Previlige

Question: I just Got the Badge Create Tag Synonyms Privilege.

What are the responsibilities of this Badge and what shall i do and what shouldn't.
Please tell me.
Answer: Credit : Magento stack exchange link
What are tag synonyms?
Tag synonyms allow us to fix incorrect tags by substituting them with the correct tags.
When should I propose a tag synonym?
Whenever you see questions being repeatedly tagged with the wrong or incorrect tag -- or multiple tags that mean the same thing -- it's a good idea to propose a tag synonym. The goal is to avoid manually editing the tags on every post by making the retagging automatic for common tag mistakes.
How do I propose or vote on tag synonyms?
Users with this privilege and a total answer score (total upvotes minus total downvotes) of 5 or more on the tag, can suggest tag synonyms. Users with a total answer score of 5 or more on the tag, can vote for tag synonyms.
When viewing a tag, look for the box at the top of the page which contains information about the tag with links below it. The last one in that list will be a link to the synonyms page. If there are already synonyms that exist for the tag, the number of synonyms will be shown there as well.
This page will list out all existing synonyms for the tag. Any suggested synonyms for the tag will appear below that with up and down arrows so that eligible users can vote on whether it is valid or invalid. Below that, there is also a box to suggest an additional synonym for that tag.
How do synonyms get approved?
When a tag synonym reaches a vote score of 4, it is accepted and becomes active. If a tag synonym reaches a vote score of -2 it is deleted.
What happens when a question is asked using a synonym?
Any tags that match active synonyms will be automatically and silently changed from their original as-entered form to the tag that the synonym points to.
This also increments a synonym counter, which you can view at /tags/synonyms to evaluate the effectiveness (or ineffectiveness) of the synonyms that are in place.
Comment: Might be minor, but it'd be better to link to [your own site's privilege page](https://magento.stackexchange.com/help/privileges/suggest-tag-synonyms) ;)
Comment: @AndrewT sounds peRFect, updated answer :)
Answer: For example
you can cast synonyms vote or suggest new synonyms for tags where you have atleast 5 upvotes
https://magento.stackexchange.com/tags/magento-1/synonyms

Create Tag Synonyms Previlige


In D3JS hierarchy charts how we can minimize previously expand tiles when clicking new tile?

Question: We have used a D3JS hierarchy chart for showing company employees in a tree view. There we groped employees by there managers. Then if we click one of manager tile, it will expand and view related employees.
There we got some UI issues with huge number of employees. If one manager had lot of employees tree is going to expand so big and hard to identify.
What we need is, Is there way to minimize previously expand Manager tiles when clicking new Manager tile. By doing this we can save more space to show currently checking view.
Answer: I assume you're expanding on the classic D3 collapsible tree example whose latest working version is now hosted on Observable. You just need to change one small block of code there in order to get what you want.
Here's how the original responds when a node is clicked:
.on("click", (event, d) => {
   d.children = d.children ? null : d._children;
   update(d);
 });

Change that too:
.on("click", (event, d) => {
  //// Store the ancestors of the node you've clicked on
  let ancestors = d.ancestors();
  //// Collapse everone
  root
    .descendants()
    .slice(1)
    .reverse()
    .forEach(function (node) {
      node.children = null;
    });
  //// Re-expand the ancestors
  ancestors.forEach(function (d) {
    d.children = d._children;
  });
  update(node);
});

I created a fork of that notebook with those modifications and, in addition, limited the initial expansion to just one step. Here's the result:

<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@observablehq/inspector@5/dist/inspector.css">

I did something similar for the University where I work. Rather than the auto-collapse on click approach you've described, I set up a search box that allows you to search for employees by name. When you search for someone, the whole tree collapses and re-expands just the path you want. The implementation is in this Observable notebook.
Comment: Great answer. For a better performance, you don't need multiple `update(d)` calls (inside the two `forEach`), just one is enough, before closing the `on` callback.
Comment: @GerardoFurtado Yes, that is a touch smoother - thank you!


Border width to change as per the inner div content width

Question: I've the below HTML Code in my document.

Hello, Welcome!. You can ask me
        questions on Compliance Policy ..

         - Bot

Hi

Hello

        - Bot

And my CSS is as below.
.hr-clas {
    border-top: 1px solid #A12EB3;
}

.chat-box-main {
    height: 400px;
    overflow-y: auto;
}

.chat-box-div {
    border: 2px solid #A12EB3;
    border-bottom: 2px solid #A12EB3;
}

.chat-box-head {
    padding: 10px 15px;
    border-bottom: 2px solid #A12EB3;
    background-color: #B25AE5;
    color: #fff;
    text-align: center;
}

.chat-box-left {
    width: 100%;
    height: auto;
    padding: 15px;
    -webkit-border-radius: 5px;
    -moz-border-radius: 5px;
    border-radius: 5px;
    position: relative;
    border: 1px solid #C5C5C5;
    font-size: 12px;
    border: 2px solid #73AD21;
    border-radius: 25px;
}

.chat-box-left:after {
    top: 100%;
    left: 10%;
    border: solid transparent;
    content: " ";
    position: absolute;
    border-top-color: #C5C5C5;
    border-width: 15px;
    margin-left: -15px;
}

.chat-box-name-left {
    margin-top: 30px;
    margin-left: 60px;
    text-align: left;
    color: #049E64;
}

.chat-box-name-left img {
    max-width: 40px;
    border: 2px solid #049E64;
}

.chat-box-right {
    width: 100%;
    height: auto;
    padding: 15px;
    -webkit-border-radius: 5px;
    -moz-border-radius: 5px;
    border-radius: 5px;
    position: relative;
    border: 1px solid #C5C5C5;
    font-size: 12px;
}

.chat-box-right:after {
    top: 100%;
    right: 10%;
    border: solid transparent;
    content: " ";
    position: absolute;
    border-top-color: #C5C5C5;
    border-width: 15px;
    margin-left: -15px;
}

.chat-box-name-right {
    color: #354EA0;
    margin-top: 30px;
    margin-right: 60px;
    text-align: right;
}

.chat-box-name-right img {
    max-width: 40px;
    border: 2px solid #354EA0;
}

.chat-box-footer {
    background-color: #D8D8D8;
    padding: 10px;
}

Here my requirement is to automatically set the width of each box(div) as per the content entered and float them accordingly to left/right.
Currently my output is as below.

Here as seen in the above screenshot, though there is only one word in the div, it is taking the entire width. Please let me know on how can I limit this to the text width.
Thanks
Comment: Set the display of the `` tag to `inline-block` instead of `block` which is its default value
Answer: try this https://plnkr.co/edit/KXF1jkOd7G9JB8j7DIGC
I have changed the div to span. Hope this helps !
Hello, Welcome!. You can ask me
    questions on Compliance Policy ..

Answer: Are you looking some thing like this, Try this add display: inline-block; to div

.hr-clas {
    border-top: 1px solid #A12EB3;
}

.chat-box-main {
    height: 400px;
    overflow-y: auto;
}

.chat-box-div {
    border: 2px solid #A12EB3;
    border-bottom: 2px solid #A12EB3;
}

.chat-box-head {
    padding: 10px 15px;
    border-bottom: 2px solid #A12EB3;
    background-color: #B25AE5;
    color: #fff;
    text-align: center;
}

.chat-box-left {
    width:auto;
    height: auto;
    padding: 35px;
    -webkit-border-radius: 5px;
    -moz-border-radius: 5px;
    border-radius: 5px;
    position: relative;
    border: 1px solid #C5C5C5;
    font-size: 12px;
    border: 2px solid #73AD21;
    border-radius: 25px;
  display: inline-block;

}

.chat-box-left:after {
    top: auto;
    left: 10%;
    border: solid transparent;
    content: " ";
    position: absolute;
    border-top-color: #C5C5C5;
    border-width: 15px;
    margin-left: -15px;
}

.chat-box-name-left {
    margin-top: 30px;
    margin-left: 60px;
    text-align: left;
    color: #049E64;
}

.chat-box-name-left img {
    max-width: 40px;
    border: 2px solid #049E64;
}

.chat-box-right {
    width:auto;
    height: auto;
    padding: 35px;
    -webkit-border-radius: 5px;
    -moz-border-radius: 5px;
    border-radius: 5px;
    position: relative;
    border: 1px solid #C5C5C5;
    font-size: 12px;
  display: inline-block;
}

.chat-box-right:after {
    top: 100%;
 display: inline-block;   right: 10%;
    border: solid transparent;
    content: " ";
    position: absolute;
    border-top-color: #C5C5C5;
    border-width: 15px;
    margin-left: -15px;
}

.chat-box-name-right {
    color: #354EA0;
    margin-top: 30px;
    margin-right: 60px;
    text-align: right;
}

.chat-box-name-right img {
    max-width: 40px;
    border: 2px solid #354EA0;
}

.chat-box-footer {
    background-color: #D8D8D8;
    padding: 10px;
}

Hello, Welcome!. You can ask me
        questions on Compliance Policy ..

         - Bot

Hi

Hello

        - Bot


Proof of the square root inequality $2\sqrt{n+1}-2\sqrt{n}<\frac{1}{\sqrt{n}}<2\sqrt{n}-2\sqrt{n-1}$

Question: I stumbled on the following inequality: For all $n\geq 1,$
$$2\sqrt{n+1}-2\sqrt{n}<\frac{1}{\sqrt{n}}<2\sqrt{n}-2\sqrt{n-1}.$$
However I cannot find the proof of this anywhere.
Any ideas how to proceed?
Edit: I posted a follow-up question about generalizations of this inequality here:
Square root inequality revisited
Comment: everytime you see $(n+1)^a - n^a$ think to $a \int_n^{n+1}x^{a-1}dx$
Comment: See also [Proof of inequality $2(\sqrt{n+1}-\sqrt{n}) < \frac{1}{\sqrt{n}} < 2(\sqrt{n} - \sqrt{n-1})$ using induction](http://math.stackexchange.com/questions/263115/proof-of-inequality-2-sqrtn1-sqrtn-frac1-sqrtn-2-sqrtn)
and [Proof by Induction: $2(\sqrt{n+1} - \sqrt{n}) < \frac{1}{\sqrt{n}} < 2(\sqrt{n}-\sqrt{n-1})$](http://math.stackexchange.com/questions/1139563/proof-by-induction-2-sqrtn1-sqrtn-frac1-sqrtn-2-sqrtn).
It can also be found as the first step in [this proof](http://math.stackexchange.com/questions/1211973/estimating-partial-sums-sum-n-1m-frac1-sqrtn/1211980#1211980)
Answer: $f(x)=\frac{1}{\sqrt{x}}$ is a decreasing function on $\mathbb{R}^+$, hence:
$$ 2\sqrt{n+1}-2\sqrt{n}= \int_{n}^{n+1}\frac{dx}{\sqrt{x}} \leq \frac{1}{\sqrt{n}} $$
as well as
$$ 2\sqrt{n}-2\sqrt{n-1}=\int_{n-1}^{n}\frac{dx}{\sqrt{x}}\geq \frac{1}{\sqrt{n}}.$$
Answer: $$2\sqrt{n+1}-2\sqrt{n}=2\left(\sqrt{n+1}-\sqrt{n}\right)=$$
$$=\frac2{\sqrt{n+1}+\sqrt{n}}<\frac{1}{\sqrt{n}} \Leftrightarrow$$
$$\Leftrightarrow 2\sqrt n<\sqrt{n+1}+\sqrt{n}\Leftrightarrow\sqrt n< \sqrt{n+1}$$
Answer: \begin{align*}
2\sqrt{n+1}-2\sqrt{n} &= 2\frac{(\sqrt{n+1}-\sqrt{n})(\sqrt{n+1}+\sqrt{n})}{(\sqrt{n+1}+\sqrt{n})} \\
&= 2\frac{1}{(\sqrt{n+1}+\sqrt{n})} \\
&< \frac{2}{2\sqrt{n}} \text{ since } \sqrt{n+1} > \sqrt{n}\\
&=\frac{1}{\sqrt{n}}
\end{align*}
Similar proof for the other inequality.
Comment: @Roby5 - calm down. It usually takes far more than 5 minutes to compose even a short post like this one. Don't berate people because someone else has the same basic idea (very common at this level of mathematics) and happened along a few minutes earlier. Such posts are only unacceptable when the later poster clearly had time to see the other post before they started their own.
Comment: 5 minutes time lag for a nearly copied answer is not accepted, even if you are on a slow network. This way someone can answer any question on this site, claiming they saw it only after their answer was posted.
Comment: I think this is a copy of Roman83 's answer.
Comment: I saw the answer only after I posted mine.
Answer: Let $f(x)=2\sqrt{x}$. Using mean value theorem we get
$$\frac{f(n+1)-f(n)}{(n+1)-n} = f'(c)$$
for some $c \in (n, n+1)$. Equivalently
$$2\sqrt{n+1} - 2\sqrt{n} = \frac{1}{\sqrt c}.$$
Since $c>n$, $$\frac{1}{\sqrt c} < \frac{1}{\sqrt{n}},$$
therefore
$$2\sqrt{n+1}-2\sqrt{n} < \frac 1{\sqrt n}.$$
Right inequality can be proved in a similar manner.
Answer: As $\sqrt n>0,$
$$2\sqrt{n+1}-2\sqrt{n}<\frac{1}{\sqrt{n}}\iff2\sqrt{n(n+1)}-2n<1$$
$$\iff2\sqrt{n(n+1)}<2n+1$$
Squaring we get
$$4(n^2+n)<(2n+1)^2=4n^2+4n+1\iff 1>0$$ which is true.
Can you follow the same method for the other inequality?
Comment: Yes, for sure. Thank you.
Answer: $$2\sqrt{n+1}-2\sqrt{n}<\frac{1}{\sqrt{n}}<2\sqrt{n}-2\sqrt{n-1}\iff\sqrt{n^2+n}-n\lt\frac 12\lt n-\sqrt{n^2-1}$$
 Put $X=n+\frac 12$ and $Y=n-\frac 12$ so you get the evidences
$$\sqrt{X^2-\frac 14}\lt X\iff X^2-\frac 14\lt X^2$$ and $$\sqrt{Y^2-\frac 14}\lt Y\iff Y^2-\frac 14\lt Y^2$$


WCF Service reference type property to be modified before serialization

Question: Let's say that we have following Service, with two operation contracts.
[ServiceContract(SessionMode = SessionMode.Required, CallbackContract = typeof(IServiceCallback))]
public interface IService : IDisposable
{
    [OperationContract]
    [ServiceKnownType(typeof(ServiceProperty))]
    [FaultContract(typeof(ServiceMethodFaultException))]
    [ServiceKnownType(typeof(object[]))]
    ServiceProperty GetServicePropertyAbc();

    [OperationContract]
    void ModifyServicePropertyAbc();
}

And the service that is implementing the IService:
public class ServiceBase : IService
{
   ServiceProperty abc;

   public ServiceProperty GetServicePropertyAbc()
    {
          //somelogic
          return abc;
    }

   public void ModifyServicePropertyAbc()
   {
    abc = new ServiceProperty();
    abc.SomeProperty = 100 * 100;
   }
}

And we have:

"Client 1" that use the ServiceBase as a proxy
"Client 2" that use the ServiceBase as a proxy

Service-host is the same for both of the clients.
And there's following scenario:

Step 1 GetServiceProperty() is being called by "Client 1" with success
Step 2 GetServiceProperty() returns abc;
Step 3 abc is being serialized to XML
Step 4 "Client 1" is getting the XML response

Is there possibility that that between Step 2 and Step 3 the "Client 2" could have modify the ServiceProperty abc with ModifyServicePropertyAbc() so the "Client 1" would have modified "abc"??
Let's assume that there's logic in GetServicePropertyAbc() method which makes lock on abc (our code is 100% thread safe but we're afraid what when we're going out of the GetServiceProperty() scope).
I'm just wondering if there's possibility that ServiceProperty abc can be modified between Step 2 and Step 3 or WCF guarantess that It won't be modified??
ServiceProperty is a reference type and it is really complex (cannot be replaced with the value type).
Answer: Most likely scenario is that since you have on your service contract that each time you make a call you are creating a new instance of your service. The IsInitiating attribute defaults to true for session based services so each time you call you start with a new instance.
SessionMode = SessionMode.Required


how to search a regular expression under path?

Question: how to search a regular expression under path?
eg, I want to find all files which contain 'UPDATE player', under path /Users/Document/.
Comment: I think this question would be more topical for superuser.com. If enough other users agree with me it will be migrated there automatically.
Answer: find /Users/Document | xargs grep your_regex

Comment: I read that question as "files which contain", not files that are named.
Answer: grep -rl 'UPDATE player' /Users/Document/


Sending yourself a copy of the email

Question:
I m using Drupal 7 with the Webform module to send email. On a form I have checkbox to send yourself an email copy. When it is checked, there will be a field to enter the email of who sends the email. The email should be send to this address also.
Comment: Hello, Please share whatever you have worked on this and what issue you have found.
Comment: I ve create a web form to send mail to website admin and it has some fields like name, sender mail,body and i ve check box whether to send this webform content to your mail address,if the user checked on it and submit it the content should sent to both user and the admin
Answer: I created a custom module for this functionality. This module file used for creating a send a copy of message to me functionality

function sendmail_webform_form_alter(&$form, &$form_state, $form_id) {
     error_reporting(E_ALL);
     ini_set('display_errors', 1);
     // webform_client_form_52  webform id
     if($form_id == 'webform_client_form_52') {
         $form['submitted']['send_a_mail_yourself'] = array(
         '#type' => checkbox,
         '#form_key' => 'send_a_mail_yourself',
         '#title'=> 'Send a copy of yourself',
         '#weight' => 4, // As your needed
         '#field_prefix' => '
',
         '#field_suffix' => '
',
         '#default_value' => array('yes' => t('send a copy of yourself')),
       );
       $form['#submit'][] = '_sendmail_webform_submit';

       }
     }

   function _sendmail_webform_submit($form, &$form_state) {
     $param = array();
     foreach($form_state['input']['submitted'] as $key => $values) {
        if(valid_email_address($values)) {
             $to = $values; //to email address
        }
        else if($key == 'send_a_mail_yourself' && $values == 1) {
              $send_a_mail = $values;  // Check send a mail to yourself checkbox

        } else {
          if($values) {
               $param[]  = $values;  // All remaining values to store to param array for use of email body
          }
        }
       }

          if($send_a_mail == 1) {
         $from = 'email@example.com';
                 foreach($param as $param_values) {
            $body[] = $param_values;
           }

        $to = $to; // Set this email address - emails will be sent to this email address!
        $params = array(
            'body' => $body,
            'subject' => 'Website Information Request',
     );
        if (drupal_mail('sendmail_webform', 'some_mail_key', $to, language_default(), $params, $from, TRUE)) {
            drupal_set_message('Thanks, we will be in contact with more information soon.');
     } else {
            drupal_set_message('There was an error subscribing you. Please try again later');
        }

    }
  }

 function sendmail_webform_mail($key, &$message, $params) {
     $headers = array(
         'MIME-Version' => '1.0',
         'Content-Type' => 'text/html; charset=UTF-8;',
         'Content-Transfer-Encoding' => '8Bit',
         'X-Mailer' => 'Drupal'
    );
    foreach ($headers as $key => $value) {
         $message['headers'][$key] = $value;
    }
      $message['subject'] = $params['subject'];
      $message['body'] = $params['body'];
 }

Answer: There are two types -  Custom and Component, if You select custom you can write your own like: email@example.com. For Component - the submitted form field value will send email. For your requirement simply add another email custom : email@example.com

Sending yourself a copy of the email


Javascript sobrescrevendo class css

Question: Ao usar uma função em javascript em dois selects populados, ele sobrescreve o css ocultando seus valores e atribuindo outra classe, conforme imagens a seguir:
Antes de usar a função:

Ao clicar no primeiro select e escolher uma opção:

Inspecionando o elemento no navegador:

Ele atribuiu o display: none e utilizou de outras classes do css para fazer essa bagunça. Ao utilizar css para atribuir display: visible !important ele reaparece porém mostra dois selects:

Não estou conseguindo resolver:
Havendo necessidade deixo o código javascript aqui!
Código javascript:
$(document).ready(function() {

    $(".select1").change(function() {
        var proxima_turma = <?php echo json_encode($proxima_turma); ?>;
        var antiga_turma = <?php echo json_encode($antiga_turma); ?>;

        var valor = $(this).val();
        var select = $(this).closest("tr").find(".select2"); // busca o select2 da mesma linha

        if (valor == "") {
            select
            .html("")
            .append("<option value=''> Selecione </option>");

        } else if (valor == "<?php echo $class_id_to;?>") {
            select.html("");

            for(var i = 0; i < proxima_turma.length; ++i) {
                select.append("<option value='" + proxima_turma[i]['section_id'] + "'>" + proxima_turma[i]['name'] + "</option>");
            }

        } else if (valor == "<?php echo $class_id_from; ?>") {

            select.html("");

            for(var i = 0; i < antiga_turma.length; ++i) {
                select.append("<option value='" + antiga_turma[i]['section_id'] + "'>" + antiga_turma[i]['name'] + "</option>");
            }
        }
    });

});

Código do select:
<select <?php if ((($transferidos != null) && ($evadidos != null)) OR (($transferidos != null) || ($evadidos != null))) ?>
class="form-control selectboxit select2" <?php if (!$disableSelect) { ?>
name="promotion_status2_<?php echo $row['student_id'];?>" style="width: 40px;"
<?php } ?> >
<?php if ((($transferidos != null) && ($evadidos != null)) OR (($transferidos
 != null) || ($evadidos != null))) { ?>
 <option value="null" selected></option>
 <?php }else{
?>
<option value="">selecione</option>
</select>

Comment: Coloca seu javascript também, para sabermos o que ele está fazendo.
Answer: Pela aparência e pela classe .selectboxit você está usando um plugin chamado SelectBoxIt, e ele possui um método próprio para popular o select adicionando novos options. Se você adicionar options diretamente no select sem chamar o método .add() do plugin, não vai fazer nenhum efeito, porque o select original é escondido pelo plugin e criado um pseudo-select customizado no lugar.
Para remover todos os options você usa:
select.data("selectBox-selectBoxIt").remove();

Para adicionar novos, após o .append, você usa:
select.data("selectBox-selectBoxIt").add();

Seu código irá ficar assim:
$(document).ready(function() {

    $(".select1").change(function() {
        var proxima_turma = <?php echo json_encode($proxima_turma); ?>;
        var antiga_turma = <?php echo json_encode($antiga_turma); ?>;

        var valor = $(this).val();
        var select = $(this).closest("tr").find(".select2"); // busca o select2 da mesma linha

         var box = select.data("selectBox-selectBoxIt");
         box.remove();

        if (valor == "") {
            select.append("<option value=''> Selecione </option>");
        } else if (valor == "<?php echo $class_id_to;?>") {
            for(var i = 0; i < proxima_turma.length; ++i) {
                select.append("<option value='" + proxima_turma[i]['section_id'] + "'>" + proxima_turma[i]['name'] + "</option>");
            }
        } else if (valor == "<?php echo $class_id_from; ?>") {
            for(var i = 0; i < antiga_turma.length; ++i) {
                select.append("<option value='" + antiga_turma[i]['section_id'] + "'>" + antiga_turma[i]['name'] + "</option>");
            }
        }

        box.add();
    });

});

Veja em funcionamento:

$(document).ready(function() {

   $(".select2").selectBoxIt();

    $(".select1").change(function() {
        var proxima_turma = [{"section_id": 11, "name": "Maneta"},{"section_id": 12, "name": "Baqueta"}];
        var antiga_turma = [{"section_id": 13, "name": "Guimeta"},{"section_id": 14, "name": "Fusqueta"}];

        var valor = $(this).val();
        var select = $(this).closest("tr").find(".select2"); // busca o select2 da mesma linha

         var box = select.data("selectBox-selectBoxIt");
         box.remove();

        if (valor == "") {
            select
            .append("<option value=''> Selecione </option>");

        } else if (valor == 1) {

            for(var i = 0; i < proxima_turma.length; ++i) {
                select.append("<option value='" + proxima_turma[i]['section_id'] + "'>" + proxima_turma[i]['name'] + "</option>");
            }

        } else if (valor == 2) {

            for(var i = 0; i < antiga_turma.length; ++i) {
                select.append("<option value='" + antiga_turma[i]['section_id'] + "'>" + antiga_turma[i]['name'] + "</option>");
            }
        }

        box.add();
    });

});

<link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/themes/smoothness/jquery-ui.css">

<link type="text/css" rel="stylesheet" href="https://gregfranko.com/jquery.selectBoxIt.js/css/jquery.selectBoxIt.css" />

         <select class="select1">
            <option value="">Selecione...</option>
            <option value="1">1</option>
            <option value="2">2</option>
         </select>

         <select class="form-control selectboxit select2">
            <option value=''> Selecione </option>
         </select>

         <select class="select1">
            <option value="">Selecione...</option>
            <option value="1">1</option>
            <option value="2">2</option>
         </select>

         <select class="form-control selectboxit select2">
            <option value=''> Selecione </option>
         </select>

Javascript sobrescrevendo class css


Express $C$ interms of the sets $A_n$

Question: [NBHM_2006_PhD Screening Test_Analysis]

Let $f$ be a real valued function on $\mathbb{R}$ define
  $$w_j(x)=\sup\{|f(u)-f(v)|: u,v\in [x-1/j,x+1/j]\}$$ $j\in \mathbb{N}$
  and $x\in\mathbb{R}$, Define next
  $$A_{j,n}=\{x\in\mathbb{R}:w_j(x)<1/n\}$$ $n=1,2,\dots$ and
  $$A_n=\bigcup_{j=1}^{\infty}A_{j,n}$$ Now let $$C=\{x\in\mathbb{R}: f
> \text{ is continuos at }x\}$$ How to express $C$ interms of $A_n$?

Well, according to the definition, $f$ iss continuos at $x$ iff $w_j(x)=0$ (I guess, I can do that by definition of continuity).
Then I guess, $C=\bigcap A_n$. I am not sure.
Thank you.
Answer: $\def\abs#1{\left|#1\right|}$
Hi, you are right about $C$. We have for $x \in \mathbb R$:
\begin{align*}
   f \text{ is continuous at } x &\iff \forall n \exists j \forall y: \abs{x-y} \le \frac 1j \Rightarrow \abs{f(x) - f(y)} < \frac 1n\\
   &\iff \forall n \exists j :\sup_{\abs{x-y} \le \frac 1j} \abs{f(x)-f(y)} < \frac 1n\\
   &\iff \forall n \exists j: w_j(x) < \frac 1n\\
   &\iff \forall n \exists j :x \in A_{j,n}\\
   &\iff x \in \bigcap_n \bigcup_j A_{j,n}
 \end{align*}
Comment: thank you martini for making thessse precise :)

Express $C$ interms of the sets $A_n$


Putting additional functionality for Commerce Files/License

Question: I am making a files selling website with Drupal 7.41. Using the Commerce Files / Commerce License Modules, I have been able to setup the after payment completes, allow file download functionality.
However the files that becomes available to download is just the raw file.
I want the file, which becomes available for download to be a zip/tar file which consists the

File sold
A simple readme.txt
A pdf file consisting license information, made for that particular user transaction. Like Envato!

Is this automation possible?
Can anybody please guide me on how I may be able to achieve this? Even pointing out the path would be helpful!
Answer: Here's what you need to get started.
You'll need to create a new license type and extend the CommerceLicenseBase class (or the file class). When your license class (whose parent class is CommerceLicenseBase) gets activated, the ->activate() method ends up calling ->save(). Your new class will implement ->save() and within that function you can:

Generate a PDF.
Generate or load a README.txt.
Create a Zip file.
Store that file and attach it to some entity, email it, etc.
Comment: Hi,
Thank you for pointing out the way! This looks achievable!
Will update the post after getting it done!
Thanks a lot!


External Excel lib for C# to run macros

Question: Do you know any external MS Excel library for C# (it should work without MS Office installed on machine) which has possibility to run macros?
It's possible to run it with "Microsoft.Office.Interop.Excel", but for that you need MS Office.
The scenario: I have MS Excel file template with macro. Adding part of the data programmatically to that template, running macro which was wrote to excel template, adding another part of data.
Thanks in advance!
Answer: NPOI is a great tool and is Open Source:
NPOI
Comment: I haven't found any method to run macros with this library. If there exists a ability to do that, could you give me a hint?
Comment: NPOI does not support macros. See this post (http://stackoverflow.com/questions/6937777/how-to-call-a-macro-from-apache-poi-library-in-java)

External Excel lib for C# to run macros


Validando evento com o operador `?`

Question: Estava implementando um método para lançar o evento PropertyChanged do INotifyPropertyChanged. Eu fiz a validação do evento de forma tradicional, ou seja, com if (PropertyChanged != null). Porém o VS me sugeriu uma forma mais enxuta que é PropertyChanged?.Invoke ( this, new PropertyChangedEventArgs ( propertyName ) );.
É óbvio que o código é autoexplicativo, ou seja, "Se PropertyChanged não for nulo, execute o método Invoke". Porém queria saber como se chama esse recurso para que eu possa pesquisar mais informações sobre ele.
Answer: Se chama "Null-Condicional operator". Mais informações aqui:
https://msdn.microsoft.com/en-us/library/dn986595.aspx
Comment: Esse link pode ser uma boa sugestão, mas sua resposta não terá validade se um dia o link deixar de funcionar. Além disso, é importante para a comunidade ter conteúdo aqui no site mesmo. Seria melhor incluir mais detalhes na sua resposta. Um resumo do conteúdo do link já ajudaria bastante! Saiba mais sobre o assunto neste item do nosso FAQ da Comunidade: [Queremos respostas que contenham somente links?](http://meta.pt.stackoverflow.com/q/42/74)

Validando evento com o operador `?`


Unable to make SIP calls using realtime with asterisk server

Question: I am unable to make SIP calls to a Realtime SIP peer,but i am able to receive calls from them.I have made some test users using the sip.conf file,the calling operations work fine when i use them.But when i call a realtime sip peer the server disconnects by itself.
My sip peer is as follows:

id  7006
                            name  edwin
                     canreinvite  yes
                         context  internal
                            host  dynamic
                             nat  force_rport
                            port  63806
                         qualify  no
                          secret  123
                            type  friend
                        disallow  all
                           allow  g729
                           allow  ilbc
                           allow  gsm
                           allow  ulaw
                           allow  alaw
                      regseconds  1577676814
                          ipaddr  192.168.123.122
                  cancallforward  yes
                            avpf  yes
                      allowguest  no
                    allowoverlap  no
                       srvlookup  yes
                        localnet  192.168.1.0/255.255.255.0
                        bindport  5060
                        bindaddr  0.0.0.0
                      soft_skill  32
                  rtcachefriends  yes
                alwaysauthreject  yes
                  session-timers  refuse

When i call this user from the user i made in my sip.conf file(shown below)  the server disconnects automatically:
[general]
context=internal
allowguest=no
allowoverlap=no
srvlookup=yes
bindport=5060
bindaddr=0.0.0.0
allow=ulaw
alwaysauthreject=yes
canreinvite=no
nat=force_rport
session-timers=refuse
localnet=192.168.1.0/255.255.255.0

[7001]
type=friend
host=dynamic
secret=123
qualify=yes
context=internal

[7002]
type=friend
host=dynamic
secret=456
qualify=yes
context=internal

[7003]
type=friend
host=dynamic
secret=789
qualify=yes
context=internal

I have enabled logging and the output is as follows:

console dial edwin@internal
  [Dec 30 03:40:46] WARNING[18968]: chan_oss.c:498 setformat: Unable to re-open DSP device /dev/dsp: No such file or directory
  [Dec 30 03:40:46] NOTICE[18968]: console_video.c:136 console_video_start: voice only, console video support not present
  pranav*CLI>
  Disconnected from Asterisk server
  Asterisk cleanly ending (0).
  Executing last minute cleanups

My Extensions table in my psql table is:
"2";"internal";"edwin";2;"Dial";"SIP/edwin,60"
"1";"internal";"edwin";1;"Answer";" "
"3";"internal";"edwin";3;"Playback";"vm-nobodyavail"
"4";"internal";"edwin";4;"Hangup";" "

So,how do i fix this so that i can receive calls using the user 'edwin'?
Comment: Can you confirm if db  is connected? and Asterisk can read peers? try to execute `sip show peer edwin`
Comment: @NasirIqbal yah it is connected.the above details of the peer are obtained by executing 'sip show'.
Answer: First of all, probably you are running a VM or said machine does not have a sound card, So it is not appropriate to use the console dial command. Instead dial from a softphone or use originate command like
originate SIP/edwin application wait 11

If it does not solve your problem then there are multiple things which can make a user unreachable.

Ping both machines from each other to check if network is reachable
Make sure that can register option is enabled in client/softphone
Also test that asterisk can write to peer table. these entries should be changed on every new registration attempt (try from different hosts)

port 63806
ipaddr 192.168.123.122
regseconds 1577676814

Set qualify=yes to keep the registration/connection alive
Comment: hey thanks,i updated my asterisk and it seems to work fine now..also changed qualify to yes.


How to know if two lines are parallel in three-dimensional space?

Question: How can we easily see that these two lines are not parallel? I normally compare the direction numbers to see if they are not a multiple of each other, but here I can not directly see the direction numbers of line F.
$D: \frac{x+1}{4}=3-y=\frac{1-z}{3}$
$F:\left\{\begin{array}{l}x-2 y+2 z=3 \\ 3 y-z=7\end{array}\right.$
Comment: Line $F$ is the intersection of two planes, so one way to get a vector parallel to its direction is to take the cross product of the normal vectors of the two planes.
Comment: You may eliminate the $z$ in $x-2y+2z=3$, and get one equation linking $x$ and $y$, and another linking $y$ and $z$. Then $F$ may be manipulated to have a form like $D$.
Answer: $M=(x,y,z)\in D \iff \begin{cases}x+1=4(3-y) \\3(x+1)=4(1-z) \end{cases} \iff \begin{cases}x=11-4y \\z=-8+3y \end{cases} \iff M\in (11,0,-8)+\mathbb R(-4,1,3)$
$M=(x,y,z)\in F \iff \begin{cases} x-2y+2z=3\\3y-z=7 \end{cases} \iff \begin{cases} x=17-4y\\z=-7+3y\end{cases} \iff M\in (17,0,-7)+\mathbb R(-4,1,3)$
$D$ and $F$ are parallel : they have the same direction, $\mathbb R(-4,1,3)$.


Adicionar funcionalidades Datatable no Laravel 5.4 com AdminLTE

Question: Boa noite senhores, Recentemente iniciei um projeto a fim de me atualizar com o laravel 5.4, criei um projeto e estou usando o adminLTE para o layout. A questão é, esse AdminLTe tem um modelo de tabela que eu quero usar. porém eu não estou conseguindo usar todas as funções dela. Tenho quase certeza de que estou fazendo o retorno dos dados no controller de forma errada, errado também imagino que esteja a forma que eu injeto os dados na tabela. Segue imagem e códigos dos arquivos. Alguem sabe me dizer onde eu estou errando?

repare que as funcionalidades de ordenação não estao disponiveis, nem search ou mesmo as informações dos registros e paginação.
Agora os codigos:
minha view home.blade.php

$(function () {
    $('#example').DataTable({
      "paging": true,
      "lengthChange": false,
      "searching": false,
      "ordering": true,
      "info": true,
      "autoWidth": false
    });
  });
@section('content')

  <link rel="stylesheet" href="{{base_path('public/bower_components/AdminLTEbootstrap/css/bootstrap.min.css')}}">

  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.5.0/css/font-awesome.min.css">

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

  <link rel="stylesheet" href="{{base_path('public/bower_components/AdminLTE/plugins/datatables/dataTables.bootstrap.css')}}">

  <link rel="stylesheet" href="{{base_path('public/bower_components/AdminLTE/dist/css/AdminLTE.min.css')}}">

  <link rel="stylesheet" href="{{base_path('public/bower_components/AdminLTE/dist/css/skins/_all-skins.min.css')}}">

Hover Data Table

                  Ação
                  Nome
                  Descrição

                @foreach ($permissao as $permissao)

                  <form action="{{route('permissao.destroy',$permissao->id)}}" method="post">
                    id}}/edit" title="Editar registro" class="btn btn-warning glyphicon glyphicon-pencil">
                      {{ method_field('DELETE') }}
                      {{ csrf_field() }}
                      <button type="submit" class="btn btn-danger glyphicon glyphicon-remove " title="Excluir registro"></button>

                   {{ $permissao->nome }}
                   {{ $permissao->descricao }}
                  </form>

    @endforeach

@endsection()

Meu PermissaoController
public function index()
{
    $caminhos = [
          ['url'=>'/admin','titulo'=>'Início'],
          ['url'=>'here','titulo'=>'Permissões']
          ];
    $permissao = Permissao::orderBy('created_at', 'desc')->paginate(10);
    return view('permissoes.home', compact('permissao', 'caminhos'));
}

Minha rota
Route::resource('permissao', 'PermissaoController');

Acho que não esqueci de nada.
Answer: Depois de uma boa noite de sono, tudo fica mais claro.
Na verdade, além de estar declarando os caminhos dos js e css fora do  da pagina. Os caminhos estavam errados, eu estava usando a variavel errada.

<link rel="stylesheet" href="{{asset("/bower_components/AdminLTEbootstrap/css/bootstrap.min.css")}}">


Expected value elimination tournament

Question: Wouldn't it just be 2 since that's the second highest?
Comment: Must 2 always play in the final? Could 2 be eliminated in the first round?
Comment: How 'random' is the placement?
Answer: Hint: the eight players are divided into two brackets of four. the lowest number of each brackets will advance to the final. since one bracket contains $1$, the question is reduced to finding expected value of lowest number if we take 4 numbers from $2,3,...8$
answer is $2.6$ btw
Answer: Well clearly, 8 can't be in the finals. Similarly, 7 can't be in the finals either because there has to be 3 people worse than 7 in the bottom half assuming that 1 is in the top half. We can narrow this down to the fact that 5 is the lowest ranking player that can make it to the finals.
We will use the definition of expectation which is
\begin{align*}
\sum_x xP(X = x)
\end{align*}
To calculate the probability that 5 is in the finals, we have to calculate the probability that the bottom bracket is just 5,6,7,8. That is quite simple. That is
\begin{align*}
\frac{{4 \choose 4}}{{7 \choose 4}} = \frac{1}{35}
\end{align*}
The probability that 4 is in the finals is
\begin{align*}
\frac{{1\choose 1}{4 \choose 3}}{{7 \choose 4}} = \frac{4}{35}
\end{align*}
The probability that 3 is in the finals is
\begin{align*}
\frac{{1\choose 1}{5 \choose 3}}{{7 \choose 4}} = \frac{10}{35}
\end{align*}
The probability that 2 is in the finals is
\begin{align*}
\frac{{1\choose 1}{6 \choose 3}}{{7 \choose 4}} = \frac{20}{35}
\end{align*}
Therefore the expected value is
\begin{align*}
5 \times \frac{1}{35} + 4 \times \frac{4}{35} + 3 \times \frac{10}{35} + 2\times \frac{20}{35}
\end{align*}
Comment: check this one https://math.stackexchange.com/a/3596825/751970 . you may be interested to find that Your answer equals  $1+(n+1)-\frac{k}{k+1}(n+1)$ for $n=7$ and $k=4$

Expected value elimination tournament


10 Coins being tossed and calculating certain probabilities

Question: Last lecture the professor addressed us with a problem that I I'v may misunderstood but I am certain it is one of the two .
In both problems we have 10 regular (no biased) coins on a table , and we wish to flip them .
In the first version of the problem let us assume we are flipping them all at the same time , so we consider the first flip as a flip for all the coins together .
Now after each flip , the coins that land heads will be removed of the group (like collected) , the question is , find the Probability that we would have collected all the 10 coins by the x-th flip , so the random variable X is the number of flips needed .
My approach was a bit simple even though the professor said it was a hard problem .  I first found the probability that X is bigger than a value x , which means it took at least more than x trails to collect all the coins , now I related this expression to "at least one coin failed x times" which is shallowly calculated P(X>x) = 10 * 0.5^x    , the 10 being that we have 10 possible coins to choose from to fail in general .
Then we obtain P(X=x) = P(X>x-1)-P(X>x) = 10*0.5^(x-1) .
Any thoughts on why my supposition and answer is incorrect , and if you can , a detailed explanation to your method .
The second version of this problem is that we count the singular flips on each coin aside instead of one big flip on the group , which is impossible so I'm putting my bet that the first version of the problem is the correct one .
Answer: The probability that a single coin comes up $T$ $x$ times in a row is exactly $.5^x$.  Therefore the probability that this one coin comes up $H$ at least once in $x$ flips is $1-.5^x$.  It follows that the probability that $10$ independent coins all come up $H$ at least once in $x$ flips is $(1-.5^x)^{10}$.
Your starting remark isn't correct.  Knowing that one coin survives with probability $p$ does not imply that at least one of $10$ survives with probability $10p$.  Think, for example, about throwing $10$ coins once....the probability that one comes up $T$ is $\frac 12$ but it is clearly false to say that this means that the probability that at least one comes up $T$ is $10\times \frac 12= 5$. The trouble is that you are counting cases repeatedly (you count the case where the first two come up $T$ at least twice, once for the first coin and again for the second).
Comment: You are correct on the point that I am counting cases over and over again but in your answer aren't you like ignoring the fact that we are removing some coins before others and shouldn't we take into account any of those changes ? Like will your method only count the number of times until every coin has shown heads once ? Or will it count cases like : x=2 ,  and in the first and second throw all the coins show success , which shouldn't be the case or else x would have been 1
Comment: I am pretending that each coin is tossed $x$ times...of course, we know that each coin is "removed" after $H$ comes up.  I am just distinguishing between "strings of length $x$ in which $H$ comes up at least once" and "the string of $x$ $T's$."  All of the first sort are removed exactly once.
Comment: Yes but what do you think would be the solution to my problem
Comment: My solution works for your problem!  You remove any coin that comes up $H$ at least once in $x$ trials.  Doesn't matter which of the $x$ trials comes up $H$.  Doesn't matter if it "would have" come up $H$ more than once.
Comment: My advice:  go through my calculation carefully for a modest sized $x$, say $x=4$.  I am claiming that the probability that a coin comes up $H$ at least once in $4$ trials is $1-.5^4=\frac {15}{16}$, because the only alternative is $TTTT$.   Check that this is the same as what you want.  You remove $H$ (prob $\frac 12$) and $TH$ (prob $\frac 14$) and $TTH$ (prob $\frac 18$) and $TTTH$ (prob $\frac 1{16}$).  Hence the probability of removal is $\frac 12 +\frac 14+\frac 18 + \frac 1{16}=\frac {8+4+2+1}{16}=\frac {15}{16}$.
Comment: About your formula , if you the summation with x going to infinity (I used 30 as infinity) you get way more than 1
Comment: Why on earth would you add them up?  That doesn't represent the probability of any event, so there's no reason at all for the sum to be bounded by $1$.  Of course, it makes sense to let $x$ tend to $\infty$....but then you get $1$ as you'd expect (if you toss the coin infinitely often you are sure to get $H$ at some point).
Comment: Shouldn't the events be connected to each other and add up to the certain event ? Yet again your argument makes sense , that the probability of x goes to infinity is 1
Comment: The events are not mutually exclusive, so the probabilities do not add.  The event "each coin has come up $H$ at least once in $5$ flips" contains  the event "each coin has come up $H$ at least once in $4$ flips".  You can only add the probabilities of mutually exclusive events.
Comment: I guess I came to understand the reason for mutual exclusion , I will consult my professor and reply again
Answer: Found the answer , we start by considering cumulative probabilities , Probability that X is smaller than a number x means at least one H in x times , which is the complement of no H's . So P(X<=x) = (1-0.5^x)^10
Thus P(X=x)=P(X<=x)-P(X<=(x-1))


How do you develop the ability to express yourself via your instrument (e.g. guitar for my case)

Question: I understand this question may be very broad and the answer may be very complex or allusive in nature. I hope I can get a little guidance from true musicians like you.
Last night I watched Ralph Macchio's Crossroads (1986) movie. It talked about the legends of Robert Johnson. There was a scene where a train went by, triggered by his emotion, Willie Brown started to mimic the train sound using his harmonica. He created beautiful phrases to paint an atmosphere for the scene. It could have been dramatized but I have no doubt that Blues musicians could easily come up with phrases to express themselves.
I played guitar for about 1.5 years. In my childhood, I had some training in classical music (violin/piano). In orchestra, I was generally given a sheet music to study and practice. When it's time to perform, I looked at the sheet music and followed conductor's gesture and signal. The mentality and mindset were very different from the guitar world. There was barely any focus on improvisation in classical music. Actually it was discouraged. I had received a bad grade for playing something that's not on the sheet.
Nowadays when I learn a solo or a song, I try to look at the notes' relationship to the underlying chord or chord progression. I would write the note's interval in relation to the chord.
From my experience of guitar lessons, most instructors generally focus on techniques. In fact, most ads I see on the internet are "Do you know the secret to playing fast?" "Do you know why you can't play fast?" I rarely see "do you want to understand the music you are playing?" Technique is certainly important, it's the foundation to everything. But at least to me, the road to develop technique is clear.
I tried to find patterns in all the solos I learned and understand why was it written that way. I'd look at solo, figure out what scale it uses; loop a live version on YouTube, transcribe what's being played. I also ask a lot of music theory related questions on StackExchange (once again, thank you all for sharing your valuable knowledge with me)
Maybe I am too inexperienced, I failed to see an obvious relationship. It's all very mystical. Is my approach to develop the ability of musical expression wrong? How did Blues musician develop their skill when they didn't have any formal training in a tough time like pre-Civil Right era? This could apply to many different cultures in this world as well.
Let's take a step back, what exactly is expression? A common set of interval changes that elicits an emotional response in human culture? In literature, writers have literary devices to communicate an idea, like metaphor, motif, theme etc... What's the equivalent in music?
Comment: @mofury I think the idea you have had of relating it to how we express ourselves through writing is a really good one that you should keep hold of. Do you know how you've become able to do it? Do you know, when you think you're expressing something, you really actually are? (i.e. in terms of how it's received by the reader) Perhaps learning an instrument is like learning to write in another language. What would your approach to expressing yourself in that setting be?
Comment: @Aaron This is a different question. After following this question and the comments, I understood that the OP is asking, "if I keep studying and practicing low-level details, techniques, theoretical concepts, analysis, etc, then will that lead to being able to use those as self-expression", and my answer is no, not necessarily. You learn expression by _using_ expressions _in a context_ and observing the effects. You must put yourself in an "operational" situation. Like on a language course you should practice _using_ the words and sentences to _achieve_ something. That's self-expression.
Comment: Did I get this right - the real question is, what _is_ this "expression" thing to begin with? Or, you've been looking at lots of technique and theory tutorials, but none of them has explained which part of all that is expression - have you missed something in the tutorials? Or is it: how could one express oneself through the techniques and theoretical concepts?
Comment: Please excuse me if my question wasn't clear. I'd say it's how to get to "one expresses oneself through techniques and theoretical concepts". For example, if I just practice/develop each technique in isolation, are they going to automatically come together? Or do I actually need to go extra step to integrate them? I can learn a technique through tens of thousands of repetition. I can understand theories, e.g. end a phrase with cadence, M7 gravitates toward root.
Comment: But I don't understand how pro musicians just pick up an instrument and create phrasing right away. Like how I can type and express my ideas via words. Is it just through repetition? If I read enough of other people's writing, I can begin to express my own thoughts? I just want to make sure that my practices are helping me to progress toward that goal.
Answer: Even people who have spent most of their lives talking find it hard to express themselves fully. So it's the same with a musical instrument. And often the music itself doesn't make it easy to inject much expression.
So, complete mastery of the instrument is a good start point, along with complete mastery of the music in question. To put your own interpretation, slant, on a piece means you know all the nuances the instrument is capable of, with you at the helm, so you can concentrate solely of wringing all the meaning out of it.
Rubato, change of tempo, of volume, of tone all play their part in that expression, so your mindset needs to be right at that time too. You become an actor. You put yourself in a specific role. If you've just lost your favourite aunt, and been sacked that day, you're hardly going to make even the happiest piece sound that happy.
Comment: Most musicians have cloned themselves to some degree! We all like to pretend to be our heroes. Take the best bits from whoever yours, and copy them by all means. But at some point, you'll need to develop your own style, so the sooner that happens, the sooner your own expressions will shine through. Or not. There are plenty of musicians out there who lacck expression - or more accurately, don't transmit that expression well. And sometimes the listener doesn't get moved. It's a two way thing. Playing with others is another aspect to be considered. Check 'playing in the pocket'.
Comment: Thank you Tim, your answer has always been very helpful to me. Does that mean I should worry less about expression, just focus on imitation and develop mastery by copying the masters? And eventually I will develop the ability to express myself?
Answer: Dave's answer is a good one. Let me add something from the different point of view.
First of all, I think you're counting on some "universal expression" that will work for everyone, but there is nothing like that, not even if you only take Western cultures. It seems that for many people there is a thin line between "awesome, powerful, emotional music" and "random unlistenable gibberish". For instance, I happened to advance that line pretty far, so conversely, when someone plays "emotional" music to me, I can just shrug and mutter something about the harmony being too rudimentary and the melody being boring. So whatever you play, you can get puzzled looks from some people and/or bored looks from other. I think there is a partial cure to that, see below.

I tried to find patterns in all the solos I learned and understand why was it written that way. I'd look at solo, figure out what scale it uses; loop a live version on YouTube, transcribe what's being played. I also ask a lot of music theory related questions on StackExchange (...).

That's a great way to improve aural skills and your understanding of theory. However, be warned that you will NOT be able to understand "why it works" because the theory doesn't say anything about that. It only tells about what does work, but not why. On top of that, when you try to take an existing bit of music and explain it using the theory, you will probably get many different ways to apply the rules to generate that bit of music. I think that the theory works best for making the music, and not so well for analyzing it.

Maybe I am too inexperienced, I failed to see an obvious relationship. It's all very mystical. Is my approach to develop the ability of musical expression wrong?

You failed to see a relationship because there is none, as explained above. And yes, I think your way to develop expression is wrong. The worst thing about it is that I can't say much about how it really works, because, as you correctly note, it's truly very mystical :—). Here are some ideas:

The emotion a musician puts into the music is pretty much automatic but very complicated. It's the way you alter the tempo, the loudness and the timbre of each note. Learning this by "normal" means like studying books is impossible, just like improvisation. The books can help a bit but most of it is on you.

I think there is only one thing you can do to learn expression and improvisation alike: Do it a lot. You will get better over time.

There are also some ways to make it happen faster and better: 1) listen to a lot of music, 2) play a lot of music on your instrument and 3) learn theory. Take what you like, try to analyze that. Play it on your instrument — by that, you will learn how to really play what you like. In this way, you will slowly build up a repository of things that work for you and the physical, real ability to produce them whenever you see fit. That's really important — doing it "in your head" will not do. Then you use these things as building blocks for your music. At least that's what I do as a classical guitarist: from time to time, I listen to new classical guitar music and perhaps learn a piece that I really liked. If you know the theory well, you can even use it to improve on those building blocks and make your "own inventions" (at least until you hear that "invention" in a 300 years old piece, which invariably happens at some point :—)).

I said that there's not anything like a universal expression, but there is still something you can do to approach it, and that is having a good melody. Harmonies are great, but melodies seem to work on a different level ("closer to the heart"). The bad thing is that while there are at least some rules that make it possible to write good harmony, there are no rules for melody (or there are, but they are next to useless). The melody either comes to you or it does not, and you can't do very much about it. There's the same mystery in writing good melodies as in any other human creative process.

Still, there's one thing you can do, and that's — you guessed it — listen to lots of music. We humans tend to learn well by example, so do that. In particular, I would recommend going into folk music, because that is pure melody, and the best melodies were picked by "natural selection" over many centuries, so it tends to contain many hidden gems to learn from. (Take Celtic music: I think its boom is caused largely by the fact that it has beautiful melodies.) In many nations there were people who meticulously collected many of those songs, so you only need to search for those collections and you have it — both score and lyrics. You only need to take care that it hasn't been "artificially covered" by something else (like in my homeland, the Czech Republic: in the western part, the original music has probably been covered by the "artificial" 300–350 years ago, and it grew dull and boring; while the eastern, "uneducated" part, held onto the original beautiful melodies).
Answer: I define expression as any sort of communicational means for advancing one's intentions. Or something. A baby cries to express hunger and/or other needs. Then there's artistic expression, which is basically the same, but through artistic means. Whatever art is. Musical expression is the same, but through musical means. For a DJ, selecting a song is musical expression. For a guitarist, things that can be done with the guitar are expression - which is a LOT of different things on many different levels. It doesn't have to be just about how to pick the strings right - picking the right piece for the situation can be within a guitarist's means too, if you like to see it that way.
You have a palette of things you can do, and you have some freedom for making choices, within restrictions and limitations. What are the things you can do technically, what is appropriate to do, what is suitable for the genre etc. Do you remember the name of the song or can you look it up? Do you remember how a specific trick is done? Even if you remember, will you be able to carry it out technically? Technical and theoretical exercises can give you more freedom by expanding your physical and intellectual abilities. Practicing pieces gives you freedom, because it increases your confidence in selecting those pieces. Etc.
It's possible to perform music completely mechanically or according to cultural conventions. "We always play this song in this situation, and we play it exactly like this." Ok. That can happen, and someone walking into that situation for the first time can be very deeply touched by the music, but I wouldn't say that the musicians expressed themselves very much. Expression should be about making choices.
But even if you have unlimited technical, intellectual and cultural freedom and confidence, how do you choose what to do? You should have some kind of an idea about what will happen if you select each particular song, chord, note, dynamic level, technique, type of vibrato, etc. The ability to predict the outcomes comes with experience, and to build experience you of course have to go through enough repetitions in practice, but you also have to have certain sensitivity to the effects of your actions. If you're deaf, you can't hear the sounds you're making, so you lack sensitivity - you might be able to see the effects from other people's reactions though, but I think that will be very difficult. Like, does the teacher say "good" or "not good"... Sometimes music education seems a bit like that! Deaf people trying to play instruments, looking at the teacher's reactions to know if they're doing it right or wrong. I think that's a slightly mistaken idea. Music should be about hearing, listening, feeling. Why are people so obsessed with theoretical descriptions of harmony, "M7 gravitates toward root", stuff like that. Have you ever dropped a ball - which way did it gravitate, toward the ground or away from it? Theory and teachers shouldn't be needed to introduce this basic phenomenon to students, or to confirm and validate the observation, only to give a name for the phenomenon. But unfortunately, sometimes the students haven't had a chance to play enough, like with toys, drop things and throw them around. In my opinion, such toying should be encouraged, to make sure that the students have personally encountered the phenomena in practice.
How to learn to express yourself through different elements of music? By practicing, listening and feeling. If you can't hear, if you can't feel any difference in different ways of playing notes, articulations, chords, phrase lengths, etc. that's going to be a problem. Whatever the thing is you want to utilize as your expressive tool, you have to practice doing that, with open ears. Teachers and lessons can provide you with new ideas to try and certain aspects of music to pay special attention to, and then you take those new ideas and start practicing them and focusing on the suggested aspects to get a feel for how they change things. If you can't technically perform them, or if you can't feel any difference even after trying the ideas for a long time in various situations and pieces, then maybe that's just something you can't use for expressing yourself. Find other ways of self-expression, there are many. Everyone can find some level and area of musical self-expression, and that defines them as a musician. Some people are content with selecting the right Spotify playlist, and that's perfectly ok, that's their level of musical self-expression. Some people might not notice any difference between any Spotify playlist or none at all, so then that's not their thing obviously. Though maybe if they're motivated, they can develop a sensitivity for it through persistent listening.
If you have trouble noticing the right aspects in the music you're making, a teacher could help you by giving ideas and feedback. "Your phrases are too long - can you try making them about the size of a line of lyrics, with some punctuation in between? Something you could actually speak or sing as a continuous phrase." And then, you take this new idea as part of your practicing, and perhaps you start paying attention to the lengths of phrases in music you listen to.
To sum up: you learn to express yourself by repeating expressions and sensing what effects the expressions have. Whatever level of abstraction the expressions are on.
Answer: You might be stepping too far back for this. The train thing was fundamental; the train beat is common to country as well, because it was a primary form of long-distance transformation. Chuck Berry mentioned the rhythm of the train in "Johnny B. Goode". That wasn't meant to communicate Ralph's character playing what he heard, but rather getting in touch with the blues tradition.
Later, after Jami Gertz leaves and Ralph plays the blues, that represents him learning to present his emotion through playing.
First and foremost with music is the social aspect. Music exists in church to allow the congregation to engage. Music exists in bars and parties to enable dancing and social interaction. Personal expression comes after many gigs, after mastery of those aspects. I would suggest you get to the point where you're expressing yourself well before you recognize that you're there.
Think about how you express emotion in conversation. It involves many things: if you're angry, you're loud. It. Could. Come. In. Short. Pieces. It could come, as Steve Vai's Jack Butler, by entering someone's personal space and taking all the air in the room. In contrast, Ralph's Eugene is sure of himself, and starts his trick bag, his electric interpretation is Paganini, with hammer-ons that say he's not done. There are never spikes that say "look at me" the same way that waving a guitar by the whammy bar in someone's face, but by playing impossibly hard technique with a reserve that says that there's more where that came from.
Contrasting, consider children. They are very early in their process of language development, but infants or toddlers can make it very clear that they're unhappy very clearly and insistently, even if, as the adults in the situation, we can't tell what they're unhappy about. You can tell that much music is similarly unhappy, even when it is hard to tell from the lyrics what the cause of the emotion might be.
I would put self-expression well after playing well with others as a priority for new musicians. Once you know the right chords and scales, and know how your playing works with those around you, then you can start worrying about expressing yourself.
Comment: Thank you Dave. Let's put it in software lingo: Does it mean that for Blues musicians, when they play together, they follow a "protocol" like the 12-bar form? Then expressions are added via dynamics much like our oral communication to each other? Playing well together is a matter of understanding the API of a genre, while what you do with the API is the "expression" part? (Loose analogy)
Comment: From an implementation standpoint, I should understand all the API (i.e. scales, harmonic functions, tight rhythmic timing, etc..) and play well with others, before I start worrying about "emotion"?
Comment: That is an apt way of looking at it, yes.
Comment: Additionally, playing with others will tell you what you need to do to get better. Likely, it'll be more timing and counting more than fancy leads and chords. It's like the Integration Test.
Answer: I fundamentally disagree with the answers that say, "First master your instrument."

No-one with the possible exceptions of Liszt and Paganini ever completely mastered their instrument. There is no cut-off point where you or anyone else can say, "Now you are a master. It is time to start expressing yourself!".  What a horrible thought!

Young musicians who go on to become virtuosi can show great expression playing Twinkle Twinkle Little Star,  even though it will be years before they will be considered 'masters'.

Listen to the early blues musicians. Their technique is often extremely rough and is usually restricted to three chords at the very most. I'm not kidding when I say that some of them could do a whole blues on just one chord. They have mastered a style of playing that is personal to them but nowadays any intermediate player could learn the technique from a video.

All of the early blues players were ignorant of any theory. In fact there isn't much theory as far as Blues is concerned (at least there shouldn't be). In the old days people would learn by watching or hearing others and copying them approximately.

Expression in music comes from your feelings and emotions. Even someone who has a speech impediment or learning disability can put an enormous amount of expression into their speech if the emotions are strong enough.
One way forward, especially for something like blues improvisation, is to say a phrase, e.g.
My head is really aching. I shouldn't have drunk so much last night.
It's best if you are expressing a real emotion or event.
a) Say the phrase with feeling
b) Say it again and notice what happens to the pitch. Where does it go up or down
c) Sing the phrase without the words (but thinking them)
d) See if you can play the wordless tune on your instrument
e) Play it until you are technically fluent
f) Play louder where your voice would go louder. Place a bend where your voice tends to bend, etc.
Answer: To "express" yourself on a mechanical or electric device you need to have mastered the physics of creating sounds on that device to the point where you do not have to think about it.  Musicians will be familiar with the phrase "stay out of the way", or something similar, told to them by a mentor or instructor.  What this means is that you cannot force the technique or even the "patterns" as you mention but let the music come out.
To accomplish this requires learning to relax, let go of ego, and just be.  Sometimes when we speak we fumble our words, and so it will be with a solo.  But if you are thinking about what lick you want to play 10 measures in to it the first note will be crap.
I'd recommend reading Kenny Werner's Effortless Mastery to get a better idea behind this.  Pepe Romero also devotes a considerable essay on this point in his book on classical guitar.
As for having something to say when the time comes?  This takes a life of devotion to digging deep in to music.  Listening to others and emulating your favorite passages from their solos.  Building up a collection of your favorite phrases and even making up your own.  Jerry Cocker writes about this in his book on Jazz Improvisation.  Rather than spending months with play along tracks trying to follow the 3rd and 7th of ii-V in every key just keep a diary of licks and play with laying them over tunes, even where you wouldn't think they'd fit based on the "key".  This approach is very harmonious with Werner's approach.  They complement each other.  One thing to keep in mind here is that it is better to be a minimalist.  Rather than try to front load with 1000 licks just focus on a single phrase but go as deep as you can with it.  Modify the phrasing, playing out of its usual context, e.g. if the lick is 3-4-5 in the major scale try in on 7-8-9 too.  Play it in every mode.  Throw a few extra notes on it, grace notes, turn or groupetto, here and there.  You will find that in this process you start to develop your own language and that is when your solos will be distinctly YOU.
Comment: Thank you, your suggestion is very practical, the idea of "going deep into one phrase"
Answer: Master your instrument.  Gain experience of all the styles it can play in.  Gain experience of the repertoire.   Steal ideas, then steal some more.
When you feel impelled to play something 'sad' or something 'happy' you'll know some tricks.   Your audience will marvel at your originality!   You will realise how much it's a synthesis of how lots of previous musicians expressed those emotions.  But don't let on :-)  Audiences like to worship Art.   We know it's mostly craft.
Answer: Short answer. Its tradition. Know the tradition of the music you want to express yourself in. This means constant listening, transcribing and youll dig deeper and deeper. Creativity is never invented it is passed on! Whenever we express something, we learned that expression from somebody else. Whether is expression in the realm of classical music, or in Jazz. To get a little philosophical, I don't think there is a self to express, but rather a tradition that you want to continue is being expressed! It can also be a combination of traditions, into one you would wish to hear!
Answer: It's not really clear whether you're talking about expression in performance or expression in composition -- these are two different things to me.
As a performer, expression comes from how and when you play each note. On guitar, you can play them very slightly early or late, dead-on the beat; plucked, strummed, hit, picked; sustained, staccato, muted, buzzing, dead, held a little long, cut a little short; on the bridge, on the neck, tapped, hammered off; vibrato, tremolo, whammy, bent, slide-on, slide-off; on different strings, on multiple strings, as harmonics; there's more, there's stuff I'm not even aware of. You need to know exactly how every one of these sounds, you need to be able to imagine a million different ways of playing exactly the same passage. When you read tab, or sheet music, or hear something you want to play, you should hear in your head exactly how you want the notes to sound, and then work out how to play that specific sound.
Expression in composition is, to me at least, more abstract and I'm not convinced it's something so well defined or understood. I don't particularly like the way some people mysticize composition, I just think "expression" in composition is highly subjective. To me it's "that shit you sing in the shower but done up to sound pretty", or "oh wow that's a cool trick ha ha I'm gonna do that".
Answer: I don't understand these answers saying there's no such thing as 'universal expression' ... because of different cultures?
I think you'll find that 'expression' equals melody.
"Is my approach to develop the ability of musical expression wrong? How did Blues musician develop their skill when they didn't have any formal training in a tough time like pre-Civil Right era?"
Formal training in what ... creating melodies?
Why not focus on creating melodies and song writing instead of technical prowess?
David Gilmore ... great example ... he plays melodies in his solos. Solos from the first Boston album.
Typically faster players don't. They are more playing a 'song of sounds' than a 'song of notes'. Can you name a single fast guitar solo that has an amazing melody? ... or are they remembered because they're some amazing combination of sounds? ... like Eruption.
Answer: My own method of learning to express myself started when I learned to talk. I listened to how others around me talked. I heard them express happiness, sadness, joy, anger, disappointment, pride, etc. and I learned to mimic what I heard when I felt those different emotions. Years later I did the same process when I learned to express myself with music. First I listened to others communicating a particular emotion. Then I learned to mimic that sound and I practiced using what I learned until it became automatic for me. Until you asked this question, I never really gave it any thought, I just assumed it was how everybody did it. I get my individuality of expression from the fact that as an individual, my interpretation of what I hear and see will always be slightly different from what others who hear and see the same thing will interpret. That's where I get my own personal style when I play it.
Comment: Interesting perspective, thank you for sharing your view. I think my initial exposure to music gave me a mechanical approach to music. As a kid, I was evaluated based on whether I could deliver the note as it was explicitly written on paper. Now I want to move away from that mentality and learn to make music like it's a language/voice of mine.