Best way to sync application servers on a load balanced web app?

Question: I'm trying to figure out how to load balance an application, such as WordPress. My server array would look like this:

Load Balancer.
Database Server.
2 or more application servers.

Most, if not all of the content will be stored in the database, so content won't be a problem, and deployments will also be solved by having both servers clone from a remote GIT repo, but what happens if someone uploads an image to one server? How would it get synced to the other?
I'm guessing that I could do this with rSync, but I feel that that is kind of outdated. Any recommendations would be greatly appreciated.
Answer: It seems that you need to look at DRBD, glusterfs, and similar products for real-time replication of your files. Of course, such solutions will be much more efficient if the network delay is too small like deploying them within the same LAN.
Answer: If the user-uploaded data is not cached, and/or is stored on a centralized network location, there isn't a problem.
Cached data is definitely a problem.  There are at least a couple of general approaches.

Maintain session affinity ("sticky" sessions) with a particular web/application server.  This essentially renders the stateless web application "stateful", and the application now has an implied connection timeout  Typically through the load balancer has a timeout, and the web server has a connection timeout and/or an http keep-alive timeout.  Load balancer timeouts can be a tougher nut to crack, as their resources may be more limited than just the application/web server.
If feasible, have an mechanism built-in to the application to synchronize created/modified/deleted data between partner web/application servers.

An intermediate caching solution such as Azure AppFabric may not be viable.  Many applications that cache large data cannot achieve the same performance when using an intermediate cache, although that would need to be determined through testing.
Comment: Yea, I see what your saying. With WordPress at least, i'm okay with each application server maintaining their own individual cache. It be curious however, to see how I could put a caching layer in front of the two application servers, If I used NGINX as a load balancer, maybe I could use that same server to act as a caching layer as well.
Comment: It really depends on the application.  If there is a lot of cached data that is used with sophisticated dynamic queries, I haven't found anything that compares to an in-memory cache, which typically returns results in < 2 milliseconds.  If it is a simple fetch of an object by id using a dictionary/hashtable, that may work fine with an intermediate cache.


Django: insert multiple input text and file

Question: I have recently tried to learn Django and I want to know it's possible to insert multiple input with this form structure to table database? if it's possible, can you tell me how it is? Thank you!!!
<form class="log-in" method="POST" enctype="multipart/form-data">
    {% csrf_token %}

        <input type="text" name="title">
        <input type="file" name="image">

        <input type="text" name="title">
        <input type="file" name="image">

        <input type="text" name="title">
        <input type="file" name="image">

<button type="submit" class="btn btn-info">Submit</button>
</form>

Comment: What you are looking for are formsets: https://docs.djangoproject.com/en/3.0/topics/forms/formsets/
Comment: if include model.py and views.py it wiil become more easy to answer your question
Comment: @hendrikschneider hey there I tried to implementation your suggestion and now i can insert multiple data with formset. Thank you !!!
Comment: @ZaqiSalmanAlexa Nice that you were able to solve it. I posted my recommendation as answer and I would be nice if you would accept it.
Answer: What you are looking for are formsets: docs.djangoproject.com/en/3.0/topics/forms/formsets


Override compass sprite images per theme with the default fallback

Question: Given the file structure similar to:
- themes
|---+ default
    |- a.png
    |- b.png
    \- c.png
 ---+ foo
    \- a.png
 ---+ boo
    \- b.png

Meaning that the directory app/assets/images/themes/default contains 3 files. The other 2 themes (foo and boo) "override" some of those files.
I need to generate sprites for each of the theme taking into account the images that are replaced for that particular theme.
For example:

the sprite for theme default should contain 3 files: default/a.png, default/b.png, default/c.png
the sprite for theme foo should contain: foo/a.png, default/b.png, default/c.png
the sprite for theme boo should contain: default/a.png, boo/b.png, default/c.png

How can I achieve this using Compass spriting?
(Using Rails 4)
Comment: They mention how to do this right on the page you linked. Look at the nested folders section.
Comment: @JustinWood no, not really. They don't mention how to "fallback" to other folders if one of the files is missing there.
Answer: There is no solution today.
But an issue exists: https://github.com/chriseppstein/compass/issues/1286


Add referencing entities into this entities renderable array

Question: Lets say I have a taxonomy called bands, and a taxonomy called band_members.
Band_members have an entity reference field relating each band member to a band.
When I view the bands taxonomy term page the band_members will not be listed.
I can modify the taxonomy term template and manually add them in there, however the bands need to be shown in popups, and the content for each popup is returned via AJAX using drupal_render(taxonomy_term_view($term)). This means any template changes won't show up. What I need to do is use a hook like hook_taxonomy_term_view_alter to add the band_members for that band into the renderable array.
However that will be quite a lot of work, and I though it seems like a fairly standard task to need to displayed referencing entities, so is there an easier way to do this?
In this example I've used taxonomies as an example, however this could apply to nodes, users or any other entities that reference each other.
Answer: Seems custom code was the easiest thing here after a bit of research...
function HOOK_taxonomy_term_view_alter(&$build) {
    if($build['#term']->vocabulary_machine_name=='bands') {
        $units = load_bands_members($build['#term']->tid);
        $build['units'] = array(
            '#markup' => theme('bands_members', array('members' => $members))
        );

    }
}

The function load_band_members returns an array of taxonomy terms and looks like this:
function load_band_members($tid) {
    $tids = db_query("SELECT tid
        FROM taxonomy_term_data td
        INNER JOIN field_data_field_band b ON b.entity_id = td.tid
        WHERE td.vid = 6 AND b.field_band_tid = :tid", array(':tid'=>$tid))->fetchCol();
    return $tids ? taxonomy_term_load_multiple($tids) : false;
}

I'm sure it would somehow be possible to get Drupal to render my band members for me, like it does on their own taxonomy term page, as opposed to me having to call my own custom render function but that will do for now...


Doubt regarding Continuous Random Variables

Question: I do know that the probability of random variables (say $X$ and $Y$) taking specific values is considered to be zero (i.e. $P(X=x,Y=y) = 0$). My doubt, however, is how do I determine the probability of events wherein ($a<X<b,Y=y$)(i.e. $P(a<X<b,Y=y)$.
I am aware that the probability of events such as ($a<X<b\mid Y=y$) can be evaluated by finding the conditional probability density function of $X$ and integrating the function over the interval $(a, b)$. But what about the case above? Is it also equal to zero? If so, could you please provide a detailed example to clarify the doubt? I have been struggling with continuous random variables for some time now.
Also, are the theorems valid for continuous random variables same/analogous to those of discrete random variables? A detailed explanation would be much appreciated.
Thanks in advance :)
Comment: It's a common confusion that beginners have. If $X$ and $Y$ are continuous random variables, then $P(a<X<b,Y=y)\leq P(Y=y)=0$ and hence $P(a<X<b,Y=y)=0$. But on the other hand $P(a<X<b|Y=y)$ is **NOT** a real number but rather a random variable by itself. That's why I rather prefer the notation $P(a<X<b|Y)$. For different values of $Y$, $P(a<X<b|Y)$ takes different values. Once you learn measure theory and then conditional expectation and then regular conditional probability, then things will be rigorously clear to you. Untill then, you have to work with intuition.
Comment: A downvote? Seriously? What is with the users of this site right now???? It is becomming a serious problem. Atleast be honest enough to state the reason for your downvote. If it is just about the edits, then it is better to leave a comment asking the op to edit and also link a mathjax tutorial alongwith. A direct downvote on a suffciently well written and posed question/doubt will only discourage users from at all participating in this site.
Comment: "Also, are the theorems valid for continuous random variables same/analogous to those of discrete random variables ?A detailed explanation would be much appreciated." Are you sure these are all the questions for today, Sir?
Comment: @Henry I see no point in doing the distinction even if strightly speaking you are right. If you have a more precise assumption on $Y$ (it belongs to a set for example), then it should be written explicitely. But if not, it is common practice to view these two terms as equal and to stick with the one that is the more convenient to you depending on the context.
Comment: Thank you so much for the clear explanation @ Mr.Gandalf Sauron. Also, is the theorem for conditional probability in case of discrete random variables valid for continuous random variables. I believe it should not be because the denominator would be zero in that case (i.e P(Y=y) is zero))
Comment: @Mr.GandalfSauron.  You say *"on the other hand $P(a<X<b \mid Y=y)$ is NOT a real number but rather a random variable by itself"* - I so not see this.  To the extent it is defined at all (you may need to take the limit with a small neighbourhood around $y$), I would have thought it could be seen as a function of $y$ and if $y$ is a given value then it *is* a real number
Comment: @Henry Well to define it completely rigorously, I need to talk about regular conditional probability.
Comment: @Mr.GandalfSauron - my query was about "a random variable in itself".  That is the case for $P(a<X<b \mid Y)$, which is a function of the random variable $Y$, but I do not see it for $P(a<X<b \mid Y=y)$
Comment: @Henry Well it is a random variable. It is $E(\mathbf{1}_{a<X<b}|\sigma(Y))$. It is a conditional expectation which is a random variable by itself and is infact defined in a n almost sure sence. Now if $X$ and $Y$ happen to have a joint density, then we can claim that $E(\mathbf{1}_{a<X<b}|\sigma(Y))=\frac{\int_{a}^{b}\int_{\Bbb{R}}f(x,y)\,dydx}{\int_{\Bbb{R}}f(x,y)\,dx}$ and this equality should be viewed in an almost sure sense. And now$P(a<X<b|Y=y)$ is **defined** to be $\frac{\int_{a}^{b}\int_{\Bbb{R}}f(x,y)\,dydx}{\int_{\Bbb{R}}f(x,y)\,dx}$ which really is a random variable.
Comment: @Henry $P(a<X<b|Y=y)$ or $P(a<X<b|Y)$ are just notations which denote $\frac{\int_{a}^{b}\int_{\Bbb{R}}f(x,y)\,dydx}{\int_{\Bbb{R}}f(x,y)\,dx}$ in this case. Now obviously, the RHS in reality is only different when $y$ is different. But there may exist $\omega$ and $\omega'$ for which $Y(\omega)=Y(\omega')=y$. So even though it seems that it is rather a real function depending on $y$ (which it is I agree) but the domain of this "function" is the probability space $(\Omega,\sigma(Y),P)$ and not $\Bbb{R}$. So it is in every sense a random variable.
Comment: @Mr.GandalfSauron I do not see $P(a<X<b\mid Y=y)$ and $P(a<X<b \mid Y)$ as the same thing.  I would say the first is $f(y)$ where $y$ is a value and the second $f(Y)$ where $Y$ is a random variable.
Comment: @Henry Both are just notations and both equal(**almost surely**) the expression $\frac{\int_{a}^{b}\int_{\Bbb{R}}f(x,y)dydx}{\int_{\Bbb{R}}f(x,Y(\omega))dx}$. You are claiming that $P(a<X<b|Y=y)$ is $f(y)$ but it should be $f(Y(\omega))$. Now obviously a composition of two functions $f(g(x))$ can be written as $f(y)$ where $y=g(x)$ and really does depend only on y, i.e. different values for different $y$. But $f\circ g$ is a function of $x$. Here, our $x$ is just $\omega$ from the probability space $(\Omega,\sigma(Y),P)$.
Comment: @Henry One can view this as either equal to $E(\mathbf{1}_{a<X<b}|\sigma(Y))$ in which case it should be thought of as a random variable. Otherwise, it can be thought of as a regular conditional probability $\nu(\cdot, X^{-1}(a,b))=\frac{\int_{a}^{b}\int_{\Bbb{R}}f(x,y)\,dydx}{\int_{\Bbb{R}}f(x,\cdot)\,dx}$ in which case this is treated as a real function of $y$.
Answer: Too long for a comment.
I would recommend to read Mr Gandalf Sauron's comment again word for word. In particular the sentence containing NOT. The formulas that reconcile both notions of conditional expectation are
\begin{align}\underbrace{E[X|Y=y]}_{\color{red}{\text{function of $y$}}}&=a\underbrace{\frac{P(X=a,Y=y)}{P(Y=y)}}_{\color{red}{\text{number}}}
+b\underbrace{\frac{P(X=b,Y=y)}{P(Y=y)}}_{\color{red}{\text{number}}}\,,\tag{1}\\[4mm]
\underbrace{E[X|Y]}_{\color{red}{\text{random variable }}}&=a\frac{P(X=a,Y=y)}{P(Y=y)}\underbrace{1_{\{y\}}(Y)}_{\color{red}{\text{r.v.}}}
+b\frac{P(X=b,Y=y)}{P(Y=y)}\underbrace{1_{\{y\}}(Y)}_{\color{red}{\text{r.v.}}}\\[4mm]
&+a\frac{P(X=a,Y=z)}{P(Y=z)}\underbrace{1_{\{z\}}(Y)}_{\color{red}{\text{r.v.}}}
+b\frac{P(X=b,Y=z)}{P(Y=z)}\underbrace{1_{\{z\}}(Y)}_{\color{red}{\text{r.v.}}}\tag{2}
\end{align}
where I assume for simplicity that $X,Y$ are random variables that take only the values $a,b$ respectively $y,z\,.$
Plug in $y$ for $Y$ into (2) and you get (1). We write the number
$$
\frac{P(X=b,Y=z)}{P(Y=z)}=P(X=b\,|Y\,=y)\tag{3}
$$
which is the conditional expectation we learned in elementary probability.

Using the bar $|$ in several contexts (1), (2), (3) leads to a lot of confusion. (Your question could be another example of that.)

When $Y$ is a continuous r.v. then $P(Y=y)=0$ and the right hand sides of (1) and (2) break down.
The left hand sides are still well defined (but differently). You should study this in the standard literature or take classes and not ask MSE to start from scratch reproducing the entire literature about discrete and continuous random variables.
Comment: Very clear explanation Kurt(+1). I remember the days when I used to get confused by conditional probability during my undergrad. It was only after a measure theoratic course in probability that things started to make sense.


Linux utility for Disk health Monitoring

Question: We are looking into implementing an in-memory utility which can recover the system in case of disk/filesystem lockup. This utility has to detect the lockup and take corrective action like rebooting or just shutting down interface.
The server platform is Gentoo Linux 2.4
Any suggestions on - any existing utility or which scripting method will work best (expect, native C++)?
Answer: you'll want S.M.A.R.T. monitoring tools (smartmontools)
http://en.wikipedia.org/wiki/S.M.A.R.T.
Note that not all statistics correlate with impending drive failure, and sometimes (for some brands and models) you may need to pass in special flags or you will get garbage. See the wikipedia article for which attributes really indicate danger.
The command is smartctl. You may need to be sudo. smartctl --all will give a summary of all drives, spinning them up very briefly to check their health.
Answer: What type of errors are you looking for?
smartmontools and smartd which ship with most distros should be able to help you. They work at a low level with the disk.

SMART on Wikipedia
smartmontools
Comment: Well the real issue is that these servers get stuck at time with no disk read/write activity but network keeps working. So we want to detect this and recover from that. Our server do have smartctl utility. But how would that help in recovery (i.e. shutting down network interface)?
Comment: If your looking for disk activity you could wrap something like `iostat` or for a cleaner way of doing it probably go and fetch the data from wherever it's buried in `/proc`
Comment: Well ours is more of a disk lockup scenario (may be caused by physical elements or purely filesystem corruption). So some program/script has to run periodically to detect that. And that program/script has to survive that failure and perform recovery action. So I may need suggestions on how that implementation will look like?


Error Inserting Cast data and null fields C#

Question: I'm working on Visual Studio 2012 using an MS Access file as Database and having a bunch of trouble with this insert:
cmd.Parameters.Add(new OleDbParameter("@codigo", cal.CodEtiq)); // Value = int
cmd.Parameters.Add(new OleDbParameter("@data", cal.Data.ToString("yyyy-MM-dd hh:mm"))); //Value = 2013-10-29 00:00
cmd.Parameters.Add(new OleDbParameter("@entidade", cal.EntidadeCal)); // Value = string
cmd.Parameters.Add(new OleDbParameter("@observacao", cal.Observacao)); // Value = string
cmd.Parameters.Add(new OleDbParameter("@certificado", cal.Certificado)); // Value = string
cmd.Parameters.Add(new OleDbParameter("@resultado", cal.Resultado)); // Value = string
cmd.Parameters.Add(new OleDbParameter("@selecionar", cal.Selecionar));// Value = int
cmd.Parameters.Add(new OleDbParameter("@null", DBNull.Value));

cmd.CommandText = "INSERT INTO [Movimento Ferramentas] VALUES (@codigo, CAST(@data AS DATETIME), @entidade, @null, @null, 'Calibração', @null, @observacao, @null, @certificado, @resultado, @selecionar, @null)";

The table is defined like this ( column = fieldtype):

Codigo = text
Data saida (aka @data) = date/hour
Entidade = text
Data Ent = data/hour
GT Ent  = text
Estado = text
GT saida = text
observacaoes =    text
requisitante = number
certificado = text
resultado = text
selecionar = Yes/No
tipo int = text

First I was getting an error saying "Data Type Mismatch In Criteria Expression" then I looked up the Cast for the date and put it like that and now it's giving me an error on it saying something like "Syntax error (operator missing) in the expression of the query CAST(@data AS DATETIME)"
Please help.
UPDATE: As suggested by @Ralph, I actually just had to put all nulls as nulls instead of going with the "@null", DBNull.Value. So, Problem Solved Thanks everyone.
Comment: I'd say that the problem is in the 2nd parameter, don't convert it to a string if the database column is defined as a datetime. Also, you can use one of the other constructors of the OleDbParameter so that you can specify the type of the parameter - check http://msdn.microsoft.com/en-us/library/System.Data.OleDb.OleDbParameter(v=vs.100).aspx
Comment: The Parameter Collection has a simple Add(name, type) overload. But OleDB doesn't know anything about named parameter.  You need to ad them in the order they are defined in the sql string. And you can't reuse a parameter either. you have to add @@null as often as its in the sql. Why don't you just write null instead of @@null there?
Comment: Without the .ToString("yyyy-MM-dd hh:mm") and the Cast I still get the "Data Type Mismatch In Criteria Expression" error
Comment: Have you tried using one of the other OleDbParameter constructor overloads, as I suggested? You can specify the type of the parameter, that should fix the problem. Check the link I added in my previous comment.
Comment: I checked it out. Issue is the other constructors become too complex. This case as you say it I just need the string, the type and the object itself. Closest to that is "OleDbParameter(String, OleDbType, Int32, ParameterDirection, Boolean, Byte, Byte, String, DataRowVersion, Object)".
Comment: @Ralf Because this column "Data Ent = data/hour" being a datetime type won't accept just null.
Comment: @MicaelFlorêncio Then it won't accept DBNull.Value routed through a parameter either.
Comment: @Ralf Ok forget it, it sorta worked thanks. Now the issue is, there's nothing on the right column... and I checked the "cal." objects, those are right.
Answer: see this...
enter code here

if date is null assign null for datetime variable
using dbnull.value
 if (@data== null)
 {
    new OleDbParameter("@Dt", SqlDbType.DateTime).Value =DBNull.Value;
 }
else
{
    new OleDbParameter(("@Dt", SqlDbType.DateTime).Value = @data;
}


Most simple way to integrate a html/jquery block into the system?

Question: i want to build a form with jquery and html without using drupal forms api (looks too complicated for me to put effort on that). How can i do this?
How do i have to use a node and how would that be visible?
Does anyone know a tutorial for this?
I would appreciate any kinds of hints...
Answer: Surely you could just build the HTML form as you normally would, and set the Filter Format to Full HTML (if you're using the WYSIWYG).  Seems an odd way of doing things though to be honest!
You could also take a look at the Webform module.  That'll allow you to store form submissions easily as well!  Or Form Builder, but I've never used it before and it doesn't appear to have a 1.0 release.
On another note, the form API in Drupal is not only REALLY powerful, but actually easier than it looks!  It's definitely worth taking time to learn, as you'll find yourself coming back to it again and again!


toFixed hanging my code

Question: I am taking practice exercises and ran into this issue.
This problem asks:

"Prompt for a number greater than 1 and to 4 decimal places. Format
  and write the number to the page displaying with only 2 digits past
  the decimal point using the toFixed() method. (e.g.  12.35, not
  12.3453)
Since this method is very new, it doesn't work in older browsers. See
  if you can get only 2 digits past the decimal point to show without
  using toFixed()."

I found the answer to the hard part through the archives here, Math.round(n*100)/100. Thanks for that. But when I tried the "easy" way, I get nothing. My work is at jsFiddle, but in a nutshell:
var num = prompt("Give me a number greater than one, with 4 decimal places.");
var num2 = prompt("Great! Do one more, please!");

num = Math.round(num*100)/100;
num2 = num2.toFixed(2);

alert(num);
alert(num2);

The exercise did not ask for a second number, but I wanted to use both methods in separate incidences. When I run this it does not alert anything. I know that it is hanging at the toFixed statement, because when I comment it out it alerts both as expected, num1 at 2 decimal places, and num2 as it was prompted (i.e. 1.2345).
So here is what I have done so far:
Mozilla's developer page shows this format: n.toFixed(1);// Returns "12345.7": note rounding
Seems exactly what I am doing.
I copied and pasted all of it in my Sublime, making sure that I called the .js file just before the closing body tag, to make sure it wasn't some loading problem I don't understand.
Plus all sorts of little tweaking.
Sorry to keep asking these questions, but since I am self-study, I have where else to go!
Comment: You have a string in num2, you need `parseFloat(num2).toFixed(2);` - press f12 and look in the console at num2 does not have a method toFixed
Comment: Values returned from, well almost anything, are always strings, and the console says "...has no method toFixed" which is a clue that it's not a number!
Answer: You need to use parseFloat. Using the function will convert the string to a float type variable, allowing for the toFixed function to work properly.
num2 = parseFloat(num2).toFixed(2);

Comment: parseFloat will convert the prompted variable from a string to a Float number, which will allow `toFixed` to do its business properly on the variable
Comment: `parseFloat` has no radix argument so this should read `parseFloat(num2)`
Comment: no problem. you can select this as the answer by using the outlined checkmark under the votes
Comment: @khanahk I've inserted that little explanation
Comment: GRRRRR! I KNEW that alerts returned strings! Didn't even think about it here, though. Thanks for helping me out!

toFixed hanging my code


Notification does not bypass Do Not Disturb mode

Question: Im trying to send a notification that would bypass DND mode if the app is added to the bypass list.
My notification settings are currently this
setPriority(NotificationCompat.PRIORITY_MAX)
setCategory(NotificationCompat.CATEGORY_CALL)
setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_RINGTONE))

And I've added my app to list of apps that can bypass DND mode on my Pixel 4A and Samsung S21. The notification is showing when not in DND mode, but not showign when DND mode is enabled.
Am I missing something?
Answer: priority appears to be unused here.
Try this:
priority = NotificationCompat.PRIORITY_MAX
setCategory(NotificationCompat.CATEGORY_CALL)
setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_RINGTONE))
setPriority(priority)

More info on the Android dev wiki: https://developer.android.com/reference/androidx/core/app/NotificationCompat.Builder#setPriority(int)
Comment: Oh, my apologies, the settings are wrapped in an apply statement, so priority is being set. I will edit
Comment: Then maybe the issue is with **CATEGORY_CALL**? On my Samsung, DND mode calls and messages are treated separately from app notifications: you don't add apps to the whitelist, but contacts instead and I think that works across traditional calls as well as WhatsApp etc. Try using CATEGORY_REMINDER instead.
Comment: Weird, CATEGORY_REMINDER made them appear on my S21, but not on my 4A.. :/
Comment: Are both of your devices on the newest version of Android (13)?


DNSSEC - Recommended parameters

Question: Does anybody know which could be the recommended values for RRSIG validity period and resign interval?
Regards
Answer: RRSIG validity period is (by default) 30 days.  auto-resigning takes place at 3/4 of validity period.
Unless you have a need to change these, the defaults are pretty solid.
[I work for ISC, maintainers of BIND and ISC DHCP]
Knobee / AlanC

DNSSEC - Recommended parameters


Sorting a List while reading from file in c#

Question: I have a text file with deliveries (id,weight,...etc,) and I read them from a Text file and save them in my list. After my list is ready I have to sort it in correct order and only then I can work.
My question: Is there a way to get list sorted while reading the data from the text file, so that each next deliverable that is being read from the file, must be inserted in the list immediately at the right place.
You can see my LoadDeliverablesFromFile method below :
public void LoadDeliverablesFromFile(String filename)
{
    StreamReader sr = null;
    string s;
    try
    {
        sr = new StreamReader(new FileStream(filename, FileMode.Open, FileAccess.Read));
        this.myDeliverables.Clear();
        s = sr.ReadLine();
        while (s != null)
        {

            string[] words = s.Split(' ');
            int id = Convert.ToInt32(words[0]);
            int weight = Convert.ToInt32(words[1]);
            int buyersID = Convert.ToInt32(words[2]);
            Deliverable del = new Deliverable(id, weight, FindPerson(buyersID));
            myDeliverables.Add(del);
            s = sr.ReadLine();

        }

    }
    catch (Exception ex)
    {
        System.Windows.Forms.MessageBox.Show(ex.Message);
    }
    finally
    {
        if (sr != null) sr.Close();
    }

}

Comment: You're describing Insertion Sort, and there are explanations for the algorithm all over the web. It's far less efficient than doing a single sort at the end. Is there a specific reason you want to sort a bunch of times, rather than just once?
Comment: On which field of your Deliverable  class you want your list to be sorted?
Comment: How large is the performance hit of sorting the list at the end? Might be unnecessary optimisation.
Comment: myDeliverables.Add(del); will add at end of list.  Use InsertAt() to place data in correct location.
Comment: Yes, insertion sort is O(N^2) on average, while a QuickSort at the end will be O(N.Log(N))
Comment: @MatthewWatson can you provide me with example please. I just want to practice. Should i implement one of the IComparable interfaces ?
Comment: Try google "insertion sort c#" - there should be a few examples.
Answer: I'm guessing myDeliverables is of type List<Deliverable>
There is no List in .NET that allows inserting an element and get it sorted at the moment of the insertion, and for a good reason
First of all, consider if you really need to sort on insertion. If the list of elements you are reading is not too large or you do not populate the list from elements in the file frequently, the performance hit of sorting everything at the end shouldn't be a problem.
If you have measured the performance hit and it is significant, then inserting elements at place in an array won't be the best choice.  list elements must be contiguous in memory so that means that after each sorted insertion all the elements after the index where you are inserted will be moved in in memory. (and depending on the size of the list, maybe a new memory allocation + copy of all elements is needed)
That's why a list does not provide a method to sort on insertion
So, the point is: if you are in this situation, then a List is not the right data structure to use. I suggest using the SortedList data structure, but contrary to what it's name might suggest, it is not actually a List, but a map, )i.e. it requires a pair of key/value elements) and you'll get your sort on insertion.
Elements in a SortedList are ordered by key, so the field of the Deliverable class you want to use to sort, must implement the IComparable interface if it is a custom Type.
Answer: You could use a for loop to iterate through the list to compare each current element of the list to the item you are planning to add. If the current item in the list is less then the item you are adding i++, else that index is your selected index. Then proceed to add the item in the list by using myDeliverables.Insert(i, new Deliverable(id, weight, FindPerson(buyersID)).
Answer: You could try to add new Deliverable item to List and then to sort that List, but I recommend you to use SortedList
Answer: I don't think you can do it with just a for loop - because this has to use two loops for and while - insertion algorithm check it in internet, there is plenty of information on it. If you use the insertion algorithm (that is at least what i used for it), note that you first add the this.myDeliverables.Add(new Deliverable(id, weight, per)); otherwise it will skip the last item, which is the 15th i think, the second assignment indeed is a bit confusing when you don't understand sorting algorithms.


Modifying rightCalloutAccessoryView when annotation is tapped

Question: I'm working on an app that uses MKMapView to track the user's progress, and I thought I would adopt the iOS 7 Apple Maps method of using a callout button to start the tracking.  However in my case the user stays on the same view, so I need to modify the button to indicate that tracking is already in progress.
I created a simple animation and added it to the button's layer when the button is tapped.  Works fine.  The problem comes in if the user dismisses and then brings back the callout.  Despite code in didSelectAnnotation to put the animation back on the layer, the view that's presented doesn't have the animation in place.  According to this post:
UIButton Not Loading Properly For MKAnnotationView
This is because the annotation view is prepared before didSelectAnnotation is called. It must be prepared well in advance because viewForAnnotation, the other place I could do this, is not being called when the callout is re-displayed.
I can't think of any way to make this work now that I know that, but I'm hoping that someone out there will have the answer.
Edit:
I tried adding the animation to the button in viewForAnnotation and then pausing it, intending to resume it when the button is tapped.  However, when the button is tapped it no longer has an animation on it - mapkit seems to have stripped it away.  It is there in didSelectAnnotation, but somewhere between the two it disappears.
I can add the animation to the whole MKAnnotationView, but that does not behave as intended - the entire thing animates, including the callout, which looks really strange.  Also, pausing the animation on this view interferes with displaying the callout.
All I'm trying to do here is make the button image "pulse" to indicate that it has already been tapped and that tracking is in progress, while leaving it looking tappable so the user knows they can tap it again to stop tracking.
I have a feeling I'm SOL here… please someone, prove me wrong!
Answer: The answer is to use a completely custom callout.  I used the following posts and sample code as a guide, and was able to get it working.
http://blog.asynchrony.com/2010/09/building-custom-map-annotation-callouts-part-1/
http://blog.asynchrony.com/2010/09/building-custom-map-annotation-callouts-part-2/


Rails 3 - All users stuck while someone is processing

Question: We have a web-app here that makes hundreds of calculations with money and other very specific numbers. It has been developed in Rails 3, which I have not much experience.
Recently, I have noticed that even in Digital Ocean server, where it runs for production, whenever an user requests to open some page for example, that does any query to get data from the database, everyone else gets stuck until the processing finishes.
It just looks like rails is running on a "single-threaded" mode, similar to running the same scenario with Tomcat in development mode in Eclipse.
Is there any trick to make it work "multi-threaded"?
I don't see any reason or even logic for it to run like this, there's no sense in making everyone wait until the request of another user finishes.
Thanks in advance to everyone!
Answer: Well, I've found the solution.
To enable Rails with WEBrick to work in a "multi-threaded" way, you'll have to simply go to the config file, and add :
# Enable threaded mode
  config.threadsafe!
After that, restart the server and the trick is done. It "solved" my problem, but ended up creating a thousand others, cause the application wasn't developed thinking about a "threadsafe" scenario, which means, that everytime I try to run similar requests at the same time, the application mixes up everything in memory, crashing.
Well, one problem at once!
The original from this topic is solved.


BizTalk 2009/2010 Change the FTP Adapter's Retry Interval

Question: Is there a way to change the default 5 minute retry interval on the FTP adapter? If looked at the FTP adapter settings as well as the actual ftp send port configurations. Is this possible to do?
Answer: Yes indeed there is.  It is not specific to the FTP adapter which is probably why you can't find it.
In BizTalk Server Administration, navigate the tree to your send port.  Right click it and choose Properties.  In the left pane, click Transport Advanced Options.  You can configure the retry interval and count settings here.
More information is available on MSDN here (scroll down the page a bit).


Image of $c_1: H^1(\mathbb CP^n, \mathcal O^*)\to H^2(\mathbb CP^n,\mathbb Z)$

Question: By the exact sequence $0\to \mathbb Z\to \mathcal O\to  \mathcal O^*\to0$ and $H^1(\mathbb CP^n, \mathcal O)=0$ we can get the injection $$\text {Pic}(\mathbb CP^n)\cong H^1(\mathbb CP^n, \mathcal O^*)\xrightarrow{c_1} H^2(\mathbb CP^n,\mathbb Z)\cong \mathbb Z$$
Since $H^2(\mathbb CP^n, \mathcal O)=\mathbb Z$, it is not clear if $c_1$ is surjective. But I heard the $c_1(\mathcal O_{\mathbb CP^n} (1))$ is the generator of $H^2(\mathbb CP^n,\mathbb Z)$. I wonder how to see this?
Answer: Well the image of $c_1$ is killed by the map $H^2(\mathbb CP^n, \mathbb Z) \to H^2(\mathbb CP^n, \mathcal O)$, which is a map $\mathbb {Z\to Z}$.
However, such a map is either $0$ or injective.
If the map is $0$, then $c_1$ is surjective, and if the map is injective, then the image of $c_1$ (which is injective) is $0$ and so $H^1(\mathbb CP^n, \mathcal O^*) = 0$, which is absurd.
It follows that the map is $0$, and so $c_1$ is surjective.
EDIT : Ted Shifrin below suggests that actually $H^2(\mathbb CP^n, \mathcal O)=0$ (which seems more reasonable to me but as I explained I don't know nearly enough about complex geonetry to argue over that).
In that case, the fact that $c_1$ is surjective follows immediately from the exactnes of the sequence (note that in any case the amswer is only related to the long exact sequence)
Comment: Why can't the map $c_1:\mathbb Z\to \mathbb Z$  be $1\mapsto n$?
Comment: I explained that : if $c_1$ is not surjective, then its image is killed by the map $\mathbb {Z\to Z}$: but that can't happen unless the image is trivial or $\mathbb Z$, otherwise we would get an injective map $\mathbb{Z/nZ} \to \mathbb Z$, but there $1$ would be sent to some element of order $n$ in $\mathbb Z$ : there aren't that many of those
Comment: Excuse me. $H^2(\Bbb CP^n,\mathcal O) = 0$. Please revise.
Comment: @TedShifrin : well I have to admit I don't know enough about cohomology to know that; but in any case if you are right, the problem is even simpler : the exact sequence automatically yields that $c_1$ is surjective. I gave the argument above because the question stated $H^2(\mathbb CP^n , \mathcal O) = \mathbb Z$.
Comment: I'm sorry. Very glib to post an answer so confidently — and not revise it — when you know nothing about sheaf cohomology and  cohomology of complex manifolds.
Comment: @TedShifrin : I gave the answer precisely because it had nothing to do with sheaf cohomology, only with the long exact sequence. Had it anything to do with the specifics of the computations, I wouldn't have. As for revision, I was hoping that the OP would see our exchange and comment on it, but you are right, I will edit


Is it possible to win a cricket match by 0 wickets?

Question: Suppose we have an ODI match between Team A and Team B. Team B batted first and scored 300 / 6 in 50 overs. After 49.5 overs, Team A reaches 300 / 9. Player X, who is on strike, is on 98. He wants to complete his century. In the following situation, what happens:

A legal ball is bowled, and the the batsman hits it straight to a fielder at long on.
Both the batsmen start running and complete a run.
Player X turns back for another run.
His partner is busy celebrating their win and does not turn back.
The fielder throws the ball towards the bowler's end.
Player X, seeing that his partner is not turning back, tries to return back.
It's a direct hit, and Player X is out.

The score is now 301 / 10, and Team A has won, but by how many wickets? 0?
Answer: The match is over as soon as the batsmen complete their first run, so the last five points (from "Player X turns back for another run") are irrelevant. Quoting specifically Law 21.6 Winning hit or extras:

As soon as a result is reached [...] the match is at an end. Nothing that happens thereafter [...] shall be regarded as part of it.

The result would be that Team A scored 301/9 and won by one wicket.
Comment: I'd more be asking "why was there a fielder at long on?". With one run to win, the opposition captain should have brought everyone in to save the single, so your hit would have gone for four and you would have got your century...
Answer: Team A has won by 1 wicket. The reason is that once a team has scored enough runs to constitute a result, nothing that happens afterwards is relevant. This is stated in Law 21, Section 6a.
In your scenario, once the batsmen have completed the first run, the game is over and the subsequent run-out is irrelevant.
The only exception to this law is stated in section 6c, which deals with a boundary. In your scenario, the batsman needed to hit a boundary, and not complete a run before the ball crosses the rope, to receive 4 or 6 runs and make his century.
Answer: The match ends as soon as the first run is scored.
I remember one incident in this context, it was a match IND vs SL where the score was level while Virender Sehwag was on 99*. He missed a century even though he hit a over-boundary as the bowler bowled a no-ball.
http://www.espncricinfo.com/sl-tri2010/content/story/472752.html


EC2 Load balancer and wildcard/multi-domain SSL certificates

Question: I am running three sites through one load balancer (and 2 child-application servers)
One of the site's has an SSL certificate, but I'd like to add a certificate for the other two sites
What is my best route here?
I've found a huge variety of certificates out there, and am a bit confused
I've seen some that are wildcard (eg. limitless subdomains secured for one domain), and some that are multi-domain (eg. up to 100 domains under the one certificate)
Is there a certificate that handles both cases?
Or could I use a multi-domain one to handle subdomains as if it were a wildcard (each site only has 3 or 4 subdomains I need protected)
Would love some guidance here
Link to any articles dealing with this would be appreciate too
Answer: I'd suggest one certificate per site (that way you can easily add a fourth site, or remove one of the existing, without touching the certs of the others).
Whether you want a wildcard for each site, or a multidomain which lists all possible subdomains depends on your setup.
If everything is in one location (EC2), wildcard is probably the cheaper and easier way w/o giving up security.
If you host stuff (for the same domain) in different locations (EC2 and own datacenter), I'd suggest multi-domain certs for every location. That way if one of the locations gets compromised, they cannot impersonate the other location (which would be possible with the wildcard cert or one multidomain listing all services of that domain).
Comment: How would that work with one load balancer that is routing traffic to all the sites?
Comment: @onassar you'd need multiple ELB instances, but those are cheap ;)
Comment: gotcha @zhenech was hoping for a solution just using the one
Answer: Here's an interesting solution:
<code>elb-create-lb superawesome --headers --listener "lb-port=443,instance-port=8443,protocol=TCP" --listener "lb-port=80,instance-port=80,protocol=http" --availability-zones us-east-1c
elb-create-lb unicorns --headers --listener "lb-port=443,instance-port=8445,protocol=TCP" --listener "lb-port=80,instance-port=80,protocol=http" --availability-zones us-east-1c
</code>
Source: http://web.archive.org/web/20150516202333/http://elwoodicious.com/2009/12/23/using-elb-to-serve-multiple-domains-over-ssl-on-ec2-for-giggles
In my own case, I just created small instance with Nginx. No problem with traffic yet. Flexible configuration. Costs within budget.
If you have subdomains, use wildcard package.
Comment: I stumbled on this earlier; will take a look and see if it fits my needs


Subtracting a positive definite matrix from a diagonal matrix

Question: It is well-known that
$$\mathrm{Diag}(x)- xx^\top \succeq 0 \iff x_i \geq 0,\ i=1,\ldots,n,\ \sum_{i=1}^nx_i \leq 1, $$
where $x \in \mathbb{R}^n$, and $\mathrm{Diag}(x)$ is the diagonal matrix whose $i$-th diagonal element is $x_i$.
Let us have another variable $y \in \mathbb{R}^n$ such that $x_i \geq y_i \geq 0$ for all $i=1,\ldots,n$. Obviously, if $y=x$, then we have $\mathrm{Diag}(y)- xx^\top \succeq 0$ by the equivalence above. My question is, can we say that for sure $\mathrm{Diag}(y) - xx^\top \not \succeq 0 $ if $y \neq x$?
As an attempt, I tried to see what happens when $n=2$. $\mathrm{Diag}(y) - xx^\top$ becomes:
$$\begin{pmatrix} y_1 - x_1^2  & - x_1x_2 \\ -x_1x_2 & y_2 - x_2^2  \end{pmatrix}$$
so I should show that if $y_1 < x_1$ or $y_2 < x_2$, then assuming diagonal is non-negative, I should show:
$$(y_1 - x_1^2)(y_2 - x_2^2) < (x_1x_2)^2.$$
I tried many ways, and I am unable to prove this.
Comment: If $x_1 = 1$, but the three other variables are zero, is that a counterexample?
Comment: Thanks for this counter example! I know it is too late and my question is more general, but actually I have a constraint $\sum_i y_i + 1 \geq 2 \sum_i x_i$.
Answer: This is not true. Suppose $x>0$ and $\sum_ix_i<1$. Then $\operatorname{diag}(x)-xx^T>0$ and hence $\operatorname{diag}(y)-xx^T>0$ when $y$ is slightly smaller than $x$.
Answer: Here is a characterization of when the matrix is positive semidefinite. Using the Schur complement, we find that
$$
\operatorname{diag}(y) - xx^\top \succeq 0 \iff \pmatrix{\operatorname{diag}(y) & x\\x^\top & 1} \succeq 0 \iff 1 - x^\top\operatorname{diag}(y)^{-1} x \geq 0.
$$
In particular, we find that $\operatorname{diag}(y) - xx^\top$ is positive definite if and only if
$$
\sum_{i=1}^n \frac{x_i^2}{y_i} \leq 1.
$$
In the case that $y = x$, this simplifies to your result.
As written, this proof only applies to the case where the entries of $y_i$ are positive. However, we can extend this by noting that the limit of positive semidefinite matrices is positive semidefinite.
Comment: @i Right.${}{}{}{}{}{}{}$
Comment: Many thanks for this nice answer. I guess the bottom right element of the Schur matrix is 1, not 0, right?


Async generic retry

Question: I have this
public static async Task Retry<T>(Func<T> action, TimeSpan retryInterval, int maxAttemptCount = 3)
{
    var exceptions = new List<Exception>();

    for (int attempted = 0; attempted < maxAttemptCount; attempted++)
    {
        try
        {
            if (attempted > 0)
            {
                Thread.Sleep(retryInterval);
            }
            return await action();
        }
        catch (Exception ex)
        {
            exceptions.Add(ex);
        }
    }
    throw new AggregateException(exceptions);
}

and try to run this by
await Retry(() => SaveFile(command, tracker.ActivityId, blobService), TimeSpan.FromSeconds(5), retryCount);

but i got error in Retry in return await action() (T does not contain definition for getAwaiter)
i need to return from the loop when action is done
and my action
Task SaveFile<TCommand>(TCommand command, string activityId, IBlobService blobService) where TCommand : DomainComman

Comment: If you're expecting to work with async functions, action should be `Func>`, not `Func`. (And, in turn, your return type should be `Task`, not `Task`).
Comment: I recommend using [Polly](https://github.com/App-vNext/Polly). It's a battle-tested retry library.
Comment: Also consider `await Task.Delay` instead of `Thread.Sleep`
Comment: Consider using an _exponential retry_ rather than a flat one.   This is useful for busy/offline periods.
Comment: @Damien_The_Unbeliever so Task Retry(Func> action, TimeSpan retryInterval, int maxAttemptCount = 3) and then await Retry<>(() => SaveFile(command, tracker.ActivityId, blobService), TimeSpan.FromSeconds(5), retryCount); ? can you post this as an answer ?
Comment: Could you include in the question the signature of the `SaveFile` method?
Comment: OK. I wanted to verify that the `SaveFile` is an asynchronous method. You could have named it `SaveFileAsync` for clarity. The `Retry` could also be named `RetryAsync` for the same reason.
Answer: There are a few issues here.

action returns T, you cannot await this, you can only await Task or Task<T>. So if you want to await action it should have the signature Func<Task<T>>
Your return type is wrong. It looks like you want to return a T, then the return type should be Task<T>
If you are using asynchronous code you should not be using Thread.Sleep, use Task.Delay instead, and await this.

You might also want to add some logging, or a custom exception to make it clearer that this was a repeated failure. Someone looking at a aggregate exception with three duplicates might not immediately figure out what is going on.
Comment: @kosnkov the generic type should typically be inferred, If you need to specify it you need to write it out fully `await Retry(...)`. An open generic type, i.e. `<>` is very rarely used. This is all assuming SaveFile returns a `Task`, otherwise you need to either move it to a background thread, or call it synchronously.
Comment: could you also add how to call it now ? i thnk this is correct await Retry<>(() => SaveFile(command, tracker.ActivityId, blobService), TimeSpan.FromSeconds(5), retryCount);
Comment: my save file looks like this private static async Task SaveFile(TCommand command, string activityId, IBlobService blobService) where TCommand : DomainCommand so what type i should put in Retry<> ? only empty generic Retry<> now compiles
Comment: @Kosnkov So your SaveFile does not return any actual value. If that is the case you should just remove all the `` and the `return` statement. I.e. your method would be equivalent to a `void` method.
Comment: but if I remove return i won't break 'for loop' and endup in throw agregateException isn't ?
Comment: @kosnkov sorry, I'm a bit tired, You should move the return to a separate statement. Since `await action()`  will not return anything.
Answer: Async functions returns Task for beeing awaitable. So in your code you TResult is T and you need to redifine the Func<T> to Func<Task<T>>.
As you return the result of action you need also to change the return type of your function to Task<T>
So you end up with:
public static async Task Retry<T>(Func<T> action, TimeSpan retryInterval, int maxAttemptCount = 3)

as SaveFile seams also to be async so you should change the call to:
await Retry(async () => await SaveFile(command, tracker.ActivityId, blobService), TimeSpan.FromSeconds(5), retryCount);

Comment: you made two mistakes here in code example, as you mentioned Func must be Func> and then i thnk you need to run it this way await Retry<>(() => SaveFile(command, tracker.ActivityId, blobService), TimeSpan.FromSeconds(5), retryCount);

Async generic retry


Synology QuickConnect Relay: Not Secure?

Question: I was reading the QuickConnect whitepaper and was overall pretty impressed. But on page 10 it explains how the Relay service works and it's implied (but not explicitly stated) that packets are decrypted on the Relay Server. They go on to pinky swear they won't snoop your traffic:

While providing the promised services, QuickConnect makes no use of collected data from registered Synology NAS servers except in delivering such services. For more details, please visit the Privacy Terms on our official website.

As most of you probably are, I can be a little paranoid about Security. My previous setup used a tcp proxy server which allowed for E2E encryption to work natively. That was however somewhat brittle and left a public port exposed. It also added latency. Hole Punching is really cool and does seem to create a encrypted tunnel E2E so that sounds perfect for my needs. A few questions:

Is it correct that QuickConnect relay isn't encrypted E2E?
Can I modify QuickConnect to fallback to my own relay?
Is my assumption correct that Hole Punching is safer than simply forwarding a public port?
Will hole punching work when putting my Synology in my router's DMZ?
In which conditions will Hole Punching not work?
Does QuickConnect uses UDP or TCP Hole Punching?
Answer:
It is correct than QuickConnect isn't end-to-end encrypted.  It is encrypted from your device to Synology, and then decrypted and re-encrypted for the voyage from Synology to your NAS.  That part is necessary (it's how TLS works), but Synology could choose to add an additional end-to-end encryption layer if they wanted (with more work and performance hits).  But they haven't.
To my knowledge you cannot modify QuickConnect to fallback to your own relay.
Most likely hole punching is safer than forwarding a public port (which is a hole that is open all the time).
Hole punching would work when putting your Synology in your router's DMZ, but would be unnecessary and would defeat the point of hole punching.  The DMZ is exposed to the internet all the time.

I don't know the answer to to 5 or 6.


Derivative of $x^x$ and the chain rule

Question: Rewriting $x^x$ as $e^{x\ln{x}}$ we can then easily calculte the ${\frac{x}{dx}}$ derivative as ${x^x}(1 + \ln{x})$. We need to use chain rule in form $\frac{de^u}{du}\frac{du}{dx}$. The question is why cannot we use the chain rule skipping the 1st step of rewriting $x^x$ as $e^{xlnx}$? The idea would be to write $\frac{u^x}{du}\frac{du}{dx}$ which simply would be $x^x\ln{x} \cdot 1$? The answer is incorrect, here we are missing the $+x^x$ term.
Comment: $\frac{d (a^x)}{dx}=a^x\ln a$ is true only for constant $a\gt0$
Comment: @MichaelHoppe Is there a reason for that or is it a coincidence?
Comment: So the answer is I can use the chain rule but there is no "elementary derivative" to use? Ok, thank you. If you put the answer in the answers I'll be able to accept it.
Comment: Using the rule for $(x^n)'$ we achieve $x\cdot x^{x-1}$, using the rule for $(a^x)'$ we get $x^x\cdot\ln(x)$.  Adding both gives the derivative of $x^x$ correctly.  Bummer.
Comment: Happenstance (like the "Sophomore's Dream"):  for the "generalized exponential" of a function to the power of a function, we have $$  [ \ u^v \ ] ' \ = \ (u^v) \ \left[ \ \frac{v}{u}  \cdot  u' \ + \ v' \cdot \ln u \ \right] \ \ . $$ from logarithmic differentiation. This collapses to $$ [ \ x^x \ ]' \ \ = \ \ x^x \ \left[ \ \frac{x}{x} \cdot 1 \ + \ 1 \cdot \ln x \ \right] \ \ , $$  but won't be quite so simple otherwise.
Answer: $$\frac{d(a^x)}{dx}=a^x\ln a$$
is true only for constant $a\gt0$.

Note that in getting the above result, the steps followed are similar to the steps for getting the derivative of $x^x$.
Let $f(x)=a^x$, $a\gt0$. Then,
$$f(x)=e^{x\ln a}$$
$$f'(x)=\frac{d(e^{x\ln a})}{d(x\ln a)}\cdot\frac{d(x\ln a)}{dx}=e^{x\ln a}\cdot\ln a=a^x\ln a$$
whereas, for $f(x)=x^x$, $x\gt0$,
$$f(x)=e^{x\ln x}$$
$$f'(x)=\frac{d(e^{x\ln x})}{d(x\ln x)}\cdot\frac{d(x\ln x)}{dx}=e^{x\ln x}\cdot(\ln x+1)=x^x(\ln x+1)$$
Answer: There is a "generalized" power rule I always taught. You can memorize it or not, but it is easy to derive if needed. If $f$ and $g$ are functions of $x$, then
$$\left(f^g\right)' = gf^{g-1}\cdot f' + f^g\log f\cdot g'$$
(To help remember this, notice that the first term is like the power rule with constant exponent, and the second term is like the power rule with constant base.)
Note that if $g$ is constant, then $g'\equiv 0$ and this reduces to the familiar rule $$\left(u^n\right)'=nu^{n-1}\cdot u'$$ and if $f$ is constant then this reduces to the familiar rule $$\left(a^u\right)'=a^u\log a\cdot u'$$
In your case, $f(x)=g(x)=x$ and we have
$$\left(x^x\right)'=xx^{x-1}\cdot 1 + x^x\log x\cdot 1 = x^x(1+\log x)$$

Derivative of $x^x$ and the chain rule


where did i go wrong when setting up ssl?

Question: I needed my site to be able to do https, however after I set it up on my server https://www.mysite.com/
says it is secure, but no page can be found. It shows the little green lock and everything.
While http://www.mysite.com/ displays the page and everything works fine.
note: I set up the certificate for iis 6 windows server 2003
What did I mess up while doing the set up that would cause https not to be found?
Comment: Post your bindings from IIS that show your IP address, etc...  You may have set that incorrectly.
Answer: If you have posted error message that we can give exact answer of this query. I am sure there is some issue in setting up SSL on IIS 6. You can refer Microsoft official guide on how to install SSL on IIS 6 here : http://support.microsoft.com/kb/299875
or contact your SSL certificate provider; I am sure they can support you to solve this issue.


Compact sets on $\sigma$-algebra and nested classes statement

Question: Let $\mathcal{K}$ be a compact set and $\mathcal{K} \subset \mathcal{A}$ - a $\sigma$-algebra. Also, let $A_n$ be a sequence of nested classes: $A_{n+1} \subset A_{n}, \cap_{i=1}^\infty A_i = \emptyset, i\neq j$. A measure is also given that has the property of "approachig compact class" (not exactly sure how this translates from Russian) (let me know if you want me to give a definition of this). (Also note that $K_n \subset A_n$ and that $\cap_{i=1}^NK_i = \emptyset$)
The notes define $A_N$ as:
$$\cap_{i=1}^N A_i$$
They then state that:

$$\cap_{i=1}^N A_i \subset \cup_{i=1}^N A_i \backslash K_i$$

And I fail to see this. $K_i$ is meant to be an element of the compact class and should be a "close representative" of $A_i$, so the difference should produce a set with pretty much nothing in it. I could see why this would be the case:
$$\cap_{i=1}^N A_i \subset \cup_{i=1}^N A_i$$
Because the sequence $\{A_n\}$ is a sequence of nested classes, so you have less and less elements. Thus, it makes sense that the union is larger. But given the above statement, it is natural to think that if you take something out of the set then:
$$\cup_{i=1}^N A_i \backslash K_i \subset \cup_{i=1}^N A_i$$
But this still does not help me understand their statement.
Answer: First of all note that $\bigcap_{i=1}^N A_i=A_N$ since $A_i\downarrow$.
Let $x\in A_N$. Since $\bigcap_iK_i=\emptyset$, there exists a $j\leq N$ such that $x\notin K_j$. Together with $A_j\supset A_N$ follows $x\in A_j\setminus K_j$ which shows the inclusion $A_N\subset \bigcup_iA_i\setminus K_i$


Pacioli problem of points (counting solutions)

Question: A well known problem: https://en.wikipedia.org/wiki/Problem_of_points
Suppose players A and B decided to play till 3 wins and the game stopped after 2:1 to A. There are 4 possible scenarios to game ending, while in 3 of them A wins. In two scenarios that A wins in round 4 the round 5 is not relevant anymore. I wondered, about the intuition why these two scenarios: (1) A wins in round 4, A wins in  round 5; (2) A wins in round 4, B wins in  round 5; are counted as two different scenarios?
Thanks!
Comment: Where in the Wiki page you linked described this scenario of continuing a $2:1$ for a game-to-$3$? When you asked `"why these two ...are counted as two different scenarios"` where did you get that statement from? Who claimed where that these are counted as two scenarios?
Answer: Assume that the game is fair, and that each player has a 50% chance of winning in any given round. Rather than counting, one could compute probabilities as follows:

A wins the 4th round: probability 50%
B wins the 4th round, A wins the 5th round: probability 25%
B wins the 4th and 5th round: probability 25%

So one arrives at the correct answer this way, but notice that the probabilities of the outcomes are different. This is fine for such a small example, but suppose we were playing until 75 wins and the current score was 46:43...this method would be tedious to calculate.
But we can also consider the game differently. Suppose the current score is $r$:$s$, and the number of required wins is $n$. Instead of playing until one player or the other wins $n$ times, simply play the game $2n-r-s-1$ times, after which a winner is assured. Then, go back through each outcome and determine the winner.
In this case, each individual outcome of the additional $2n-r-s-1$ games has the same probability of occurring, namely $\frac{1}{2^{2n-r-s-1}}$. So calculating the probability of a player winning reduces to counting the number of outcomes of this extended game where the player wins. This is a much easier problem to both calculate and derive a general solution for.


In a circle, chord AB is congruent to chord CD. They intersect at point S. Prove that arc AC is congruent to arc BD.

Question: I presume that one should show the angle B is congruent to the angle A. However, in the figure I made, the angle A is congruent to the angle C.
Answer: Let $A\in\smallsmile CD$.
Thus, $D\in\smallsmile AB$. (It means $ADBC$ is a quadrilateral).
Id est, $$\widehat{AC}=\widehat{CD}-\widehat{AD}=\widehat{AB}-\widehat{AD}=\widehat{BD}.$$
Answer: Two congruent chords $AB$ and $CD$ in a circle are equal in distance from the center. These chords interesct at $S$, and have midpoints $E$ and $F$ respectively. The perpendicular bisector of a chord in a circle goes through the origin, or equivalently a radius perpendicular to a chord bisects the chord. Here $EO$ and $FO$ are perpendicular to $AB$ and $CD$ respectively, and are equal since $AB$ and $CD$ are congruent, and so an equal distance from the centre $O$.
$AB\cong CD$
$OA\cong OB\cong OC\cong OD$
Hence triangles $AOB$ and $COD$ are similar, and so $\angle AOB \cong \angle COD$. Hence $\overparen{AB}\cong\overparen{CD}$ since the arcs subtend equivalent central angles.
Now to prove the claim:
Proof.1
We note:
$\angle COD =\angle AOB$
$\angle AOD = \angle AOB-\angle DOB$
$\angle AOD = \angle COD-\angle AOC$
Hence
$\angle AOB-\angle DOB=\angle COD-\angle AOC$, but since $\angle AOB \cong \angle COD$ this becomes
$\angle AOC=\angle BOD$
Hence $\overparen{AC}\cong\overparen{BD}$ since the arcs subtend the equivalent central angles $\angle AOC$ and $\angle BOD$ respectively.
Proof.2
We have $\overparen{AB}\cong\overparen{CD}$. Hence
$\overparen{AD}:\overparen{AC}\propto\overparen{AD}:\overparen{DB}\implies\overparen{AC}\cong\overparen{DB}$


Batch operation keeps looping after completion

Question: The batch operation I created works fine, until it's done.  Once it's done it just loops back and does it again.  It will loop through until the VM runs out of resources.
I am fairly certain this has to do with my completeImport method.  If I throw a syntax error in there it will finish the import successfully but then error out once it gets to that method.
The controller for the batch op: (I ommited methods that had nothing to do with the batch itself.  They were for CRUD or building URLs.)
class MyModuleController {

  public function import() {
    $endpoints = array(
      'courses' => $this->getEndPoint('courses', NULL),
    );

    foreach ($endpoints as $data_type => $endpoint) {
      $response = $this->getResponse($endpoint);
      $operations = MyModuleController::processResponse($response, $data_type);

      $batch = array(
        'title' => 'Importing ' . $data_type,
        'operations' => $operations,
        'finished' => 'mymodule_complete_import',
        'init_message' => t('Importing...'),
        'progress_message' => t('Operation @current out of @total.'),
        'error_message' => t('Batch failed.'),
        'file' => drupal_get_path('module', 'mymodule') . '/mymodule.import.inc',
      );

      batch_set($batch);

      return batch_process('academy/courses/import');
    }

    return array(
      '#type' => 'markup',
      'value' => t('Imported?'),
    );
  }

  public static function processResponse($response_data, $data_type) {
    $operations = array();

    foreach ($response_data as $data) {
      switch ($data_type) {
        case 'courses':
          // Used to look up if a course was already imported.
          $id = (string) $data->Id;

          $data_array = array(
            'Name'                      => (string) $data->Name,
            'Active'                    => ((string) $data->Active == 'true' ? 1 : 0),
            'CourseCodeForBulkImport'   => (string) $data->CourseCodeForBulkImport,
            'EcommerceLongDescription'  => (string) $data->EcommerceLongDescription,
            'EcommerceShortDescription' => (string) $data->EcommerceShortDescription,
            'ForSale'                   => ((string) $data->ForSale == 'true' ? 1 : 0),
            'Code'                      => (string) $data->Code,
            'Id'                        => $id,
            'OriginalId'                => (string) $data->OriginalId,
            'Price'                     => (string) $data->Price,
            'Description'               => (string) $data->Description,
          );

          break;
      }

      $operations[] = array(
        'mymodule_response_importer',
        array($id, $data_array, $data_type),
      );
    }

    return $operations;
  }

  public static function completeImport() {
    return new RedirectResponse(Url::fromRoute('system.admin_content'));
  }

}

mymodule.import.inc:
function mymodule_response_importer($id, $data, $data_type, &$context) {
  $entity = MyModuleController::findExisting($data_type, $id);

  switch ($data_type) {
    case 'courses':
      if ($entity === FALSE) {
        MyModuleController::createNode($data);
      }
      else {
        MyModuleController::updateNode($data, NULL, $entity);
      }

      break;
  }
}

function mymodule_complete_import() {
  MyModuleController::completeImport();
}

Answer: I was able to fix it by using the magic send() method for RedirectResponse class and building a full URL (mostly) manually.
  public static function completeImport() {

    $url = $GLOBALS['base_secure_url'];
    $url .= $GLOBALS['base_path'];
    $url .= Url::fromRoute('system.admin_content')->getInternalPath();
    $url .= '?status=All&type=academy_webinar&title=&langcode=All';

    $redirect = new RedirectResponse($url);

    $redirect->send();
  }

Comment: I am using `batch_set($batch);` for setting batch inside submitForm() function in admin configuration page. But my batch process is not initiating instead of simple for submission happens. Am I missing anything? Do I need to include any particular class in my page?
Comment: @ARUN it doesn't sound like you're having the same issue I was.  You'd be better off creating your own question to provide more details.


Integrating over time the dot product of the volume integrals of current density and its time derivative

Question: This question comes from electrodynamics, but I'm stuck at the math aspect.
Consider, in any volume $V \in \mathbb{R}^3$, two fields $\rho\left(\vec{r},t\right)$ and $\vec{J}\left(\vec{r},t\right)$ related by the continuity equation $$-\frac{\partial \rho\left(\vec{r},t\right)} {\partial t} = \nabla \cdot \vec{J}\left(\vec{r},t\right)$$
The variable $\vec{r}$ represents position, and $t$ is, of course, time. Now consider two time instants $t_1$ and $t_2$ such that for all $\vec{r} \in V$, $$\rho\left(\vec{r},t_1\right) = \rho\left(\vec{r},t_2\right),\qquad \vec{J}\left(\vec{r},t_1\right) =\vec{J}\left(\vec{r},t_2\right)$$
If we define two volume integrals like this:
$$
\vec{Y}\left(t\right)=
   \iiint_V
      \vec{J}\left(\vec{r},t\right)
   \space dV\left(\vec{r}\right)
\qquad
\vec{Z}\left(t\right)=
   \iiint_V
      \frac {\partial \vec{J}\left(\vec{r},t\right)} {\partial t}
   \space dV\left(\vec{r}\right)
$$
Can the following be proved?
$$
  \int_{t_1}^{t_2}
    \vec{Y}\left(t\right)
    \cdot
    \vec{Z}\left(t\right)
  \space dt
  = 0
$$
Thanks...
Answer: As long as your volume $V$ doesn't depends on time, you can exchange the order of
differentiation and integration (assuming all functions involved are regular enough).
$$ \frac{d}{dt}\vec{Y}(t)
= \frac{d}{dt} \iiint_{V} \vec{J}(\vec{r},t)dV(\vec{r})
= \iiint_{V} \frac{\partial \vec{J}}{\partial t}(\vec{r},t)dV(\vec{r}) = \vec{Z}(t)
$$
The integral you want can now be computed as follows:
$$\int_{t1}^{t2} \vec{Y}(t)\cdot\vec{Z}(t) dt = \int_{t1}^{t2} \vec{Y}(t)\cdot\frac{d\vec{Y}}{dt}(t) dt = \frac12 \int_{t1}^{t2} \frac{d}{dt}|\vec{Y}(t)|^2 dt = \frac12 \left[|\vec{Y}(t)|^2\right]_{t1}^{t2}$$
Since you assume $\vec{J}(t_1,\vec{r}) = \vec{J}(t_2,\vec{r})$ for all $\vec{r}$, you get
$\vec{Y}(t_1) = \vec{Y}(t_2)$ and hence:
$$\int_{t1}^{t2} \vec{Y}(t)\cdot\vec{Z}(t) dt = \frac12 \left( |\vec{Y}(t_2)|^2 - |\vec{Y}(t_1)|^2 \right) = 0$$


Zend Registry in ZendFramework

Question: Hello i am trying to override array value
So i have something like this.
Zend_Registry::set('config', $config);

$config is array
 $config = ['timeZone' => 'GMT'];

is it possible to override just single value in already set array not whole array.
for Example something like this
 Zend_Registry::set('config::timeZone', 'NewOne');

Zend_Reistry has inheritance from ArrayObject, so if that is possible in SPL ArrayObject, so if that is possible in SPL, it's possible here, but i can't find reference.
Answer: It is possible, but not via the set method. The set method simply calls ArrayObject::offsetSet, and there is no magic there. You're on the right track though, since Zend_Registry extends ArrayObject, we can access the contents using standard array syntax, so you can treat an instance of ZendRegistry like an array that has your config array at the index "config".
<?php
// Create our config array
$config = [
    'country' => 'US',
    'lang' => 'EN',
    'timeZone' => 'EST'
];

// Set it in the registry
Zend_Registry::set('config', $config);

// Since registry extends ArrayObject, we can access the contents like an array
Zend_Registry::getInstance()['config']['timeZone'] = 'GMT';

// Get our config from the registry
$updatedConfig = Zend_Registry::get('config');

// Verify that the timeZone was updated
assert($updatedConfig['timeZone']=='GMT');

Zend Registry in ZendFramework


Change conditional min-width CSS definition

Question: I found that the collapsing menu in the Wordpress theme twentytwelve that transforms into a dropdown if the screen is too narrow is based on this conditional rule in twentytwelve/style.css
<code>@media screen and (min-width: 600px) {
    [css rules for actual elements if conditon above applies]
}
</code>
I currently build a child theme based on twentytwelve, where this min-width should be 885px instead of 600px.
Changing the value within twentytwelve would be easy, but isn't really a good style.
Neither would be to copy-paste the relevant css into the child and adapt it.
Is there an elegant way with pure CSS?
I'm rather certain that some workaround with a script would be possible
(yes, I am aware that there's a twentythirteen theme)
Answer: That is the pure CSS way, however...From my favorite theme, try responsive jQuery rules:
<code>/*
Responsive jQuery is a tricky thing.
There's a bunch of different ways to handle
it, so be sure to research and find the one
that works for you best.
*/

/* getting viewport width */
var responsive_viewport = $(window).width();

/* if is below 481px */
if (responsive_viewport < 481) {

} /* end smallest screen */

/* if is larger than 481px */
if (responsive_viewport > 481) {

} /* end larger than 481px */

/* if is above or equal to 768px */
if (responsive_viewport >= 768) {

}

/* off the bat large screen actions */
if (responsive_viewport > 1030) {

}
</code>
Or your could hard code it into the template file by adding a style="" attribute and formatting the media query you have inside of it. This will make only that div in that template affected by the media query.
Comment: I need to work around the mother CSS theme definition somehow.
I don't think that this piece of code is particular helpful as I want to keep the actual style, but using a different width argument. So *if* I use scripting I would have to copy the style for said element with a different width and reverse the one previously set by the mother theme, as I have to do the later one anyway.
But what I asked about here is, whether someone knows a nice workaround for CSS; or an easy one via scripts other than the one I just described.
Comment: I have never seen one like you're describing. Without media queries the above is about as close as you get. Are you aware of min-width & max-width CSS rules? You could change the width:600px; rule somewhere within that media query, to max-width:885px; But I'm not too sure without seeing it. Do you have a link to share? This is why Child themeing is not good for projects with customization.


Upload docx file downloaded from google drive using paperclip

Question: I want to upload docx file downloaded from google drive using gem paperclip but I am getting Invalid content type error. Below is my code
has_attached_file :initial_document
validates_attachment :initial_document, content_type: {content_type: %w(image/jpeg image/jpg image/png application/pdf application/msword application/vnd.openxmlformats-officedocument.wordprocessingml.document)}

I am able to upload file created from ms word but not from google drive.
During debugging, I found that the content type of the .docx file is application/zip I am using Rails 5.0 and paperclip 5.1
Comment: Are you sure its `application/zip`? If so just add it to the `content_type`
Comment: yeah, its application.zip , I have allowed application.zip but while downloading I received the same file without any extension
Answer: The problem is in below line,
validates_attachment :initial_document, content_type: {content_type:

here, content_type is repeated, which is not correct syntax.
replace above with
validates_attachment :initial_document,
  content_type: %w(
    application/vnd.openxmlformats-officedocument.wordprocessingml.document
    application/pdf
    application/msword
    application/word
    application/x-msword
    application/x-word
    application/zip
    text/plain
    image/jpeg
    image/jpg
    image/png
  )

Here application/zip is important for the .docx file
I have tested with above changes and document object is created successfully as below
    #<Document:0x0d0bd8f0> {
                                :id => 1,
           :document_list_file_name => "sample-document.docx",
        :document_list_content_type => "application/zip",
           :document_list_file_size => 12711,
          :document_list_updated_at => Wed, 19 Sep 2018 11:56:02 UTC +00:00
    }

Hope, this will solve your issue.
Comment: My syntax is also correct, when I add application/zip, it works but after downloading, it gives the file without any extension


Suggestion for trigger that sends email if threshold is broken

Question: This is quite a broad question but ill try and summarise it as best I can.
I have an MVC front end which displays/allows processing of records which are classed as outstanding. I also have a scheduled console app which runs nightly and attempts to resolve each of these records using some logic I wrote.
I have a new requirement, which is to have an email sent every time the total number of outstanding records exceeds a certain amount, this amount needs to be configurable.
The table will contain every record with a flag to say if they have been resolved or not, so I will need to count the outstanding's then fire an email to notify if the threshold is broken.
I initially thought about adding a SQL Server trigger on insert however I soon realised that if no more records were added for a few days but the total number stayed above the threshold because nobody resolved them, then no further email would be sent.
I need the email to send every day on a schedule independently of insert/update.
So now I'm thinking possibly a SQL Server job, or an SSIS package or even a service which runs, but I'm aware this threshold number needs to be configurable.
So what would be the quickest simplest solution to my requirements, I'm open to any suggestion as long as it ticks all the boxes.
Answer: An SQL Server scheduled job seems to me to be the simplest way to go.
you can add a table to your database that will hold the threshold number and read it's value from there.
In many cases a GeneralParams table is a good thing to have anyway.
The other option you mentioned (windows service) is also configurable in many ways: you can use a GeneralParams table, or the App.Config file of the service (but you will have to restart it every time you change the app.config), or even a simple text file. anything goes. the downside is that it's outside of your sql server, but the upside is that it is probably easier to send emails from.
Comment: I agree. Should have thought about it myself.
Answer: Given that the OP already has a console app running on a schedule, the most logical choice would be to simply add this check to the console app along with the email sending logic. It will be much easier to send emails that way, anyways, especially if you employ something like Postal, which will let you use MVC-style views to create your emails.


How to write a javascript funcion to check that my text box is containg special character or not?

Question: I want to check that my text box is containing special character or not, using java script.
for this i am using following code
function CheckUserId() {
    var txt = document.getElementById('<%=TextBox1.ClientID%>').value;
    var regexp = "/^[a-zA-Z0-9]+$/";
    if (regexp.match(txt)) {
        alert("No special character ");
        return true;
    }
    else {
        alert("Special character");
        return false;
    }
    }

I am calling this java script function on textbox onblur. TextBox code is following
  <asp:TextBox ID="TextBox1" runat="server" onblur="CheckUserId()" ></asp:TextBox>

but it is showing always alert message  "special character" .Whats wrong with my code?
Please help me
Comment: Please have a look at this document http://www.codeproject.com/Questions/234476/Javascript-to-Check-if-field-has-special-character
Answer: You have the string and the pattern the wrong way round on your if statement. The syntax for a javascript match is string.match(regexp). Try instead:
if (txt.match(regexp))

Comment: Remove the pattern from the string and it will work. Ie. `var regexp = /^[a-zA-Z0-9]+$/;` Although, do note that the pattern does not allow for spaces. I don't know if that is intentional, but to include them just add a space into the character class.
Comment: I changed according to your suggestion then also same output. Is my regular expression right?
Answer: In addition to what others pointed, you have made another mistake: var regexp = "/^[a-zA-Z0-9]+$/" is a string, not RegExp object. Remove quotes around regular expression or use var regexp = new RegExp("/^[a-zA-Z0-9]+$/") syntax.
Here is the working example: http://jsfiddle.net/LJdeE/
function CheckUserId() {
    var txt = document.getElementById('<%=TextBox1.ClientID%>').value;
    var reg = /^[a-zA-Z0-9]+$/;
    if (reg.test(txt)) {
        alert("No special character");
        return true;
    }
    else {
        alert("Special character");
        return false;
    }
}

Answer: It is (text.match(regex)) and not (regex.match(text))
Answer: ^\s*([0-9a-zA-Z ]+)\s*$

try this regex.
i have tried it it is working


Given the densities of 2 components in a solid mixture, could you determine the mass of one knowing the total volume and mass?

Question: Given you know the volume and mass of a solid mixture, could you determine the mass of one of the two components if you know their individual densities, I think geologist use a method that allows this, though the question might have to do with Chemistry so I'll ask on both sites.
Comment: Try constructing some linear equations based on given information. You can take two volumes as variables.
Answer: Sure you could. Let the total mass be $M$, total volume be $V$, densities of the two parts be $d_1$ and $d_2$. Let the unknown masses be $m_1$ and $m_2$.
Since mass is conserved, $m_1 + m_2 = M$
Since volume is also conserved, ${m_1\over d_1} + {m_2\over d_2} = V$
Linear equations in two variables, easily solvable.


How to change the background-color of the whole row when thead row has less columns than tbody rows?

Question: I'm wondering how can I have the same width for all the rows in the table?
As you can see in the page...I want to change the background color of the header but the header doesnt have the same width as the  element in the body.
How can I have  the same width for all the rows so the background color covers the whole width?
Thanks!
http://jsbin.com/ucafeh/1/
<!DOCTYPE html>

<link href="http://twitter.github.io/bootstrap/assets/css/bootstrap.css" rel="stylesheet" type="text/css" />
<link href="http://twitter.github.io/bootstrap/assets/css/bootstrap-responsive.css" rel="stylesheet" type="text/css" />

<meta charset=utf-8 />
<title>JS Bin</title>

                    Date
                    hl
                    Invoice
                    fefe
                    fefefef
                    fe VAT
                    C. dfgdf VAT
                    dfgdf

                17.17.17
                50123
                Invoice
                Hola señor
                -123.00
                111
                1200
                GSP
                item
                last-item

Comment: Is that red line something you drew in, or is that actually rendered in the page? If it's actually rendered in the page, please post a complete example with your CSS that we can use to reproduce this.
Comment: could you please show us the code for the whole table, including the existing CSS, preferably in a jsfiddle snippet ?
Comment: You want to change the `color` of all cells *except* the last cell, or just have the `color` extend to the *end* of the last cell? And where is that empty space, following the last cell, coming from?
Comment: @j08691 I added a jsbin-file
Comment: By the way, in your tbody section you have th rather than td elements to contain your table values.
Answer: Can you simply add 2 empty th elements before the closing tr tag inside thead (see this example: http://jsbin.com/iduxem/1)?
Then you could use the following simple CSS...
.table thead th {
  background-color: green;
}

Answer: Try this.  Make the table span the whole width with 100%;
table {
  width: 100%;
}
tr {
  background-color: green;
}

http://jsbin.com/oliwiq/1/
Answer: to color a row style the
 element with a background color
to expand the table to use all available width, style the
 to be width:100% or fill the table with data and let it autosize itself
Answer: Not sure what your css was, but you can give your last TH a class and change the color.
Like so: http://jsfiddle.net/thomasbrudy/sCmvj/
Or you can also use the last-child css selector.
th:last-child{
    background:red;
}

Comment: hi Thomas I added a jsbinf-file so u understands what I mean...thanks.


Simple proof there is no continuous bijection from $\mathbb{R}^n$ onto $[0,1]^m$

Question: This is inspired by this question.
Using invariance of domain or some such theorem, it is easy to prove there is no continuous bijection $f:\mathbb{R}^n\to [0,1]^m$ for any $n,m\in\mathbb{N}$. Otherwise, composing it with the inclusion in $\mathbb{R}^m$, we would get that $[0,1]^m$ must be open in $\mathbb{R}^m$.
However, I imagine there must be a much simpler proof using simpler properties of the cube and the Euclidean space. For instance, it's very easy to prove this for $m=1$ and any $n$, as in the question I linked to.
Any ideas?
EDIT. Two answers have been so far suggested, but Kevin's is incomplete, and I believe the other is incorrect.
Comment: @RiversMcForge Usually the argument is that the image of a compact set under a continuous map is still compact. But here it is not assumed that the inverse of $f$ is continuous... It's just a continuous bijection, not a homeomorphism.
Comment: @Kevin.S Nice idea, but I think it's nontrivial to assure the image of a neighrbourhood of $x_0$ contains a neighbourhood of $(1,...,1)$.
Comment: Hi Cronus, I have a thought but I've not seriously check its validity. Suppose $\exists$ such $f$, then $\exists x_0=(a_1,a_2,...a_n)$ s.t. $f(x_0)=(1,1,1,....,1)$, since $f$ is continuous, $\exists U$ open neighborhood of $x_0$ s.t. $f(U)=(k,1]^m$, so for any $y\in U, y\neq x_0$, then there must exist repetition. The argument for this part is what I need to consider more, but before that, we can roughly discuss the idea.
Comment: Oh! I see that problem. thanks to point it out.
Comment: Why can't you use compactness? $\Bbb{R}^n$ is non-compact in the standard topology but $[0, 1]^m$ is. A continuous bijection (homeomorphism) must preserve compactness. QED.
Comment: @whatsup That's a good point, but when I look at other examples of continuous bijections without continuous inverses (eg $f: [0, 2π) \rightarrow S^1$ given by $f(t) = (\cos(t), \sin(t))$) there's usually some way for distant points to end up "inappropriately close" because of some kind of "hole" in the space. Here, that clearly can't happen, as both spaces lack "holes" and are contractible—at least, it can't happen without sacrificing bijectivity.
Answer: I improved the my previous idea, but it's too long to write a comment, so I decided to post it here. If anything goes wrong, I will delete my answer or edit it. Actually, I'm suspicious that I missed something because this question seems to be more complicated....
Assume $(\Bbb{R}^n,d_1)$ and $([0,1]^m,d_2)$ be the two metric spaces.
Suppose $\exists$ such $f$ and Let $x_0=(a_1,a_2,...,a_n)\in\Bbb{R}^n$ s.t. $f(x_0)=(1,1,...,1)$. Then, since both spaces are metric spaces, we see that $d_1(x_0,y)<\epsilon\implies d_2(f(x_0),f(y))<\delta$ by continuity. So, in general, we can take two sets $U,V$ containing $x_0$, where $U=\prod_{i=1}^{n-1}(a_i-\epsilon,a_i+\epsilon)\times(a_n-\epsilon,a_n]$ and $V=\prod_{i=1}^{n-1}(a_i-\epsilon,a_i+\epsilon)\times[a_n,a_n+\epsilon)$. Their images $f(U),f(V)\subset(1-\delta,1]^m$.

Case 1: If $f(U)\cap f(V)=\varnothing$

Suppose it's possible, then each point in $f(U\cap V)=f(\prod_{i=1}^{n-1}(a_i-\epsilon,a_i+\epsilon)\times a_n)$ would have two distinct images when it's in $U$ and in $V$, which contradicts the assumption that $f$ is bijective.

Case 2: If $f(U)\cap f(V)\cap ((1-\delta,1]^m\setminus f(U\cap V))\neq\varnothing$

Then there must exist repetitions that undermines the assumption about bijectivity.

Case 3: If $f(U)\cap f(V)=f(U\cap V)$

Then we let $$U=\prod_{j=1}^{n-2}(a_j-\epsilon,a_j+\epsilon)\times (a_{n-1}-\epsilon,a_{n-1}]\times a_n$$ and $$V=\prod_{j=1}^{n-2}(a_j-\epsilon,a_j+\epsilon)\times [a_{n-1},a_{n-1}+\epsilon)\times a_n.$$ By doing this, we restricts the image to an $(m-1)$ dimensional cube containing $(1,1,...,1)$, so we face exactly the same three situations again, and a similar argument push this to the $(m-2)$ dimension, where $U$ becomes $$\prod_{j=1}^{n-3}(a_j-\epsilon,a_j+\epsilon)\times (a_{n-2}-\epsilon,a_{n-2}]\times\prod_{j=n-1}^na_j$$ and $V$ becomes $$\prod_{j=1}^{n-3}(a_j-\epsilon,a_j+\epsilon)\times [a_{n-2},a_{n-2}+\epsilon)\times\prod_{j=n-1}^na_j.$$
We repeat that process with new $U,V$ on and on until the images get to dimension one, which reduces to the situation of $\Bbb{R}^n\to l\approx[0,1]$ (restricting the range to a line segment). Their images, (when restricted to $l$), should be $(a,1]$ and $(b,1]$ (the notation is a little bit weird... but should be half open segments) respectively, where $1-\delta<a,b<1$. then the intersection must be nontrivial and contain extra points.
I missed the space-filling curve, as Cronus pointed out in his comment. The main obstruction of this method is that I've not found any way to argue the fractal curves. I'm still thinking, but maybe someone could help me out.
I thought about the reason why we need to reduce the dimensions: if $m>1$, then we always get a plane or something that $U$ and $V$ may not be able to intersect as desired because the image has various directions to go, but in $m=1$, there is only one direction, so the image of $U$ and $V$ will certainly intersect each other that contains extra points.
I know that this part is hard to understand. It's also hard to describe clearly, so I think we may need further discussion on that......

I'm not really sure if this is valid, but it'll never get verified and edited unless I post it. If someone found flawness in this answer, please kindly point out and I'll reconsider or delete my post.

Edit:
Actually, if both spaces were equipped with the order topology built on the usual dictionary order, then this would be easy.
Assume $f$ is conts bijective, then $\exists x,y\in\Bbb{R}^n$ s.t. $f(x)=(0,...,0)$, $f(y)=(1,...,1)$. Because $\Bbb{R}^n$ is connected and $[0,1]^m$ is assumed to be an ordered set in the order topology, we can apply the (generalized version) intermediate value theorem: Since in the order topology, the interval $(f(x),f(y))$ must go through all points in the cube, which corresponds to the image of the interval $(x,y)$. Now, the point in $\Bbb{R}^n\setminus (x,y)$ needs to have image but it will undermines the bijectivity, which gives us a contradiction.
Comment: Thanks for taking the time to write this. It's a bit long so it might take me a while before I have the time to read it, but I will. :-)
Comment: @Cronus thank you, but be careful because I think I missed something important in this question. I'm not really confident about the case 3. : )
Comment: Hmm I see. I took a look now and I think there's a mistake in this part: "We repeat that process with new U,V on and on until the images get to dimension one, which reduces to the situation of Rn→l≈[0,1] (restricting the range to a line segment)." The image of a line might not be a line; see here: https://en.wikipedia.org/wiki/Space-filling_curve
Comment: But your idea might still work
Comment: @Cronus I see what you meant. The so-called "line" is not necessarily a line. The main idea that I was trying to show is that because $(1,...,1)$ must be the end point while $x_0$ is an interior point, now if we are able to restrict the range to a one dimensional object, then we can say that there must exist repetition that undermines bijectivity. But now, I will need a ligetimate way of deduction. sorry for making such a mistake.
Comment: Yes, I think your idea was good, it might still work... And don't be sorry! Thanks for trying to help.


Dúvida no caso de Paragem

Question: listasIguais :: (Eq a) => [a] -> [a] -> Bool

listasIguais [] p = False

listasIguais p [] = False

listasIguais (x: xs) (y:ys) = x == y && (listasIguais xs ys)

listasIguais [(2,4),(4,6),(8,9)] [(1,4),(2,6),(4,9)]
False

Este resultado deveria de ser verdadeiro. Penso que me enganei no caso de paragem. Será que me sabem dizer qual é o meu erro ?
Answer: Se eu entendi bem, você está querendo dizer que as listas são iguais caso o segundo elemento de cada item seja igual. Ou seja, a comparação deveria ser feita apenas pelo segundo elemento da tupla.
Na verdade, o código atual está comparando tuplas e não apenas o segundo elemento. Como a tupla (2, 4) é diferente de (1, 4) a comparação já falha aí.
Para comparar pelo segundo elemento pode ser feito da seguinte forma:
module Main where

listasIguais :: (Eq b) => [(a, b)] -> [(a, b)] -> Bool
listasIguais [] [] = True
listasIguais [] p = False
listasIguais p [] = False
listasIguais (x:xs) (y:ys) = (snd x) == (snd y) && (listasIguais xs ys)

emptyList = []::[(Int, Int)]

main = do
    print $ listasIguais emptyList emptyList -- True
    print $ listasIguais [] [(1,4),(2,6),(4,9)] -- False
    print $ listasIguais [(2,4),(4,6),(8,9)] [(1,4),(2,6),(4,9)] -- True

Repare que foi necessário mudar a declaração de listasIguais para assumir que é uma lista de tuplas.
Repare também o uso de snd para pegar o segundo elemento de cada tupla.
A declaração de emptyList é necessária para ajudar o compilador a entender o tipo quando a lista está vazia.
E faltava incluir o caso de duas listas vazias. Sem essa equação, a função sempre retornaria False pois no final ía cair em uma das duas equações de lista vazia que retornam False.
Comment: Obrigado, fiquei esclarecido
Comment: Não esquece de votar e marcar a resposta como escolhida :)

Dúvida no caso de Paragem


Find the multiplicative inverse of 23 in Z26

Question: I have no number theory training, but I did many google reading prior coming here. There are so many ways to solve this problem but I am lost.
How would you find the answer to the question
Find the multiplicative inverse of 23 in $Z_{26}$?
Can someone please explain to me (step by step) the quickest and most general way that can be understood by someone who has no rigorous training doing Euclidean algorithm, etc? I think this will benefit the rest of the community out there who are yelled at by their instructors assuming their students would know these things by doing Google search.
I don't mean to make such request, but I am pretty confused.
Thank you!

I've seen people coming up with solutions like a war machine. There must be quicker way for small m other than doing Euclidean or solving as diophantine equation.
Answer: In this case the numbers are small enough that the easiest approach is trial and error: find a multiple of $23$ that leaves a remainder of $1$ when divided by $26$. But we can be a bit cleverer than that: notice that $23$ is $-3$ in $\Bbb Z_{26}$. Now $(-3)(9)=-27=-1$ in $\Bbb Z_{26}$, so $(-3)(-9)=1$ in $\Bbb Z_{26}$: $-9$ is the multiplicative inverse of $-3$. Finally, $-9=26-9=17$ in $\Bbb Z_{26}$, and we've got our answer: the multiplicative inverse of $23$ in $\Bbb Z_{26}$ is $17$. As a check, $17\cdot23=391=1+15\cdot26$.
Comment: you mean that "$-9$ is the multiplicative inverse of $-3$".
Comment: @Lubin: I do indeed; thanks for catching the typo.
Answer: Here is one way to find the inverse. First of all, $23$ has an inverse in $\mathbb{Z} / 26 \mathbb{Z}$ because $gcd(26,23) = 1$. So use the Euclidean algorithm to show that gcd is indeed 1. Going backward on the Euclidean algorithm, you will able to write $1 = 26s + 23 t$ for some $s$ and $t$. Thus $23 t \equiv 1 \text{ mod } 26$. So $t$ is an inverse of $23$ in $\mathbb{Z} / 26 \mathbb{Z}$.
Now you just have to find this $t$. For the details, move cursor over the box

 26 = (1)(23) + 3
 23 = (7)(3) + 2
 3 = (1)(2) + 1
 2 = (2)(1) + 0
 Hence the gcd is $1$. Now going backward on the Euclidean algorithm, you get
 1 = 3 - (1)(2)
 Using the second line, you get
 1 = 3 - (1)(23 - (7)(3))
 1 = 3 - 23 + (7)(3)
 1 = (-1)(23) + 8(3)
 using the first line
 1 = (-1)(23) + 8(26 - (1)(23))
 1 = -1(23) + 8(26) + (-8)(23)
 1 = -9(23) + 8(26)
Hence the inverse of 23 is -9. Moreover $-9 \equiv 17 \text{ mod } 26$. So $-9$ or equivalently $17$ is the inverse of $23$.

A nice exercise to test your understanding of this is to use this idea to prove that if $p$ is prime, then $\mathbb{Z} / p \mathbb{Z}$ is a field.
Answer: Generally one can use the Extended Euclidean Algorithm - see here for a convenient manual method. But in this case it is simpler to proceed directly as follows
$$\rm\ mod\ 26\!:\ \ \frac{1}{23}\,\equiv\, \frac{27}{-3}\,\equiv\,-9 $$
Briefly, here it is by the Extended Euclidean Algorithm (follow the link for much more).
$$\rm\begin{eqnarray} &&\ \ 26\, &=&\ \ \  1&\cdot& 26\, +\, 0\cdot 23 \\
&&\ \  23 &=&\ \ \ 0&\cdot& 26\, +\, 1\cdot 23 \\
\rm row_1\,\ -\ row_2\to && \ \ \  3 &=&\ \ \  1&\cdot& 26\, -\, 1\cdot 23 \\
\rm row_2 - 8\,row_3\to && \color{#C00}{-1} &=& -8&\cdot& \color{blue}{26}\, +\, \color{#0A0}{9\cdot 23} \end{eqnarray}$$
Therefore, examining the last row we deduce, $\rm\ mod\ \color{blue}{26}\!:\,\ \color{#0A0}{9\cdot 23}\equiv \color{#C00}{-1},\ $ so $\ 1/23\equiv -9.$