Q:

Are Job's friends the voice of the Accuser?

I have often struggled with the book of Job, wondering what rubric should guide my interpretation as I read through the speeches of Job's "friends". They say so much that is "true" (so much that squares with the rest of Scripture), but clearly they are not to be trusted (hence, the Lord's rebuke of them in Job 42:7). So how can I interpret what they're saying?
Then the thought occurred to me: perhaps these speeches represent the voice of Satan (= "the Accuser"). I had always assumed his voice ended in chapter two. But doesn't it make sense that the one who is named "the Accuser" would continue to accuse his target throughout the duration of the "test"?
Reading the book in this way really opened my eyes to the Slanderer's shrewd and cunning schemes: mixing truth with lies so craftily, as he always has. Thought of in this way, the accusations sound quite familiar to the lines he still uses today against God's children: "You brought this on yourself" (4:8)
"You think you're so godly, you think you're so wise—you're nothing but a witless loser!" (11:12) "You're a foolish sinner!" (15:2-6) "You're evil and there's no hope for you!" (18:5-21) (All my loose translations, of course.)
If this is an accurate interpretation, Job isn't a book about navigating adversity and hardships as much as it is about how to respond to the lies & accusations of the evil one. And note that Job's responses are less often directed at the accusers as much as they are directed at God. Speaking anachronistically, Job is demonstrating how to put on the "armor of God" to take his stand against the fiery darts of the enemy. He underscores clearly the importance of responding to the accusations by putting our hope in the Advocate (9:33-35, 16:19-20, 19:25)
So what do you think? Am I stretching it? Is this eisegesis? Or could this be what the Author had in mind?
(Richard had some good thoughts in this related question, but he doesn't address my question specifically.)

A:

This is an intriguing interpretation, but there are a couple things that I think militate against it:
First, Job 32:2-3 seems to frame the discussion that precedes it in terms similar to the traditional interpretation as concerning theodicy. Elihu is angry because Job has taken up the cause of his own justice rather than that of God's. He is also angry because Job's friends, in the name of justifying God, have condemned a righteous man. These themes don't fit well with an "armor of God" type framework.
Second, if Job is to be understood as an example of one who fights off well the lies of the Adversary, it is difficult to make sense of God's rebuke of Job at the climax of the book. Why would God, after Job has so valiantly fought off the Adversary, then take the time to expose Job's lack of knowledge regarding the operation of the world?
Lastly, in the epilogue in 42:7-9 we see Job's friends offer sacrifices for their folly, with God appointing Job as a mediator for his friends. Both of these actions would seem uncharacteristic if we were to understand the three friends as Satan.
In my opinion, it's better to see the three friends as representing a particular (malformed) worldview concerning suffering and the justification of God. They are zealous for God, but their zeal is not backed by knowledge.

A:

While I agree with Soldarnal's analysis, this question is interesting enough that I would like to play devil's advocate.  I've been mulling over the issue all week so bear with my (overly-long) answer.
God's Accuser
The setup of Job is the Adversary looking for a way to discredit God:

The Adversary answered the Lord, “Does Job not have good reason to fear God? Why, it is You who have fenced him round, him and his household and all that he has. You have blessed his efforts so that his possessions spread out in the land. But lay Your hand upon all that he has and he will surely blaspheme You to Your face.” —Job 1:9-11 (NJPS)

On the surface, the charge is that Job only fears Gob because he receives material blessings (and in chapter 2, because he is protected from physical suffering).  But close under the surface stands the charge that God bribes His people so that they will love Him.
The text tells us explicitly what Job might have done to cause the charge against God to be found true:

Then Job arose, tore his robe, cut off his hair, and threw himself on the ground and worshiped. He said, “Naked came I out of my mother’s womb, and naked shall I return there; the Lord has given, and the Lord has taken away; blessed be the name of the Lord.”
For all that, Job did not sin nor did he cast reproach on God. —1:20-22 (NJPS)
...
His wife said to him, “You still keep your integrity! Blaspheme God and die!” But he said to her, “You talk as any shameless woman might talk! Should we accept only good from God and not accept evil?” For all that, Job said nothing sinful. —2:9-10 (NJPS)

Job's wife's suggestion is that he throw in the towel on a relationship with God and give up on life.  But Job easily rises to the challenge and does not sin.
Job's Accusers
At it's center, Job is a poetic dialogue with his three friends.  Job pleads for God to answer why he must endure suffering and pain.  He appeals to God for vindication since he is a righteous man.  The replies from his friends are accusations that punishment came because of Job's sin, which the reader knows is the precise opposite of the truth.
So Job is stuck between a rock and a hard place: he's not going to cast reproach on God for taking away what he was given.  But he can't accept the charge that his suffering was the result of sin either.  Remember that in the first two chapters, God explicitly affirms that Job is "a blameless and upright man who fears God and shuns evil."  Accepting the charge would serve God's Adversary just as well as direct blasphemy.  It would make God to be a liar.
The Trial of God
Along the way, Job's friends act as Job's accuser and since God has picked Job to be His champion, they are acting as God's accusers too.  Now there's no indication that either Job or his friends are aware of the heavenly drama told in the prologue.  But just as the Accuser puts God to the test in heaven, Job's friends put him on trial on earth.  And Job acknowledges that he would like to put God on trial as well:

Indeed I know that it is so:
  Man cannot win a suit against God.
If he insisted on a trial with Him,
  He would not answer one charge in a thousand. —9:2-3 (NJPS)

And in his final speech, Job swears that he is innocent:

By God who has deprived me of justice!
  By Shaddai who has embittered my life!
As long as there is life in me,
  And God’s breath is in my nostrils,
My lips will speak no wrong,
  Nor my tongue utter deceit.
Far be it from me to say you are right;
  Until I die I will maintain my integrity. —27:2-5 (NJPS)

Elihu the clever
I disagree with the common belief that Elihu was essentially correct in his theodicy.  Rather, Elihu cleverly reiterates the accusations of the three friends and supplements them with the assertion that God will not answer Job's case against him.  In many ways, his arguments ring true: God does punish the wicked, uses suffering to discipline the righteous, and, even when He answers Job, God does not justify Himself.  (God doesn't even explain what was going on in heaven!)
But Elihu's arguments come directly out of the Adversary's playbook:

Who placed the earth in His charge?
  Who ordered the entire world?
If He but intends it,
  He can call back His spirit and breath;
All flesh would at once expire,
  And mankind return to dust. —34:13-15 (NJPS)

Elihu's argument might be summarized as:

God's job is to create us and give us good things.
If we disobey Him, He will use pain and suffering to punish and correct us.
We can't expect Him to respond to our complaints since He is always just and we are never right to complain.

If you remember from the first two chapters, the Adversary hopes to discredit God by removing God's blessings from Job.  He hopes to prove that the way God wins love for himself is by rewarding those He favors with good things and correcting those who stray with pain.  Elihu's words are theologically correct, but they don't address the greater truth that God wants a relationship with people.  If Job accepted the simple explanation that God is punishing Job for some unknown sin he'd committed, Job would be giving up on his relationship with God and thus winning the bet for the Adversary.
God has the final word
Finally, God speaks.  I argued elsewhere that God finds Elihu beneath contempt, but here I note that while God does pass judgment on Job and his three friends, He does not explicitly deal with either the Adversary or Elihu at this time.  Surprisingly, His speech does not seem to answer Job's charges either.  He first asserts His dominion over the physical (Job 38) and animal worlds (Job 39).  Then He prompts Job to make a short reply and proceeds to proclaim authority over the behemoth (Job 40) and then Leviathan (Job 40:25-41:26 in the Tanakh and Job 41 in most English translations).
Seemingly, the behemoth (a superlative beast) and Leviathan are part of the animal world that God already showed authority over in chapter 39.  But a reasonable reading might be that these are mythical creatures that represent evil.  Unlike their representation in Babylonian mythology, however, God made the behemoth:

He is the first of God’s works;
  Only his Maker can draw the sword against him.—Job 40:19 (NJPS)

Unlike humanity (which does have dominion over animals), God has dominion and authority over the Leviathan and is able to capture him and bring him into submission.  Job accepts these words as a proper answer to Job's charges against God, which only works if God metaphorically had declared His dominion over evil itself.  Job 42:1-6 signals his acceptance of God's promise to tame evil.  The conclusion of the book shows Job's trust to be well-founded as he finds justice for himself and his three friends.
God's justice against the Accuser is delayed
But we don't see God enact justice against the Adversary or against Elihu.  I do not believe this is an oversight by the author.  Rather, it seems we are, like Job, to trust that God will set all wrongs right in the end.  The final end of the Leviathan is addressed in other Biblical texts such as:

In that day the Lord will punish,
  With His great, cruel, mighty sword
  Leviathan the Elusive Serpent—
  Leviathan the Twisting Serpent;
  He will slay the Dragon of the sea. —Isaiah 27:1 (NJPS)

If the author of Job truly equates the behemoth and Leviathan with the Adversary, it would seem that is also his fate.  And if Elihu truly opposes God, it's not a stretch to identify him with the Adversary of chapters 1 and 2.
Good lies often include true statements
What makes Job a tough nut to crack is that Job's friends really don't stray far from the truth.  Even Elihu presents ideas that are largely previews of what God will say in conclusion.  There aren't a lot of verses I can find that seem to be theologically wrong (either to the Jewish understanding or my own Christian understanding).  If the serpent in Genesis 3 and Satan in Matthew 4 are the same person as the Accuser of Job, we shouldn't be surprised to hear true, but not complete statements from his imitators.  God is angry with Job's friends because they said things that are not true about God, but I'm hard pressed to identify anything they said that was wrong.
Worse, I see God repeating many of the same arguments that we'd already heard from Job's friends.  The two things that God adds to the conversation (it seems to me) are His own voice and the description of the end of all evil (chapters 40 and 41).  Job asks for God to answer him, his friends don't offer any hope that will happen, and yet God does come and reveal that all will be set right in the end.
Summary
Finally, I see Eliphaz, Bildad, and Zophar in much the same light as we see Peter in Mark 8:31-33 (HCSB):

Then He began to teach them that the Son of Man must suffer many things and be rejected by the elders, the chief priests, and the scribes, be killed, and rise after three days. He was openly talking about this. So Peter took Him aside and began to rebuke Him.
But turning around and looking at His disciples, He rebuked Peter and said, “Get behind Me, Satan, because you’re not thinking about God’s concerns, but man’s!”

They aren't identical with Satan, but they are speaking his lines.  Remarkably, Peter argues in a very similar vein to Job's friends: God doesn't require innocent men to suffer.

A:

Are Job's friends the voice of the Accuser?

In my framework for understanding Job, in the context of justice, the men roughly represent:

Job: The wisdom of Ecclesiastes (mis-applied)
Eliphaz, Bildad and Zophar: The wisdom of Proverbs (also mis-applied)
Elihu: the voice of one crying in the wilderness: "Prepare the way of the Lord"1

Job identifies with the logic of Ecclesiastes (briefly summed us as "There is injustice everywhere but submit to God regardless"), for example:

22 It is all one; therefore I say,
      ‘He destroys both the blameless and the wicked.’  ESV

Job mis-applies Ecclesiastes because he comes within a hairs breadth of using it's logic to judge God Himself. It is telling that God's eventual response contains no attempt at self-justification, rather a strong assertion that he cannot be judged by Job.

Eliphaz, Bildad and Zophar follow the logic of Proverbs (briefly summed up as "do well and you will be blessed"), for example:

8 As I have seen, those who plow iniquity
      and sow trouble reap the same.  ESV

See also Proverbs 22:8:

8 Whoever sows injustice will reap calamity,
      and the rod of his fury will fail.  ESV

The friends mis-apply Proverbs because they take (true) general principles and add in (false) assumptions about Job and his circumstances.

Elihu prepares the way for God's arrival by silencing Job and rebuking both him and his friends. His arrival coincides with the cessation of the back and forth debate, and his words are summed up early on:

2 Then Elihu the son of Barachel the Buzite, of the family of Ram, burned with anger. He burned with anger at Job because he justified himself rather than God. 3 He burned with anger also at Job's three friends because they had found no answer, although they had declared Job to be in the wrong.  ESV

It is well worth noting that God does not even refer to Elihu once he arrives on the scene—this strongly suggests he is an agent of God rather than a character in the play like Job and his friends
In conclusion, Eliphaz, Bildad and Zophar are not (directly) the voice of the Accuser—they are the people who should have been able to rebuke Job for his self-righteousness before God, but they get it completely wrong by mis-applying the wisdom of Proverbs.

1 "Elihu" is really the name Elijah with a different ending.


Q:

DataGridView issues

I'm trying to loop through my foreach loops and spit out output to my datagridview.
The datagridview has 3 defined columns:  Path, Old File Name, New File Name
However, I keep hitting errors.
First, here is the code:
public partial class SanitizeFileNames : Form
{

    public SanitizeFileNames()
    {
        InitializeComponent();
    }

    public void Sanitizer(List<string> paths)
    {
    string regPattern = (@"[~#&!%+{}]+");
        string replacement = "";

        Regex regExPattern = new Regex(regPattern);
        List<string> existingNames = new List<string>();

        StreamWriter errors = new StreamWriter(@"C:\Documents and Settings\bob.smith\Desktop\SharePointTesting\Errors.txt", true);
        StreamWriter resultsofRename = new StreamWriter(@"C:\Documents and Settings\bob.smith\Desktop\SharePointTesting\Results of File Rename.txt", true);

        dataGridView1.Rows.Clear();
        var filesCount = new Dictionary<string, int>();

           try
            {

              foreach (string files2 in paths)
              {

                string filenameOnly = Path.GetFileName(files2);
                string pathOnly = Path.GetDirectoryName(files2);
                string sanitizedFileName = regExPattern.Replace(filenameOnly, replacement);
                string sanitized = Path.Combine(pathOnly, sanitizedFileName);

                if (!System.IO.File.Exists(sanitized))
                {
                    System.IO.File.Move(files2, sanitized);
                    DataGridViewRow dgr2 = new DataGridViewRow();
                    dgr2.Cells[0].Value = pathOnly;
                    dgr2.Cells[1].Value = filenameOnly;
                    dgr2.Cells[2].Value = sanitized;
                    resultsofRename.Write("Path: " + pathOnly + "\r\n" + "Old File Name: " + filenameOnly + "\r\n" + "New File Name: " + sanitized + "\r\n" + "\r\n");

                }

                else
                {
                    if (filesCount.ContainsKey(sanitized))
                    {
                        filesCount[sanitized]++;
                    }
                    else
                    {
                        filesCount.Add(sanitized, 1);
                    }
                    string newFileName = String.Format("{0}{1}{2}",
                    Path.GetFileNameWithoutExtension(sanitized),
                    filesCount[sanitized].ToString(),
                    Path.GetExtension(sanitized));
                    string newFilePath = Path.Combine(Path.GetDirectoryName(sanitized), newFileName);
                    System.IO.File.Move(files2, newFilePath);
                    DataGridViewRow dgr2 = new DataGridViewRow();
                    dgr2.Cells[0].Value = pathOnly;
                    dgr2.Cells[1].Value = filenameOnly;
                    dgr2.Cells[2].Value = newFileName;
                    resultsofRename.Write("Path: " + pathOnly + "\r\n" + "Old File Name: " + Path.GetFileNameWithoutExtension(files2) + "\r\n" + "New File Name: " + newFileName + "\r\n" + "\r\n");
                }
               }
              }
            catch (Exception e)
            {

             errors.Write(e);

            }

    }

    private void SanitizeFileNames_Load(object sender, EventArgs e)
    {

    }

    private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
    {

    }

}

First off, I'm new to C# so I'm not even 100% sure this is correct.  What this code does is take paths that are passed in from another method and "clean" the file names by removing invalid chars (as defined in my regex pattern).  If the file name already exists, append the filename with a number that increases incrementally (i.e. ~test.txt and %test.txt would both be renamed to test.txt.  with my code, ~test.txt becomes test.txt and %test.txt becomes test1.txt).
I'm trying basically to append this data to my datagridview (should the file go to the else if(filesCount.ContainsKey(sanitized) loop).
I get errors with Path.GetFileNameWithoutExtension(), Path.GetExtension(), Path.Combine(), Path.GetDIrectoryName().  The error is as follows:

'System.Windows.Forms.DataGridViewTextBoxColumn'
  does not contain a definition for
  'GetFileName' and no extension method
  'GetFileName' accepting a first
  argument of type
  'System.Windows.Forms.DataGridViewTextBoxColumn'
  could be found (are you missing a
  using directive or an assembly
  reference?)

I have no idea what this means or how to fix this.  Can someone help?

A:

I suspect you have a DataGridViewTextBoxColumn variable/field  called 'Path' somewhere. Rename that variable and/or use the full name System.IO.Path.GetFileName() etc.
As a more general remark, stop using the DatagridView as a data-structure. Do yourself a favor, define a class with the (column) properties you want, declare a BindingList<MyFileClass> and bind the DataGridView to that list.


Q:

Regex issue in C# for constructing new pattern

I am using this regular expression
string expression = "q(\\d+)(M){0,1}(T){0,1}(W){0,1}(TH){0,1}(F){0,1}(S){0,1}(SU){0,1}";

Consider days of week.
M, T, W, TH, F, S, SUN

Whenever we enter any string we want to extract first pattern of days of week and ignore the other one.
Let me give you examples

If Input string is : q10MTWTHFSSUN465689213MTWSU45454, then output should be  q10MTWTHFSSUN
Input string = q10MSSUN454545asdasdsaMTWTHUR
Output should be q10MSSUN

CODE
    string expression = "q(\\d+)(M){0,1}(T){0,1}(W){0,1}(TH){0,1}(F){0,1}(S){0,1}(SU){0,1}";
    Console.Write("\nEnter string:");
    string value = Console.ReadLine();
    var result = Regex.Match(value, expression, RegexOptions.IgnoreCase);

    if (result != null)
    {
        Console.Write(result.ToString());
    }

I tried the above pattern, but failing in some scenerios.
FAILING SCENARIO
Input string q10THSSUN454545asd
Output should be q10THSSUN but it is coming out as q10T because it is treating TH as Tuesday because of T

A:

Try this:
q(\\d+)(M){0,1}(T(?!H)){0,1}(W){0,1}(TH){0,1}(F){0,1}(S(?!U)){0,1}(SU){0,1}
The regex for matching 'T' (Tuesday) explicitly fails if the following letter is a 'H' (so that TH takes precedence). Same goes with Saturday and Sunday.
You could also replace the {0,1} with ? for brevity, but it's just a matter of preference, really.


Q:

How to get the ChoiceField value from a form in Django?

I want to get the chosen email-id from a drop down list made from ChoiceField. I have written a code but apparently it is not working.
How do I do it ?
Here is my views.py
@login_required
def assign(request):
    if request.method == 'POST':
        assign_now = AssignTask(data=request.POST, user=request.user)
        if assign_now.is_valid():
            task_title = assign_now.cleaned_data.get('title')
            task_description = assign_now.cleaned_data.get('desc')
            assign_email = assign_now.cleaned_data('assign_to')
            assign_email = dict(AssignTask.fields['assign_to'].choices)[assign_email]
            user_details = User.objects.get(email=assign_email)
            t = Task(title=task_title, description=task_description, assigned_to=user_details)
            t.save()
            return HttpResponse('
Successfully assigned task
')
        else:
            return HttpResponse('
<Task assignment failed/h2>')
    else:
        return HttpResponse('
Request method error
')

Here is my forms.py
class AssignTask(forms.Form):
    title = forms.CharField(max_length=200)
    description = forms.CharField(widget=forms.Textarea)
    assign_to = forms.ChoiceField(widget=forms.Select(choices=[]))

    def __init__(self, *args, **kwargs):
        self.user = kwargs.pop('user')
        user_email = self.user.email.split('@')[1]
        super(AssignTask, self).__init__(*args, **kwargs)
        self.fields['assign_to'] = forms.ChoiceField(choices=[(i.email, i.email) for i in User.objects.filter(is_active=True, email__icontains=user_email)])

Error that I am getting is:
File "/home/gblp250/PycharmProjects/assignment/todoapp/views.py" in assign
  118.             assign_email = assign_now.cleaned_data('assign_to')

Exception Type: TypeError at /assign
Exception Value: 'dict' object is not callable

A:

From the error traceback, We can understand, you are missing a .get() function
so, try this,
 assign_email = assign_now.cleaned_data.get('assign_to')
instead of
 assign_email = assign_now.cleaned_data('assign_to')

complete view function
@login_required
def assign(request):
    if request.method == 'POST':
        assign_now = AssignTask(data=request.POST, user=request.user)
        if assign_now.is_valid():
            task_title = assign_now.cleaned_data.get('title')
            task_description = assign_now.cleaned_data.get('desc','Sample Description')
            assign_email = assign_now.cleaned_data.get('assign_to')
            user_details = User.objects.get(email=assign_email)
            t = Task(title=task_title, description=task_description, assigned_to=user_details)
            t.save()
            return HttpResponse('
Successfully assigned task
')
        else:
            return HttpResponse('
<Task assignment failed/h2>')
    else:
        return HttpResponse('
Request method error
')


Q:

detect changes in a JS Object using Angular js

I have a javascript object suppose user is the name of my object and in angular js it looks like this
$scope.user = {
  name:'Arpit',
  class:'Computer Science',
  year:'2017',
  gender:'male'
}

This object I am fetching from the database and opening in the edit screen, now if in the HTML form if any field got changed by the user in edit mode I want to highlight the particular field using my CSS class applyborder. My logic is working for the first time when I am changing any field value but when I reset the value as original the class should be removed, but it is not removing the class. My angular js code is:
            //Value Change Detection
            Object.keys($scope.user).filter(function (key) {
                $scope.$watch('user.' + key, function (newVal, oldVal) {
                    if (newVal != oldVal) {
                        var ele = $('[ng-model="user' + '.' + key + '"]');
                        ele.addClass("applyborder");
                    }
                    else  if(oldVal == newVal){
                        var ele = $('[ng-model="user' + '.' + key + '"]');
                        ele.removeClass("applyborder");
                    }
                });
            });

It is treating last entered value as oldVal but it should treat to the value which comes from the database. Thanks.

A:

This is the expected behavior of $watch.
You can keep a copy of the object you received from database using angular.copy:
var originalUser = angular.copy($scope.user).
then check:
//Value Change Detection
        Object.keys($scope.user).filter(function (key) {
            $scope.$watch('user.' + key, function (newVal, oldVal) {
                if (newVal != originalUser[key]) {
                    var ele = $('[ng-model="user' + '.' + key + '"]');
                    ele.addClass("applyborder");
                }
                else  if(originalUser[key] == newVal){
                    var ele = $('[ng-model="user' + '.' + key + '"]');
                    ele.removeClass("applyborder");
                }
            });
        });


Q:

I want to load a local html file through chrome custom tab, is that workable?

Currently I put my html file in assets, and I load it in WebView. Can I load it through chrome custom tab?

A:

No, it is not possible to open file:// URLs in customtabs.


Q:

How can I restrict passing values on disabled HTML input objects for processing by a ColdFusion cfquery?

My HTML/web programming skills are pretty much at a newb level, and I've tried searching for a bit on this, but haven't found anything really relevant.
Below I have a sample of code that's using some jQuery (I think?  Basically google treatment scraped together - I don't know the differences between javascript and jQuery) to disable/enable input objects on the page based on the choices.  My intention is to compile a ColdFusion cfquery based off these selections to write more specific queries than the ones we're currently using.
Keeping in mind I definitely want to stick to CF for the SQL side of things (the infrastructure is already setup here, I have an app to reference already, etc), what's the best practice way to only send the enabled values through for processing?  My thought was to use a form and open in new window, but I don't know how to submit only the 'enabled' input objects through.  I figure potential options outside of that might be running the cfquery on all of the data on this page and having a "show" button that narrows things down (inefficient, would like to only query the data that I want), or figuring out a way to submit disabled objects with a throwaway value assigned to them that can be ignored on the form processing page....but I'm hoping some ninjas can tell me a ninja way to do it.
==============

      <input type=radio name="group_or_individual" id="individual" value="individual" checked>Individual Statistics

  <input type=radio name="group_or_individual" id="group" value="group">Group Statistics

        <input type=radio name="comparison_interval" id="month_to_month" value="month_to_month" disabled checked>Consecutive Month-to-Month Comparison (ie, Jan 2011, Feb 2011, Mar 2011, etc)

        <input type=radio name="comparison_interval" id="specific_month" value="specific_month" disabled>Specific Month in Previous Years (ie, Jan 2010, Jan 2011, Jan 2012, etc)

        Starting Year
        <select name="starting_year" id="starting_year" disabled>
           <option value="2010">2010
           <option value="2011">2011
        </select>
        Starting Month
        <select name="starting_month" id="starting_month" disabled>
           <option value="1">Jan
           <option value="2">Feb
           <option value="3">Mar
           <option value="4" selected>Apr
           <option value="5">May
           <option value="6">Jun
           <option value="7">Jul
           <option value="8">Aug
           <option value="9">Sep
           <option value="10">Oct
           <option value="11">Nov
           <option value="12">Dec
        </select>

        Ending Year
        <select name="ending_year" id="ending_year" disabled>
           <option value="2010">2010
           <option value="2011">2011
        </select>
        Ending Month
        <select name="ending_month" id="ending_month" disabled>
           <option value="1">Jan
           <option value="2">Feb
           <option value="3">Mar
           <option value="4" selected>Apr
           <option value="5">May
           <option value="6">Jun
           <option value="7">Jul
           <option value="8">Aug
           <option value="9">Sep
           <option value="10">Oct
           <option value="11">Nov
           <option value="12">Dec
        </select>

        Specific Month to be Compared Annually
        <select name="annual_month" id="annual_month" disabled>
           <option value="1">Jan
           <option value="2">Feb
           <option value="3">Mar
           <option value="4">Apr
           <option value="5">May
           <option value="6">Jun
           <option value="7">Jul
           <option value="8">Aug
           <option value="9">Sep
           <option value="10">Oct
           <option value="11">Nov
           <option value="12">Dec
        </select>

        <ul id="List2" style="list-style-type: none;"

              <input type=checkbox name="group_time_focus_monthly" id="group_time_focus_monthly" disabled checked>Call Data By Month

              <input type=checkbox name="group_time_focus_dow" id="group_time_focus_dow" disabled>Call Data By Day of Week

                       Include Days:

 <input type=checkbox name="group_dow_sunday" id="group_dow_sunday" disabled checked> Sunday

 <input type=checkbox name="group_dow_monday" id="group_dow_monday" disabled checked> Monday

 <input type=checkbox name="group_dow_tuesday" id="group_dow_tuesday" disabled checked> Tuesday

 <input type=checkbox name="group_dow_wednesday" id="group_dow_wednesday" disabled checked> Wednesday

 <input type=checkbox name="group_dow_thursday" id="group_dow_thursday" disabled checked> Thursday

 <input type=checkbox name="group_dow_friday" id="group_dow_friday" disabled checked> Friday

 <input type=checkbox name="group_dow_saturday" id="group_dow_saturday" disabled checked> Saturday

              <input type=checkbox name="group_time_focus_hourly" id="group_time_focus_hourly" disabled>Call Data By Hourly Interval

                       Include Hourly Interval:

 <input type=checkbox name="group_hourly_1" id="group_hourly_1" disabled checked> 12AM - 1AM    <input type=checkbox name="group_hourly_13" id="group_hourly_13" disabled checked> 12PM - 1PM

 <input type=checkbox name="group_hourly_2" id="group_hourly_2" disabled checked> 1AM - 2AM      <input type=checkbox name="group_hourly_14" id="group_hourly_14" disabled checked> 1PM - 2PM

 <input type=checkbox name="group_hourly_3" id="group_hourly_3" disabled checked> 2AM - 3AM      <input type=checkbox name="group_hourly_15" id="group_hourly_15" disabled checked> 2PM - 3PM

 <input type=checkbox name="group_hourly_4" id="group_hourly_4" disabled checked> 3AM - 4AM      <input type=checkbox name="group_hourly_16" id="group_hourly_16" disabled checked> 3PM - 4PM

 <input type=checkbox name="group_hourly_5" id="group_hourly_5" disabled checked> 4AM - 5AM      <input type=checkbox name="group_hourly_17" id="group_hourly_17" disabled checked> 4PM - 5PM

 <input type=checkbox name="group_hourly_6" id="group_hourly_6" disabled checked> 5AM - 6AM      <input type=checkbox name="group_hourly_18" id="group_hourly_18" disabled checked> 5PM - 6PM

 <input type=checkbox name="group_hourly_7" id="group_hourly_7" disabled checked> 6AM - 7AM      <input type=checkbox name="group_hourly_19" id="group_hourly_19" disabled checked> 6PM - 7PM

 <input type=checkbox name="group_hourly_8" id="group_hourly_8" disabled checked> 7AM - 8AM      <input type=checkbox name="group_hourly_20" id="group_hourly_20" disabled checked> 7PM - 8PM

 <input type=checkbox name="group_hourly_9" id="group_hourly_9" disabled checked> 8AM - 9AM      <input type=checkbox name="group_hourly_21" id="group_hourly_21" disabled checked> 8PM - 9PM

 <input type=checkbox name="group_hourly_10" id="group_hourly_10" disabled checked> 9AM - 10AM     <input type=checkbox name="group_hourly_22" id="group_hourly_22" disabled checked> 9PM - 10PM

 <input type=checkbox name="group_hourly_11" id="group_hourly_11" disabled checked> 10AM - 11AM   <input type=checkbox name="group_hourly_23" id="group_hourly_23" disabled checked> 10PM - 11PM

 <input type=checkbox name="group_hourly_12" id="group_hourly_12" disabled checked> 11AM - 12PM   <input type=checkbox name="group_hourly_24" id="group_hourly_24" disabled checked> 11PM - 12AM

A:

What you have there would work fine. Disabled form fields don't get sent on form-submit.
One thing to be VERY careful of is that, just because you have javascript on the front-end that is doing what it can to prevent things from coming through, your server-side code still needs to assume that everything coming to is is hostile and needs to check all inputs to make sure they are valid.


Q:

How to display triple nested dictionary values in a Django template?

I have a list of dictionaries produced by a raw django query and a custom sorting algorithm:
ordered_list = [{'qmaLevel': Decimal('1'), 'materials': None, 'qmaQuantityPerParent': Decimal('1.00000'), 'qmaPartShortDescription': '12U x 600 x 650 Professional Rack ', 'qmaQuoteAssemblyID': 0, 'qmaPartID': 'RACK S9 ', 'quantity': Decimal('1.00000'), 'qmaParentAssemblyID': 0},
{'qmaLevel': Decimal('2'), 'indent': '____', 'materials': None, 'qmaQuantityPerParent': Decimal('1.00000'), 'qmaPartShortDescription': '. ', 'qmaQuoteAssemblyID': 1, 'qmaPartID': 'COLOUR ', 'quantity': 1.0, 'qmaParentAssemblyID': 0},
{'qmaLevel': Decimal('3'), 'indent': '________', 'materials': None, 'qmaQuantityPerParent': Decimal('1.00000'), 'qmaPartShortDescription': 'Colour: Mannex Suede ', 'qmaQuoteAssemblyID': 21, 'qmaPartID': '800-560192 ', 'quantity': 1.0, 'qmaParentAssemblyID': 1},
{'qmaLevel': Decimal('2'), 'indent': '____', 'materials': None, 'qmaQuantityPerParent': Decimal('1.00000'), 'qmaPartShortDescription': '. ', 'qmaQuoteAssemblyID': 2, 'qmaPartID': 'FRAME ', 'quantity': 1.0, 'qmaParentAssemblyID': 0},
{'qmaLevel': Decimal('3'), 'indent': '________', 'materials': {1: {'qmmPartID': '128114 ', 'qmmPartShortDescription': '1.30;300;200;Black/White;Acrylic;Label; ', 'imrWeight': Decimal('0.00000')}, 2: {'qmmPartID': '800-560271 ', 'qmmPartShortDescription': 'Rivet;Alum;Truss;4.0;8.7; ', 'imrWeight': Decimal('0.00149')}, 3: {'qmmPartID': '800-560350 ', 'qmmPartShortDescription': 'Key;Ring;20mm; ', 'imrWeight': Decimal('0.00000')}}, 'qmaQuantityPerParent': Decimal('1.00000'), 'qmaPartShortDescription': 'Label 19" Rack Container Commercial ', 'qmaQuoteAssemblyID': 22, 'qmaPartID': '1A000 ', 'quantity': 1.0, 'qmaParentAssemblyID': 2},
{'qmaLevel': Decimal('3'), 'indent': '________', 'materials': {1: {'qmmPartID': '800-560008 ', 'qmmPartShortDescription': 'Colour;Powdercoat;General;Production Use ', 'imrWeight': Decimal('1.00000')}, 2: {'qmmPartID': '124632 ', 'qmmPartShortDescription': '1.90;M2;ZAN; ', 'imrWeight': Decimal('14.91500')}}, 'qmaQuantityPerParent': Decimal('1.00000'), 'qmaPartShortDescription': 'Frame Top x 600 x 650 Typ 0P ', 'qmaQuoteAssemblyID': 23, 'qmaPartID': '0R000P ', 'quantity': 1.0, 'qmaParentAssemblyID': 2},
{'qmaLevel': Decimal('3'), 'indent': '________', 'materials': {1: {'qmmPartID': '124632 ', 'qmmPartShortDescription': '1.90;M2;ZAN; ', 'imrWeight': Decimal('14.91500')}, 2: {'qmmPartID': '800-560008 ', 'qmmPartShortDescription': 'Colour;Powdercoat;General;Production Use ', 'imrWeight': Decimal('1.00000')}}, 'qmaQuantityPerParent': Decimal('4.00000'), 'qmaPartShortDescription': 'Frame Vertical 12U H2 Type 1 ', 'qmaQuoteAssemblyID': 24, 'qmaPartID': '0S0221 ', 'quantity': 4.0, 'qmaParentAssemblyID': 2},
{'qmaLevel': Decimal('3'), 'indent': '________', 'materials': {1: {'qmmPartID': '800-560008 ', 'qmmPartShortDescription': 'Colour;Powdercoat;General;Production Use ', 'imrWeight': Decimal('1.00000')}, 2: {'qmmPartID': '124632 ', 'qmmPartShortDescription': '1.90;M2;ZAN; ', 'imrWeight': Decimal('14.91500')}}, 'qmaQuantityPerParent': Decimal('1.00000'), 'qmaPartShortDescription': 'Frame Bottom x 600 x 650 Type 0P ', 'qmaQuoteAssemblyID': 25, 'qmaPartID': '0T000P ', 'quantity': 1.0, 'qmaParentAssemblyID': 2},
{'qmaLevel': Decimal('2'), 'indent': '____', 'materials': {1: {'qmmPartID': '800-560008 ', 'qmmPartShortDescription': 'Colour;Powdercoat;General;Production Use ', 'imrWeight': Decimal('1.00000')}}, 'qmaQuantityPerParent': Decimal('1.00000'), 'qmaPartShortDescription': '. ', 'qmaQuoteAssemblyID': 3, 'qmaPartID': 'MOUNTING ', 'quantity': 1.0, 'qmaParentAssemblyID': 0},
{'qmaLevel': Decimal('3'), 'indent': '________', 'materials': None, 'qmaQuantityPerParent': Decimal('1.00000'), 'qmaPartShortDescription': 'Base Pro. Levelling Feet + Mount Plate Kit GA ', 'qmaQuoteAssemblyID': 27, 'qmaPartID': '0E220 ', 'quantity': 1.0, 'qmaParentAssemblyID': 3},
{'qmaLevel': Decimal('4'), 'indent': '____________', 'materials': {1: {'qmmPartID': '800-560349 ', 'qmmPartShortDescription': 'M10;40;Levelling Foot Adjust Screw; ', 'imrWeight': Decimal('0.03081')}, 2: {'qmmPartID': '800-560268 ', 'qmmPartShortDescription': 'M16;Zinc;Hex;Locknut ', 'imrWeight': Decimal('0.00000')}, 3: {'qmmPartID': '800-560097 ', 'qmmPartShortDescription': 'M05;Zinc;Flange;Nut; ', 'imrWeight': Decimal('0.00164')}, 4: {'qmmPartID': '800-560266 ', 'qmmPartShortDescription': 'M10;Zinc;Hex;CLS8 ', 'imrWeight': Decimal('0.00905')}, 5: {'qmmPartID': '128263 ', 'qmmPartShortDescription': 'M16;M10;M24;Mild;Hex;Threaded;Bush;22mm; ', 'imrWeight': Decimal('0.00000')}, 6: {'qmmPartID': '800-560098 ', 'qmmPartShortDescription': 'M05;15;Steel ', 'imrWeight': Decimal('0.00000')}}, 'qmaQuantityPerParent': Decimal('4.00000'), 'qmaPartShortDescription': 'Levelling Feet ', 'qmaQuoteAssemblyID': 39, 'qmaPartID': '800-250215 ', 'quantity': 4.0, 'qmaParentAssemblyID': 27},
{'qmaLevel': Decimal('5'), 'indent': '________________', 'materials': {1: {'qmmPartID': '800-560098 ', 'qmmPartShortDescription': 'M05;15;Steel ', 'imrWeight': Decimal('0.00000')}, 2: {'qmmPartID': '124632 ', 'qmmPartShortDescription': '1.90;M2;ZAN; ', 'imrWeight': Decimal('14.91500')}}, 'qmaQuantityPerParent': Decimal('1.00000'), 'qmaPartShortDescription': ';;;;;Leveling;Foot;Plate; ', 'qmaQuoteAssemblyID': 40, 'qmaPartID': '800-250137 ', 'quantity': 4.0, 'qmaParentAssemblyID': 39},
{'qmaLevel': Decimal('3'), 'indent': '________', 'materials': {1: {'qmmPartID': '124887 ', 'qmmPartShortDescription': 'Rivet;Steel;Dome;4.8;1.6-6.4; ', 'imrWeight': Decimal('0.00000')}, 2: {'qmmPartID': '800-560013 ', 'qmmPartShortDescription': 'M06;Nutsert;Open;Large;Flange; ', 'imrWeight': Decimal('0.00000')}, 3: {'qmmPartID': '800-560014 ', 'qmmPartShortDescription': 'M06;16;Zinc;Phillips;Hex;Serrated ', 'imrWeight': Decimal('0.00502')}}, 'qmaQuantityPerParent': Decimal('4.00000'), 'qmaPartShortDescription': 'Gusset Mount Rail 12U x 600 ', 'qmaQuoteAssemblyID': 28, 'qmaPartID': '03020D0 ', 'quantity': 4.0, 'qmaParentAssemblyID': 3},
{'qmaLevel': Decimal('4'), 'indent': '____________', 'materials': {1: {'qmmPartID': '124633 ', 'qmmPartShortDescription': '1.50;M2;ZAN; ', 'imrWeight': Decimal('11.77500')}, 2: {'qmmPartID': '800-560008 ', 'qmmPartShortDescription': 'Colour;Powdercoat;General;Production Use ', 'imrWeight': Decimal('1.00000')}}, 'qmaQuantityPerParent': Decimal('1.00000'), 'qmaPartShortDescription': 'Mount Rail Gusset 12U Universal ', 'qmaQuoteAssemblyID': 41, 'qmaPartID': '127040 ', 'quantity': 4.0, 'qmaParentAssemblyID': 28},
{'qmaLevel': Decimal('4'), 'indent': '____________', 'materials': {1: {'qmmPartID': '124632 ', 'qmmPartShortDescription': '1.90;M2;ZAN; ', 'imrWeight': Decimal('14.91500')}, 2: {'qmmPartID': '800-560008 ', 'qmmPartShortDescription': 'Colour;Powdercoat;General;Production Use ', 'imrWeight': Decimal('1.00000')}}, 'qmaQuantityPerParent': Decimal('1.00000'), 'qmaPartShortDescription': '12U;0600;;;C;Mount;Rail; ', 'qmaQuoteAssemblyID': 42, 'qmaPartID': '127014 ', 'quantity': 4.0, 'qmaParentAssemblyID': 28},
{'qmaLevel': Decimal('2'), 'indent': '____', 'materials': None, 'qmaQuantityPerParent': Decimal('1.00000'), 'qmaPartShortDescription': '. ', 'qmaQuoteAssemblyID': 4, 'qmaPartID': 'FRONT DOOR ', 'quantity': 1.0, 'qmaParentAssemblyID': 0},
{'qmaLevel': Decimal('3'), 'indent': '________', 'materials': {1: {'qmmPartID': '800-560008 ', 'qmmPartShortDescription': 'Colour;Powdercoat;General;Production Use ', 'imrWeight': Decimal('1.00000')}}, 'qmaQuantityPerParent': Decimal('1.00000'), 'qmaPartShortDescription': 'No Door Required ', 'qmaQuoteAssemblyID': 29, 'qmaPartID': 'NO DOOR ', 'quantity': 1.0, 'qmaParentAssemblyID': 4},
{'qmaLevel': Decimal('2'), 'indent': '____', 'materials': None, 'qmaQuantityPerParent': Decimal('1.00000'), 'qmaPartShortDescription': '. ', 'qmaQuoteAssemblyID': 5, 'qmaPartID': 'REAR DOOR ', 'quantity': 1.0, 'qmaParentAssemblyID': 0},
{'qmaLevel': Decimal('3'), 'indent': '________', 'materials': {1: {'qmmPartID': '800-560008 ', 'qmmPartShortDescription': 'Colour;Powdercoat;General;Production Use ', 'imrWeight': Decimal('1.00000')}}, 'qmaQuantityPerParent': Decimal('1.00000'), 'qmaPartShortDescription': 'No Door Required ', 'qmaQuoteAssemblyID': 34, 'qmaPartID': 'NO DOOR ', 'quantity': 1.0, 'qmaParentAssemblyID': 5},
{'qmaLevel': Decimal('2'), 'indent': '____', 'materials': None, 'qmaQuantityPerParent': Decimal('1.00000'), 'qmaPartShortDescription': '(when viewed from front of rack) ', 'qmaQuoteAssemblyID': 6, 'qmaPartID': 'LEFT SIDE PANEL ', 'quantity': 1.0, 'qmaParentAssemblyID': 0},
{'qmaLevel': Decimal('2'), 'indent': '____', 'materials': None, 'qmaQuantityPerParent': Decimal('1.00000'), 'qmaPartShortDescription': '(when viewed from front of rack) ', 'qmaQuoteAssemblyID': 7, 'qmaPartID': 'RIGHT SIDE PANEL ', 'quantity': 1.0, 'qmaParentAssemblyID': 0},
{'qmaLevel': Decimal('2'), 'indent': '____', 'materials': None, 'qmaQuantityPerParent': Decimal('1.00000'), 'qmaPartShortDescription': '. ', 'qmaQuoteAssemblyID': 8, 'qmaPartID': 'ACCESSORIES ', 'quantity': 1.0, 'qmaParentAssemblyID': 0},
{'qmaLevel': Decimal('2'), 'indent': '____', 'materials': None, 'qmaQuantityPerParent': Decimal('1.00000'), 'qmaPartShortDescription': '. ', 'qmaQuoteAssemblyID': 9, 'qmaPartID': 'PDU ', 'quantity': 1.0, 'qmaParentAssemblyID': 0},
{'qmaLevel': Decimal('2'), 'indent': '____', 'materials': None, 'qmaQuantityPerParent': Decimal('1.00000'), 'qmaPartShortDescription': '. ', 'qmaQuoteAssemblyID': 10, 'qmaPartID': 'FRONT VCM ', 'quantity': 1.0, 'qmaParentAssemblyID': 0},
{'qmaLevel': Decimal('2'), 'indent': '____', 'materials': None, 'qmaQuantityPerParent': Decimal('1.00000'), 'qmaPartShortDescription': '. ', 'qmaQuoteAssemblyID': 11, 'qmaPartID': 'REAR VCM ', 'quantity': 1.0, 'qmaParentAssemblyID': 0},
{'qmaLevel': Decimal('2'), 'indent': '____', 'materials': None, 'qmaQuantityPerParent': Decimal('1.00000'), 'qmaPartShortDescription': '. ', 'qmaQuoteAssemblyID': 12, 'qmaPartID': 'PACKAGING ', 'quantity': 1.0, 'qmaParentAssemblyID': 0}]

Each dictionary has a nested dictionary called materials and each materials dictionary has some more nested dictionaries with a key qmmQuoteMaterialID which will be 1 to 6 in this example but can have any number from 1 to n depending on the query. Example:
{'qmaLevel': Decimal('4'), 'indent': '____________', 'materials': {1: {'qmmPartID': '800-560349 ', 'qmmPartShortDescription': 'M10;40;Levelling Foot Adjust Screw; ', 'imrWeight': Decimal('0.03081')}, 2: {'qmmPartID': '800-560268 ', 'qmmPartShortDescription': 'M16;Zinc;Hex;Locknut ', 'imrWeight': Decimal('0.00000')}, 3: {'qmmPartID': '800-560097 ', 'qmmPartShortDescription': 'M05;Zinc;Flange;Nut; ', 'imrWeight': Decimal('0.00164')}, 4: {'qmmPartID': '800-560266 ', 'qmmPartShortDescription': 'M10;Zinc;Hex;CLS8 ', 'imrWeight': Decimal('0.00905')}, 5: {'qmmPartID': '128263 ', 'qmmPartShortDescription': 'M16;M10;M24;Mild;Hex;Threaded;Bush;22mm; ', 'imrWeight': Decimal('0.00000')}, 6: {'qmmPartID': '800-560098 ', 'qmmPartShortDescription': 'M05;15;Steel ', 'imrWeight': Decimal('0.00000')}}, 'qmaQuantityPerParent': Decimal('4.00000'), 'qmaPartShortDescription': 'Levelling Feet ', 'qmaQuoteAssemblyID': 39, 'qmaPartID': '800-250215 ', 'quantity': 4.0, 'qmaParentAssemblyID': 27},

I need to display the contents in the qmmQuoteMaterialID dictionary in a Django template but not sure how to go about it. Here is my current template:
{% for qmaQuoteAssemblyID in ordered_list %}

    {{ qmaQuoteAssemblyID.qmaLevel }}

      {% autoescape off %}
        {{ qmaQuoteAssemblyID.indent|escape }}
      {% endautoescape %}
      {{ qmaQuoteAssemblyID.qmaPartID }}

    {{ qmaQuoteAssemblyID.qmaQuoteAssemblyID }}
    {{ qmaQuoteAssemblyID.qmaParentAssemblyID }}
    {{ qmaQuoteAssemblyID.qmaPartShortDescription }}
    {{ qmaQuoteAssemblyID.qmaQuantityPerParent|floatformat:"2" }}
    {{ qmaQuoteAssemblyID.quantity|floatformat:"2"}}

    {% if qmaQuoteAssemblyID.materials != None %}
      {% for qmmQuoteMaterialID in qmaQuoteAssemblyID.materials %}

          {{ qmmQuoteMaterialID.qmmQuoteMaterialID }}
          {{ qmmQuoteMaterialID.qmmPartID }}
          {{ qmmQuoteMaterialID.qmmPartShortDescription }}
          {{ qmmQuoteMaterialID.imrWeight }}

      {% endfor %}
    {% endif %}

{% endfor %}

At the moment the above template is allocating the correct amount of rows for the parent item however it is not displaying anything as I don't seem to be calling the related data properly.

A:

Okay, it seems you forgot about the minor details of accessing the ordered list. In default without providing any method accessing the dict just simply return the key.
What you need to do, iterate its items:
{% if qmaQuoteAssemblyID.materials != None %}
  {% for key, qmmQuoteMaterialID in qmaQuoteAssemblyID.materials.items %}

      {{ qmmQuoteMaterialID.qmmQuoteMaterialID }}
      {{ qmmQuoteMaterialID.qmmPartID }}
      {{ qmmQuoteMaterialID.qmmPartShortDescription }}
      {{ qmmQuoteMaterialID.imrWeight }}

Here you can read more about the dict data-structure, its method and looping techniques.

https://docs.python.org/3.4/tutorial/datastructures.html#dictionaries
https://docs.python.org/3.4/library/stdtypes.html#typesmapping


Q:

R code that applies a function to subsection of variables of a dataframe and saves it to original dataframe

I have a dataframe like mtcars
I want to program a function that searches for all variables of mtcars that start with "c", converts them to character and saves them back to mtcars.

A:

Here is one way:
f <- function(x, str = "^var") {
    want <- grep(str, names(x))
    x[, want] <- sapply(x[, want], as.character)
    x
}

[Edit: alternative version that implements the points raised by @hadley in comments.]
f <- function(x, str = "^var") {
    want <- grepl(str, names(x))
    x[, want] <- lapply(x[, want], as.character)
    x
}

The function allows you to pass through the string you want to match on, but defaults to "^var" as you requested. The "^" indicates we want to find names that start with "var", not any name that contains "var".
Example:
> bigdf <- data.frame(var1 = LETTERS[1:3], var2 = letters[1:3], var3 = 1:3,
+                     stuff = 4:6)
> bigdf
  var1 var2 var3 stuff
1    A    a    1     4
2    B    b    2     5
3    C    c    3     6
>
> bigdf2 <- f(bigdf)
> bigdf2
  var1 var2 var3 stuff
1    A    a    1     4
2    B    b    2     5
3    C    c    3     6
> str(bigdf2)
'data.frame':   3 obs. of  4 variables:
 $ var1 : chr  "A" "B" "C"
 $ var2 : chr  "a" "b" "c"
 $ var3 : chr  "1" "2" "3"
 $ stuff: int  4 5 6


Q:

Upgrading to Ringtail 13.04 broke some APT repositories?

When I run sudo apt-get update on Ringtail, I get this:
Err http://overviewer.org debian/./ amd64 Packages
404  NOT FOUND [IP: 208.69.124.224 80]

and
Err http://overviewer.org debian/./ i386 Packages
404  NOT FOUND [IP: 208.69.124.224 80]

I went on the Overviewer channel on Freenode and asked them about the repository, and they checked and say there's nothing wrong with their end, so I uninstalled overviewer on my 12.10-powered laptop, and tried again and it works fine there.
Overviewer IRC snipet:
[08:54] <achin> on our server, i can see the file debian/Packages, but not debian/binary-amd64/Packages
[08:54] <achin> i suspect that something might have changed in ringtail?

Here's the (condensed) contents of my sources.list:
# deb cdrom:[Ubuntu 12.10 _Quantal Quetzal_ - Release amd64 (20121017.5)]/ quantal main restricted
# deb cdrom:[Lubuntu 13.04 _Raring Ringtail_ - Alpha amd64 (20130403)]/ raring main multiverse restricted universe
# deb cdrom:[Ubuntu 13.04 _Raring Ringtail_ - Release amd64 (20130420)]/ raring main restricted

## Added by Seann 27 Dec 2012 - Minecraft Map Overviewer
deb http://overviewer.org/ debian ./

The instructions on Overviewer.org are as follows:

Overviewer.org APT Repository
This is the Overviewer.org APT Repository, which hosts frequent builds of Minecraft Overviewer for use on Debian-based systems, such as Ubuntu or Debian itself. In order to use this repository, add the following line to your /etc/apt/sources.list:
deb http://overviewer.org/debian ./
Then, run apt-get update as root to update your repository information.
Installing Overviewer is as simple as running apt-get install minecraft-overviewer. Since this repository is updated at the same time as the Windows builds on GitHub, you can also upgrade through APT. To upgrade, run apt-get update, then apt-get install minecraft-overviewer again.

And I've done all that, as you can see from my sources.list ... So... what changed between 12.10 and 13.04, and how do I fix it? It's not a REALLY big deal because I was able to download and manually install the update, but it's annoying to say the least.

A:

Your problem is a space in the apt line,
you've got:
deb http://overviewer.org/ debian ./
should be:
deb http://overviewer.org/debian ./


Q:

How to use a cell reference in Field Item pair of GETPIVOTDATA

I have the below formula to get data from a pivottable
GETPIVOTDATA("Sales", $A$4, "[Month].[Month]", "[Month].[Month].&[March]")

Now I'm trying to use this formula by replacing March with C13 and the formula looks like this:
GETPIVOTDATA("Sales", $A$4, "[Month].[Month]", "[Month].[Month].&[C13]")

But it's giving !Ref error. I tried giving &[&C13&] as well. But none are working.
Can someone help me in fixing this?

A:

You just need to provide the reference to the cell e.g. C13 outside the string containing the month reference. Like this:
GETPIVOTDATA("Sales", $A$4, "[Month].[Month]", "[Month].[Month].&["&C13&"]")


Q:

page overflowing in table environment due to content outside tabulars

We made a command to print our software requirements but now that we hit things that use a lot of space we have an overflow issue.
We used a table environment to keep everything together and avoid weird things like a final bar ending up on a different page but this clearly is a hack.
I use two tabulars as writing text in a huge table cell was frustrating that a white line didn't results in a paragraph brake anymore.
How do I change this such that the overflows are gone and if a requirement gets spread over 2 pages each part has at least a few lines of content? Preferably without having to edit to much cases where this is already used?
\documentclass[12pt,a4paper]{report}

\usepackage{booktabs}

\newcommand{\requirement}[5]{
  \begin{table}[H]
  \begin{tabular*} {\textwidth} {  p{0.70\textwidth} r }
    \toprule
    \emph{#3} & \textbf{ID.#1.#2} \\
    \midrule
  \end{tabular*}
    #4

   \vspace{10pt}
    \textbf{Motivation:}\\
    #5

  \vspace{-5pt}
  \begin{tabular*}{\textwidth}{@{}p{\textwidth}}
      \bottomrule
  \end{tabular*}
  \end{table}
}

\begin{document}
long\\long\\long\\long\\long\\long\\long\\long\\long\\long\\long\\long\\long\\long
long\\long\\long\\long\\long\\long\\

\requirement{R}{6}{Name}
{Requirement way to long
long\\long\\long\\long\\long\\long\\long\\long\\long\\long\\long\\long\\long

long\\long\\long\\long\\long\\long\\long\\long\\long\\long\\long\\long\\long\\long

long\\long\\long\\long\\long\\long\\long\\long\\long\\long\\long\\long\\long\\long

long\\long\\long\\long\\long\\long\\long\\long\\long\\long\\long\\long\\long\\long
}
{motivation}

\end{document}

A:

Use a longtable.
MWE:
\documentclass[12pt,a4paper]{report}
\usepackage{booktabs,longtable,array}

\newcommand{\requirement}[5]{%
  \begin{longtable}[l]{@{}p{0.70\textwidth}>{\raggedleft\arraybackslash}p{\dimexpr0.30\textwidth-4\tabcolsep}}
    \toprule
    \emph{#3} & \textbf{ID.#1.#2} \\
    \midrule
    #4

  \end{longtable}
   \vspace{10pt}
    \noindent\textbf{Motivation:}\par
    \noindent#5

  \vspace{-5pt}
    \noindent\rule{\linewidth}{1pt}%
}

\begin{document}
\requirement{R}{6}{Name}
{Requirement way to long
long\\long\\long\\long\\long\\long\\long\\long\\long\\long\\long\\long\\long\\long\\
long\\long\\long\\long\\long\\long\\long\\long\\long\\long\\long\\long\\long\\long\\
long\\long\\long\\long\\long\\long\\long\\long\\long\\long\\long\\long\\long\\long\\
long\\long\\long\\long\\long\\long\\long\\long\\long\\long\\long\\long\\long\\long\\
}
{motivation}

\end{document}

Output

A:

\documentclass[12pt,a4paper]{report}

\newcommand{\requirement}[5]{\par
\smallskip
\hrule
\nopagebreak
\noindent{\large\strut}\textit{#3}\hfill\textbf{ID.#1.#2}
\par
\nopagebreak
\hrule
\par
\nopagebreak
\smallskip
\clubpenalty10000
#4 \par
\par
\nopagebreak
\hrule
\noindent{\large\strut}\textbf{Motivation:}\par
\smallskip
\clubpenalty10000
#5\par
\par
\nopagebreak
\hrule
\par
}

\begin{document}
\requirement{R}{6}{Name}
{Requirement way to long
long\\long\\long\\long\\long\\long\\long\\long\\long\\long\\long\\long\\long\\long\\
long\\long\\long\\long\\long\\long\\long\\long\\long\\long\\long\\long\\long\\long\\
long\\long\\long\\long\\long\\long\\long\\long\\long\\long\\long\\long\\long\\long\\
long\\long\\long\\long\\long\\long\\long\\long\\long\\long\\long\\long\\long\\long
}
{motivation}

\end{document}


Q:

Use the increased navigation-bar title in iOS 11

iOS 11 Beta 1 uses the increased navigation-bar title for almost all system-apps (it started doing this in iOS 10 and the Music app). I am wondering if Apple has a public API for this coming in iOS 11, or whether it will stay private for now.
The behavior is that the title has an increased font-size, is left aligned and will move to the navigation-bar once the user scrolls down. I've attached some screens showing this behavior in the Messages app here:

Although I could not find any reference in the UINavigationController and UINavigationBar so far, maybe someone knows some more details!

A:

The only change done to UINavigationBar API for iOS 11 is prefersLargeTitles.
Documentation here: https://developer.apple.com/documentation/uikit/uinavigationbar/
You can do it to your own apps with one small change: check "Prefers Large Titles" for your navigation bar in IB, or if you prefer to do it in code using:
navigationController?.navigationBar.prefersLargeTitles = true

If you need to change the text attributes of the large title you need to use the new largeTitleTextAttributes property on UINavigationBar:
UINavigationBar.appearance().largeTitleTextAttributes = [
    NSAttributedString.Key.foregroundColor: UIColor.black
]

A:

UINavigationBar has a prefersLargeTitles: Bool property. Docs here.
class UINavigationBar {
   var prefersLargeTitles: Bool
}

UINavigationItem has a largeTitleDisplayMode: UINavigationItem.LargeTitleDisplayMode property. Docs here.
class UINavigationItem {
   var largeTitleDisplayMode: LargeTitleDisplayMode
}

Both of these can be modified in the Interface Builder.
To turn on this behavior set navigationController.navigationBar.prefersLargeTitles to true. Then you can control each individual view controller in the navigation controller stack by setting navigationItem.largeTitleDisplayMode.
The general design guidelines by Apple are that large titles shouldn't be used everywhere (for example, the Clock app does not use them), and it's generally preferred that only the first level of the navigation controller uses the large titles. However, these are just general guidelines.
Large titles are introduced in What's New in Cocoa Touch video (7:37).

A:

Just check "Prefers Large Titles" in the Navigation Bar attribute inspector in Storyboard / Interface Builder:


Q:

Go err: cannot use cur (type *user.User) as type string in argument to f.WriteString

How do I convert data to a string type? I need to write down the data I need to the file which is either not a variable, how do I do it?
Code:
package main

import "os"
import "os/user"
import "encoding/json"

func main(){
    f, err := os.OpenFile("test.txt", os.O_APPEND|os.O_WRONLY, 0600)
    if err != nil {
        panic(err)
    }
    defer f.Close()

    cur, err := user.Current()
    if err != nil {

    } else {

        if _, err = f.WriteString(cur); err != nil {
        panic(err)
        }
    }
}

I do not need to use the cur.Username field. Only a variable.

A:

File.WriteString() expects a string argument, yet you attempt to pass cur to it which is of type *user.User, a pointer to a struct. This is obviously a compile-time error.
user.User is a struct with the following definition:
type User struct {
        // Uid is the user ID.
        // On POSIX systems, this is a decimal number representing the uid.
        // On Windows, this is a security identifier (SID) in a string format.
        // On Plan 9, this is the contents of /dev/user.
        Uid string
        // Gid is the primary group ID.
        // On POSIX systems, this is a decimal number representing the gid.
        // On Windows, this is a SID in a string format.
        // On Plan 9, this is the contents of /dev/user.
        Gid string
        // Username is the login name.
        Username string
        // Name is the user's real or display name.
        // It might be blank.
        // On POSIX systems, this is the first (or only) entry in the GECOS field
        // list.
        // On Windows, this is the user's display name.
        // On Plan 9, this is the contents of /dev/user.
        Name string
        // HomeDir is the path to the user's home directory (if they have one).
        HomeDir string
}

Choose what you want to output to the file, most likely the Username field or maybe the Name field. These are fields of string type, so these you can pass without a problem:
if _, err = f.WriteString(cur.Username); err != nil {
    panic(err)
}

If you want to write out the complete User struct, you may use the fmt package, conveniently the fmt.Fprint() or fmt.Fprintf() functions:
if _, err = fmt.Fprintf(f, "%+v", cur); err != nil {
    panic(err)
}


Q:

Fastest way to sort and concatenate million or billion STL vectors

What is the best way to sort and concatenate million or billion STL vectors into a single STL vector. Presently, the way I am doing it is to just iterate over the vectors and perform each operation.
Here is the pseudo code
typedef unsigned long long int ULLInt;

ULLInt N = 1000000;

vector<vector<ULLInt> > vecVec( N, vector<ULLInt>() );
vector<ULLInt>          concatVec;

// ...
// ... fill vectors inside vecVec here
// ..  we also get here the total number of values inserted in all vectors (count)
// ...

// reserve the space
concatVec.reserve( count);

// sort each vector and concatenate them in sequence
for( ULLInt i=0; i<N; i++)
  sort( vecVec[i].begin(), vecVec[i].end() );
  concatVec.insert( concatVec.end(), vecVec[i].begin(), vecVec[i].end() );
end for

Note that there is no requirement for concatVec to be sorted. Thanks for suggestions.

A:

One thing I'd do is ask if you really need to concatentate a million std::vectors.  What if you added each vector to a list and made your own iterator that would traverse each element in each vector?  For most algorithms, that would be indistinguishable from one massive vector.  And, depending on the load, the extra work done in the custom iterator would be far less than all the work needed to actually concatenate all the vectors.

A:

How about this:

Split the vectors into cores piles. Calculate the size needed for each pile
Reserve space in a vector for all the data
Split this vector into cores parts.
Feed the parts and the piles to a thread for merging.

some quick code (prob. won't compile but you might get the point):
typedef vector<vector<ULLINT>> ManyVectors;

void merge(ManyVectors vector_of_vectors) {
  const int cores = 16;
  std::array<ManyVectors, cores> piles = split_vector(vector_of_vectors,cores);
  std::array<size_t, cores> sizes = calculate_sizes(piles,cores);
  std::vector<ULLINT> result;
  result.reserve(sum_of_sizes(sizes));
  int used = 0;
  int core = 0;
  for (ManyVectors& pile: piles) {
    std::thread(merge_vectors, pile, result.begin()+used);
    used += sizes[core];
    core += 1;
  }
}


Q:

Adding subplots to figure using for loop

I am trying to add 8 heatmaps (subplots) to a figure but I can't seem to manage it. Could you please help me?
# in order to modify the size
fig = plt.figure(figsize=(12,8))
# adding multiple Axes objects
fig, ax_lst = plt.subplots(2, 4)  # a figure with a 2x4 grid of Axes

letter = "ABCDEFGH"

for character in letter:
    x = np.random.randn(4096)
    y = np.random.randn(4096)
    heatmap, xedges, yedges = np.histogram2d(x, y, bins=(64,64))
    extent = [xedges[0], xedges[-1], yedges[0], yedges[-1]]

    # Plot heatmap
    plt.clf()
    plt.title('Pythonspot.com heatmap example')
    plt.ylabel('y')
    plt.xlabel('x')
    plt.imshow(heatmap, extent=extent)
    plt.colorbar()
    plt.show()

Thank you!

A:

First you were creating two separate figures by calling
plt.figure() and then plt.subplots() (that last function creates both a figure and an array of axes)
Then you need to iterate over your axes, and plot on each one of these axes, instead of clearing the figure at each loop (which is what you were doing using plt.clf())
You can use the plt.XXXX() functions, but those only work on the "current" axes, so you have to change the current axes at each iteration. Otherwise, you would be better off using the Axes.set_XXXX() functions, like in the other answer by @yatu. See here for more information.
    fig, ax_lst = plt.subplots(2, 4, figsize=(12,8))  # a figure with a 2x4 grid of Axes
letters = "ABCDEFGH"
for character,ax in zip(letters, ax_lst.flat):
    x = np.random.randn(4096)
    y = np.random.randn(4096)
    heatmap, xedges, yedges = np.histogram2d(x, y, bins=(64,64))
    extent = [xedges[0], xedges[-1], yedges[0], yedges[-1]]

    # Plot heatmap
    plt.sca(ax) # make the ax object the "current axes"
    plt.title(character)
    plt.ylabel('y')
    plt.xlabel('x')
    plt.imshow(heatmap, extent=extent)
    plt.colorbar()
plt.show()


Q:

Chrome canvas 2d context measureText giving me weird results

Here's a compact version of my problem

let canvas = document.createElement('canvas')
let ctx = canvas.getContext('2d')
ctx.font = '11pt Calibri'
ctx.fillStyle = '#000000'
let temp = ctx.font
console.log(ctx.font)
console.log(ctx.measureText('M').width)
ctx.font = 'bold ' + ctx.font
console.log(ctx.font)
console.log(ctx.measureText('M').width)
ctx.font = 'italic ' + ctx.font
console.log(ctx.font)
console.log(ctx.measureText('M').width)
ctx.font = temp
console.log(ctx.font)
console.log(ctx.measureText('M').width)

Running this code in chrome produces incorrect numbers, at least at the end. First I'm setting the font to '11pt Calibri', but chrome immediately changes it to '15px Calibri' for some reason, and because of that it's producing text that's slightly bigger than correct. I read that the canvas runs at 96dpi so the correct px should be 14.6.
After that, I'm measuring the width of a text M, which comes out at 12.53401184 for me, this number is important.
After that, I've modified the font to add bold and italic, and then I roll it back to what the font originally was. Now when I measure it, it gives me 12.824707, which is a massive 0.3px off. I'm drawing text on a canvas with anywhere from 600px to 800px width, and I need it to wrap correctly, so I need it to be precise to 1px over the line, so individual letters need to have at least 0.02px accuracy, which worked decently until I started using bolds and italics.
None of the above problems exist on firefox, and disabling canvas hardware acceleration on chrome doesn't seem to have any effect. I'm using chrome 52.0 which is the current latest version.
Edit: I figured out you don't even need to do any of that to get the incorrect number, simply doing this is enough.

let canvas = document.createElement('canvas')
let ctx = canvas.getContext('2d')
ctx.font = '11pt Calibri'
ctx.fillStyle = '#000000'

console.log(ctx.font)
console.log(ctx.measureText('M').width)
let temp = ctx.font
ctx.font = temp
console.log(ctx.font)
console.log(ctx.measureText('M').width)

A:

Don't use "pt" for font sizing on canvas.
CSS Absolute and Magic Units
Using pt for font sizing is not recommended as it has no real meaning for media that represent visual information in terms of pixels (discrete indivisible image units) and is displayed on screens which have no fixed pixel density.
pt is an absolute measuring unit, the same as cm while px is a "magic unit" and only ever has an absolute meaning when the media type is print.

OP: "I read that the canvas runs at 96dpi so the correct px should be 14.6."

This is not correct the canvas does not have a absolute measuring unit. A pixel as a CSS unit only has an absolute dimension when the media type is print in which case 1px = 1/96 of an inch. The canvas is not considered as a printed media.

Why does the Width change?
The apparent problem
ctx.font = '11pt Calibri'
console.log(ctx.font);                   // 15px Calibri
console.log(ctx.measureText('M').width); // 12.534011840820312
ctx.font = ctx.font
console.log(ctx.font);                   // 15px Calibri
console.log(ctx.measureText('M').width); // 12.82470703125

Though the ctx.font values are the same the measured font widths are different
The simple solution
ctx.font = ctx.font = '11pt Calibri';

Will avoid the measured size discrepancies, but i am sure that nobody would consider this as anything but an ugly work around to an "apparent" browser specific bug.
The solution
Don't use pt units when setting canvas fonts.
What is going on.
The issue is a misunderstanding of what the ctx.font property actually is. It does not represent the current font's actual internal representation but rather an abstract human readable form.

W3C 2D Canvas: "On getting, the font attribute must return the serialized form of the current font of the context."

The process of serialization will lose precision. Serialising CSS values.The W3C standard specifies that the font-size be in px units which in this case further amplifies the apparent "bug"
The font properties set function takes the CSS font string, parses it. If valid then sets the canvas internal font and writes the serialized CSS font value to context.font The two do not have to match and the standard does not specify that they should.

Summary
The behaviour as described in the question is not a "bug". Inconsistency between browsers though (as always) is a concern. If we are to follow the standards, one could consider that browsers not showing the measurement inconsistency have interpreted the standard incorrectly and filled a ambiguity with their own interpretation (though this is speculative on my part).
The simple solution to the problem is to follow the standard's guidelines and not use pt when setting font-size values for anything but printed media.
As with all computer media "dpi" only ever has meaning when printing and is not defined until then. Nor do pixels necessarily equate to dots when printing. Always use resolution when referring to pixels rather than dp1 (my pet hate)


Q:

What is the process to get American green card and citizenship while on a H1B visa?

What process needs to be followed in order to acquire an American Green Card and subsequent citizenship if one is in the US on an H1B ?

A:

There are many paths to both a Green Card and Citizenship, including employment based, family based (e.g. marriage) and various special interests.
Since you are in the US on an H1B, you are likely employed, and if you are lucky your employer will sponsor you for a Green Card. It is a long and fairly complicated process. You should contact your HR department; however if they are not used to doing this it may be an uphill struggle to get them to spend the time and money on an application.  This slide show  from "Coming to America" (slides 8 to 15) has a good summary.
As for citizenship, most paths to that go through the Green Card. Once you have a Green Card there is a waiting period before you can apply. There are other routes like joining the US Military. See the USCIS website.


Q:

Bounding the commutator [A,B] in terms of the numerical radius

Given a norm $N$ over ${\bf M}_n(\mathbb C)$, it is a natural question to find the best constant $C_N$ such that
$$N([A,B])\le C_N N(A)N(B),\qquad\forall A,B\in{\bf M}_n(\mathbb C).$$
The answer is known at least in the following cases:

the operator norm $\|A\|_2=\sup\frac{\|Ax\|_2}{\|x\|_2}$ where the norm over $\mathbb C^n$ is the standard Hermitian $\|x\|_2^2=\sum_j|x_j|^2$. Then
$$\|[A,B]\|_2\le2\|A\|_2\|B\|_2$$
is optimal for $n\ge2$.
the Frobenius norm $\|A\|^2_F=\sum_{i,j}|a_{ij}|^2$. Then a theorem by Böttcher & Wentzel (2008) tells us that
$$\|[A,B]\|_F\le\sqrt2\|A\|_F\|B\|_F,$$
and again this is optimal.

I have a third norm in mind, yet of a different nature: the numerical radius
  $$r(A)=\sup_{x\ne0}\frac{|x^*Ax|}{\|x\|^2}.$$
  This is the smallest radius of a disk $D(0;r)$ containing the numerical range (or Hausdorffian) of the matrix.
  What is the optimal constant $C_{nr}$ such that $r([A,B])\le C_{nr}r(A)r(B)$ for all $A,B$ in ${\bf M}_n(\mathbb C)$ ?

Let me point out that $r$ is not submultiplicative. We have at best $r(MN)\le 4r(M)r(N)$, which gives by the triangle inequality $r([A,B])\le8r(A)r(B)$, but this is certainly not optimal. However, it is a super-stable norm, in the sense that $r(M^k)\le r(M)^k$ for every $k\ge1$.
This question naturally extends to $n$-commutators, in the spirit of my previous question Standard polynomials applied to matrices .
Edit. See below Piotr Migdal's answer and my adaptation of it. It gives $C_{nr}=4$.

A:

I got
$$r([A,B])\leq 4\sqrt{2} r(A) r(B).$$
It is lower than $8$ but still higher than the conjuncture $C_{nr}=4$.
I used the following facts:

For normal (i.e. $X^\*X=XX^\*$) matrices we have $r(X)=\sigma_1(X)$ (the largest singular value of X).
$\sigma_1(XY-YX)\leq 2 \sigma_1(X)\sigma_1(Y)$
Also, note that for $X$ and $Y$ hermitian (i.e. $X^\*= X$ and $Y^\* = Y$ ) we have

$$r(X+iY) \geq \max\left(\sigma_1(X),\sigma_1(Y)\right),$$
$$r(X+iY) \leq \sqrt{\sigma_1^2(X) + \sigma_1^2(Y)}.$$
Lets decompose $A$ and $B$ in their hermitian and antihermitian parts,
$$A = A_h + i A_a, \quad B= B_h+i B_a.$$
Then
$$r^2([A,B]) \leq \left( \sigma_1([A_h,B_h]-[A_a,B_a])\right)^2
+ \left( \sigma_1([A_h,B_a]+[A_a,B_h])\right)^2$$
$$\leq\left( 2\sigma_1(A_h)\sigma_1(B_h)+2\sigma_1(A_a)\sigma_1(B_a) \right)^2
+ \left( 2\sigma_1(A_h)\sigma_1(B_a)+2\sigma_1(A_a)\sigma_1(B_h) \right)^2$$
$$=4 ( \sigma_1^2(A_h) + \sigma_1^2(A_a) )( \sigma_1^2(B_h) + \sigma_1^2(B_a) )
+16 \sigma_1(A_h) \sigma_1(A_a) \sigma_1(B_h) \sigma_1(B_a)$$
$$\leq 8( \sigma_1^2(A_h) + \sigma_1^2(A_a) )( \sigma_1^2(B_h) + \sigma_1^2(B_a) )$$
$$\leq 32 r^2(A)r^2(B).$$

A:

Here is a partial result.
Claim. $4 \le C_{nr} \le 8$.
Proof. The upper bound has already been shown by the OP. The lower-bound follows by
\begin{equation*}
  A =
  \begin{bmatrix}
    0 & 1\\\\
    0 & 0
  \end{bmatrix},\qquad
  B =
  \begin{bmatrix}
    0 & 0\\\\
    -1 & 0
  \end{bmatrix}
\end{equation*}
for which
$$\frac{r([A,B])}{r(A)r(B)} = \frac{1}{\frac 12\times\frac 12}=4.$$
(Note: Slightly more generally, the $1$ in the above matrices can be replaced by an nonzero scalar).
Based on some experiments mentioned in my comments to Denis, I am led to the following attractive conjecture.
Conjecture: $C_{nr}=4$.

Additional Remarks.
Define $$X :=
  \begin{bmatrix}
    0 & 1\\\\
    0 & 0
  \end{bmatrix},$$
and let $A$, $B$ be arbitrary. Then, it is easy to see that we have the commutator inequality:
\begin{equation*}
  r(X \otimes [A,B]) \le 4 r(X \otimes A) r(X \otimes B),
\end{equation*}
where $\otimes$ denotes the Kronecker product.

A:

The answer by Piotr Migdal can be modified to give the accurate inequality
$$r([A,B])\le4r(A)r(B),\qquad\forall A,B\in{\bf M}_n(\mathbb C).$$
The only new argument is that for every matrix $M$, there exists an angle $\theta$ such that $r(M)=\|{\rm Re}(e^{-i\theta}M)\|_2.$
Actually, we do have
$$r(M)=\sup_\alpha\|{\rm Re}(e^{-i\alpha}M)\|_2.$$
Hereabove, the real part is defined as ${\rm Re} N=\frac12(N+\bar N^T)$. Notice that I employ the notation $\|\cdot\|$ (operator norm) which coincides with $\sigma_1$.
Let us apply this to $M=[A,B]$. With $\theta$ as above, let us decompose $e^{-i\theta}A=A_{\theta h}+iA_{\theta a}$. Then let us proceed as Piotr did:
$$r([A,B])=\|{\rm Re}[e^{-i\theta}A,B]\| = \|i[A_{\theta h},B_a]+i[A_{\theta a},B_h]\|\le2(\|A_{\theta h}\|\cdot\|B_a\|+\|A_{\theta a}\|\cdot\|B_h\|),$$
which gives
$$r([A,B])\le4r(e^{-i\theta}A)r(B).$$
Hence the result.


Q:

Auto Increasing ID in MS Access Database using C#

protected void Button1_Click(object sender, EventArgs e)
    {
        OleDbConnection con = new OleDbConnection();
        con.ConnectionString =
         "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=d:\\NewProject\\MainData.accdb;Persist Security Info=false";
        string query1 = "select BlogId from BlogTable where UserName=@username";
        OleDbCommand cmd1 = new OleDbCommand(query1, con);
        cmd1.Parameters.AddWithValue("@username", TextBox1.Text);
        con.Open();
        int id =(int)cmd1.ExecuteScalar()+1;
      string query2="insert into BlogTable values(id,@1,@2,@3)";
        OleDbCommand cmd = new OleDbCommand(query2, con);
        cmd.Parameters.AddWithValue("@1", TextBox1.Text);
        if(RadioButton1.Checked)
            cmd.Parameters.AddWithValue("@2", RadioButton1.Text);
        if (RadioButton2.Checked)
            cmd.Parameters.AddWithValue("@2", RadioButton2.Text);
        if (RadioButton2.Checked)
            cmd.Parameters.AddWithValue("@2", RadioButton3.Text);
        if (RadioButton2.Checked)
            cmd.Parameters.AddWithValue("@2", RadioButton4.Text);
        if (RadioButton2.Checked)
            cmd.Parameters.AddWithValue("@2", RadioButton5.Text);
        if (RadioButton2.Checked)
            cmd.Parameters.AddWithValue("@2", RadioButton6.Text);
        cmd.Parameters.AddWithValue("@3", TextArea1.Text);

        int i = cmd.ExecuteNonQuery();
        if (i >= 1)
            Label1.Text = "Record Saved";
        else
            Label1.Text = "Record not Saved";

        con.Close();
    }
}

In my MS Access database I've set my id type to Autonumber though it still does not increase automatically. What do I do?
With the above code it returns an error that one of the parameter does not have value.
My table looks like this:

BlogId: AutoNumber
Username: Text
Category: Text
Blog: Text

A:

You should omit the Autonumber field from the insert statement, and only insert values for the other fields, e.g.:
string query2="insert into BlogTable (Field1, Field2, Field3) values(@1,@2,@3)";

Change Field1, Field2, & Field3 to the names of the fields to be populated with the values held by parameters @1, @2, & @3.
You also seem to have a number of typos here:
if (RadioButton1.Checked)
    cmd.Parameters.AddWithValue("@2", RadioButton1.Text);
if (RadioButton2.Checked)
    cmd.Parameters.AddWithValue("@2", RadioButton2.Text);
if (RadioButton2.Checked) // <---------------------------- Should this be RadioButton3?
    cmd.Parameters.AddWithValue("@2", RadioButton3.Text);
if (RadioButton2.Checked) // <---------------------------- Should this be RadioButton4?
    cmd.Parameters.AddWithValue("@2", RadioButton4.Text);
if (RadioButton2.Checked) // <---------------------------- Should this be RadioButton5?
    cmd.Parameters.AddWithValue("@2", RadioButton5.Text);
if (RadioButton2.Checked) // <---------------------------- Should this be RadioButton6?
    cmd.Parameters.AddWithValue("@2", RadioButton6.Text);


Q:

Extend complex types from an existing schema

I need to extend an existing XML document with new elements without losing the ability to validate it against both the unchanged original schema and an extended schema defined by me.
For example, lets say I want to add Code and Price elements to an existing Book document, as follows:
<aa:Book xmlns:aa="http://www.aa.com"
         xmlns:bb="http://www.bb.com">
  <aa:Title>Complete Works</aa:Title>
  <aa:Author>Shakespeare</aa:Author>
  <bb:Code>98</bb:Code>
  <bb:Price>31.6</bb:Price>
</aa:Book>

The original schema (which I cannot change) would look something like this:
<xs:schema targetNamespace="http://www.aa.com"
           xmlns:xs="http://www.w3.org/2001/XMLSchema"
           xmlns="http://www.aa.com"
           elementFormDefault="qualified">
  <xs:element name="Book" type="Book--type" />
  <xs:complexType name="Book--type">
    <xs:sequence>
      <xs:element name="Title" type="xs:string" />
      <xs:element name="Author" type="xs:string" />
    </xs:sequence>
  </xs:complexType>
</xs:schema>

How would I create a new schema that defines these new elements such that a SchemaSet containing both these schemas can successfully validate the extended XML document above?
I've tried the following usual complex type extension pattern:
<xs:schema targetNamespace="http://www.bb.com"
           xmlns:xs="http://www.w3.org/2001/XMLSchema"
           xmlns="http://www.bb.com"
           xmlns:aa="http://www.aa.com"
           elementFormDefault="qualified">
  <xs:import namespace="http://www.aa.com" />
  <xs:complexType name="Book--type">
    <xs:complexContent>
      <xs:extension base="aa:Book--type">
        <xs:sequence>
          <xs:element name="Code" type="xs:int" />
          <xs:element name="Price" type="xs:double" />
        </xs:sequence>
      </xs:extension>
    </xs:complexContent>
  </xs:complexType>
</xs:schema>

However this causes errors stating that the element aa:Book doesn't define a child element bb:Code, which makes total sense.
Is this even possible?
For reference, here is the code I'm using to validate the document:
var fail = new ValidationEventHandler((sender, e) => Debug.Fail(e.Message));
var schemaSet = new XmlSchemaSet();
schemaSet.Add(XmlSchema.Read(new StringReader(original), fail));
schemaSet.Add(XmlSchema.Read(new StringReader(extension), fail));
var settings = new XmlReaderSettings
    {
        ValidationType = ValidationType.Schema,
        Schemas = schemaSet
    };
settings.ValidationEventHandler += fail;
using (var stream = File.OpenRead(fileName))
using (var reader = XmlReader.Create(stream, settings))
{
    while (reader.Read()) {}
}

A:

It turns out that xs:redefine is what I was looking for. It allows you to redefine an existing element in a new schema without touching the original schema or the document being validated.
Using my original example, a book can be extended using the following two schemas:
<xs:schema targetNamespace="http://www.bb.com"
           xmlns:xs="http://www.w3.org/2001/XMLSchema"
           xmlns="http://www.bb.com"
           elementFormDefault="qualified">
  <xs:element name="Code" type="xs:int" />
  <xs:element name="Price" type="xs:double" />
</xs:schema>

<xs:schema targetNamespace="http://www.aa.com"
           xmlns:xs="http://www.w3.org/2001/XMLSchema"
           xmlns="http://www.aa.com"
           xmlns:bb="http://www.bb.com"
           elementFormDefault="qualified">
  <xs:import namespace="http://www.bb.com" />
  <xs:redefine schemaLocation="http://www.aa.com">
    <xs:complexType name="Book--type">
      <xs:complexContent>
        <xs:extension base="Book--type">
          <xs:sequence>
            <xs:element ref="bb:Code" />
            <xs:element ref="bb:Price" />
          </xs:sequence>
        </xs:extension>
      </xs:complexContent>
    </xs:complexType>
  </xs:redefine>
</xs:schema>


Q:

Is it possible to add properties to a serialized collection?

Is there a way to add elements and attributes to a serialized collection subclass?
Here's an example, given the following class:
[XmlRoot("MyTs")]
public class MyCollection : HashSet<MyT>
{
    [XmlAttribute]
    public string Name { get; set; }

    //[XmlElement]
    public string Description { get; set; }
}

The serialized XML does no contain the additional element and attribute. Is there a way to add it, which still using the serialization class as HashSet subclass?
For the above example, I want the following XML:
<?xml>
<MyTs name="name">
  <MyT/>
  <MyT/>
  <MyT/>
  <Description>Some long verbal rubbish</Description>
</MyTs>

A:

To XmlSerializer, something is either a collection xor a data object. Not both.
You can, however, do:
[XmlRoot("MyTs")]
public class MyRoot
{
    [XmlAttribute]
    public string Name { get; set; }

    //[XmlElement]
    public string Description { get; set; }

    private readonly HashSet<MyT> items = new HashSet<MyT>();
    [XmlElement("MyT")]
    public HashSet<MyT> Items {get { return items;}}
}

which will have the xml structure you want.


Q:

Need help with a zeta-like function?

Some time ago I found interesting modifications to Euler's prime product that produces a square number and its square root.  The parts that were still unknown were the corresponding sums. I have finally found the sum which produces the square.
The solution is to use $\textit{5-rough}$ numbers---numbers whose least prime factors are $\geq 5$. See Mathworld and Wiki.
At OEIS we find this formula for $\textit{5-rough}$ numbers:
FORMULA (6n + (-1)^n - 3)/2 by Antonio Esposito, Jan 18 2002

Edit--- We include 1 in this formula even though it is not considered a rough number
$$
\psi (n)\equiv\frac{1}{2} \left(6 n+(-1)^n-3\right)
$$
Edit2--- We replace the function with one that converges faster.
$$
\psi (n)\equiv\frac{(6 n-5) (6 n-1)}{\sqrt{72 (n-1) n+26}}
$$
Here we show the sum and product that produce the square number:
$$
\sum _{n=1}^{\infty } \psi (n)^{-2} = \prod _{n=3}^{\infty }
(1-(p_n)^{-2})^{-1} = \frac{\pi^2}{9}
$$
Here we show the sum and product that produce the square root:
$$
\sum _{n=1}^{\infty } \phi (n)^{-2} = \prod _{n=1}^{\infty }
(1-(6 n)^{-2})^{-1} = \frac{\pi}{3}
$$
A function for the second sum is still unknown:
$$
\phi (n)\equiv\textbf{?}
$$
I tried using $\textit{3-smooth}$ numbers---numbers whose prime factors are $\leq 3$, but that converges to $1.499999\ldots$
Here is one function that uses an alternating series, but I would prefer something that can be squared during the summation (to make it more zeta-like).
$$
\sum _{n=0}^{\infty } (-1)^n \left(\frac{1}{6 n+5}+\frac{1}{6 n+1}\right) = \frac{\pi}{3}
$$
My question: Does anyone have any ideas on how to craft this last function?

A:

By reworking the alternating sum, I found, for $s=2$:
$$
\sum _{n=1}^{\infty } \left(\frac{1}{(6 n-1)^s}+\frac{1}{(6 n-5)^s}\right) = \prod _{n=3}^{\infty }
(1-(p_n)^{-s})^{-1} = \frac{\pi^2}{9}
$$
The LHS is the only formula that is equal to the RHS for all $s>2$.
Therefore, the square root product is only a curiousity and not worth further attention.
I am accepting this answer to remove the post from the unanswered queue.


Q:

Moving hexagons with cube coordinates into a square formation

It works for most of it:

The problem starts when the height is alot larger than the width (3x9, 3x11, 5x11 etc.)

As you can see the first line is out of place, increasing the height further will repeat this pattern.
Here is the code (Note: my z and y for cube coordinates is swapped):
void SpawnHexGrid(int Width, int Height)
    {
        int yStart = -Height / 2;
        int yEnd = yStart + Height;

        for (int y = yStart; y < yEnd; y++)
        {
            int xStart = -(Width + y) / 2;
            int xEnd = xStart + Width;

            if (Width % 2 == 0)
            {
                if (y % 2 == 0)
                {
                    xStart++;
                }
            }
            else
            {
                if (y % 2 != 0)
                {
                    xStart++;
                }
            }
            Debug.Log("y: " + y + " , Start: " + xStart + " , End: " + xEnd);

            for (int x = xStart; x < xEnd; x++)
            {
                SetHexagon(new Cube(x, y));
            }
        }
    }

Edit:
After changing to @Idle_Mind solution my grid looks like this:

Edit again:
I found a solution, after changing to @Idle_Mind's solution I corrected the tilting by using y again:
int xStart = -Width / 2 - (y / 2);

but this caused a similar problem as before, but this time I realized it had something to do with the way an int is rounded, when y is negative xStart would be 1 lower then expected, so I just add 1 whenever y is negative:
int add = 0;

    if (y < 0)
    {
        add = 1;
    }
    int xStart = -Width / 2 - ((y - add) / 2);

This works like a charm now, thanks everyone.

A:

Change your SpawnHexGrid() to:
void SpawnHexGrid(int Width, int Height)
{
    int xStart = -Width / 2;
    int yStart = -Height / 2;
    int yEnd = yStart + Height;

    for (int y = yStart; y < yEnd; y++)
    {
        int xEnd = xStart + Width + (y%2==0 ? 0 : -1);

        for (int x = xStart; x < xEnd; x++)
        {
            SetHexagon(new Cube(x, y));
        }
    }
}

My test rig:

---------- EDIT ----------
I don't understand why you're using the y value as part of your calculation for x. Make the x constant for a whole column as you'd expect for a regular grid. In my code, the shorter rows still start at the SAME x coord as the longer ones; it's the length of them that changes. Then, when you draw, I simply calculate the position for a normal grid, but add half the width of the hexagon for all odd y positions resulting in the offset you need for the hexagons.
For example, here is a 5x5 grid drawn "normally" without offsetting the odd Y rows.  It's clear that the starting X coordinate for all rows is the same:

So the stored x,y coord are all based on a normal grid, but the drawing code shifts the odd y rows.  Here's where I change the X coord, only for drawing, of the odd y rows:
if (pt.Y % 2 != 0)
{
    center.Offset(Width / 2, 0);
}

So, after adding the offset (again, only at drawing time) for odd Y rows, it now looks like:

And here is the grid shown with the internal coord of each hexagon being displayed:

Hope that makes it clear how I approached it.


Q:

Include user data in different controller

I'm trying to render an activity list in the form of json so I can use that data in my AngularJS app. This is my activities controller:
def index
  @activities = PublicActivity::Activity.order("created_at desc")
  respond_to do |format|
    format.json do
      render :json => @activities.to_json()
    end
  end
end

And it renders the json like this:
{"id":3,"trackable_id":6,"trackable_type":"Movie","owner_id":1,"owner_type":"User","key":"movie.create","parameters":{},"recipient_id":null,"recipient_type":null,"created_at":"2015-12-30T12:31:24.765Z","updated_at":"2015-12-30T12:31:24.765Z"},
{"id":2,"trackable_id":5,"trackable_type":"Movie","owner_id":1,"owner_type":"User","key":"movie.create","parameters":{},"recipient_id":null,"recipient_type":null,"created_at":"2015-12-30T11:55:06.766Z","updated_at":"2015-12-30T11:55:06.766Z"},

As you can see there is a value called owner_id. This coincides with the user id of the user that did the activity.
I of course have a user model with name, email etc. values. So for the first user with the id 1 it looks like this,
{"id":1,"email":"john@doe.nl","name":"John Doe"},

Is it possible to check the owner_id in the activities and find the user_id that coincides, and then add the name, email, etc. value to the activity controller?
The result would be a json render like this:
{"id":3,"trackable_id":6,"trackable_type":"Movie","owner_id":1,"email":"john@doe.nl","name":"John Doe","owner_type":"User","key":"movie.create","parameters":{},"recipient_id":null,"recipient_type":null,"created_at":"2015-12-30T12:31:24.765Z","updated_at":"2015-12-30T12:31:24.765Z"},
{"id":2,"trackable_id":5,"trackable_type":"Movie","owner_id":1,"email":"john@doe.nl","name":"John Doe","owner_type":"User","key":"movie.create","parameters":{},"recipient_id":null,"recipient_type":null,"created_at":"2015-12-30T11:55:06.766Z","updated_at":"2015-12-30T11:55:06.766Z"},

A:

Sure! Just include it in your to_json method:
render :json => @activities.to_json(include: :owner)

Assuming that activity has_one owner
You can also choose to include only specific attributes from the included model. More information on how to handle these serializations can be found in the to_json Rails Docs


Q:

How to Checked and Unchecked Checked-box item of a List-box?

Am Using the checkbox in listbox items, how to Checked and Unchecked all checkboxes from the listbox?
<ListBox Height="168" HorizontalAlignment="Left" Margin="45,90,0,0" Name="listBox1" VerticalAlignment="Top" Width="120">
    <ListBox.ItemTemplate>
        <DataTemplate>
            <CheckBox Content="{Binding Name}" IsChecked="{Binding Ck, Mode=TwoWay}"/>
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>

DataBinding is :
        List<uu> xx = new List<uu>();
        xx.Add(new uu { Name = "A", Ck = false });
        xx.Add(new uu { Name = "A", Ck = false });
        listBox1.ItemsSource = xx;

Update :
Is it possible to do something like this:
 foreach (ListBoxItem item in listBox1.Items)
        {
            CheckBox ch = (CheckBox)item;
            ch.IsChecked = true;
        }

A:

A couple of things to consider.
1) First use an ObservableCollection (preferred) or a BindingList instead of a List as your datasource
2) Make sure you implement INotifyPropertyChanged on your  class.  See an example here
3) Now that you have your binding setup correctly, loop through the collection and set the checked property to false using a foreach or other loop.  The binding system will handle the rest and the changes in your list will be properly reflected on the UI
UPDATE:  Added a brief code example
In your code-behind:
    ObservableCollection<uu> list = new ObservableCollection<uu>();

    MainWindow()
    {
        InitializeComponent();

        // Set the listbox's ItemsSource to your new ObservableCollection
        ListBox.ItemsSource = list;
    }

    public void SetAllFalse()
    {
        foreach (uu item in this.list)
        {
            item.Ck = false;
        }
    }

Implementing INotifyPropertyChanged in uu class:
public class uu: INotifyPropertyChanged
{
    private bool _ck;

    public bool Ck
    {
        get { return _ck; }
        set
        {
            _ck = value;
            this.NotifyPropertyChanged("Ck");
        }
    }

    private void NotifyPropertyChanged(string name)
    {
        if (PropertyChanged != null)
        {
            PropertyChanged(this, new PropertyChangedEventArgs(name));
        }
    }

    #region INotifyPropertyChanged Members

    public event PropertyChangedEventHandler PropertyChanged;

    #endregion
}


Q:

UITableView add cell Animation

Can any one help me out with UITableView animating issue?
By default we have animation for deleting cell and reordering cells in UITableView.
Can we have animated adding cell, if so how to do it.
I have checked out Three20, did not not get how twitter has done the table expand animation under MyProfile>ReTweets.
Want to try it without Three20 frameowrk, using the existing animation in UITableView.

A:

You can use the following UITableView method:
- (void)insertRowsAtIndexPaths:(NSArray *)indexPaths withRowAnimation:(UITableViewRowAnimation)animation

Example with self.dataSource being a mutable array and your table only having 1 section:
[self.dataSource addObject:@"New Item"];
NSIndexPath *newIndexPath = [NSIndexPath indexPathForRow:[self.dataSource count]-1 inSection:0];
[tableView insertRowsAtIndexPaths:[NSArray arrayWithObject:newIndexPath] withRowAnimation:UITableViewRowAnimationFade];

Note: Subtracted 1 from datasource count since NSIndexPath is zero indexed.

A:

Swift
Example array that is the data source for the table view
var myArray = ["Cow", "Camel", "Sheep", "Goat"]

The following will add a row with animation at the top of the table view.
// add item to current array
myArray.insert("Horse", atIndex: 0)

// insert row in table
let indexPath = NSIndexPath(forRow: 0, inSection: 0)
tableView.insertRowsAtIndexPaths([indexPath], withRowAnimation: UITableViewRowAnimation.Fade)

Multiple updates
If you need to do multiple insertions and/or deletions then surround them with beginUpdates() and endUpdates().
tableView.beginUpdates()
tableView.insertRowsAtIndexPaths([addIndexPath1, addIndexPath2, ...], withRowAnimation: .Fade)
tableView.deleteRowsAtIndexPaths([deleteIndexPath1, deleteIndexPath2, ...], withRowAnimation: .Fade)
tableView.endUpdates()

Further reading

Documentation


Q:

Anchor links that point to ID of a hidden element will cause browser to automatically show the element and scroll to it when clicked

Anchor links that point to ID of a hidden element will cause browser to automatically show the element and scroll to it when clicked. I've seen some girl post a demo of this, but I cannot find it anymore. No JavaScript please.

A:

After some research and tests I have concluded that Mozilla engine doesn't auto-show hidden divs when linked using anchors.


Q:

drop down inside check box bootstrap

I'm using bootstrap 2 and i want a drop down inside check box label like this.
<label class="checkbox">
    <input type="checkbox">
    i want to buy
    <select class="which">
        <option>1</option>
        <option>2</option>
    </select>
    something
</label>

i want clicking on 'something' change status of checkbox. it's cool in chrome, but in firefox the drop down doesn't work and clicking on it changes status of checkbox. i use'd stop propagation method but doesn't help. this way of using drop down and checkbox is true?
Thanks

A:

It is illegal markup. Try validate the the above code. It will report "The label element may contain at most one input, button, select, textarea, or keygen descendant."
You have two inputs. Seems FireFox renders this "correct", the select box as part of the label, triggering its parent, the label, when it is clicked.
I suggest you make valid markup, using two labels :
<label class="checkbox">
    <input type="checkbox" id="check">
    i want to buy
</label>
<select class="which">
   <option>1</option>
   <option>2</option>
</select>
<label for="check">
    something
</label>

see fiddle -> http://jsfiddle.net/AbaZH/ works in FireFox (also)


Q:

Three20 TTThumbviewcontroller paging Load more link doesn't add more rows

I am struggling since few days to make this work. I got the Load More link for loading more thumbnails and when I select the link it loads additional records and datasource is updated accordingly. However it doesn't add additional rows and update Load More link with next page indexes. However additional images are added in existing rows, but wouldn't add new rows with additional images.
Is it something I have to change in photoindex after additional records are added from datasource?
I am loading data from sqlite and I have really large number of records. I was looking into other library just because I can't make this work. :(. I still really want to use this library.
Any help in identifying the problem is really appreciated. Thanks in advance

A:

Error was in PhotoSource method which returns maxPhotoIndex.
It has to be in sync with currentPage & number of photos per page.