Transfering audio recordings from reel-to-reel to PC

Question: My PC doesn't have a "line-in" jack - only USB and HDMI. How do I connect the stereo RCA output from my reel-to-reel deck to my PC to transfer the audio to the PC?
Answer: With a USB soundcard.  If you don't need a microphone input, there are several pretty solid USB soundcards in quite affordable price range with line-level inputs to be had on the second-hand market.  Just make sure that the driver situation with your PC is good.  "Class-compliant" cards with USB 2.0 "high speed" connection are the best bet for stuff that is going to work without a lot of headaches for a variety of current and future systems.
I've banked on the combination of a solid minidisc desk (with A/D converters and digital outputs) and a cheap USB 1.1 sound-card with digital optical input myself at one time (with the rationale of "digital is lossless, so price doesn't matter once we are digital") but that was not a good scheme because of the dropouts.
Comment: If you buy a new soundcard/interface it will either include the necessary drivers (software that allows your computer to understand and use the hardware) or it will be "class-compliant" meaning it works without any installing any additional drivers because it uses existing generic drivers. A common problem with proprietary drivers is that they aren't updated for new operating systems. I have an old interface that is fine in theory but useless because it only has drivers for Win XP. Class-compliant drivers solve this problem.
Comment: What do you mean by "make sure the driver situation is good"? Is there some "matching" involved?


Significance of 0 error results

Question: I want to see how many people have COVID in a certain region (London) and I use a sample of 10 people out of 1000 (btw the sample size isn't an issue) and test them for COVID and find that none of them have COVID. What conclusions can I draw for this? Obviously I cannot say that no one in London has COVID and I cant use a margin of error from this. Are there any conclusions I can draw from my results? Is there anything else I can do?
Comment: Try the [rule of three](https://en.wikipedia.org/wiki/Rule_of_three_(statistics)) for a simple confidence interval
Answer: This is a difficult problem, since you can't even get a standard error to create a confidence interval. One idea is to use Laplace's rule of succession where we add two artificial observations to our data. You say you observed ten people, none of whom had COVID. Then pretend that you observed two more, one who had COVID and one who did not. Then you have $1/12$ as COVID cases and can do the usual proportion testing and confidence intervals.
An alternative could be some kind of Bayesian method where you use an assumption or knowledge (such as the prevalence in Manchester) as your prior distribution.

Significance of 0 error results


Show that $\{ f \in G \mid f(2) = 1 \}$ is a subgroup of a group $G$ of functions $\mathbb{R} \to \mathbb{R}^*$

Question:
Let $G$ be a group of functions of the form $\mathbb{R} \rightarrow \mathbb{R}^{*}$, where the multiplication of $G$ is given by the pointwise multiplication of functions. Let $H = \{ f \in G \mid f(2) = 1 \}$. Prove that $H$ is a subgroup of $G$.

I have to check that $(fg^{-1})(2) = 1$ for all $f,g \in H$. If this holds then $H$ is a subgroup. But how do I determine $g^{-1}(2)$?
Thanks
Comment: It's not $g^{-1}$ in the "inverse function" sense, it's $g^{-1}$ in the $\frac{1}{g}$ sense.
Comment: Yes, be very careful with that $g^{-1}$ here. Very dangerous, given the usual meaning when $g$ is a function.
Comment: Well, $g^{-1}$ is such that $g^{-1}(x)g(x)=1$ for every $x \in \mathbb{R}$.
Answer: For $f,g \in G$, their product (in the group $G = \{\mathbb{R} \to \mathbb{R} - \{0\}\}$) is the function $f \cdot g$ defined by $(f \cdot g) (x) := f(x) g(x)$ for every $x \in \mathbb{R}$. (I'm just writing this to be sure if I understood the definition of the "multiplication" of $G$ correctly)
Let $f \in H$, i.e. $f(2) = 1$. Consider its inverse $\tilde{f}$. It holds that $\tilde{f} \cdot f \equiv I$ (where $I(x) = 1$ for all $x$). Thus for any $x \in \mathbb{R}$ we have $\tilde{f}(x)f(x) = 1$. Inserting $x = 2$, we obtain $\tilde{f} \in H$.
Let now $f,g \in H$, i.e. $f(2) = g(2) =1$. Then we have to evaluate their product $f \cdot g$ at $2$. Thus $(f \cdot g) (2) = f(2) g(2) = 1 \cdot 1 = 1$, i.e. $f \cdot g \in H$.
Answer: Note $H$ is nonempty since it contains the constant function $f(x)=1$, so that in particular, $f(2)=1$.
Now if $f_1,f_2\in H$, then $$f_1\cdot(f_2)^{-1}=\frac{f_1}{f_2}$$
is a function from $\mathbb{R}$ to $\mathbb{R}^*$ since $f_1$ and $f_2$ are ($f_1$ is never zero, so the fraction isn't either). Lastly: $$f_1(1)\cdot(f_2(1))^{-1}=\frac{f_1(1)}{f_2(1)}=\frac{1}{1}=1$$ so $f_1\cdot(f_2)^{-1}\in H$.


How to fill attributes with values from input?

Question: How to fill attributes with values from input? I have something like this.
class Names(object):

    def __init__(self, name, nickname):

        self.name = name
        self.nickname = nickname

And in another class...
def userlog():
    name = input("Your name: ")
    nickname = input("Your nickname: ")

I need to put values in this attributes and save them to .txt file.
Comment: Your question is unclear, could you rephrase it?
What is exactly your problem - is it getting input from user? passing variables as argument?
Answer: Try this:
def userlog():
    name = input("Your name: ")
    nickname = input("Your nickname: ")
    provided_inputs = Names(name, nickname)

For saving it on a text file, you could try a CSV format just as strings. One format could be "name, nickname"
Use the following function for saving the info:
def write_to_file(file_path, text_to_write, write_type='wt'):
    with open(file_path, write_type) as f:
        f.write(text_to_write)
        f.close()

Once you have that ready, modify your userlog function as follows:
def userlog():
    .........
    provided_inputs = Names(name, nickname)  # This saves onto Names class
    write_to_file('/tmp/you_path',
                  '{},{}'.format(name, nickname)  # This saves the strings on a file

Answer: Your question contains 2 parts:

How to create an instance of the class Names
How to write that instance to text file

To address the first part, after you have the user types in the name and nick name, you can create a new object like this:
def userlog():
    name = input("Your name: ")
    nickname = input("Your nickname: ")
    user = Names(name, nickname)
    return user

For the second part, you need to open a file for writing, and write it out in any format you like:
user = userlog()
with open('output.txt', 'wt') as output_file:
    output_file.write('Name: {}'.format(user.name))
    output_file.write('Nick: {}'.format(user.nickname))


Javascript stop scrolling on touchmove after scrolling has already started

Question: I have a simple example where a user starts to scroll on a touch screen, and then after one second, I want to disable scrolling.  I thought event.preventDefault() would stop the scrolling but it doesn't seem to work after scrolling has already started
Here is an example: https://jsfiddle.net/7s5m8c6L/30/
let allowScroll=true;

function TS(e){//touchstart handler
  setTimeout(function(){
    allowScroll=false;
  },1000)
}

function TM(e){//touchmove handler
  if(!allowScroll){
    e.preventDefault();
  }
}

In this example, you can start scrolling, and after a second, I want the scrolling to stop, but it does not.  I know there are ways that I can get this to work with CSS (adding overflow:hidden), but I would particularly like to know why preventDefault doesn't work.
Answer: If you are using chrome, there is a hint in the console:

[Intervention] Ignored attempt to cancel a touchmove event with cancelable=false, for example because scrolling is in progress and cannot be interrupted.

The problem is exactly that Event.cancelable. Unfortunately for you this property is read-only and it is not safe to call preventDefault for a not cancelable event. If you print e.cancelable in the TM function you can observe that throughout the scrolling e.cancelable is false.


Parse CSV file and print the desired out put

Question: Very new to nodejs. I have the following CSV file which is nothing but a report.
Label,# Samples,Average,Median,90% Line,95% Line,99% Line,Min,Max,Error %,Throughput,Received KB/sec,Std. Dev.
LAUNCH-APPLICATION,25,446,282,612,1425,2224,271,2224,0.00%,3.0,6.2,438.29
BOOKROOM,25,571,571,582,591,592,547,592,100.00%,3.9,5.9,11.44
TOTAL,50,508,561,591,612,2224,271,2224,50.00%,5.7,10.1,316.22

Want to print in this format,
LAUNCH-APPLICATION instead of #samples I want to print No of Samples:25, Average:446 like this.
for example:
LAUNCH-APPLICATION: No of Samples:25,Average:446,95% Line:1425,99% Line:2224
BOOKROOM: No of Samples:25,Average:446,95% Line:1425,99% Line:2224
I have tried with
const stream = file.createReadStream('../ParsedReport/reportChange.csv')
const readlineFile = readLine.createInterface({ input: stream })

let data = [];

readlineFile.on("line", (row) => {
    data.push(row.split(","));
});

readlineFile.on("close", () => {
    //console.log(data);
    // starting from 1 to skip the first row and -2 for skipping the last two row.
    for(let j=1; j <= data.length-2 ; j++) {
        for(let i = 0; i < data[0].length; i++) {
            console.log(data[0][i],'-----------',data[j][i]);
       }
    }

});

Sample CSV file screenshot:

appreciate for help.
Answer: I would suggest using a dedicated CSV parsing libary such as Papa Parse, this makes parsing such files very simple.
We'd create a formatRow function that takes a row object and formats it in the desired way:
const Papa = require('papaparse');
const fs = require("fs");

let csvData = fs.readFileSync('../ParsedReport/reportChange.csv', 'utf-8');
let { data } = Papa.parse(csvData, { header: true });

function formatRow(row) {
    return `${row.Label}: No of Samples: ${row['# Samples']}, Average: ${row.Average}, 95% Line: ${row['95% line']}, 99% Line:${row['99% Line']}`;
}

// We wish to exclude the first and last two lines...
let requiredData = data.slice(1, data.length - 2);
for(let row of requiredData) {
    console.log(formatRow(row));
}

The output will look like:

LAUNCH-APPLICATION: No of Samples: 25, Average: 446, 95% Line: undefined, 99% Line:2224
BOOKROOM: No of Samples: 25, Average: 571, 95% Line: undefined, 99% Line:592
TOTAL: No of Samples: 50, Average: 508, 95% Line: undefined, 99% Line:2224

The data array will look like so:

    [
      {
        Label: 'LAUNCH-APPLICATION',
        '# Samples': '25',
        Average: '446',
        Median: '282',
        '90% Line': '612',
        '95% Line': '1425',
        '99% Line': '2224',
        Min: '271',
        Max: '2224',
        'Error %': '0.00%',
        Throughput: '3.0',
        'Received KB/sec': '6.2',
        'Std. Dev.': '438.29'
      },
      {
        Label: 'BOOKROOM',
        '# Samples': '25',
        Average: '571',
        Median: '571',
        '90% Line': '582',
        '95% Line': '591',
        '99% Line': '592',
        Min: '547',
        Max: '592',
        'Error %': '100.00%',
        Throughput: '3.9',
        'Received KB/sec': '5.9',
        'Std. Dev.': '11.44'
      },
   ]

Comment: want to exclude the first and last two line. But with your code the last two lines are printing.
Comment: You can use Array.slice to remove the undesired rows. I'll update the answer!


MySQL Case Statement with LIKE for string

Question: I have a table with an existing user_agent column that I want to make a new column based on if user agent contains the substrings 'windows' or 'os x' in MySQL and I can't figure out what is wrong or find examples of case statements with LIKE for strings on this site. My version of MySQL is 8.0.26.
SELECT user_id,
    CASE user_agent
    WHEN LIKE '%windows%' THEN 'Windows'
    WHEN LIKE '%OS X%' THEN 'Mac'
    Else 'Other'
    END AS Operating System

    FROM pageviews;

Answer: SELECT user_id,
    CASE
    WHEN user_agent  LIKE '%windows%' THEN 'Windows'
    WHEN user_agent  LIKE '%OS X%' THEN 'Mac'
    Else 'Other'
    END AS  `Operating System`

    FROM pageviews;

Comment: Yep, that's the correct syntax. For alias names, though, you should use standard double quotes or MySQL's proprietary backticks. Don't use single quotes. They are meant for string literals and using them for names instead can lead to unexpected and undesired results sometimes.
Comment: @ThorstenKettner thanks! just update my answer after your comment.


Are minor scales meant to be in sharp or flat keys?

Question: I know you can read minor scales in both sharp and flat keys, but which is preferred in the world of music?
Is it more useful to know them best as say Eb minor or D# minor?
I know it doesn't make a change in the scale whichever way you read it, and as long as you know the relationships of sharps and flats you can figure out which is which in the opposite key type, but I just want to know which way I should learn them.
Comment: I don't think this really is a question.  "... know them best..."  has no applicability in music theory or performance.
Answer: The way the circle of 5ths is setup, you would typically use F# minor instead of Gb minor, C# minor instead of Db minor, G# minor instead of Ab minor, and Bb minor over A# minor. You can uses either either Eb minor or D# minor because of where it falls on the circle.
So 3 keys you would use sharps for, 1 you would use flats for, and one is rather interchangeable. It makes sense that sharp keys are slightly more likely then flat keys because the difference between major and minor is 3 lowered notes.  See the picture below:
Comment: D# is **not** the same as Eb , even though they may sound the same.  Dive into some theory books for appropriate discussions.
Comment: @CarlWitthoft I understand they are not the same, but for the sake of this question it is much simpler to say they are since the OP groups them together. Likewise with any discussion about enharmonic notes they are they are not the same, but for most applications of them are treated the same.
Comment: One factor that might influence your choice is if there are any modulations to other keys. As a simple example, if you happen to modulate to the parallel major, it might be preferred to go from E-flat minor to E-flat major, rather than from D-sharp minor to D-sharp major (but either is preferable to going from D-sharp minor to E-flat major, which should be avoided if at all possible).
Answer: To make the scales more friendly to newer musicians, you typically want to frame a scale in such a way that it seems to have the notes modified as little as possible. To contrast the Eb and D# natural minor scales:
1    Eb   D#
2    F    E# -> (F) (we usually consider E# as F)
3    Gb   F#
4    Ab   G#
5    Bb   A#
6    C    B# -> (C)  (we usually consider B# as C)
7    D    C## -> (D)  (we usually consider C## as D)
8    Eb   D#
As you can see, more work must be done to translate the D# minor scale to the actual note, with a double sharp (in the melodic minor), meaning the note shown on the scale is C, but the musician must modify it with two sharps, and the actual note played is D.
In general, it is preferred to use the Eb minor representation for the above reason. However, if you change keys in the piece, perhaps to a more accessible sharp key, it would be reasonable to avoid switching from flats to sharps, and to stick with the D# minor representation.
If you don't have a particular piece in mind, start learning the Eb. But then work your way through all of the keys so that you can more easily handle more difficult pieces when presented with them.
Comment: That looks like melodic minor, not natural minor. In Eb natural minor, you have a Cb (B), but no "strange" notes in D# natural minor.
Answer: The simple answer is that you use whichever one has less sharps or flats.  So, five flats over seven sharps, five sharps over seven flats, and either six flats or six sharps (they are both the same).  This is just as you would do with major keys.
Perhaps the reason you ask the question about minor keys is that a minor key always has either three less sharps or three more flats than its enharmonic (i.e., same name) major key.  So, C major has no sharps or flats, and C minor has three flats.  B major has five sharps, B minor has two.  Where it gets tricky is here: G major has one sharp, and G minor has two flats.  (Get it? Two flats is three more flats than one sharp...sort of.)  And here: Db major has five flats, and Db minor has eight.  Except there are only seven notes!  So we say C# minor instead, and it has four sharps.  (C# major, same key as Db major, has seven sharps.)
So, again, we generally go with the simplest way to get the key we want.
Note that this is all only true when you use "equal temperament" as opposed to other forms of tuning.  I can't speak for other instruments (and for other instruments I'm sure what I'm about to say is less accurate), but if you're working with the piano, you can safely ignore any other form of tuning for twenty years or so without any negative impact on your musical development.
Answer: It's not just minor scales.  We also have the choice between C# major and Db major etc.
As a rule of thumb, pick the one with the smaller key signature.
Eb major has three flats, D# major has nine (double sharps count as two).  You couldn't even WRITE that key signature!  So no contest.
But don't be pedantic.  Db major has five flats, C# major has 7 sharps.  But that isn't necessarily a shoo-in for Db major.
Answer: There are actually two aspects to consider in order to answer to this question. One is about the practical aspects related to music which is intended to be played on modern instruments with a basically european heritage. In this regard, there really are two ways to describe one scale (although each way still might lead to different chords being used as harmonies) and one is probably more common. This aspect has been addressed in other answers.
To address the second aspect, which is that Eb and D# actually are not different names for the same scale, one has to dig a little deeper. When starting from basic physics, there are several ways to tune an instrument "correctly". For a long time many different tuning methods, e. g. pythagorean tuning were used. In those systems Eb and D# were actually different tones and, following from this, Eb minor and D# minor were two distinct scales. This only changed in the Baroque, where the invention of the well temperaments first allowed for instruments playing in all keys reasonably well without retuning (and where, as a prerequisite for this tones like Eb and D# were the same frequency [1])  and then the equal temperament [2]  which is the way most modern instruments are tuned.
Incidentally, most classical or jazz musicians I know still make a difference between e. g. G# and Ab when talking about music, even if (at least on a piano), they refer to the same tone.
[1] see wikipedia for "enharmonic"
[2] see wikipadia
Answer: There are two primary considerations when picking a key: what are you most comfortable writing in, and, more importantly, what is most comfortable for the instrumentalists who will be performing your piece?
I recommend you read the top two answers to this question: What's the point of keys others than C and Am? Briefly, which key you pick well slightly affect the sounds that your musicians will be able to produce and how easily they'll be able to read your music. For example, string instruments have a fuller and brighter sound in the keys of A, D, and G major and their relative minors because they get to use strings in open positions.
More importantly to your question, string players most frequently see music written in keys with sharps instead of flats. So if you want to write a piece for strings in the relative minor of A major, you have to choose whether to call it F# minor or Gb minor. Strings would be more comfortable reading F# minor. In contrast, jazz band and symphonic wind ensembles members usually see keys in flat key signatures and might be more comfortable with Gb minor.
And finally, what key you use is somewhat of an arbitrary choice. If you can't decide whether to use a flat or sharp key signature based on the instruments that will be performing your song, you should pick based on whatever key you personally want to write in.
Answer: In other words: what key you pick is a matter of arbitrary convention, if you are dealing with equal temperament.  But it might be a practical matter of ease of sightreading, say for saxophonists or brass who are more used to flat keys.


Validating node creation / edit form

Question: I'm using form_alter to play with the node form for a specific content type. This content type has many different fields and I'm also using Field Collection module to organize all these fields & logic, if that makes any difference.
Apparently, there are some incompatibilities between the Field Collection & Field Dependencies modules so I thought I might be able to build a similar field dependency functionality with my own module.
I've created a validation function for the form. My problem is that I'm trying to access $form_state values that users insert in the form in order to validate these values but I think I'm doing something totally wrong here:
function _mymodule_my_validation_function($form, &$form_state){
    $short_field_name = $form_state['values']['long_field_name'];
    if (empty($short_field_name) || $$short_field_name == '') {
        form_set_error('error','That field cannot be empty!');
    }
}

Unfortunately this validation script doesn't work. To be more exact, I
dpm($form_state);

in my form_alter and $form_state doesn't even contain 'values' (shouldn't it be present but empty?).
Is there a different best practice for validation node form fields instead of dealing with the $form_state['values'] array?
Also, I need to be able to see the values submitted by users each time the node form is submitted. Currently, I dpm($form) in my form_alter function and everything is returned on the node/%/edit page as expected. But how can I catch submitted values on the node/% page after submitting the node form??
Update:
When I call dpm($form_state) within my validation function I get what I need if the form doesn't validate (as we still are on the same node edit page). But how can I receive the (new/changed) values that users entered in the form fields in case the form is submitted successfully and user is directed to content list page?
Comment: It depends where you've put `dpm`. If you've put it in the main form it will call on page load and be empty. You have put `dpm()` in the validate or submit function to see the data you've entered.
Answer: For custom forms
The preferred way is to call hook_form_validate for hook_form but you can use $form['#validate'][] = 'custom_validate_function' to call validate function
function hook_form(&$form,&$form_state,$form_id) {

$form = array();

// write your custom fields here..........
return $form;

}

function hook_form_validate($form, &$form_state) {
 $short_field_name = $form_state['values']['long_field_name']['und'][0]['value'];
    if (empty($short_field_name) || $short_field_name == '') {
        form_set_error('long_field_name','That field cannot be empty!');
    }

}

For built in forms by creating content type
function hook_form_alter($form, &$form_state, $form_id) {
  if ($form_id == 'your_form_id') {
    $form_state['#validate'][] = 'form_1_validate';
    $form_state['#submit'][] = 'form_1_submit';
  }
}

function form_1_validate($form, &$form_state) {

$short_field_name = $form_state['values']['long_field_name']['und'][0]['value'];
    if (empty($short_field_name) || $short_field_name == '') {
        form_set_error('long_field_name','That field cannot be empty!');

}
}

function form_1_submit($form, &$form_state) {

//To get the user selected or user submitted values you should look into code below
$field_name_values = $form_state['values']['field_name'];

}

Comment: `$form_state['#validate'][]`

should be:

`$form['#validate'][]`
Comment: The omitted "['long_field_name']['und'][0]['value']" was causing the problem, thank you. When I call dpm($form_state) within my validation function I get what I need if the form doesn't validate (as we still are on the same node edit page). But how can I receive the (new/changed) values that users entered in the form fields in case the form is submitted successfully and user is directed to content list page?
Comment: check my updated answer for that and please add this comment  to your question.

Validating node creation / edit form


If $f(x)\nearrow\infty$ in $[a, \infty)$ and $f'(x)$ is continuous in $[a, \infty)$ then $\int_{a}^{\infty}\frac{f'(x)}{f(x)}\sin(f(x))$ converges

Question:
If $f(x)\nearrow\infty$ in $[a, \infty)$ and $f'(x)$ is continuous in $[a, \infty)$ then $\int_{a}^{\infty}\frac{f'(x)}{f(x)}\sin(f(x))$ converges

I'm not exactly sure what to try here. I thought of Dirichlets test but I can't seem to identify the right functions to make it work.
Comment: I've never seen that notation before; what does $f(x)\nearrow\infty$ mean? Or did you just mean $f(x)\to\infty$?
Comment: @Adrian: I think it means $f(x)$ is increasing in the interval and $\lim_{x\to\infty}f(x)=\infty$.
Answer: Try a change of variables to reduce it to an integral of a sinc function.
Comment: Thanks. I got $$\int_{f(a)}^{\infty}\frac{\sin t}{t}dt$$ which does converge according to Dirichlets test. Why do I need the information regarding continuity of $f'(x)$ and that $f(x)$ is increasing?
Comment: I don't think that $f$ being increasing is necessary.  Continuity of $f'$ is a standard assumption in the proof that integration by substitution works, because the elementary calculus version of FTC is usually done with continuously differentiable functions.  The hypotheses required to generalize are more complicated.  E.g., I believe it would suffice for $f$ to be absolutely continuous on bounded intervals, as long as you're willing to trade in Riemann integrals for Lebesgue integrals.
Answer: Integration by parts gives
$$\int_a^b \frac{f'(x)}{f(x)}\sin(f(x)) \, dx = \frac{-\cos(f(x))}{f(x)}\Bigg \vert_a^b - \int_a^b \frac{f'(x)}{f(x)^2}\cos(f(x)) \, dx $$
But now
$$\left| \int_a^b \frac{f'(x)}{f(x)^2}\cos(f(x)) \, dx \right| \le \int_a^b  \frac{f'(x)}{f(x)^2}  \, dx = \frac{1}{f(x)}\Bigg \vert_b^a$$
Edit: Looking at it again, there might be some trouble with f being zero somewhere...
Comment: I thought of integration by parts, but instead tried taking $u=\ln(f(x)),\ v=\sin(f(x))$ but that didn't work. Hadn't thought of this though.
Comment: Yeah, that's certainly the first impulse seein $f'/f$. The possible zero of $f$ shouldnt be a problem btw. Since $\sin(f(x))/f(x)$ can be extended continuously. So you can split up the integral over $[a, \infty)$ in one over $[a,1]$ and $[1, \infty)$ if necessary.
Comment: For this to work, note that $f' \ge 0$ is required. (As opposed to the other answer.)


Visual Studio Express 2013 for Web - Save file with encoding unchanged

Question: VSEW 2013 is changing the encoding of a file when it saves it - a problem that did not occur for me in VSEW 2012.  I cannot remember whether I changed the config. to prevent this in VSEW 2012, or whether it worked as required by default.
In any case I cannot work out how to conserve the encoding, except for each file individually via File > Save As and explicitly setting the required encoding. It would be tedious (and very error-prone) to rely on this approach.
In particular, an HTML file originally encoded as UTF-8 without BOM (without signature) is saved as UTF-8 with BOM by VSEW 2013.
Is there any global setting to prevent VSEW 2013 from changing the encoding, or to set it always to use UTF-8 without BOM?
JPL
P.S. The free Fix File Encoding extension (FixFileEncoding_11.vsix) from Vlasov Studio does what is required (and more), but can be installed on Visual Studio Pro only, not the Express version.  http://vlasovstudio.com/fix-file-encoding/index.html
Comment: It seems that this problem does not apply to all text files, as I originally thought, but only to HTML files containing , i.e. in my case all my web pages (a few hundred of them).

I have in the past had problems with web files containing a BOM, but it was some years ago and I cannot remember the details.  Today I tried a test page encoded as UTF-8 with BOM on all the live web servers I currently use and on my test web server - no problems that I could see.
Comment: Thanks for fixing the typo.

But does no-one have any experience of how to fix this?  Surely no-one actually wants to have a BOM inserted in HTML files?  This is a breaker for me - if there is no fix or easy work-around, I shall have to revert to the 2012 version or switch to a different HTML/JS/CSS editor.
Comment: It looks like it will be OK to live with this - neither reverting to the 2012 version of VSEW nor switching to a different IDE is at all attractive.

In the short term there will be a mix of files with and without a BOM.  I hope this does not cause a problem with TFS source code control/comparisons. (WinDiff shows a difference when the only difference is the BOM; DiffMerge ignores the BOM.)
Answer: You can install Fix File Encoding for VS2013. According to the site, it "automatically detects when a UTF-8 file is opened in Visual Studio and sets its encoding to UTF-8 without signature. If you don't edit the file, it remains unmodified. If you edit the file, it will be saved without the BOM."
It worked just fine to me. Hope it helps.


How to plot a heatmap/phase diagram with spacing defined by axes coordinates

Question: I am trying to plot a phase diagram with the areas of the squares defined by x,y axes coordinates, rather than equally spaced.
For example I have the following arrays:
import numpy as np

x = np.array([ 10,  50, 100, 150])
y = np.array([100,  80,  60,  40,  20,  10,   5])
z = np.array([[0.31, 0.33, 0.34 , 0.34],
       [0.31, 0.34, 0.34, 0.34],
       [0.30, 0.34, 0.35, 0.34],
       [0.30, 0.33, 0.34 , 0.34],
       [0.29, 0.31, 0.31, 0.31],
       [0.29, 0.30, 0.30, 0.29],
       [0.28 , 0.28, 0.28 , 0.29]])

I have tried plotting it as a dataframe using sns.heatmap(), but I cannot change the areas of the squares to be sized according to the x,y coordinates instead of equally sized.
I get this result:
heatmap

I also tried following a suggestion I found here: Plotting a 2D heatmap
using the code modified here as below, but this way the areas are different but not quite correct:
import matplotlib.pyplot as plt
import numpy as np

z_min, z_max = np.abs(z).min(), np.abs(z).max()

fig, ax = plt.subplots()

c = ax.pcolormesh(x, y, z, cmap='RdBu', vmin=z_min, vmax=z_max, shading='auto', edgecolors='black')
ax.set_title('pcolormesh')
# set the limits of the plot to the limits of the data
ax.axis([x.min(), x.max(), y.min(), y.max()])
fig.colorbar(c, ax=ax)

plt.show()

which gives this result, this seems almost what I would like but the sqares are not the correct sizes and I cannot quite figure out why:
pcolormesh

It would be great if I could also annotate the plot with the actual values for each square!
Answer: The x and y of pcolormesh indicate the positions of the edges between the cells. If you have 4 cells horizontally, there are 5 edges.
Supposing your given x and y are cell widths, you can use np.cumsum() to calculate the edge positions.
import matplotlib.pyplot as plt
import numpy as np

x = np.array([10, 50, 100, 150])
y = np.array([100, 80, 60, 40, 20, 10, 5])
z = np.array([[0.31, 0.33, 0.34, 0.34],
              [0.31, 0.34, 0.34, 0.34],
              [0.30, 0.34, 0.35, 0.34],
              [0.30, 0.33, 0.34, 0.34],
              [0.29, 0.31, 0.31, 0.31],
              [0.29, 0.30, 0.30, 0.29],
              [0.28, 0.28, 0.28, 0.29]])

fig, ax = plt.subplots()

x_edges = np.append([0], x.cumsum())
y_edges = np.append([0], y.cumsum())
c = ax.pcolormesh(x_edges, y_edges, z, cmap='RdBu', shading='auto', edgecolors='black')
ax.set_title('pcolormesh')
fig.colorbar(c, ax=ax)

plt.tight_layout()
plt.show()

The edges can be used to calculate the positions of the centers of the cells, and e.g. label the rows and columns with the x and y amounts.
x_mids = (x_edges[:-1] + x_edges[1:]) / 2
y_mids = (y_edges[:-1] + y_edges[1:]) / 2
ax.set_xticks(x_mids, x)
ax.set_yticks(y_mids, y)

Comment: Thank you so much! This was not quite the result I wanted, maybe I just didn't explain properly, but it did point me to the right direction and I managed to have the correct result thanks to you reply! Thanks again a lot!
Answer: import matplotlib.pyplot as plt
import numpy as np

x = np.array([10, 50, 100, 150])
y = np.array([100, 80, 60, 40, 20, 10, 5])
z = np.array([[0.31, 0.33, 0.34, 0.34],
              [0.31, 0.34, 0.34, 0.34],
              [0.30, 0.34, 0.35, 0.34],
              [0.30, 0.33, 0.34, 0.34],
              [0.29, 0.31, 0.31, 0.31],
              [0.29, 0.30, 0.30, 0.29],
              [0.28, 0.28, 0.28, 0.29]])

fig, ax = plt.subplots()
ax.set_aspect('equal')

x_edges = np.append([0], x)#.cumsum())
y_edges = np.append([0], y)#.cumsum())

c = ax.pcolormesh(x_edges, y_edges, z, cmap='RdBu', shading='auto', edgecolors='black')

ax.set_xticks(x) #_edges[1:], x)
ax.set_yticks(y) #_edges[1:], y)

ax.set_title('pcolormesh')
fig.colorbar(c, ax=ax)

plt.tight_layout()
plt.show()

Comment: Instead of `ax.set_xticks(x_edges[1:], x)` you can directly use `ax.set_xticks(x)`. The first parameter tells the positions of the ticks, the second parameter indicates labels (strings or numbers) to be placed at those positions.  If positions and labels are the same, it is recommended to leave out the second parameter, making the code more robust against future adaptations.
Comment: Thanks! I've edited the answer :)


Could anyone help to describe the two different priority ceiling protocols, ICPP and OCPP?

Question: As far as I know, for ICPP, a process can acquire the ceiling priority as soon as it accesses the shared resources. But for OCPP, when and how can the process with accessing to shared resources acquire the ceiling priority? Is it when ANY other process tries to access any shared resources? But which priority can it acquire then?
Answer:
But for OCPP, when and how can the process with accessing to shared resources acquire the > ceiling priority?

In OCPP the process only gets its priority boosted (set to the ceiling of the resource or to the priority of a higher-than-ceiling waiting thread) if it is blocking a higher task from executing.
From www2.in.tum.de/hp/file?fid=319

OCPP has an added restriction compared to ICPP that a process can lock
  a resource only if its dynamic priority is higher than the priority
  ceiling of ANY resource currently locked by other processes.

This last property comes from the fact that OCPP doesn't set the priority of the holding task right away after acquisition it can be subject to priority inversion (being postponed by a task that is lower in its original non-boosted priority).
These problems are solved in ICPP.


RAID 1+0 and varying sized disks

Question: I am setting up a RAID 1+0 with 8 drives with the following:

2x 300GB (15K RPM)
6x 600GB (15K RPM)
PERC H730 controller

I'm a bit confused what my total usable disk space would come out as. Would it be ~1200GB?
Also, is there any RAID reason the seller would specifically recommend varied sizes (which they did) as opposed to all the same sizes?
Comment: I would use the two smaller drives mirrored for the OS, the 6 remaining drives in a RAID 10.  If you did that, you'd have a RAID 1 with 300GB, and a RAID 10 with 1800GB.  I would be quite surprised if they were recommending you put varied disk sizes in a single RAID array.
Comment: Don't? Is there any reason you won't want to go with equally-sized drives?
Comment: @Zeno, Does the system you are looking at support UEFI?  If Dell built you a system with 8x600GB drives and you put those all into a single RAID10, you wouldn't be able to boot from that volume unless you have UEFI.  I haven't ordered a system from Dell in about 9 months, but really seemed to hide away the UEFI option, and really liked promoting a set of drives for the OS, and separate for the DATA volume.  That way you can have a bootable system, that doesn't require UEFI.
Comment: @Zoredache Ah, looks like it does: https://qrl.dell.com/Files/en-us/Html/Manuals/R630/Choosing%20the%20System%20Boot%20Mode=GUID-12C950B3-B0EF-4089-867E-89277DB2DA6A=3=en-us=.html
Comment: Not sure why Dell wouldn't let you build a system with 8x600GB drives.  configure.us.dell.com seems to show that as a valid configuration for a R630.  You going through a VAR or something?  Could just be the rep you are working with isn't actually paying attention to what you are asking for.  Sometimes you need to be quiet forceful to get them to pay attention and spec things out the correct way.
Comment: @Zoredache Going through a Dell Enterprise Product Specialist, but yeah... guess I'll just try clarifying again
Comment: They expect you to use 2 disks for OS. But with modern RAID controllers, you can make a single array of disks and carve them into right-sized logical volumes (virtual disks)
Answer: In order to avoid this from being an X-Y problem, let's address the real issue:
The Dell configurator won't allow you to spec equal sized disks for your RAID 1+0.
They expect you to use 2 disks for OS. But with modern RAID controllers, you can make a single array of disks and carve them into right-sized logical volumes (virtual disks).
So make a big array of all disks and make a small virtual disk for the OS; e.g. 200GB. Then make another virtual disk for your data drives. These show up as discreet block devices in the OS.

RAID 1+0 and varying sized disks


How to send from ESP32 to Arduino?

Question: I am using ESP32 to read a temperature sensor and I wont to send this reading to Arduino to act according to different reading
what should be the connection between the ESP32 and Aruido?
Answer: Should is not the appropriate word, I would suggest to use the UART (Serial.print() and Serial.read()).
Because the ESP has an operating voltage of 3.3V and Arduino 5V, you must use a level shifter.

How to send from ESP32 to Arduino?


Reinitialize global variables without refreshing the page in javascript

Question: Mine is a web Application, In a jsp page I have a div(outerDiv), inside which many inner Divs are added by dragging and dropping contents and a set of global variables are initialised !
I have the following requirement.
  I have a button click, as like refreshing the whole page I need to clear and reset all the contents of the outerDiv, i.e., clear the inner Div and reinitialize all the global variables present in js file without refreshing the page.
I found jquery .empty  the outerDiv, By calling <code>$("#attrList1").empty();</code>
But If I again drag and drop any content inside outerDiv, it cannot be added as the div is removed.
How do I do this ? How to reset the global variables in a javascript file?
Any suggestions !
Comment: can you provide a fiddle as we can give answer to reset the global variables but i think it will not solve your problem you need that DIV reseting problem solution too.
Comment: the global variable can be reset by re-adding the relevant script tag to the document. the problem is likely not globals though, it's pre-bound events, which need to be manually un-bound.
Answer: First, declare a global variable :
<code> var currentURL = document.URL;
</code>
Then to refresh the inner div i.e., to refresh a particular div content, try this:
<code> $('#outerDivContentID').load(currentURL+ ' #outerDivContentID');
 /*Note, be sure to include a space before the hastag.*/
</code>
At this point of time, i.e., when u click the button, reinitialize the global variables by setting a flag.
Hope this works.
Answer: If you just want to reset your global variables. Have them in a function and call it when you need to reset.
<code>$(function(){
//declare global variables or initialize them like var i=0;
 var init = function(){
// set the variables to their inital values i.e i = 0;
};

// Do whatever you want.
// Call the init to reset.
init();
});
</code>


Traffic control upload don't limit bandwidth

Question: I'm making some rule to limit the bandwidth per ip connection on my VPN server. My command works for download but doesn't for upload, I don't know what I'm doing wrong here :
<code>#!/bin/bash
TC='/usr/sbin/tc'
interface='eth0'
interface_speed='1gbit'
download_limit="5mbit"
upload_limit="5mbit"

$TC qdisc add dev $interface root handle 1: htb default 30
$TC class add dev $interface parent 1: classid 1:1 htb rate $interface_speed burst 15k
$TC class add dev $interface parent 1:1 classid 1:10 htb rate $download_limit burst 15k #DOWNLOAD LIMIT WORKS
$TC class add dev $interface parent 1:1 classid 1:20 htb rate $upload_limit burst 15k #UPLOAD LIMIT DOESN'T WORK
$TC qdisc add dev $interface parent 1:10 handle 10: sfq perturb 10
$TC qdisc add dev $interface parent 1:20 handle 20: sfq perturb 10
</code>
The result I get from speedtest :

Full script :
<code>#!/bin/bash
TC='/usr/sbin/tc'

interface="$dev"
interface_speed="1gbit"
client_ip="$trusted_ip"
client_ip_vpn="$ifconfig_pool_remote_ip"
download_limit="5mbit"
upload_limit="5mbit"
handle=`echo "$client_ip_vpn" | cut -d. -f4`

function start_tc {
  tc qdisc show dev $interface | grep -q "qdisc pfifo_fast 0"
  [ "$?" -gt "0" ] && tc qdisc del dev $interface root; sleep 1

  $TC qdisc add dev $interface root handle 1: htb default 30
  $TC class add dev $interface parent 1:1 classid 1:10 htb rate $download_limit ceil $download_limit
  $TC class add dev $interface parent 1:1 classid 1:20 htb rate $upload_limit ceil $upload_limit
  $TC qdisc add dev $interface parent 1:10 handle 10: sfq perturb 10
  $TC qdisc add dev $interface parent 1:20 handle 20: sfq perturb 10
}

function stop_tc {
  tc qdisc show dev $interface | grep -q "qdisc pfifo_fast 0"
  [ "$?" -gt "0" ] && tc qdisc del dev $interface root
}

function filter_add {
  $TC filter add dev $interface protocol ip handle ::${handle} parent 1: prio 1 u32 match ip ${1} ${2}/32 flowid 1:${3}
}

function filter_del {
  $TC filter del dev $interface protocol ip handle 800::${handle} parent 1: prio 1 u32
}

function ip_add {
  filter_add "dst" $client_ip_vpn "10"
  filter_add "src" $client_ip_vpn "20"
}

function ip_del {
  filter_del
  filter_del
}

if [ "$script_type" == "up" ]; then
        start_tc
elif [ "$script_type" == "down" ]; then
        stop_tc
elif [ "$script_type" == "client-connect" ]; then
        ip_add
elif [ "$script_type" == "client-disconnect" ]; then
        ip_del
fi
</code>
Answer: With tc, you are only shaping upload. Since tc is on your server, it is shown as download on your speed test.
To shape download aswell, you can take a look on ifb mirroring. (Tc: ingress policing and ifb mirroring)


Lower opacity of other text if it's not mouseover in Javascript

Question: I'm working on a project where I need to hover on a text which will not make it transparent but the rest of the text will.
In my code, I have a table where each row has its own text. I know how to set an ID attribute when you hover over the text but I couldn't figure out how to make the non selected text transparent.
The idea is that the ID, "test", will not turn the text transparent, any text that does not have the ID will turn transparent.
I would definitely prefer a Javascript solution.
Here's my window.onload code:
window.onload = function () {
let selectedRow = document.querySelector("tr");
selectedRow.addEventListener("mouseover", function () {
    createID(selectedRow);
    transparent(selectedRow, createID(selectedRow));
}, false)

selectedRow.addEventListener("mouseout", function () {
    nonTransparent(selectedRow);
}, false);
}

And here are my functions outside the window.onload:
function createID(elem){
    elem.setAttribute("id", "test");
}

function transparent(elem, id) {
    for (let i = 0; i < elem.length; i++) {
        if (elem[i] !== id) {
            elem[i].style.opacity = "0.25";
        }
    }
}

function nonTransparent(elem) {
    for (let i = 0; i < elem.length; i++) {
        elem[i].style.opacity = "1";
    }
}

And here's my table:

    Name
    Age
    Country

    John Doe
    24
    United Kingdom

    Jane Doe
    34
    United States of America

Comment: If I gather your code correct you want to make each non hovered `tr` transparent, which is easy doable in css. Also your `createID()` will provide the same `id` multiple times, which is *not an ideal* thing. Furthermore you are passing `undefined` as second argument to `transparent()` due to `createID()` not returning anything.
Comment: What is the status of this?
Answer: Not certain, but it looks like this is what you want to end up with. css only solution.

table:hover tr{
  opacity: 0.25
}

table tr:hover{
  opacity: 1
}

table tr td:hover{
  background-color: #e6e6fa
}

    Name
    Age
    Country

    John Doe
    24
    United Kingdom

    Jane Doe
    34
    United States of America

Your JavaScript has too many flaws to actually start commenting on it.


Drop Down List only renders with selected item if the selection has more than 3 characters

Question: In my controller I pass a list of values to the view to be used as the options for a select element by selecting from my database as SelectListItems, which works well enough. The problem is that when passing a selected option back to the view, the select only renders with the selected value if the selection is more than 4 characters (or at least while trying to figure out why it was happening, it only happened with the ones less than 4 characters). It also works perfectly if I select something with 4 characters, and then something with less than 4. I'm not sure why this happens or how to fix it. Here's (what I believe to be) the relevant code:
The Controller:
public async Task<IActionResult> Index(string selection = null){
    //code shortened for brevity
    if (!String.IsNullOrEmpty(selection))
    {
        ViewData["List"] = new SelectList(values.Select(c => new SelectListItem
        {
            Text = c,
            Value = c
        }), "Value", "Text", selection);
        ViewData["Selection"] = selection;
    }
}

The View:
<form asp-action="Index" method="get">
    <select asp-items="@ViewBag.List" name="selection" class="form-control" id="selectionDDL">
        <option value="">All</option>
    </select>
</form>

Appreciate any help!
Comment: I actually think I found the problem: if the 'selection' variable was null I just sent that values as a selectlist directly back to the view, without specifying the value and text as I do in the 'if' portion of the block. Not sure why it would only then work with selections of more than 4 characters, but this fixed it.
Answer: I actually think I found the problem: if the 'selection' variable was null I just sent that 'values' variable as a selectlist directly back to the view, without specifying the value and text as I do in the 'if' portion of the block. Not sure why it would only then work with selections of more than 4 characters, but this fixed it.


Let $A$ be the matrix of eigenvectors of an Hermitian $H$. Prove that $HA=AB$ with $B$ diagonal matrix with the eigenvalues of $H$

Question: Suppose we have a hermitian matrix $H$, and a matrix $A$ composed of eigenvectors of $H$, such
that
$\langle  A_i \mid A_i \rangle =1$, where $A_i$ is the $i$-th column of matrix H.
How to prove that $HA=AB$, where $B$ is a diagonal matrix whose diagonal elements are eigenvalues of $H$?
Thanks
Comment: So I'm guessing you're asking why an Hermitian matrix can be diagonalized with respect to an orthonormal basis in $\mathbb{C}^n$?
Comment: What is "such that =1, where i is the i-th column of matrix H" supposed to mean? It seems like you're missing some words.
Comment: sorry such that =1. That was typing error
Comment: Can you edit your post?
Comment: :) that is done
Comment: Sorry that is not my question
Comment: Then you should probably try to be clearer.
Comment: I mean that was not my question)))) Thank you for your link, that was very useful
Comment: @Silencer This is not a duplicate, and it is fairly clear. This is not about diagonalizing $H$. You could very well have the same eignevector repeated $n$ times in the matrix $A$.
Answer: Let $(X_j)$ be $n$ eigenvectors for $H$, possibly linearly dependent or even repeated. So we just have $HX_j=\lambda_j X_j$ for $j=1,\ldots,n$ and no further assumption.
Then consider the matrix $A$ whose $j$th column is $X_j$. When you compute the matrix product $HA$, the $j$th column is $HX_j=\lambda_j X_j$.
Now denote $D$ the diagonal matrix whose diagonal is $\{\lambda_1,\ldots,\lambda_n\}$. When you compute the matrix product $AD$, the $j$th column is $\lambda_jX_j$.
So $HA=AD$ as they have the same columns.
Note: you don't need the assumption that the $X_j$'s have norm one, and more importantly, you don't need $H$ to be hermitian. $H$ could be any matrix, as long as you take eigenvectors of $H$ to form the columns of $A$.


Best way to ensure decimal interpretation of string with leading zeros?

Question: I have some simple data with leading zeros, and I want to interpolate some additional values.  Something like this:
$ printf "C011=4\nC015=8\n" | perl -ne '/C(\d\d\d)=(.*)/; $l{$1}=$2 }{ $l{13}=($l{15}-$l{11})/2+$l{11}; printf "C%03d=%f\n",$_,$l{$_} for keys %l;'
C011=4.000000
C013=0.000000
C015=8.000000

Okay.  Perl's not matching 11 to 011
In the simple case above, you might think, hey, whatever, let's use the leading zeros in the hash keys for the arithmetic:
$ printf "C011=4\nC015=8\n" | perl -ne '/C(\d\d\d)=(.*)/; $l{$1}=$2 }{ $l{013}=($l{015}-$l{011})/2+$l{011}; printf "C%03d=%f\n",$_,$l{$_} for keys %l;'
C011=4.000000
C011=0.000000
C015=8.000000

Here I apparently have as keys the string 011 which printf turns into 11, and the octal number 013, which printf turns into 11.  And the lookup of the 011 and 015 values still failed.
What are the options in perl for avoiding the behavior of numbers with leading zeros (and no 9's) being interpreted as octal?  I want the hash keys to have their appropriate decimal value.
I have a workaround.  I just want to see if it's the most succinct solution.  Something like a global don't-do-this, I'm never using octals.
Expected output:
C011=4.000000
C013=6.000000
C015=8.000000

Comment: **Helpful tip**: To drop leading zeroes from a string which is otherwise a valid number do this: `$s=$s+0; # Just add zero to it` But first check your string is a valid number.
Answer: The problem with the original code is that hash keys are strings, and 011 and 11 are different strings.

Solution 1: Use the correct string.
perl -ne'
   /C(\d\d\d)=(.*)/; $l{$1}=$2;
   END {
      $l{"013"}=($l{"015"}-$l{"011"})/2+$l{"011"};
      printf "C%s=%f\n",$_,$l{$_} for sort keys %l;
   }
'

It's simpler to include the C.
perl -ne'
   /(C\d\d\d)=(.*)/; $l{$1}=$2;
   END {
      $l{C013}=($l{C015}-$l{C011})/2+$l{C011};
      printf "%s=%f\n",$_,$l{$_} for sort keys %l;'
   }
'

Solution 2: Convert the captured strings to match those produced by the code.
Replace $l{$1}=$2 with $l{0+$1}=$2.
This will numify 011 to eleven, then stringify that to 11.
This supports any number of leading zeros.
Comment: In Perl, scalars are coerced into numbers where a number is expected (addition, multiplication, `sprintf %d`, etc), and coerced into strings when a string is expected (`print`, hash key, etc).  `sprintf %d` is fine, but `0+` is cheaper and a bit more self-documenting (because noone would use `0+` for anything else).
Comment: Solution2 is what I was looking for.  In my actual program, I have to use the keys themselves as numbers in other arithmetic, so it's the `0+` numification that I was searching for.   I was actually using `sprintf "%d",$1` where you have suggested `0+$1`
Comment: @ysth, I do use `END { }` personally. Saving 4 chars is no reason to use `}{`. The `}{` is from the OP's code. But you know what, I already added a `sort`, so I'll have the program use `END { }`.
Comment: In the real program, I have `sub n {$a <=> $b};` once and `sort n keys %l... ` wherever I need a numerical sort.  Numbers with different numbers of characters don't sort well.  But that and the eskimo kiss operator weren't the point.
Comment: `sort`''s default sort function works fine where I used it because the numbers were padded to the same length using zeroes


Validação de formulário de email com javascript

Question: Criei um formulário para envio de email, consigo enviar o e-mail mas não consigo verificar se os campos estão preenchidos.

<!doctype html>

<meta charset="utf-8">
<title>Contato</title>

Envie sua mensagem:

<form method="post" action="http://www18.locaweb.com.br/scripts/FormMail.pl"/>

<input type="text" placeholder="Nome" required name="name" id="name">

<input type="text" placeholder="Email" required name="email" id="email">

<input type="text" placeholder="Assunto" required name="subject" id="subject">

<input type="text" placeholder="Mensagem" required name="message" id="message">

        <button type="submit" name="Submit" onclick="javascript: var submit = checkEmail(getElementById('id').value); return submit;"> ENVIAR MENSAGEM </button>

    </form>

Comment: O que quer dizer com "*não verifica os campos*"?
Comment: Não verifica se os campos foram preenchidos e não verifica se o email está correto, e estando tudo certo, não aparece a mensagem final de email enviado com sucesso.
Comment: M. Nunes, conseguiu resolver?
Comment: Sim, consegui resolver, segui a orientação do Icaro Martins, funcionou perfeitamente.
Answer: Olhei seu código mudei a forma como você esta tentando fazer o submit e corrigi alguns problemas e coloquei alguns comentários para explicar o que fiz, espero que te ajude. =D

function checkEmail () {
        var frm = document.forms[0];
///                           ^ faltava o `s`, alem de ser uma array
     var name = frm.name.value;
///                     ^ name == `HTMLElement` pelo codigo parece que você quer o `value`
     var email = frm.email.value;
     var subject = frm.subject.value;
     var message = frm.message.value;
     var count = 0;
     var flagError = false;
     var error="";

     if (name == "") {
      error += "O campo Nome deve ser preenchido.";
      count = count + 1
      flagError = true;
     }

     if (email == "") {
      error += "O endereço de e-mail deve ser preenchido.";
      count = count + 1
      flagError = true;
     }

     if (subject == "") {
      error += "O campo Assunto deve ser preenchido.";
      count = count + 1
      flagError = true;
     }

     if (message == "") {
      error += "O campo Mensagem deve ser preenchido.";
      count = count + 1
      flagError = true;
     }

     if (count > 0 ){
              alert("Os seguintes erros foram encontrados:\n" + error);
///              a variável usada esta com o nome errado `erro`   ^
              return;
///             ^  estava aparecendo dois alerts entao coloquei um return aqui

     }

     if (!flagError) {
      var illegalChars = /(@.*@)|(@\.)|(@\-)|(@_)(\.@)|(\-@)|(\.\.)|(^\.)|(\.$)|(\.\-)|(\._)|(\-\.)|(_\.)|(^_)|(_$)|(_\-)|(\-\-)|(^\-)|(\-$)|(\-_)/;
      if (email.match(illegalChars)) {
       error += "O endereço de e-mail contém caracteres inválidos.";
       count = count + 1
       flagError = true;
      }
     }

     if (!flagError) {
      var emailFilter = /^\S+\@(\[?)[a-zA-Z0-9_\-\.]+\.([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$/;
      if (!(emailFilter.test(email))) {
       error += "O endereço de e-mail não está em um formato válido.";
       count = count + 1
       flagError = true;
      }
     }

     if (!flagError) {
      var emailFilter = /^([a-zA-Z0-9\@_\-\.\+]+)$/;
      if (!(emailFilter.test(email))) {
       error += "O endereço de e-mail não está em um formato válido.";
       count = count + 1
       flagError = true;
      }
     }
     if (!flagError) {
      flagError = false;
            frm.submit()
///              ^ fazer o submit do form se tudo estiver correto
      window.alert("Mensagem enviada com sucesso!")
      }

     if (flagError) {
      window.alert(error);
     }

     return !flagError;
    }
    <!doctype html>

    <meta charset="utf-8">
    <title>Contato</title>

Envie sua mensagem:

    <form method="post" action="http://www18.locaweb.com.br/scripts/FormMail.pl"/>

<input type="text" placeholder="Nome" required name="name" id="name">

<input type="text" placeholder="Email" required name="email" id="email">

<input type="text" placeholder="Assunto" required name="subject" id="subject">

<input type="text" placeholder="Mensagem" required name="message" id="message">

            <button type="button" onclick="checkEmail()"> ENVIAR MENSAGEM </button>

        </form>

Comment: Agradeço a ajuda
Comment: Perfeito, totalmente funcional.
Answer: Analisando seu código, encontrei dois problemas que estão impedindo o funcionamento de seu código.

A forma como você captura o valor dos elementos inclusos no seu formulário.
A variável erro no trecho: alert("Os seguintes erros foram encontrados:\n" + erro); não existe.

Solução¹: A propriedade form no trecho document.form não existe, acredito que você tentou acessar o HTMLCollection pela propriedade forms.
Note que a propriedade forms retorna uma Coleção de objetos HTML de acordo com a quantidade de formulários inclusos em seu código fonte, então para solucionar seu problema você vai acessar o atributo da seguinte forma: document.forms[índice], como só existe um formulário, vamos utilizar o índice 0(já que só existe um formulário). Ao acessar o formulário, os campos também são retornados em uma lista de inputs. Como você possui 4 campos, vamos acessá-los da seguinte maneira: document.forms[índice].[índice_do_elemento];. Observe a seguinte imagem para facilitar o entendimento.

Ou seja, para acessar os itens, você vai substituir seu código:
var name = document.form.name;
var email = document.form.email;
var subject = document.form.subject;
var message = document.form.message;

por:
var name = document.forms[0][0].value; //name
var email = document.forms[0][1].value; //email
var subject = document.forms[0][2].value; //subject
var message = document.forms[0][3].value; //message

Solução²: Basta alterar a variável erro, para error. Uma vez que a variável erro não existe.
Nota: Existem várias maneiras para acessar os elementos de seu formulário, a forma que utilizei para solucionar seu problema foi apenas para manter sua sintaxe.


Por quê recebo este erro no locale.h? [Error] expected declaration specifiers or '...' before numeric constant

Question: O erro ( [Error] expected declaration specifiers or '...' before numeric constant ) é apontado no
setlocale(LC_ALL, "Portuguese");
Porém, a biblioteca locale.h e a vírgula estão presentes e declaradas no código anteriormente, por que recebo este erro?
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>
#include <locale.h>

#ifndef _BIBLIO_H
#define _BIBLIO_H

#include "biblio.h"

#define lim 100
#define prod 500

setlocale(LC_ALL, "Portuguese");

//declarando as funções do programa
void cadastro();
int cad_fornecedor();
int cad_produto();
void menu();

Comment: O setlocale deve estar dentro de uma função, provavelmente a main.
Answer: Como o @anonimo citou, setlocale() precisa estar dentro da main(), ou de alguma outra função, e especulo que um dos fatores abaixo estejam relacionados a esse erro.

O setlocale(LC_ALL, "C"); ser executado antes de qualquer outro código do usuário.

E o comportamento ser indefinido quando o setlocale() é chamado de alguma thread, enquanto outra thread está executando um printf() ou até o próprio setlocale() por exemplo.


Making hosted applications resilient to BGP failures

Question: My company builds various web sites for its customers with a dedicated hosting provider.
This hosting provider accidentally shutdown the devices responsible for Border Gateway Protocol (BGP) announcements for a small range of IPs. Since I'm lucky like that, one of these IPs happened to be the public IP address assigned to the load balancer for all of the web traffic for our customers. As a result, the BGP routing advertisement for this range was withdrawn and quickly became unreachable worldwide.
The hosting provider remedied the problem once alerted to it, but that cost us over 15 minutes of downtime, which we're anxious to avoid in the future.

How could we monitor this? It's a lot lower level than our normal monitoring, which just checks apache httpd status, JVMs, etc. We have internal monitoring which uses Advent AppEngine to check server processes, apache server status responses, application home page responses.
Are we able to take steps to fix this ourselves; e.g. by making our own BGP announcements somehow?

I'm happy for pointers / suggested reading rather than just straight answers, since this level of the stack is completely new to me and I'd like to fill in the gaps of my knowledge.
Answer: You're unlikely to be able to work around this, unless your address space is large enough for you to be able to run your own BGP. Even then, you're vulnerable to BGP failures by your peers.
If you're using multiple DNS servers in separate ASes, you may be able to have some kind of work around by setting a low TTL and failing over to a separate web server in a different netblock/data centre by changing DNS once problems are noted. Even this will take several minutes however, at the least.
EDIT: as pointed out by Chris, if you're running BGP, you need all of your peers to fail before you become unreachable.
Comment: That's why you have 2 providers and you peer with both.
Comment: If you have different datacenters you could also load-balance at DNS level. In case of routing holes affecting one of your DC the users will still have _partial_ connectivity even during the failover.
Answer: You're unlikely to be able to run BGP unless you have at least a /23 of Provider Independant address space and have an ASN number. As such, you need to trust your hosting company. Router changes tend to be fairly rare, so the likelihood of this problem happening again is slim. You could investigate any SLA you have with them, but this is probably just going to involve getting a refund on your hosting fees.
As far as monitoring is concerned, we have a dedicated server outside our network, which we use as an external Nagios server. You could buy a cheap VPS server and use that to monitor things from the PoV of an external user. For example, we check SMTP and HTTP work, rather than checking that exim and apache are running, which we do on our internal monitoring.
Comment: You can probably advertise a /24 as easily as a /23 -- your providers may summarize that, but likely you'll be getting IP addresses from them anyhow, so it isn't a crisis...
Comment: If you're using PA space, it's very unlikely that you'd need to or want to run BGP. Quite a lot of places will also filter out networks smaller than /23 routes to reduce their routing tables.
Comment: People with smaller routers may filter to /23 but providers won't and they're the ones you care about.  If you're dual homed and connected to provA and provB and have address space in provB's assignments, you'll still be covered because provA and provB peer upstream of you and even if almost everyone else summarizes routes down to /20 (for the sake of argument) you can be damned sure that provA and provB *don't* summarize away a customer's route.  A remote session will hop onto provB's network right up to the break then, because they peer with provA, use that for the rest of the trip.
Comment: Also, monitoring from an outside network will have other advantages over BGP monitoring: it will detect non-BGP failures.
Answer: For the record, it exists several gratis BGP monitor and alarm systems. None provide a resolution of 15 mn as you want. And, since you can have many other causes of outage, monitoring the IP connectivity from the outside is the only real solution.

Cyclops
RIPE IS
BGPmon, my favorite

A general article about BGP monitoring, in french.
Answer: Depending on how things are setup, the size of the netblock being advertised, and how things get agregated upstream, you may be able to use one of the looking glass scripts to monitor BGP announcements for the block your server is in.
It may be easier to just ping both your host and the router one step back from your server from the outside.  You can use traceroute to determine which address to use.
There is very little you can do to prevent your hosting company from doing this again.  In order to do so you would need to have a router or other host running BGP connected to your provider at a minimum.  Unless you also have another provider, it wont help if they accidentally turn off the peering router.
A better solution may be to have a failover site as mentioned by another answer.  Depending on your risk tolerance you can setup failover to happen in a very short time but it involves complete control of your DNS.
Comment: He was talking about 15 mn of downtime. Reading the looking glasses will take more time than that. Pinging from the outside is indeed the best solution.
Answer: Your options are pretty limited.  You can yell and scream at your provider, you can move to another provider, you can get 2 different IP ranges and advertise services on both and have short TTLs on your DNS entries.
But
If you really want to solve this, move to a colo facility with a meetme room and buy bandwidth and IP addresses from a couple providers.  Then, register an ASN with arin (or whatever registrar is correct for wherever you live) and peer with the providers yourself.
If you're buying enough bandwidth, it won't be hard to get them to cough up a /24 or /23.  The peering is also going to be pretty easy, depending on the size of the colo facility and the amount of bandwidth you're going to be asking for.
If you're writing big checks and you act like you know exactly what you want (and what you want is reasonable) it isn't hard to get this stuff done.  If you farm it out to your "provider" you'll always be on the dumb end of the stick.
Comment: Be wary of providers that will "cough up" a /24 or /23 of address space based on how much you are spending rather than demonstrable need.  Chances are they are breaking the rules that they agreed to when becoming an LIR.

Provision of Provider Independant address space is out of your service provider's hands.  AFAIK no RIRs will make a PI assignment based on invoice size...
Comment: Like Russell says - I'd be very wary if an LIR is willing to bypass the application/documentation process just to get a sale. It could place the assignments and the LIR in jeopardy. You need to demonstrate need to the LIR and the LIR must make that available to the RIR. Renumbering is always possible but it certainly isn't easy.
Comment: Providers have lots of addresses.  They own them, you use them, you change providers you give the addresses back.  No need to talk to a registrar except for the AS number.  The need you provide the provider is that you want it to be reliable.  The only real hazard is that it is slightly harder to change away from the provider who is loaning you their address space, but that's always the case unless you get your addresses directly from a registry, which as you say, is slightly harder (you *do* need to demonstrate need, as described in one of the docs I linked to).
Comment: ISPs give out netblocks all the time.  How is this any different, except that you're associating an AS with that netblock and advertising it out to to providers?  There isn't any funny business going on -- you have a legitimate need to dual home your enterprise and you don't need a giant allocation of addresses so you just get the addresses from the provider, which I assume is kinda what their business is.  Chances are you can even just get a /29 from them and your two providers are happy to route those.  They may not appear in the global route tables, but that's not a problem.
Comment: If the /29 is part of ProviderA's allocation and is not showing up through ProviderB from the core and ProviderA then suddenly no longer announce it, how does the (non-announced) network via ProviderB actually help?
Comment: chris> You were talking specifically about pushing through large assignment requests on the account of bandwidth sales. That's not the same as handing out a tiny /29. Some RIRs do accept multi-homing as a valid reason for a /24. But like any large request, the need should be correctly demonstrated and documented.
Comment: @danc: Yes, I was saying you could get a /24 if you ask your ISP and you're giving them enough money and you tell them you want to multihome with another ISP.  I hardly call a /24 a "large" request.  Selling IP addresses and packets kinda what ISPs do, isn't it?  And, I'd say that, if I'm multihoming, a /24 is just the same as a /29, as far as the providers are concerned.
Comment: @vatine: If I am multihomed to ispA and ispB and I've got a /29 from ispA's range.  Both ispA and ispB will have my /29 in their routing tables, ispC may be a lame isp, or maybe they're in botswana so they just don't care.  They will simply summarize my route to go through ispA alone.  That's fine unless ispA vanishes completely because ispA and ispB peer with each other, so if ispA's last hop to me is down, it will hand the traffic off to ispB and ispB will take care of it the rest of the way.
Answer:
You can monitor your provider announcements by asking public route-servers (http://www.traceroute.org/#Route%20Servers) about the prefix you're using. You can automate this kind of monitoring by telneting these route servers.
If you use enough bandwidth, have the budget and the skills for such deployment, you can ask for an AS number and an IP address range. However, this is costly, and since RIRs are going out of IPv4 addresses, you'll have to give real proof of your needs.


Anyone got a regex for all known international postcode/zipcodes?

Question: I've been searching for a global postcode based regex but not found one. Anyone know of one that exists?
Comment: What do you want the regex to actually do? Bearing in mind that a decent regex just for UK postcodes is "((A[BL]|B[ABDHLNRST]?|C[ABFHMORTVW]|D[ADEGHLNTY]|E[HNX]?|F[KY]|G
[LUY]?|H[ADGPRSUX]|I[GMPV]|JE|K[ATWY]|L[ADELNSU]?|M[EKL]?|N[EGNPRW]
?|O[LX]|P[AEHLOR]|R[GHM]|S[AEGKLMNOPRSTY]?|T[ADFNQRSW]|UB|W[ADFNRSV]
|YO|ZE)[1-9]?[0-9]|([E|N|NW|SE|SW|W]1|EC[1-4]|WC[12])[A-HJKMNPR-
Y]|[SW|W]([1-9][0-9]|[2-9])|EC[1-9][0-9]) [0-9][ABD-HJLNP-
UW-Z]{2}", it's possible that one for multiple countries could become a tad complicated... (http://en.wikipedia.org/wiki/Postcodes_in_the_United_Kingdom)
Answer: Not sure if this really makes sense to try to test for, I think it would be:
 0-18 characters which can contain: 0-9 + the basic Latin alphabet + spaces, hyphens, parentheses and a Cyrillic letter.
And I'm not at all sure that even that would cover all possibilities.
Comment: @Amarghosh: But I think I've seen that people sometimes put a space in the middle? And if that's correct, then even that simple regex becomes a bit more complex (though I'm not sure if spaces are required in any country so possibly you could just strip out all spaces before doing the match).
Comment: People put spaces while writing (for ease of reading I guess), but that's not the standard. But I agree that an all encompassing regex for any post code will be cumbersome.
Comment: Spaces are part of the format of UK postcodes. For example, "BS1 6XB". The space isn't generally considered as optional, so they're almost always written like that.


Installing python36 onto pfsense

Question: I'm currently trying to install python36 onto the main pfsense system, this is so I can get netdata and a few other things installed.
However, I'm having problems with trying to find the command too download it. Just keeps telling me it can't find python, py36 or anything of the such, if you could please let me know the commands needed to download python 36 that would be great.
Thanks
Answer: pfSense is based on FreeBSD so you have to try
sudo portmaster lang/python3

(This will build from source, including its dependencies)
or
sudo pkg install python3

(To only fetch binary files)
To search about more python3 packages, then run following command in terminal:
psearch python3

Comment: Updating pfSense-core repository catalogue...
pfSense-core repository is up to date.
Updating pfSense repository catalogue...
pfSense repository is up to date.
All repositories are up to date.
pkg: No packages available to install matching 'python3' have been found in the repositories
Above is the error that it's giving me when I run pkg install python3, I've tried portmaster lang/python3 and it says it can't find portmaster, pkg install portmaster gives the same error as above, any ideas?
Comment: Can you run `psearch python3` and paste results here ? or `psearch python`

Installing python36 onto pfsense


Method checking and proof of differentiability for the given function

Question:
Let $f :\mathbb{R} \to \mathbb{R}$  be a continuous function such that $f (x^2) =
 f (x^3)$ for all $x$ ∈ $\mathbb{R}$ . Consider the following
statements.
(I) f is an odd function
(II) f is an even function
(III) f is differentiable everywhere.
Which of them are true ?

My method was as f is continuous for all $R$ putting $x = -t$ in the equation we get $f (t^2) =f (-t^3) = f (t^3)$ from this taking the last two I can say $f (-x) = f (x)$, for differentiability I would need to check limit $\frac{f (x)-f (a)}{x-a}$, but here how do we check to conclude differentiability too?
Answer: Question III.
Let $y>0$.  Then $y=x^3$ for some $x>0$ and $x^2 = y^{3/2}$.  So
we have $f(y) = f(y^{3/2})$.
Let $y \in (0,1)$.  Now let $y_n = y^{(3/2)^n}$.  Then $y_n \to 0$ and $f(y_n) = f(y)$ for all $n$.
Since $f$ is continuous and $y_n \to 0$, we have $f(0)=f(y)$.  So $f$ is constant on $[0,1)$.  As we know $f$ is even, we have $f$ is constant on $(-1,1)$.
Similarly, let $y > 0$.  Taking $y_n = y^{(2/3)^n}$ we have $y_n \to 1$, so $f(y) = f(1)$.  And again, $f$ is even so now we know $f$ is constant on $\mathbb R$.
Not only is $f$ differentiable, but $f'(x) = 0$ for all $x$.


Formation Of Sets

Question: I don't know whether the theorem below is true or not. If true, is there any proof of the theorem.

Number of ways of dividing $l_1$ sets containing $p_1$ objects each and $l_2$ sets containing $p_2$ objects each and so on.. is equal to $\frac{n!}{(p_1)!^{l_1}(p_2)!^{l_2}.......(p_k)!^{l_k}(l_1)!(l_2)!.....(l_k)!}$.

Where $(l_1)(p_1)+(l_2)(p_2).....+(l_k)(p_k)=n$
Comment: Yes, you can resemble groups as sets
Comment: Thanks for correcting me I didn't knew that
Comment: No problem :) https://en.wikipedia.org/wiki/Group_(mathematics)  It is interesting subject... Give it a try when you have time.. I am hesistating to say that sets and elements are used together and not sets and objects.. There is something called category.. category and objects are used together... sets and elements are used together... may be just a choice of words for now but in advanced mathematics it might cause some confusion..
Answer: You have
$$\sum_{i=1}^kl_ip_i = n$$
Now, make $k$ rows, such that each row contains $l_ip_i$ objects. Further divide the $i^{th}$ row in $l_i$ block each containing $p_i$ objects. Now, there are $n!$ ways of arranging the $n$ objects and each such arrangement corresponds to an arrangement of objects in these $k$ rows we have made. Now, call two objects to be in same group if they are in same block. This gives rise to two kinds of repetitions in calculating the number of groupings, as follows.
In every row, we can permute the blocks among each other keeping the groupings same. Thus we have $l_i!$ repetitions in the $i^{th}$ row and thus we have to divide $n!$ by $l_1!l_2!\cdots l_k!$.
Also, we can permute the elements in a block among themselves keeping the same groupings. Thus we have $(p_i!)^{l_i}$ in $i^{th}$ row. Hence, the total number of required groupings are $$\frac{n!}{l_1!l_2!\cdots l_k!\times (p_1!)^{l_2}(p_2!)^{l_2}\cdots (p_k!)^{l_k}}$$
Hope it helps:)
Comment: What if $$\sum_{i=1}^kl_ip_i < n$$ ??
Comment: Then $n-\sum_{i=1}^kl_ip_i$ is another group.

Formation Of Sets


Showing Divergence of a complex sequence

Question: Given a sequence $z_{n} = z^n+z^{2n}$ where $z$ is a complex number. How do I show that the sequence diverges when $|z| > 1$? I see that even in the cases where one cancels other, the magnitude of $z^2$ is always bigger than $z$, so there is no cancellation. So I know this sequence diverges. But how do I show that it does?
Comment: Have you tried "completing the square"? $\, x+x^2=(x+1/2)^2-1/4.$
Comment: @user1337 That's a very good answer in my opinion. Why don't you write it up?
Answer: $$|z_n|\ge\left||z^{2n}|-|z^n|\right|=|z|^n(|z|^n-1)\Rightarrow |z_n|\to\infty$$


What is the maximum value in a finite selection of a normally distributed variable?

Question: A parameter of an object is normally distributed with a mean m and a std. dev. s. If r such objects are randomly selected, what is the maximum expected value M of the parameter in the selection?
Cross-posted from: https://mathoverflow.net/questions/105903/what-is-the-maximum-expected-value-in-a-finite-selection-an-object-with-normal-di
Comment: Note that for large $n$, the asymptotic theory result was given here: http://stats.stackexchange.com/q/34418/5739
Comment: The expected value is `m`, so there is no point in asking about its maximum.
Comment: @StasK: (+1) There is an interesting and somewhat subtle feature to note here. Since convergence in distribution does not imply that the means converge to that of the limit distribution, we may wonder whether that holds in this particular case, especially since we are dealing with maxima, where the prospect of mass "escaping to infinity" would seem to be more plausible. In fact, the means *do* converge, as proven by [Pickands (1968)](http://projecteuclid.org/euclid.aoms/1177698320).
Comment: @caardinal, that's an interesting note.
Comment: The maximum expected value or the expected value of the maximum? (This question is a bit rhetorical; answers can be given for both, but one is more interesting than the other.) Also, I recall a recent duplicate or near-duplicate; it would be worth doing a quick site search.
Comment: I wanted the expected value of the maximum, but I don't see it to be different from the maximum expected value. Can you explain my error?
Answer: Let $\Phi(x) = P[X\leq x]$ when X is normal with mean m and standard deviation s.  Then
$$ \Phi^n(x)= P[\max (X_1,X_2,..., X_n) \leq x].  $$
So $E[\max (X_1,X_2,..., X_n)] = \int_{-\infty}^{\infty} x n \Phi^{n-1}(x) \Phi^{\prime}(x)dx$.
Comment: $\Phi'$ is of course the derivative of $\Phi$
Comment: What is $\Phi^{\prime}$?


Can I add a field collection to a block?

Question: I have made a field collection, exported as a Feature and now I'd like to add it to a block.  Does anyone have any suggestions?  I have added fields to blocks through the form API, but that doesn't seem to apply here.
I would like to add this field collection through code, rather then finding a module.
I've looked at hook_block_configure to add the form there, but I don't know if I can add a type that isn't listed in Form API reference.
Comment: Field collection or paragraph type cannot be added to blocks.
Answer: How about doing it through Views.
You can create a block view, add your field collection to the view, then use the view as a block.
Comment: There is no need to create a view page.  Simply create a view as a block as suggested by Hayk.  Unless you already have the BEAN module enabled for something else AND OR don't have views installed, I would suggested using views.   (1 less module)
Comment: This is perfectly valid, but I rather use the Bean solution as you don't have to worry about having a page url and not having google indexing it.
Answer: With the default Block system you can't add fields to Blocks.
You can use the Bean module, which converts Blocks into Entities. Then you will be able to add fields to it.
Comment: I know you can't add fields to the Blocks through the UI, but what about through hook_form?
Comment: Or not through hook_form specifically, but through code more generally?
Comment: You can use hook_block_configure() to add form configuration to a block but adding a Field Collection that way isn't possible.
Answer: You really need to have a look at the Bean to answer this question. Here is a quote about its project page:

Think of a Bean as a method to provide new types (compared to node this would be a content type) which then provides an add content interface to create as many blocks as you require (see screenshot below). The bean content can then be placed around the site just like any other block.

This module also works great in combination with the UUID and UUID Features Integration modules.
The video tutorial Drupal Bean module tutorial - using Bean Admin UI provides a great introduction to really understand the power of this module, and the kind of things you can do with it. It also shows how the Bean module transforms Drupal blocks into fieldable entities.


Delete/Drop columns with name beginning with X*

Question: I have the following data and framework:
raw = { 'A': [1, 10],'B': [100,1000],'logA': [0, 1], 'logB':[2,3]}
df= pd.DataFrame(raw, columns=['A','B','logA','logB'])

How can I drop all columns that starts with "log"? I have tried df.drop(['logA','logB'],axis=1), but I want to know if there is something I can do with df.columns.str.startswith('log').
Answer: Yes
Option 1
use loc and boolean indexing
df.loc[:, ~df.columns.str.startswith('log')]

    A     B
0   1   100
1  10  1000

Option 2
Use pd.DataFrame.filter with a negative lookahead regex
df.filter(regex='^(?!log)')

    A     B
0   1   100
1  10  1000


Difference between Virtual Address vs physical address

Question: what is the meant by the statement "A computer system supports 32-bit virtual addresses as well as 32-bit physical addresses " , its confusing. I know there is memory management unit(MMU) which does the converstion of virtual address to physical but i am not able to understand what does that statement actually mean?
Please help !!!
Thanks in advance.
Answer: In a nutshell this phrase means: only 4G of physical RAM is supported by hardware and each process can have 4G of virtual memory (so sum across all processes > 4G). Virtual memory will consist of some amount of physical RAM and some amount of swap file.
Comment: what if machine has 80 GB HDD and sum of all processes exceeds HDD space as virtual memory resides in HDD , what type of error it will generate ?
Comment: it depends on particular operating system, but in general if either virtual space of particular process is exhausted (i.e. particular process allocates more than 4G) or all pages from both RAM and page file assigned to some process (i.e. no free page) you'll get some kind of out of memory error (e.g. std::bad_alloc in c++) and mostly the error will be the same for both kind of situations.
Comment: one more note. you should consider only requested memory. e.g. if there are 2 processes and computer has only 2G of RAM and 2G of paging file - processes won't see out of memory error until they require 4G of virtual memory in sum. So, first process allocate 2G of virtual memory and second process allocates 1.9G - everything is OK, but when one of them allocate another 0.1+ G - out of memory error will be thrown.
Comment: Also note that this is very simplified explanation, to get full picture of memory management by modern OS, I'd recommend you to read some good book on this (e.g. http://www.amazon.com/Understanding-Linux-Kernel-Third-Edition/dp/0596005652/ref=cm_lmf_tit_2)


How to Find basis from set of polynomials

Question: Let $$P=\{(a+d)x^3+(a+b)x^2+(c+d)x+i(b+c)|a,b,c,d \in \mathbb{C}\} $$
I need to find basis for this Vector subspace.
my suggest answer :
we got :  $$a(x^3+x^2)+b(x^2+i)+c(x+i)+d(x^3+x)=P$$
so its easy to see that : $$B=\{(1 ,1,0,0),(0,1,0,1),(0,0,1,1),(1,0,1,0)\}$$
is the standard basis .
Is this correct ? if not How Can i find the basis ?
thanks
Answer: $B=\{(1 ,1,0,0),(0,1,0,1),(0,0,1,1),(1,0,1,0)\}$
Notice that $$(1 ,1,0,0)-(0,1,0,1)+(0,0,1,1)=(1,0,1,0)$$
Hence the vectors are linearly dependent and cannot be a basis.
Try to prove that $C=\{(1 ,1,0,0),(0,1,0,1),(0,0,1,1)\}$ is linearly independent.
Also note that $(1,1,0,0)$ corresponds to $x^3+x^2$. Try to write out which polynomial those vector correponds to.
Comment: oh that's correct , thanks alot .


If two topological manifolds are homotopy equivalent, what does this tell us about the categories of vector bundles over them?

Question: A question in the latest differential geometry assignment asks us to show that every vector bundle over $[0,1]$ is trivial. However, the proofs available online typically use machinery we haven't been exposed to yet, like affine connections, or Cech cohomology. So I've been thinking about what elementary arguments can be used to show this. I envision that one possible proof would look a bit like this:

$[0,1]$ is homotopy equivalent to the point.
Every vector bundle over the point is trivial.
Hence every vector bundle over $[0,1]$ is trivial.

Step 3 is the part I'm unsure about. What I'd like to know is

Question. If two topological manifolds are homotopy equivalent, what does this tell us about the categories of vector bundles over them?
Answer: Isomorphism classes of vector bundles of rank $r$ on $X$ are classifed by homotopy classes of maps $f : X \to \text{Gr}(r, \infty)$, this is the theorem 1.16 in the notes by Hatcher. (Here $\text{Gr}(r, \infty)$ is the infinite grassmanian of $r$-planes).
Comment: It's also worth pointing out that $X$ doesn't have to be a manifold for this to hold.


How to view PDF files in a modal/overlay

Question: I have pdf (managed) files on the server that I want users to view in a modal. This will be part of a module I'm creating. There are a couple of modules that help with this, but I haven't found a good way to incorporate those yet.
One of the most promising seems PDF Reader, but it requires you to create a node before it will do its magic. I would like to just use the file (managed file, stored using Drupal) and not create a separate node for each file.
I'm open for any suggestion. I have already implemented some CTools modals and Modal Forms (for easy display of Webform content) so I can work with that. But maybe it would be easier to create a node on the fly of the content type created for PDF Reader (say pdf file) and show that with a custom node--pdf-file.tpl.php. But how to create such a node then and how to get it in a modal?
Or maybe there is a more simple solution altogether. I'm using Drupal 7.
Answer: PDF Reader does not require you to create node. It only requires you to have file in a field, in any kind of entity. If your file is managed, something uses it (in usage table). just expose that data to entity api, make file a field and you are good.
If you want to avoid entities, this module is open source. Use it as a learning tool. Borrow it's code. Give credit where credit is due, and use as you need.
Comment: Thanks! I was sort of hoping this was possible and I'm not opposed to entities and even like doing things the "Drupal way". However, I'm not very familiair with the entity API so could you perhaps elaborate a bit on your steps? The files are uploaded using a Webform.
Answer: You can use the native browser solution to render the PDF and colorbox for the popup (using the iframe method).

Colorbox is a light-weight customizable lightbox plugin for jQuery.
  This module allows for integration of Colorbox into Drupal.


If I learn Codeigniter, can I use it with Drupal or is that a bad idea and I should use Expression Engine?

Question: Will learning Codeigniter (or any framework for that matter such as CakePHP or Zend) help my development in Drupal or are they two separate systems that won't really benefit the other when I have knowledge in one?
I know expression engine is a CMS developed specifically with codeigniter in mind, but Drupal has a larger community and I was hoping I'd still be able to stick with drupal as well and see if me knowing codeigniter (currently what i'm studying, i haven't gotten into drupal yet) will be of any use for developing in drupal.
Answer: Drupal & CodeIgniter are different PHP frameworks (Drupal could be considered the CMS that became a Framework). Your work/learning in CodeIgniter will undoubtedly give you perspective when working with Drupal and grow your coding skills, but it wont necessarily help you learn Drupal Core API's and Methodologies.
I recommend getting into Drupal cause it's hawt (in demand), once you get your head around assumptions & common patterns it helps you build things very fast, the community is huge and all the cool kids are doing it. But if you are learning CodeIgniter and want to leverage that learning in EE, that makes perfect sense...and if that's what you/your clients want, rock on.
To start with Drupal I recommend getting into what it can do out of the box with Core & Popular Contrib Modules:
http://drupal.org/documentation/structure
Here are a few more learning resources for drupal:
http://drupalize.me  (video site with lotsa free content and fair priced paid content)
http://planet.drupal.org  (the drupal planet feed, lotsa great tutorials come down the pipe)
http://api.drupal.org  (your friendly Core API docs)
http://drupal.org   (excellent multisite search kicks butt for finding help on your topic)
Comment: One advantage of drupal is that if you are half way competent you can get work very quickly since it's so popular, and since it's more of a cms you can do small jobs easily and quickly. From a getting work standpoint I'd suggest learning drupal first. From a purely academic standpoint I'd suggest CI.
Comment: That is a much bigger question :) I would say your not going to hurt for knowledge of CI & Drupal & Node.js for that matter. In time you'll know when an App needs to get off the ground without any CMS assumptions and also when Drupal is perfect...then again in time drupal will just be perfect for everything (jk) ;P
Comment: To find a web developer job better (i'm planning on freelancing), is it better to just specialize either drupal or codeigniter rather than both? Or do most web developers know one framework and one CMS inside out regardless if knowledge in each helps the other? I'm trying to figure out my career path.
Comment: thanks, then I'll keep on studying CI for now and also get into Drupal afterwards.
Answer: Both Codeigniter and Drupal is great but Codeigniter and Drupal's structures are different. Learning Codeigniter for Drupal does not sound like a great idea.
Comment: I'm just getting started out and was under the false impression that web developers needed to know at least one framework and one CMS. So just to clarify, it's more like, learn and specialize in either Drupal or Codeigniter, rather than specialize in one CMS (drupal) and one framework (Codeigniter), is this more correct?
Answer: Please don't use them both, cause you will just waste your time.
Instead, start with CI cause it's easier, find out how the code works, develop some sites or applications and then start with Drupal which is much more complex at least for customizing, but yet more powerful CMS. I haven't tried Expression Engine yet, but it has really nice feedback especially from designers.


Fatal error: Call to undefined function cache_get()

Question: I am getting the following error on the server
Fatal error: Call to undefined function cache_get() in includes/module.inc on line 665
Drush command terminated abnormally due to an unrecoverable error.                                                                                [error]
Error: Call to undefined function cache_get() in includes/module.inc, line 665

How to fix this?
Comment: In my case Ubuntu was setup to use php7 by default. Drush needs php5 assuming your server is also using php5... Try `sudo ln -sfn /usr/bin/php5 /etc/alternatives/php`
Comment: In my case I found the underlying issue by adding `function cache_get() { return false; }` to `settings.php`.
Answer: For me, the cause was different: some errors are not caught by Drupal's error handler.
I used a new DateTime() in my settings.php (probably very rare)
It generated an error because the date.timezone setting in my CLI php.ini wasn't set.
To find the real error (this is the interesting part of the answer for all of you, I think) :
Edit your module.inc, line 723.
Add these lines before the cache_get call.
if (!function_exists('cache_get')){
    debug_print_backtrace();
}
$implementations = cache_get('module_implements', 'cache_bootstrap');

It might give you lots of information about the real source of the issue!
Comment: I had a syntax error in settings.php that resulted in Fatal error: Call to undefined function cache_get(). I'd suggest those having this issue to double check their settings.php file.
Comment: This is basically for PHP latest version issues where session.save_handler does not working. So please remove the bellow line from settings.php
ini_set('session.save_handler',     'user');

or

Replace the line by session_set_save_handler(new SessionHandler());

----------------------------
Current line
ini_set('session.save_handler',     'user');
Needs to Replaced by
session_set_save_handler(new SessionHandler());
Comment: This was very useful for me, me problem was because an issue in fast404. There seems to be several ways to reach this error, this technique will help to debug. Thanks
Comment: Happy to help :)
Comment: comment by @tapas was it for me. I had this issue when running drush; but only when i didn't set --uri. The default settings.php was old although i had fixed it for my multisite. When i used --uri=mymultisite; then it works. Multisite settings.php had been updated to one compatible with PHP 7
Answer: When you type drush in the command line you probably reached the right place to solve your problem. This error arises when drush is not up-to-date and this occurs when you install drush from the official repository in Ubuntu.
The workaround is easy: just install a new version of drush!
And to do so, you have to install from the backports package of Ubuntu.
Comment: I also came around same solution, I am using Drush 4.6. To which version can i upgrade?
Comment: @DineshKumarSarangapani someone downvote on this recently was that you?


Criar um alerta de data expirada em uma Gridview em ASP.NET em C#

Question: Estou fazendo um projeto final, onde é feito um cadastro de tarefa, descrição e data. Mas não estou conseguindo colocar um aviso/alerta/mensagem na tela para avisar ao usuário que uma tarefa está expirando. Estou programando para web em ASP.NET, C# e o Banco é SQL Server Express.
Tentei com este código, mas nada acontece.
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
        {
                if (e.Row.RowType == DataControlRowType.DataRow)
                {
                    DateTime dt = DateTime.ParseExact(e.Row.Cells[3].Text, "0:dd/MM/yyyy", System.Globalization.CultureInfo.InvariantCulture);
                    if (dt < DateTime.Now)
                        e.Row.Style.Add("background-color", "red");
                }
        }

Gostaria de deixar dessa forma quando uma data do sistema coincidir com o mesmo do computador, não necessariamente idêntico mas com algum contorno, ou uma cor de fundo na linha do GridViewer para destaque.
Comment: Por favor, poste o código em texto. É difícil efetuar os testes com apenas uma foto como exemplo
Comment: Coloquei o código em texto.
Comment: iDate precisa ser uma string com uma data. Caso queira usar a hora do computador pode usar o DateTime.Now ou DateTime.UtcNow.
Answer: A comparação das datas nunca é executada por conta do Response.Redirect.
Você pode remover o código do redirect e substituir o IF das datas pelo código abaixo para verificar a comparação das datas.
if(dt1.Date > dt2.Date)
{
  Response.Write("Tarefa expirando.");
}
else
{
  Response.Write("TESTE");
}

Comment: Muito obrigado tvdias, por falta de atenção minha passou despercebido o comando Response.Redirect. Enfim, coloquei conforme a sua sugestão, mas deu outro erro: "A cadeia de caracteres não foi reconhecida como um DateTime válido".
Comment: Infelizmente não deu certo. Mudei o código, mas continua sem funcionar também. Obrigado assim mesmo tvdias.
Comment: tvdias, consegui! Apenas coloquei no método certo do GridViewer. Precisei retirar o Response.Redirect. Muito obrigado pela ajuda!!!
Comment: Nesse caso é interessante criar uma resposta para a sua própria pergunta explicando detalhadamente a solução e depois aceitar a mesma. @IsraelCostaeSilva