Non-zero nilpotent operator

Question: I know that if an operator $T\in L(V)$ is nilpotent, then $T^{dim(V)}=0$.
I am struggling to construct an example of a nilpotent operator $T\in L(V)$ which satisfies the condition $T^{dim(V)-1}\neq 0$.
Is there a such example?
It would be great if someone could explain in detail.
Comment: "Example 1" in https://en.wikipedia.org/wiki/Nilpotent_matrix, or https://en.wikipedia.org/wiki/Shift_matrix.
Comment: @MartinR Thank you but I do not quite get why that  could be an example. Can you explain?
Comment: Perhaps I misunderstood your question. What is $N$ and how is it related to $T$?
Comment: @MartinR sorry there was a typo and I just edited it.
Comment: Example 1 is: $A=\begin{bmatrix}0&1\\0&0\end{bmatrix}$. Then $A^1 \ne 0$, $A^2 = 0$. The shift matrix is the generalization to $n$ dimensions.
Comment: @MartinR Thank you. Can you give me an example for 3x3 matrix?
So I can piture the concept better?
Comment: Have a look at the "shift matrix" $S$ in https://en.wikipedia.org/wiki/Nilpotent_matrix#Classification.
Comment: @MartinR I got the idea now!
Answer: The companion matrix $C$ of $X^n$ has $X^n$ as its minimal polynomial. Therefore, $C^n=0$ but $C^{n-1}\ne0$.

Non-zero nilpotent operator


System.InvalidCastException. OK... Where?

Question: I'm really having trouble using Linq on a SortedList. I have a Class Library and a Test WinForms app. The class library code is:
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace JTS
{
    public static class Pictures
    {
        public static class PictureManagement
        {
            public static SortedList<int, Picture> PictureList = new SortedList<int, Picture>();

            public static class Acquire
            {
                public static Picture ById(int id)
                {
                    Picture picture = null;

                    if(PictureList != null)
                    {
                        picture = (Picture)from pic in PictureList
                                          where
                                              pic.Key == id
                                          select (pic.Value as Picture);
                    }
                    return picture;
                }
            }
        }

        public class Picture : PictureBox
        {
            public int Id { get; set; }

            public class PictureProperties
            {
                public string Name { get; set; }
                public string Extension { get; set; }
                public string OriginalPath { get; set; }
                public Image OriginalPhoto { get; set; }
                public string Credits { get; set; }

                public Size DesignTimeSize { get; set; }
                public Point DesignTimeLocation { get; set; }

            }

            public PictureProperties Properties { get; set; }

            public class PictureThumbnail
            {
                public string Name { get { return "T" + Name; } }
                public Size Size { get; set; }
            }

            public PictureThumbnail Thumbnail { get; set; }
        }
    }
}

and the Test winforms app code is:
using JTS;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WindowsFormsApplication7
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        public void test()
        {
            for(int i = 0; i < 10; i++)
            {
                JTS.Pictures.PictureManagement.PictureList.Add(i, new JTS.Pictures.Picture()
                    {
                        Id = i,
                        Properties = new JTS.Pictures.Picture.PictureProperties()
                        {
                            Name = "Travis",
                            Credits = "people in here"
                        },

                        Thumbnail = new JTS.Pictures.Picture.PictureThumbnail()
                        {
                            Size = new Size(250, 250)
                        }
                    });

                Console.WriteLine("pics added to list");

                Console.WriteLine("getting Picture by id 3");

                JTS.Pictures.Picture pic = JTS.Pictures.PictureManagement.Acquire.ById(3);

                Console.WriteLine(pic.Id);
            }
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            test();
        }
    }
}

If you're going to paste this into VS, don't forget to Add System.Windows.Forms as a Reference to the class library.
The problem I'm having is when I run the Test winforms application, on FormLoad, I get an exception, which says:

An unhandled exception of type 'System.InvalidCastException' occurred
  in JTS.dll
Additional information: Unable to cast object of type
  'WhereSelectEnumerableIterator2[System.Collections.Generic.KeyValuePair2[System.Int32,JTS.Pictures+Picture],JTS.Pictures+Picture]'
  to type 'Picture'.

Now, I know what an invalid cast is. But I don't know what it's referring to. Where have I made an invalid cast?
Comment: Nit: `JTS.Pictures.PictureManagement.Acquire.ById(3);` probably shouldn't be *in* the loop..
Comment: @user2864740 yep, thanks for picking that up.
Answer: According to the error message, the error is here:
picture = (Picture)from pic in PictureList
                               where  pic.Key == id
                               select (pic.Value as Picture);

Try this:
picture = from pic in PictureList
                      where  pic.Key == id
                      select (pic.Value as Picture)).FirstOrDefault();

Or, since it is a SortedList, why not simply use this?
var picture = PictureList[id];

Comment: @Yasser: Edited it just a little bit more.
Comment: Anytime mate. Just to add in a lil more - [First() vs FirstOrDefault()](http://stackoverflow.com/a/1024577/1182982)
Comment: Thanks @PatrickHofman much appreciated. I'll be using `...PictureList[id]` for this from now on. But at-least I know for future reference how to do something like this with Linq.
Answer: picture = (Picture)from pic in PictureList
                                          where
                                              pic.Key == id
                                          select (pic.Value as Picture);

This query returns IEnumerable<Picture>, not Picture.
Try this:
picture = (Picture)from pic in PictureList
                                          where
                                              pic.Key == id
                                          select (pic.Value as Picture).First();

Answer: This query returns an IEnumerable<T> after get executed:
from pic in PictureList
where pic.Key == id
select (pic.Value as Picture)

You can't cast it to single Picture, if you want to get a single item, use First or Single method.
(from pic in PictureList
where pic.Key == id
select (pic.Value as Picture)).First();

Answer: Using Lambda:
Picture picture = PictureList.Where(pic => pic.Key == id).FirstOrDefault().Value;

This code replace the part where you doing a select from the PictureList collection. The problem with your code is that the where clause returns a collection of Picture and you're assigning the collection to a Picture which is not a collection, hence you're getting an InvalidCastException.
Comment: What is the intent of this snippet? Should it be added or replaced? Where should it go? Why does it fix the problem?
Comment: This code replace the part where you doing a select from the PictureList collection. The problem with your code is that the "Where" clause return a collection of Pictures and you're assigning the collection to a Picture which is not a collection hence you're getting an InvalidCastException.


Copying the neo4j browser visualisations with d3.js

Question: I'm looking to create some visualisations for my neo4j data, and there are some really nice settings in use in the browser that's bundled with it, but there seem less than straightforward to emulate when using d3 - my setup was based on the neo4j visualisation guide at http://neo4j.com/developer/guide-data-visualization/ but this guide doesn't really get you anywhere near what the browser achieves.
For example, I'm looking to emulate:

multiple curved path between nodes
paths which end at the edge of the node, and not the center
graph initialised in a static position (though could probably just hide until d3 presumably fires some event)

I've not seen any official CSS/JS release to get the same effects, so I guess it's assumed the user will code from scratch. Are there any other options for quickly achieving this?
Many thanks
Answer: I think that's kind of the holy grail.  If you make it, would you share it with us? ;)
In the meantime, sigma.js is a pretty nice library.  Linkurious even released a set of tools on top of it to do even more:
https://github.com/Linkurious/linkurious.js
Comment: I was hoping D3 could solve my problem, as the neo4j browser uses it itself, but Linkurious was next on my list to try out anyway! thanks!


JSON data passing between html pages

Question:
Possible Duplicate:
Javascript DOM errors

I have my following html code:

  // no onLoad() anymore!!

My JavaScript code is as follows:
$.ajax({
        type: 'GET',
        url: ........,
        dataType: "json",
        complete: function (xhr, statusText) {
            alert(xhr.status);
        },
        success: function (data, textStatus, jqXHR) {
            alert(JSON.stringify(data));
            if(document.getElementById(1).style.display == "block"){
                document.getElementById(1).style.display = "none";
                document.getElementById(2).style.display = "block"; }
            addBooks(data); // Passing JSON to be replaced on page
        },

        function (data, textStatus, jqXHR) {
            alert(data);
            alert('error');
        },
    });

function addBooks(data) { // USing DOM to populate the tables

    //var  newdata=document.getElementById('addBooks');
    //newdata.setattribute()

    //get the unordered list

    var newdata = document.getElementById('addBooks');
    var parent = document.getElementById('gBookList');
    //removeChildrenFromNode(parent);

    //create list divider
    var listdiv = document.createElement('li');
    listdiv.setAttribute('id', 'gBookListDiv');
    listdiv.innerHTML = ("Books Found:");
    parent.appendChild(listdiv);
    // (this is where the first error happens)

    //create dynamic list

    for (i = 0; i < data.length; i++) {
        // (this is where the second error happens)

        //create each list item
        var listItem = document.createElement('li');
        listItem.setAttribute('id', 'gBookListItem');
        parent.appendChild(listItem);
        //var link = document.createElement('a');
        //link.setAttribute('onclick','displayBook(data[i])');
        //link.setAttribute('href','#FindBook)');
        //listItem.appendChild(link);
        var pic = document.createElement('img');
        pic.setAttribute('src', data[i].pictureURL);
        pic.setAttribute('width', '80px');
        pic.setAttribute('height', '100px');
        pic.setAttribute('style', 'padding-left: 10px');
        link.appendChild(pic);
        var brk = document.createElement('br')
        link.appendChild(brk);
        var title = document.createElement('p');
        title.innerHTML = data[i].title;
        title.setAttribute = ('style', 'float:right');
        link.appendChild(title);
        var author = document.createElement('p');
        author.innerHTML = data[i].author;
        link.appendChild(author);
    }
    var list = document.getElementById('gBookList');
    // $(list).listview("refresh");
}

/*function removeChildrenFromNode(node){
            while (node.hasChildNodes()){
                node.removeChild(node.firstChild);
            }
        //}*/

I keep getting the following error which prevents me from populating the list , I am using Chrome

Uncaught TypeError: Cannot call method 'appendChild' of null
Uncaught TypeError: Cannot read property 'length' of undefined

I have posted this question yesterday, but I just wanted a fresh perspective on what the error could be.
Comment: Didn't you [already ask this question](http://stackoverflow.com/questions/11622324/javascript-dom-errors)?
Comment: yes , I did , I mentioned it in the question
Comment: Cleanup your old question (e.g. fix the code formatting). If you had more rep you could also start a bounty on it to get some more attention on it.
Comment: As others have mentioned, you should not ask the exact same question twice. You should make edits to your original question or ask those who have posted answers for clarification or more information. You've also accepted an answer on your original question, which indicates that your issue has been resolved. Please try to work within the original question.
Comment: Ok , Apologies , I am new to SO , thank you I have made the edits
Answer: There could be a few issues here :-

Are you doing this cross domain? If you are consider using JSONP instead which will solve some of the issues you may be seeing with data being "withheld" due to security policies.
You are also accessing a varible and making a assumption it has a value
var parent = document.getElementById('gBookList');
Before you use the parent tag, you should ensure that its not null (or a empty reference) and that the element (gBookList) does infact exist in your document.
Answer: must uncomment
// var link = document.createElement('a');

in
link.appendChild(pic);

this element is not decalred yet (in your case is just commented)!

JSON data passing between html pages


inflection point of degree 3 polynomial

Question: I want to show that the inflection point of a degree 3 polynomial $f(x)$ is at
$$
x = \frac{x_1 + x_2 + x_3}{3},
$$
if $f(x_1) = f(x_2) = f(x_3) = 0$. I was trying to show that the sign of $f''(x)$ changes at $x$, but how can I show this for an arbitrary polynomial?
Answer: Let $f(x)=ax^3+bx^2+cx+d$. That means the sign of $f''(x)$ changes when $6ax+2b=0$, so when $x=\frac{-b}{3a}$.
Since the sum of the roots of $f$ equals $\frac{-b}{a}$, we have that $x=\frac{-b}{3a}=\frac{x_1+x_2+x_3}{3}$.
Comment: @somebody Because $$\begin{eqnarray*}
f(x) &=&ax^{3}+bx^{2}+cx+d \\
&=&a(x-x_{1})(x-x_{2})(x-x_{3}) \\
&=&ax^{3}-a\left( x_{1}+x_{2}+x_{3}\right)
x^{2}+a(x_{1}x_{2}+x_{1}x_{3}+x_{2}x_{3})x-ax_{1}x_{2}x_{3}\text{,} \\
&\Rightarrow &-a\left( x_{1}+x_{2}+x_{3}\right) =b
\end{eqnarray*}$$
Comment: See the example with the cubic function here: http://en.wikipedia.org/wiki/Vieta%27s_formulas#Example
Comment: why is the sum $x_1+x_2+x_3$ equal to $-b/a$?
Answer: You know that $f(x)=ax^3+bx^2+cx+d$, so $f''(x)=6ax+2b=0$ implies that $x=$ $___$. What do you know about the relationship between the coefficients $a,b,c,d$ and the roots $x_1,x_2,x_3$?

inflection point of degree 3 polynomial


Inequality with a norm

Question: I need help with the following:
Let $A=\left(\begin{array}{cc}a & b \\c & d\end{array}\right)$, with $a\in\mathbb{R}$, $b\in(l^{1})^{*}$, $c\in l^{1}$, and $d\in L(l^{1},l^{1})$.
Let $h\in l^{1}$.
What I'm trying to show is that then
$||Ah||\leq||A||_{1}\cdot||h||$, where $||A||_{1}=\sup_{j}\sum_{i}|A_{ij}|$ (maximum absolute column sum).
My attempt so far: I recalled the definition of the operator norm
$|||A|||=\sup_{h\neq0}\frac{||Ah||}{||h||}$
and looking at itmy inequality seemed to follow by definition, since $||A||_{1}$ is an example of an operator norm, right? Can it be that simple?
Thank you.
Answer: Strictly speaking, one has first to show that the right hand side of the defining equation of $\|A\|_1$, which a priori belongs to $\mathbb{R}_{\geq0} \cup \{\infty\}$, is actually a finite number. Then, establishing the inequality $\|Ah\| \leq \|A\|_1\|h\|$ for $h \in \ell^1$, we will deduce that $A \in L(\ell^1,\ell^1)$. Only then can we speak of the operator norm of $A$, and observe that in fact it equals $\|A\|_1$, as we have $|||\,B\,||| = \|B\|_1$ for all $B \in L(\ell^1,\ell^1)$.
Since $(\ell^1)^* \simeq \ell^\infty$, we identify $b \in (\ell^1)^*$ with a bounded sequence $(b_j)_{j=1}^\infty \subset \mathbb{R}$. Similarly, we view $d \in L(\ell^1,\ell^1)$ as an infinite real matrix $(d_{ij})_{i,j=1}^\infty$ for which $\|d\|_1 = \sup_{j\geq1}\sum_{i=1}^\infty|d_{ij}| < \infty$. Finally, we write $c = (c_i)_{i=1}^\infty$ and $h = (h_j)_{j=1}^\infty$. With this notation, we have
$$ \|A\|_1 = \sup\left\{|a|+ \sum_{i=1}^\infty|c_i|,\  \sup_{j\geq1}\left(|b_j| + \sum_{i=1}^\infty|d_{ij}|\right)\right\}.$$
Since $|a|+\sum_{i=1}^\infty|c_i| = |a| + \|c\| <\infty$ and
$$\sup_{j\geq1}\left(|b_j| + \sum_{i=1}^\infty |d_{ij}|\right) \leq \sup_{j\geq1}|b_j| + \sup_{j\geq1}\sum_{i=1}^\infty |d_{ij}| = \|b\|_\infty + \|d\|_1 < \infty,$$
we have $\|A\|_1 < \infty$ as well. Now, consider $\|Ah\|$. We have
$$\begin{multline} \|Ah\| = \left|ah_1 + \sum_{j=1}^\infty b_jh_{j+1}\right| + \sum_{i=1}^\infty\left|c_ih_1 + \sum_{j=1}^\infty d_{ij}h_{j+1}\right| \leq\\ |a|\,|h_1| + \sum_{j=1}^\infty |b_j|\,|h_{j+1}| + \sum_{i=1}^\infty\left(|c_i|\,|h_1|+\sum_{j=1}^\infty|d_{ij}|\,|h_{j+1}|\right). \end{multline}$$
Re-grouping the terms in the above expression and changing the order of summation in the convergent double series with non-negative terms $\sum_{i=1}^\infty\sum_{j=1}^\infty |d_{ij}|\,|h_{j+1}|$, we obtain the estimate
$$\begin{multline} \|Ah\| \leq \left(|a| + \sum_{i=1}^\infty|c_i|\right)|h_1| + \sum_{j=1}^\infty\left(|b_j| + \sum_{i=1}^\infty|d_{ij}|\right)|h_{j+1}| \leq\\ \|A\|_1|h_1| + \sum_{j=1}^\infty\|A\|_1|h_{j+1}| = \|A\|_1\|h\|, \end{multline}$$
as required.
Comment: thank you for an extensive answer!
Comment: You are welcome.
Comment: just one quick question, what would be a way to show that $l^{1}$ is isomorphic to $l^{\infty}$?
Comment: The space $\ell^\infty$ is isomorphic to $(\ell^1)^*$ (the dual of $\ell^1$). Given an element $u\in\ell^\infty$, define a linear functional $u^\flat:\ell^1\to\mathbb{R}$ via the rule $$u^\flat(x)=\sum_{i=1}^\infty u_ix_i$$ for $x\in\ell^1$. Since $|u^\flat(x)| \leq \sum_i|u_i|\,|x_i|\leq\sum_i\left(\sup_j|u_j|\right)|x_j|=\|u\|_\infty\|x\|< \infty$, we deduce that $u^\flat(x)$ is correctly defined (i.e. that the series on the right in the definition of $u^\flat$ converges), and that $u^\flat$ is bounded, with $\|u^\flat\|\leq\|u\|_\infty$. (to be continued)
Comment: Since $u^\flat$ depends linearly on $u$, we have defined a continuous linear map $(-)^\flat:\ell^\infty\to(\ell^1)^*$. Now, suppose that $f \in \ell^1$, and for $j \in\mathbb{Z}_{\geq0}$ let $e^j \in \ell^1$ be the sequence with terms $(e^j)_i = 0$ if $i \neq j$, and $(e^j)_j = 1$. Let $f^\sharp \in \ell^\infty$ be the sequence with terms $$(f^\sharp)_i = f(e^i).$$ Since $f$ is bounded and $\|e^i\| = 1$, we have $|(f^\sharp)_i| \leq \|f\|$ for all $i$. Hence, $f^\sharp$ is indeed bounded, with $\|f^\sharp\|_\infty \leq \|f\|$. (to be continued)
Comment: Since $f^\sharp$ depends linearly on $f$, we have a continuous linear map $(-)^\sharp : (\ell^1)^* \to \ell^\infty$. Clearly, $(u^\flat)^\sharp = u$ for every $u \in \ell^\infty$. On the other hand, suppose that $f \in (\ell^1)^*$. Given $x = (x_i)_{i=1}^\infty \in \ell^1$, define a sequence $(x^n)_{n=1}^\infty$ of elements of $\ell^1$ via the rule $$x^n = \sum_{j=1}^n x_j e^j = (x_1,\ldots,x_n,0,0,\ldots).$$ Since $\|x^n-x\| = \sum_{i>n} |x_i| \to 0$ as $n\to \infty$, we have $\lim_{n\to\infty} x^n = x$ in $\ell^1$. (to be continued)
Comment: Therefore, $$f(x) = \lim_{n\to\infty} f(x^n) = \lim_{n\to\infty}\sum_{i=1}^n f(e^i)x_i = \sum_{i=1}^\infty (f^\sharp)_i x_i.$$ This shows that $(f^\sharp)^\flat = f$. Hence, $(-)^\flat$ and $(-)^\sharp$ are mutually inverse continuous isomorphisms between $\ell^\infty$ and $(\ell^1)^*$.
Comment: Also, the inequalities $\|u^\flat\| \leq \|u\|_\infty = \|(u^\flat)^\sharp\|_\infty \leq \|u^\flat\|$ imply that $\|u^\flat\| = \|u\|_\infty$ for $u \in \ell^\infty$. Similarly, $\|f^\sharp\|_\infty = \|f\|$ for $f \in (\ell^1)^*$. Therefore, $(-)^\sharp$ and $(-)^\flat$ are actually isometries.

Inequality with a norm


XCode error EXC_BAD_ACCESS when using sqlite3 + table + tab bar

Question: I have a class ClsDatabase that is called to save / retrieve data.
There are also 2 views. The 2nd view have table that will display information based on what ClsDataBase retrieved. A tab-bar controls the 2 views.
It can load initially with the 1st view shown. However, when I select the 2nd view, it stops at main.m's
return UIApplicationMain(argc, argv, nil, NSStringFromClass([TestTabBarAppDelegate class]));

with error message: EXC_BAD_ACCESS.
I tried create another project but without ClsDatabase and just print some dummmy values in table, and it works. Not sure if its because of the class ClsDatabase
AppDelegate.m
#import "TestTabBarAppDelegate.h"
#import "TestTabBarFirstViewController.h"
#import "TestTabBarSecondViewController.h"

@implementation TestTabBarAppDelegate

@synthesize window = _window;
@synthesize tabBarController = _tabBarController;

- (void)dealloc
{
    [_window release];
    [_tabBarController release];
    [super dealloc];
}

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    self.window = [[[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]] autorelease];
    UIViewController *viewController1 = [[[TestTabBarFirstViewController alloc] initWithNibName:@"TestTabBarFirstViewController" bundle:nil] autorelease];
    UIViewController *viewController2 = [[[TestTabBarSecondViewController alloc] initWithNibName:@"TestTabBarSecondViewController" bundle:nil] autorelease];
    self.tabBarController = [[[UITabBarController alloc] init] autorelease];
    self.tabBarController.viewControllers = [NSArray arrayWithObjects:viewController1, viewController2, nil];
    self.window.rootViewController = self.tabBarController;
    [self.window makeKeyAndVisible];
    return YES;
}

(2nd view).h
#import <UIKit/UIKit.h>

#import "ClsDatabase.h"

@interface TestTabBarSecondViewController : UIViewController<UIApplicationDelegate, UITabBarControllerDelegate>{
    NSArray *arrDebtor;
    ClsDatabase *dbDebtor;
}

@end

(2nd view.m)
#import "TestTabBarSecondViewController.h"

@implementation TestTabBarSecondViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        self.title = NSLocalizedString(@"Second", @"Second");
        self.tabBarItem.image = [UIImage imageNamed:@"second"];
    }
    return self;
}

- (void)viewDidLoad
{
    NSString *strSql;
    dbDebtor = [[ClsDatabase alloc] initWithDbName:@"Debt"];
    arrDebtor = [[NSArray alloc] init];

    strSql = [NSString stringWithFormat:@"SELECT * FROM Debtor"];
    arrDebtor = [dbDebtor ReturnQueryArray:strSql];

    [super viewDidLoad];
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section             {
    if ([arrDebtor count] == 0) {
        return 1;
    }
    else {
        return [arrDebtor count];
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *cellIdentifier = @"Debtor";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];

    if ([arrDebtor count] == 0) {
        if (indexPath.row == 1) {
            if (cell == nil)
            {
                cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier] autorelease];
        }
            cell.textLabel.text  = [NSString stringWithFormat:@"No tables or records found"];
            return cell;
        }
    }
    else {
        if (cell == nil)
        {
            cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier] autorelease];
        }
        NSMutableDictionary *dictDebtor = [arrDebtor objectAtIndex:indexPath.row];
        cell.textLabel.text  = [dictDebtor valueForKey:@"Name"];
        return cell;
    }
}

Comment: When I tried to use NSZombieEnabled to track this type of error, the apps just quit before zombie message, when I clicked the 2nd tab.
Comment: You are posting too much code. Try to cut down on it and just show the parts that you suspect may contain the issue.
Comment: yup. already reduced to the minimal...sorry for that.
Answer: You are doing lot's of things in code that should be done with IB and storyboarding.
Your logic in cellForRowAtIndexPath will fail on the first row, when indexPath.row is 0 and your arrDebtor is empty and your cell has not been created yet. That would explain the EXC_BAD_ACCESS error.


Output an empty alt tag for an image in with views?

Question: I have an image field in a view. How can I output empty alt text for the image.
(For decorative images this is the correct markup
http://www.w3schools.com/tags/att_img_alt.asp )
Comment: Big surprise!  W3CSchools seems to have gotten this one right (at least there is WCAG 2.0 note that says this too: http://www.w3.org/TR/WCAG20-GENERAL/H67.html).  However, should never, ever cite W3CSchools as a source for *anything* that has to do with mark-up.  (But see also this note about decorative images: http://www.w3.org/html/wg/drafts/html/master/embedded-content-0.html#a-purely-decorative-image-that-doesn%27t-add-any-information )
Answer: If you have disallowed the "alt" text in your field configuration, the system will output and empty value as you want. But if the field has a value in the attribute, you could modify it with hook_preprocces_field().
Comment: Is the field configuration part of the content type admin screen or a setting for the view's field?
Comment: The field configuration in your content type.


Como pegar o value de botões criados através de um loop foreach em php/laravel?

Question: Pessoal eu tenho um array com tamanhos de um produto, segue o exemplo do array:

E para cada tamanho eu crio um botão através de um foreach, segue trecho do código onde crio os botões:

    Tamanho:
    @foreach($stocks as $stock)
        <button id="stock" class="btn-stock" value="{{ $stock->id }}" data-quantity="{{ $stock->quantity }}" onclick="verifyStock();">{{ $stock->unit->name }}</button>
    @endforeach

Para mim prosseguir com minha aplicação eu preciso verificar se o produto tem estoque e para verificar isso eu preciso da quantidade, uma informação que já vem no array, e eu estou tentando jogar ela em um script através de um data attributes, porém o problema é que não importa em qual botão eu clico ele sempre vem o valor do primeiro elemento do array... e como lá em cima eu já fiz um foreach era para estar vindo certo, não era? Segue abaixo a minha função js:
$(document).ready(function() {
    verifyStock();
});

function verifyStock() {
    var quantity = $('#stock').val();
    // var quantity = $('#stock').attr('data-quantity');
    console.log(quantity);
}

Alguém poderia me explicar o que está faltando, onde está faltando e o pq?
Answer: Acredito que o erro está ocorrendo porque você está tentando pegar o valor a partir de um ID, o problema é que no HTML o ID é único, e quando você faz o foreach, você está iterando mais elementos com o ID "stock". Uma solução simples seria enviar o próprio elemento com o 'this', e buscar os valores que você precisa pela response dele.
    <button class="btn-stock" value="{{ $stock->id }}" data-quantity="{{ $stock->quantity }}" onclick="verifyStock(this);">{{ $stock->unit->name }}</button>

e no script:
function verifyStock(response) {
    console.log(response);
}

A partir daí você pode manipular o response, que será o botão clicado, e retornar os valores dos 'data', do 'value' e tudo que estiver dentro deste botão
Answer: O problema ta no teu codigo js
$(document).ready(function() {
    verifyStock();
});

function verifyStock() {
    var quantity = $('#stock').val();
    // var quantity = $('#stock').attr('data-quantity');
    console.log(quantity);
}

perceba que voce esta buscando o valor do id stock, para o js existem varios ids stack pois vc rodou no foreach dai ele vai pegar o valor do primeiro elemento com esse id
A solução seria colocar o id junto e enviar para a função js assim

    Tamanho:
    @foreach($stocks as $stock)
        <button id="stock{{$stock->id}}" class="btn-stock" value="{{ $stock->id }}" data-quantity="{{ $stock->quantity }}" onclick="verifyStock({{ $stock->id }});">{{ $stock->unit->name }}</button>
    @endforeach

js
$(document).ready(function() {
        verifyStock();
    });

    function verifyStock(id) {
        var quantity = $('#stock'+id).val();
        // var quantity = $('#stock').attr('data-quantity');
        console.log(quantity);
    }


In how many ways can a teacher divide a group of seven students into two teams each containing at least one student?

Question: Can someone please help me with this?
In how many ways can a teacher divide a group of seven students into two teams each containing at least one student? two students? What about when seven is replaced with a positive integer n≥4?
I thought about using combinations.But not sure how to go from there.
Answer: Assuming the students are not interchangeable, for $n$ students there are $2^n$ subsets to make a team.  Two of these are not allowed:  the null set and the whole set, as both result in a team with no members.  Then we have counted each team twice, once selecting it and once selecting all the rest.  So there are $\frac 12(2^n-2)$ ways to make two teams each with at least one student.  If you need at least two students per team, start from the last.  There are $n$ single student teams that are no longer allowed, so the answer here is $\frac 12(2^n-2)-n$
Comment: It is nice to see that the properties of the power of a set can be used to solve a problem in combinatoric.
Answer: I'd look at a generating function. We have $a + b = 7$, with $a$ and $b$ representing our groups. So if $a, b \geq 1$, we have $f_{a}(x) = \sum_{i=1}^{7} x^{i}$. $f_{b}(x)$ is the same function. So we let our generating function, $g(x) = f_{a}(x) * f_{b}(x) = x^{2} * (\frac{1-x^{7}}{1-x})^{2}$. Then simply expand out using binomial identities to get your answer.
So expanding out $(1-x^{7})^{2}$, we get $num(x) = \binom{2}{0} - 2x^{6}$. Expanding out the denominator gives us $denom(x) = \sum_{i=0}^{7} \binom{i + 2 - 1}{i} x^{i}$. Now multiply $num(x) * denom(x)$, and take the coefficient of the $x^{7}$ term. That's your answer.
More reading on generating functions: http://www.dreamincode.net/forums/topic/304589-a-look-at-the-knapsack-problem-with-generating-functions/
Best of luck!
Comment: Note: This solution assumes that students are indistinguishable.
Answer: at least $1 : 3$ ways
at least $2 : 2 $ ways
if seven replaced by positive integer $n≥4 $:
at least 1 : if $n$ is even number so the number of ways = $\frac{n}{2}$
              if $n$ is odd number so the number of ways = $(n-1)$
at least 2 : if $n $ is even number so the number of ways = $\frac{n}{2}-1$
                   if $n$ is odd number so the number of ways = $\frac{n-1}{2}-1$
Comment: Using MathJax/Latex will make it easier for everyone else to read.  Please review some tutorials.
Comment: I don't think "at least 1:3 ways" is correct. (A)+(remaining), (AB)+(remaining), (ABC)+(remaining), (ABCD)+(remaining) are 4 ways already. Not to mention other combinations.
Answer: well, the basic breakdown goes:
1-6, 2-5, 3-4
For the 1-6, there are 7 choices for the student that is by himself, and the other 6 are dictated by the one by himself, so there are 7 ways to break them up into 2 groups with one student in one and 6 in the other.
For 2-5, you have 7 options for the first person in the group of 2, and then 6 options for the second person, and again -- the other 5 people are the other team.  7*6 means there are 42 ways to break it up into 2 and 5.
For 3-4, you have 7 options, then 6 options, then 5 options for the group of 3, the other 4 people are automatically on the other team.  7*6*5=210 ways to to break it up into 3 and 4.
Hope that helps.
Edit:  What I did above has repeats that I did not consider, so adding a a different, hopefully more useful explanation.
Consider A,B,C,D,E,F,G as the seven people in your group.  If you break the group into to a group of 1 and a group of six, you have seven possibilities (any one of the seven people could be in the group all by themselves.
If you break the group into 2 and 5, as shown above, there are 42 ways to pick 2 people out of a group of 7, but some of those ways are repeats.  Specifically, (A,B) = (B,A).  In fact, every pair of students has a repeat (just picking them in reverse order), so really only half of the 42 methods are different from each other.  So, we only get 21 different ways to break them up into a group of 2 and a group of 5.
If you break them up into a group 3 and 4, there are 210 ways to do this, but again, we get repeats.  Consider picking (A,B,C).  This is the same as picking (A,C,B),  (B,A,C), (B,C,A), (C,A,B), (C,B,A) (this is arranging 3 objects, so we have 3 choices for first place, 2 for the second, and one choice for the last object).  So there are six ways to pick the same group.  In other words, only $\dfrac{1}{6}$ of the groups are unique.  210/6 = 35 different ways to break them up into a group of 3 and a group of 4.
Comment: Ah good call, I was leaving order in.  Thanks for pointing that out. Will edit it.


Remover coluna de números gerada automatica no Pandas Dataframe

Question: Criei um dataframe no pandas, esta funcionando tudo perfeito, mas quando exporto pro Excel, ele aparece essa primeira coluna com esses números. Gostaria de remove-la, mas comandos como .drop não funcionam.
df = {}
item = []
count = []
def dataframe(df):
    for i in ranking:
        item.append(i['item'])
        count.append(i['count'])
    df = pd.DataFrame(df, columns=('Item','Count'))
    df['Item'] = item
    df['Count'] = count
    df.sort_values('Count', axis=0, ascending = False, inplace=True)
    df.to_excel('C:/hashtag_teste.xlsx')
    print(df)
    return df

Answer: Por padrão, DataFrame.to_excel salva o índice do seu DataFrame junto da tabela de Excel. O índice de um DataFrame (também por padrão) é uma sequência numérica começando de 0.
É fácil mudar este comportamento ao salvar o arquivo Excel. Simplesmente passe o argumento index=False:
df.to_excel('C:/hashtag_teste.xlsx', index=False)

Comment: Eu achei que tivesse tentado isso, mas talvez estivesse colocando no lugar errado. Ainda estou aprendendo.

Muito Obrigado pela ajuda :)


Improve performance in Lat/Long geo location

Question: I have two tables, Bins and Locations, the first with 3 million records, the second with 30 million. I am trying to match Bin for Location with the following code
Create Table #tbl_locations (LocationID int not null, Lat float not null, Lon float not null)
Create Table #tbl_bins (BinID int not null, MinLat float not null, MaxLat float not null, MinLon float not null, MaxLon float not null)

CREATE NONCLUSTERED INDEX [IX_tbl_locations] ON [#tbl_locations] ([Lat] ASC, [Lon] ASC)
ON [PRIMARY]
CREATE NONCLUSTERED INDEX [IX_tbl_bins1] ON [#tbl_bins] ([MinLat] ASC, [MaxLat] ASC)
ON [PRIMARY]
CREATE NONCLUSTERED INDEX [IX_tbl_bins2_ABC] ON [#tbl_bins] ([MinLon] ASC, [MaxLon] ASC)
ON [PRIMARY]

Select L.LocationID, C.BinID
From   #tbl_bins C
Inner Join #tbl_locations L
ON (L.Lat Between C.MinLat And C.MaxLat)
AND (L.Lon Between C.MinLon And C.MaxLon)

Unfortunately the performance is extremely bad, I have already tried to index the different fields but that did not help enough. Everything still takes more than 10 minutes to run.
Any idea of how can I make this perform better? Maybe a better matching algorithm? SQL Server 2012 SP3.
BinID and LocationID already have a PRIMARY KEY CLUSTERED created on them.
When I check the Execution Plan I see that the JOIN is performed by a NESTED LOOP.
The output of STATISTICS IO is
Table '#tbl_locations_________________________________________________________________________________________________________000000000283'.
Scan count 2631070, logical reads 25575057, physical reads 0, read-ahead reads 0, lob logical reads 0, lob physical reads 0, lob read-ahead reads 0.
Table '#tbl_bins________________________________________________________________________________________________________000000000284'.
Scan count 17, logical reads 14741, physical reads 0, read-ahead reads 0, lob logical reads 0, lob physical reads 0, lob read-ahead reads 0.

Thanks a lot!

Edit - if instead of Temp Tables I use real ones, this would be the schema exported
/****** Object:  Table [dbo].[tbl_Bins]    Script Date: 5/30/2017 3:49:05 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[tbl_Bins](
    [BinID] [int] NOT NULL,
    [MinLat] [float] NOT NULL,
    [MaxLat] [float] NOT NULL,
    [MinLon] [float] NOT NULL,
    [MaxLon] [float] NOT NULL,
 CONSTRAINT [PK_tbl_Bins] PRIMARY KEY CLUSTERED
(
    [BinID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

GO
/****** Object:  Table [dbo].[tbl_Locations]    Script Date: 5/30/2017 3:49:05 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[tbl_Locations](
    [ExposureID] [int] NOT NULL,
    [Accgrpid] [int] NOT NULL,
    [LocID] [int] NOT NULL,
    [Lat] [float] NOT NULL,
    [Lon] [float] NOT NULL,
 CONSTRAINT [PK_tbl_locations] PRIMARY KEY CLUSTERED
(
    [ExposureID] ASC,
    [Accgrpid] ASC,
    [LocID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

GO
/****** Object:  Index [IX_tbl_bins1]    Script Date: 5/30/2017 3:49:05 PM ******/
CREATE NONCLUSTERED INDEX [IX_tbl_bins1] ON [dbo].[tbl_Bins]
(
    [MinLat] ASC,
    [MaxLat] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
GO
/****** Object:  Index [IX_tbl_bins2_ABC]    Script Date: 5/30/2017 3:49:05 PM ******/
CREATE NONCLUSTERED INDEX [IX_tbl_bins2_ABC] ON [dbo].[tbl_Bins]
(
    [MinLon] ASC,
    [MaxLon] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
GO
/****** Object:  Index [IX_tbl_locations]    Script Date: 5/30/2017 3:49:05 PM ******/
CREATE NONCLUSTERED INDEX [IX_tbl_locations] ON [dbo].[tbl_Locations]
(
    [Lat] ASC,
    [Lon] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
GO

Comment: try running the query by discarding result set option and see how fast it completes,if it completes fast,then network might be your bottleneck
Comment: Just curious...how many rows does that query return?
Comment: Is it faster if you add LocationID to the IX_tbl_locations index?
Comment: Doesn't this produce a massive cartesian product? You have no criteria on `#tbl_bins` (BTW, drop the Hungarian Notation please) so you're going to get every possible combination of location and bin.
Comment: I suspect an index on (MinLat, MaxLat, MinLong, MaxLong) will do the trick. In other news, this seems like a spatial query (that is "find things based on their position in the world"). Is there any reason not to use SQL Server's built-in spatial capabilities?
Comment: Sorry… lost track of this one. If your query is "find things within a certain radius of other things", the spatial queries can serve you well. It's definitely a different approach, though.
Comment: Hey @hatchet , the query returns about 35 millions as you can have more bins per location. Cheers
Comment: Sorry @hatchet I forgot to mention that both BinID and LocationID have already a PRIMARY KEY CLUSTERED on them
Comment: @alroc the target of the join is to find to which buckets a location belongs - probably there are better ways to do it, I agree...
Comment: @TheGameiswar - no performance improvements with the discarding results option set.
Comment: Can you provide sample repro,you can script schema , statistics from generate scripts option.This way we can repro the exact behaviour you are facing
Comment: @TheGameiswar I added the STATISTICS IO - is that what you meant? The schema is what I described in the question.
Comment: I am sorry,that's not what I requested.you can right click database,go to generate scripts ,you can select tables,now in advanced tab,you can select options like schema , statistics,indexes...
Comment: If you provide the output I requested,we can repro the same behavior
Comment: I confirm this script involves just temporary tables. Any way I can export statistics from those?
Comment: Thanks for the suggestion @BenThul I will give it a go. Do you think the SQL spatial stuff could perform well?
Comment: I will give it a go whenever I have some time. I am very interested to see how this can affect performance.  Thanks a lot!
Comment: Have you run `update statistics` on the tables? What's the output of `explain` for this query?
Answer: I have found a way to improve this.
SELECT     L.LocationID, C.BinID
FROM       #tbl_bins C
INNER JOIN #tbl_locations L
ON         (L.Lat Between C.MinLat And C.MaxLat)
AND        (L.Lon Between C.MinLon And C.MaxLon)
WHERE FLOOR(C.MinLat * 1000 ) <= FLOOR(L.Lat*1000)
AND   FLOOR(C.MinLon * 1000 ) <= FLOOR(L.Lon*1000)
AND CEILING(C.MaxLat * 1000 ) >= CEILING(L.Lat*1000)
AND CEILING(C.MaxLon * 1000 ) >= CEILING(L.Lon*1000)

This helps the query by reducing the amounts of Bins to join to 1.
Comment: This doesn't look like a good solution - it's just a workaround until you solve your actual problem.
Comment: Unfortunately I run out of ideas and time :-/ I promised myself to give a go using spatial queries. Will keep this posted.
Comment: maybe you should try my answer then
Answer: Create a covering index:
CREATE INDEX IX_tbl_lat_long_locations ON [#tbl_locations] (Lat, Lon, LocationID)

Having such an index means the table doesn't need to be accessed in order to retrieve the LocationID.
Make it a CLUSTERED index if you can.


Is it possible to highlight interpolated perl variables in emacs?

Question: Recently I've started using emacs and after overcoming a number of hurdles in making cperl-mode operate in a way that is agreeable I've become stumped by this problem. Currently I have all scalars in regular use being highlighted except for where they are interpolated. Is such syntax highlighting possible under this mode? Currently I'm using emacs 23.1 and jrockway's cperl-mode 5.23
Thanks
Answer: It won't highlight interpolated variables in strings, but it will do it in regular expressions.  I'll bet that could be adapted by somebody who knows elisp.


What is the xpath to find all Anchor Elements inside another Element?

Question: I have a problem with locating a certain element using xpath in WebDriver. Below is my approach:
Scenario 1:
Below finds all anchor Elements whose 'href' contains value provided. Using this approach I am able to locate 38 Elements. Agreed. Works as expected.      driver.findElements(By.xpath("//a[contains(@href,'http://www.holidayiq.com/hotels/')]"));
Scenario 2: I first locate a class named 'Rank-bar' which is available only once. I then use the same xpath to locate all anchor tags within this class only. Expected anchor tags is 4 However, I still find 38 Elements using this approach as well.
WebElement elements2 = driver.findElement(By.className("rank-bar"));
elements2.findElements(By.xpath("//a[contains(@href,'http://www.holidayiq.com/hotels/')]"));

What is that I am doing wrong here? Please help.
Answer: Actually you are again searching to find anchor element on whole document context that's why you are finding same.
If you want to search anchor element on elements2 context, you need to search with .// xpath as below :-
elements2.findElements(By.xpath(".//a[contains(@href,'http://www.holidayiq.com/hotels/')]"));

Or you can find same thing in just on liner using cssSelector as below :-
List<WebElement> allLinks = driver.findElements(By.cssSelector(".rank-bar a[href*='http://www.holidayiq.com/hotels/']"));

Answer: You should build a direct xpath like this:
//*[@class='rank-bar']//a[contains(@href, 'http://www.holidayiq.com/hotels')]

as you see you are used contains, this means you could also have something like:
//*[@class='rank-bar']//a[contains(@href, 'holidayiq.com/hotels')]

and find the elements from one step like:
driver.findElements(By.xpath("//*[@class='rank-bar']//a[contains(@href, 'holidayiq.com/hotels')]"));


How to deal with seniors' bad coding style/practices?

Question: I am new to work but the company I work in hires a lot of non-comp-science people who are smart enough to get the work done (complex) but lack the style and practices that should help other people read their code.
For example they adopt C++ but still use C-like 3 page functions which drives new folks nuts when they try to read that. Also we feel very risky changing it as it's never easy to be sure we are not breaking something.
Now, I am involved in the project with these guys and I can't change the entire code base myself or design so that code looks good, what can I do in this situation?
PS> we actually have 3 page functions & because we do not have a concept of design, all we can do is assume what they might have thought as there is no way to know why is it designed the way it is.
I am not complaining.I am asking for suggestion,already reading some books to solve the issues Pragmatic Programmer;  Design portion from B.Stroustrup; Programming and principles by B.Stroustrup;
Comment: Hope they dont read Stack Overflow?
Comment: What makes a 3-page function C-like?
Comment: I have the same problem. What did you did in the end?
Comment: You do not have it that bad. The place where I work does not have coding standards or code reviews... :(
Comment: It seems as "3-page function C-like" that is not literally; just an exagaration to drive home a point. However, there are 3 page functions/methods out there, I have seen a 2,000-line code with no comments and I have seen pages that do about 6 different things.
Comment: Nick, changed the name ;-) , thanks!
Answer: The best and most important thing you can do is lead by example.  Do things the right way and try to improve things slowly.  You aren't going to fix anything overnight.
Make sure every piece of code that you are responsible for is better after you are done with it.  Over time, the system will tangibly be better because of your efforts.
After you build a strong reputation with your co-workers, try go start some code reviews or lunch-training sessions to get everyone up to speed on better ways to do things.
In a nutshell: it will be difficult and frustrating, but it's possible.  Good luck.
Comment: Not *every* piece of code. If these old-timers have any sense of ownership at all, they'll resent the new kid making gratuitous changes. You'll be creating a conflict that will cause your style to be treated with contempt, whatever its merits. *Do* lead by example with any new code though.
Comment: @Mark that's actually a really good point (although, I must admit, I hate that it's true)...  Check edits.
Comment: What is the most annoying thing you can experience? That somebody comes and rewrites your code /because they think they are better/ and then causing some bug to be introduced which senior guy then needs to fix...
Comment: @Anders you are 100% correct assuming that the new kid doesn't know better and that the original code is of good quality.  I don't think the OP is just another cocky kid, I think he really sees some poor code that he feels he can make better.  The situations are different but not necessarily mutually exclusive.
Comment: Andres,

I am not asking to change their existing code neither I can change it for better, these guys are all PRO with 15+ years experience. but the code is not structured and we have to read it (makes it impossible) in our day-to-day life. I am trying to do something which will allure them to adopt process/standards/convention as they  still are writing new code in the same way, of course you can't go and correct all code your self as you have your own work to do. or your manager kicks you out ;-). it kills all motivation of doing things systematically
Answer: Your best bet is to NOT to handle it at all. Here are potential problems if you try:

You will be criticized for doing something you were not told to (makes performance reviews go real bad.)
You will have less time to do your own work.
You will not advance your career by cleaning working code- if it is not broke then do not touch it.
Never make enemies with people who control your career- unintentionally implying they are obsolete morons does not help your cause (especially in a bad economy).

Focus on making your own code great. Battling poorly written code is part of the ill of being a Software Engineer. You are in the wrong profession if you will not stand for it.
A little off point but important- You may need to switch jobs or teams if possible once the economy picks up. Mixing with a truckload of bad coders who do not bother to update their knowledge and practices dulls your own programming skills and weakens your marketability.
Comment: This is a much more pragmatic answer than the accepted one
Answer: If you're a junior dev, then the only thing you can really do is write code as elegantly and readable as possible.
If your style is indeed better, other people might notice and say "hey we should adopt this formula"
Actions speak louder than complaints, which is something I noticed.
Comment: Unfortunately that rarely happens. If a senior dev writes functions that are 3 pages long, they're too far gone. Can't fight them though; have to get along. Best bet is to try to outshine them as much as possible in your own code.
Answer: The present is embodied in Hexagram 47 - K'un (Oppression): Despite exhaustion, there may yet be progress and success. For the firm and correct, the really great man, there will be good fortune. He will fall into no error. If he make speeches, his words cannot be made good.
The future is embodied in Hexagram 6 - Sung (Conflict): Though there is sincerity in one's contention, he will yet meet with opposition and obstruction. If he cherish an apprehensive caution, there will be good fortune. If he prosecute the contention to the bitter end, there will be evil. It will be advantageous to see the great man. It will not be advantageous to cross the great stream.
Comment: Odd, but I like it. Please continue to post.
Answer: I was in the exact same shoes before. I got hired as a C++ programmer to 'lead the team' on how to use C++ by an enthusiastic manager. That was about a decade ago. Some of the newer engineers loved me, the seniors despised me. Our system was basically a pseudo-C++ system. It was like C with classes, but it appeared that people didn't even understand the usefulness of things like constructors since they hardly appeared.
You complain about functions that are 3 pages long; we had functions that were 8000 lines long full of long jumps, function pointer casts, etc. One of the seniors even formatted the code with 2-space indentations so that super deep nested blocks can be written without using much horizontal space since the seniors seemed to be allergic to writing functions and procedural programming in general. Someone even inlined a 2000 line function thinking it would make things faster. You might be dealing with some bad code, but I was dealing with the most horrid copy-and-paste code imaginable.
Unfortunately I was very young and cocky. I didn't get along with the seniors, I fought against them in territorial battles over code. They responded by creating coding standards which no sane C++ programmer could follow (ex: it's okay to use operator new, but don't use exception handling, don't use constructors or destructors, etc). As a result I wrote the most bizarre and stupid standards-workaround C++ code just to kind of rebel against those standards since I refused to write C-style code given the reason I was hired (I didn't hate C so much, but writing C code was not part of the job description: I was hired essentially as a C++ consultant), even though the standards made C-style coding the only practical way to do things. I only kept my job because I put in so much overtime to make sure that my code works very well in spite of these ridiculous coding standards.
It wasn't until years later when others started to see things my way that we lifted the silly standards and started writing more natural, easy-to-read C++ code complete with STL and boost goodies, RAII, exception-handling, etc. That isolated the seniors who refused to write code in a more sane fashion and they were finally forced to adapt.
In retrospect, I could have done things much better. The seniors were intent not to allow me to be put in a teaching position, but I think I would have gotten my point across much faster with my head down. The biggest regret I have is trying to work around the impossible coding standards rebelliously rather than getting them rectified through clear and rational discussions. As a result, I have really stupid and obfuscated C++ code in the system which people attribute to me even though that's not how I normally write C++ code. The regular developers I work with understand this, but the seniors still point to it as an example of why C++ is bad.
In short, I recommend that you focus on making more friends rather than enemies. Your friends will support you, and if your way is better and you can clearly demonstrate it, you can isolate the few who will never agree.
Comment: thanks @stinky472, I am no expert,
I am learning.  And if I am the one who's teaching, my future looks scary to me(where do I learn?)!
Comment: @Gollum I really think C++ Coding Standards will brighten your day. It might be hard to get your co-workers to read it, but if they don't, it'll still strengthen your own arguments in favor of certain practices - the ones that really matter. You also don't need to be authoritative. We're all students when it comes to programming, just share what you've learned.
Answer: Being enthusiastic to code the right way is a good trait to possess and in the software industry we will always encounter other developers who write code that is not quite in line with our "perfect way" of coding. This should never be interpreted as rubbish code, or inept coders, because we all start out like that in some shape or form.
Always respect your peers around you as you want them to respect you. It's certainly not easy to do in an environment that highly regards ego, but attempting to approach a topic like this is never easy.
It's how you communicate
Try different approach angles, remember you are there to learn as much as to render a service.
So commenting on the "poor" code style in an "in-your-face" kind of approach might not be the result you were looking for. So then back up a bit and try approaching the topic with "I was considering the style of code used and have a few suggestions..." and see the difference that gives.
Where I work now, the one thing I've learnt is that it's fine to comment on something that's might not be good quality but then I had better have a better solution to present.
In other words, be prepared to back up your words with useful solutions and not because you feel so.
Comment: thanks Mike, I definitely do not fight but I am worried about my growth. If I don't see how a good Code looks like, how I am going to write that way.
Comment: Reading other people's code is a good way to find out what is good and what is bad. Remember it takes a number of years for a tree to grow, we are no different. Read and learn. That's a good starting point, and as a developer, don't be afraid to ask questions. :)
Answer: I can empathize.
I'm below two senior programmers who have very unique styles that I find frustrating.  We have code that consists of one main function that's 1000 lines long.  (That is not a typo.)  Our coding standards discourage globals, so we make every program one App object.  Now our globals are member variables!  When we need an iteration interface for C++ classes, why should we use the begin, end, and operator++ conventions, when First, AtLast, and Next can be used instead.  We've wrapped up third party libraries in custom interfaces for no good reason.  (We've wrapped log4cxx and lost functionality for no reason I can tell, and one of our date classes consists of a shared pointer to a boost::date object with a fraction of the functionality.)
Here's how I've kept my sanity.  I've focused on the new languages and tools.  This is our company's first project involving Python, and I've spent my time writing utilities and programs there.  While the senior programmers code in what they're familiar with, I've got near free rein of all the Python code.  I couldn't stand the C++ APIs we use, so I duplicated most of the same functionality in Python in a much more friendly way, and the other developers prefer it too.
Likewise, we have little familiarity with log4cxx and less with boost-build, both of which I've taken time to study in depth and know good enough that people come to me with questions.  I've written a handful of resources on our wiki giving usage tips for log4cxx and numpy and other tools.
Comment: There is a good reason for preferring begin, end, and operator++ at least, and that would be static polymorphism. Some boost functions expect a container to implement methods named begin and end (boost::range, e.g.), and using operator++ makes those iterators standard-compliant which is also necessary for polymorphism with generic algorithms. I didn't like the style either when I first used C++, but when I found out that just providing a standard-compliant random-access iterator in my data structure allowed me to sort elements, search for elements, etc. automatically, I changed my mind.
Comment: The other things sound horrible though. Good luck with your efforts!
Comment: stinky472, I agree 100%.  I was being sarcastic. :-)
Answer: This is the most basic reason why establishing coding standards and code review processes are a good idea.
I will not write three page functions no matter what coding standards and processes are established, but some people will. They will create 20 local variables at the beginning, without initializing any of them. You'll have pointers and integers with unspecified values. You won't know the exact meaning and scope of each variable. Etc etc.
Try to convince your manager and, later, your team, with solid arguments. Maybe you could start with a shared reading of Effective C++ or C++ Coding Standards. Try to stress the point that, when working this way and creating better code, everybody wins. If they see this as a win-win situation, they will be more open to the change.
Comment: +1 for suggesting C++ Coding Standards. I can't praise that book enough for working with a team on a C++ system as a way to get everyone on the same page without arguing over petty things like formatting style.
Answer: This is how it is, get used to it or quit and find a place where it isn't like that.  You will be marginalized if you criticize their efforts and they may feel threatened if you do indeed write your own, better code or improve theirs.  At the end of the day they deliver code and management sees a black box that works and that's all that matters.  Plus, you'll be just another kid from college who thinks he knows something about development at a business and laughed at and ostracized when not around.  Honestly, a lot of the times these systems are built like this because of shaky requirements, lots of functionality bolted on with time and managements lack of respect for a stable software development process.
Not all companies are like this.  I'd start looking for a new job to be honest.
Comment: Leaving a steady position (especially directly out of school) is not often a good decision - regardless of the existing codebase. Adaptation and the eagerness to inject change will get you much further in life.
Comment: I'm saying start searching for new opportunities.  I've worked in environments like that and it isn't qualitative at all.  Adapting to poor coding standards and design is not helpful.  My advice to this kid is stick around if need be but don't expect anyone to respect his opinion if he's fresh out of school.  And calling other developers out with his current status is dangerous and not beneficial.  He either has to put up with it and face the reality he won't learn much from these types or he can start searching for a new place to work where people share his values.
Comment: nathan, totally agree with you.
Answer: I fervently hope, this is the best opportunity to grow by facing the challenge.As Robert said,try to lead by example.If possible let them adopt your pattern.
Answer: You are not alone. I too faced recently, luckily we have support from Senior Management for Code Reviews.
1. Even a single line change for Bug fix should be reviewed online.

Comments on code can be classified as CodingStandard/Suggestion/Clarification/Major/Minor etc
While giving comments to senior you can start with Clarification/CodingStandard rather than Major
Answer: You could address the issue of "we are afraid to touch it for fear of breaking it" by writing extensive unit tests.  Once you get the unit tests in place, you will be freed to refactor at will.  If your unit tests still pass after the refactoring, you can be confident you haven't broken anything.
Comment: It's been my experience that it is really difficult to write tests for things with such complicated internal models.  What I've tended to do, instead, is to try to write testable (preferably pure) functions for the particular pieces I could easily tease out of these balls of mud, test the new functions, then modify the original code to use them.  Repeating this process ultimately gets you much more comprehensible code.
Comment: @Aidan +10 that is a nice idea!
Answer: Just place a copy of "Clean Code" (Martin), "Refactoring: Improving the Design of Existing Code" (Fowler) or "Effective C++" somewhere in the office where people may start browsing the books. From now on, word will spread. Seriously, its never too late to learn! ;)
Comment: we have all the books but the problem is these people don't have interest. And I have rarely seen a guy looking for a book or blog or any information.
Comment: maybe you should suggest burning books again ;) time for a new job? Seems that there is not much what you could learn from them, too.


Arguments corrupted on passing in to function?

Question: I'm seeing something that's got me stumped. Maybe you folks can advise.
What appears to be a valid arguments are getting corrupted when passed to a different function.
Here is my setup:

LibA.a
LibB.a
SampleApp
MyApp.c

The bad function call is going from LibA in to LibB.
LibA, LibB and SampleApp have all been pre-complied (thankfully in debug mode) by an older version of Sun Studio on Solaris x86/64. SampleApp uses both LibA and LibB and runs just fine on my system.
MyApp uses both LibA and LibB in a manner similar to SampleApp. Yet, MyApp crashes due to this pointer corruption.
// File scoped string declared
static const char myString[] = "SomeText"

// The function call looks like
libAfunc(myString, myIntVar)

// The called function prototype is like
int libAfunc(const char* strArg, int intArg)

When single stepping the code, I see the pointer in the caller (myString) being valid and being passed as a parameter. In the callee, the address in the passed-in parameter pointer (strArg) is simply wrong.  In fact, all the parameters are actually wrong after passing in.
Note: The caller is in the pre-compiled LibA and the callee is in the pre-compiled LibB. I'm never even touching that code since it's all pre-compiled. Further, the code itself is probobly correct since SampleApp uses those functions, and runs fine.  (Although the call sequence could be slightly different...)
I'm thinking that my error is in the linking stage, but I'm not sure what it could be.
Any ideas?
Thank you
Comment: Maybe it's a size issue ... in your app, `sizeof (char*) != sizeof (int)`, but the libraries (wrongly) assume they're the same. Try compiling as 32-bits.
Comment: Is the integer parameter passed correctly?
Comment: @nonot1: what platform is this? If it is Windows, do the calling conventions match? If not, forget that. If it is, say, Solaris, it could be something like http://download.oracle.com/docs/cd/E19455-01/806-0477/chapter3-56/index.html. Don't know if there are different calling conventions on other platforms.
Comment: In the callee, does the address passed in appear in one of the CPU registers, or somewhere higher up or lower on the stack? Do you see the bit pattern (the hex pattern) anywhere?
Comment: @Oli: No, it is not.  I thought it was, but after sanity checking the value again, I see it's also way off.
Comment: @nonot1: Ok.  Perhaps you could simplify/clarify your question then?  The fact that we're talking about a pointer sounds like a red herring.
Comment: @Oli Good point.  Question updated to reflect all the args being wrong.
Comment: @pmg I everything is 64-bit.  Why do you say the libs might assume `sizeof (char*) == sizeof (int)`?
Comment: I was just trying a possible explanation: your program would put 8+4 bytes in the stack, but the library would read 4+4. If everything is 64-bit though, I think my point is moot.
Comment: I understand that you link against the two libraries as they are given by a third party? Are these compiled with debugging? Otherwise your debugger might just not show things correctly, there.
Comment: @Rudy This is on Solaris. Can the Calling Convention be affected by the linker?  I'll take a closer look at the registers and stack tomorrow.
Comment: @nonot1: I doubt the calling convention can be affected by the linker, since a different calling convention usually causes different code to be generated, and that is what the compiler does, not the linker. But I don't know if this is the case on Solaris.
Answer: Can you compile SimpleApp with your compiler? Does it still work?
I'm not familiar with your particular platform, but there was a time with some compilers where pointers could be different sizes depending upon the compiler options used.
If your compiler was producing (say) 64 bit pointers and the libs were using 32 bit pointers then your symptoms make sense.
Comment: I don't think Solaris linker can link 32-bit libraries against 64-bit code and vice versa.
Comment: Linux linker certainly can't.


Reverse classload order on a Java thread

Question: Is it possible to reverse the classloading path on a single Java thread where the java application is ran standalone.
Ie All other threads operate correctly and search the classpath front to back, whilst a single thread will search the classpath back to front.
Comment: Possible duplicate of [Is possible to have 2 child threads with different classpath in each one?](http://stackoverflow.com/questions/3522332/is-possible-to-have-2-child-threads-with-different-classpath-in-each-one)
Comment: What is you goal ? Why do you want to reverse the classloading path order ?
Answer: What is the actual use case? Why that thread alone needs to look up in reverse order?
You can try creating your own customer class loader to do the look up in reverse order from the class path and set that class loader as the context class loader for that thread using the thread.setContextClassLoader(..) api. Then explicitly use that context classloader to load the classes or any other resources.
But couple of caveats:
1) Generally the classloaders are parent first..Which means, when u create a custom class loader u will be setting parent class loader (generally system class loader unless u have used any other custom loaders in your application). Else u will not be able to load the java.* classes which can only be loaded by bootstrap loader, which is the root. As per rule u should delegate a class loading request to parent first and only if not found, then load yourself. So when u try parent, it will anyway look up in the original order and load the class. So for this to work, u will have to break that rule. Instead of delegating to parent first, u will have to look up in reverse in your classloader and only if not found, should delegate to parent class loader to load it
2) If parent class loader has already loaded the class, ur class loader may again load it. That means, the classes loaded in this thread will be considered as a separate instance.
Never tried this, but in theory this should work...but all practical purpose, this may not be useful for the reason mentioned in (2).
These links will be useful:link1 link2 link3
Another way is, just change your system class loader and when u load/find class, look up in whichever order you want based on the current thread name.
Both approaches are weird, but the requirement is such that :-)


Let $H$ be a normal subgroup of $G$ and $W$ an irreducible representation of $H$. Then $gW$ is irreducible.

Question: Let $H$ be a normal subgroup of $G$ and let $W_{i}$ be the irreducible representations of $H$. I want to show that for each $g \in G$, $gW_{i}$ is also an irreducible representation. It is easy to show that $gW_{i}$ is $H-$stable and thus a representation of $H$;
$$hgW_{i}=g(g^{-1}hg)W_{i}=gW_{i}$$
It is also easy to see that $W_{i}$ and $gW_{i}$ are isomorphic as vector spaces and so in particular have the same dimension.
I feel like it show be easy to see that $gW_{i}$ is also irreducible, but I just can't seem to get my head around it. A little hint would be much appreciated.
Answer: Hint: Try by contrapositive. Show that if $gW_i$ has a proper subrepresentation, then so must $W_i = g^{-1}(gW_i)$.
Comment: Thanks, that was a great idea!


How level sets associated with a quadratic expression can switch from one to two components?

Question: So I have two equations:
$$
x^2 + y^2 - z^2 = 1/2
$$
and
$$
x^2 + y^2 - z^2 = -1/2,
$$
which represent single-sheeted hyperboloid, and a two-sheeted hyperboloid, respectively. How do you explain how this different sign has this effect on the level surfaces?
Comment: I have taken the liberty to change the former title "How to explain why this equation represents what it represents?" which is uninformative into this one "How level sets associated with a quadratic expression can switch from one to two components ?"
Answer: The best way is to look at level surfaces at constant $z$.  At $z=1/2$ you get
$$x^2+y^2=3/4$$
for the first one, and
$$x^2+y^2=-1/4$$
for the second one.  The first one therefore has a circle as the level surface, while the second has no solution, which disconnects the graph.  For larger values of $z$ you do get a circle for both, but the fact that there are values of $z$ for which no solution exists makes the second graph disconnected, into 2 sheets.
Comment: Thanks, this helped me a lot!
Answer: In normal form, the constant is always positive.  So in normal form, you have \begin{align*}
x^2 + y^2 - z^2 &= 1/2 &\text{and}  \\
-x^2 + -y^2 + z^2 &= 1/2  \text{.}
\end{align*}
Then count the minus signs to see how many sheets there are.
To expose the geometry, arrange for all variable's signs to be positive.  For
$$  x^2 + y^2 = z^2 + 1/2  $$
the left-hand side is a circle and the right-hand side is a radius lower bounded by $\sqrt{1/2}$, so the upper and lower barts are joined by a "tube" of radius $/sqrt{1/2}$.  For
$$  x^2 + y^2 = z^2 - 1/2  $$
the left-hand side is a circle and the right-hand side only gives realizable radii when $|z| \geq \sqrt{1/2}$.
Answer: Indeed, a graphical explanation is very convincing. Look at the (rather fundamental) figure :

on which we see 3 "level surfaces" of function :
$$w=f(x,y,z)=x^2+y^2-z^2$$
for values $w=-1/2, 0,1/2$ representing resp. an hyperboloid with 1 sheet, a cone which is a transition surface, and an hyperboloid with 2 sheets.
In fact, level surfaces generalize level curves to dimension 3.
Answer: Note that the expression $x^2+y^2-z^2$ has rotational symmetry about the $z$-axis, which can be seen by introducing polar coordinates:

$x=r\cos t, y= r\sin t \Rightarrow r^2-z^2 = \pm\frac{1}{2}$

This means, any intersection of a plane containing the $z$-axis with $x^2+y^2-z^2 = \pm \frac{1}{2}$ produces the curve $r^2-z^2 = \pm\frac{1}{2}$ with $r\geq 0$.
Factoring shows that we have in both cases a hyperbolic curve:

$(r-z)(r+z) = \pm\frac{1}{2} \Leftrightarrow r+z = \pm\frac{1}{2(r-z)}$

Now, just check the shape of the two curves (for example plotting on an $r$-$z$-coordinate system):

$r^2-z^2 =\frac{1}{2} \Leftrightarrow z = \pm\sqrt{r^2-\frac{1}{2}} \Rightarrow$ only one branch (the seeming two branches are connected at $z =0 \Leftrightarrow r=\frac{1}{\sqrt{2}}$) $\Rightarrow$ one sheet
$r^2-z^2 =-\frac{1}{2} \Leftrightarrow z = \pm\sqrt{r^2+\frac{1}{2}} \Rightarrow$ two branches $\Rightarrow$ two sheets


Usage of captive network

Question: sorry for my english.
I want to do an app that use captive network. My idea is that when an user try to connect to a captive portal network the app will open instead od the relative web sheet.
I know that i have to use the function CNSetSupportedSSIDs(), but i don't understand how to implement it.
thanks in advance!
Comment: What did you try already? https://developer.apple.com/library/ios/documentation/SystemConfiguration/Reference/CaptiveNetworkRef/Reference/reference.html
Answer: This is the code that i have already wrote.
<code>- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    NSArray *array = [NSArray arrayWithObjects:@"SSID of my network",nil];
    bool ok = CNSetSupportedSSIDs((__bridge CFArrayRef) array);

    if(ok)
    {
        NSLog(@"completed %lu",(unsigned long)[array count]);
    }
    else
    {
        NSLog(@"failed");
    }
    // Override point for customization after application launch.
    return YES;
}
</code>

Usage of captive network


Having trouble with proofs using generated sigma algebras

Question: I've just started with an advanced course in measure theory and I'm having trouble working with $\sigma$-algebras. Here's my problem:
Let $(S,\Sigma, \mu)$ be a measure space. Call $N \subset S$ a $(\mu,\Sigma)$-null set if there exists a set $N' \in \Sigma$ with $N \subset N'$ and $\mu(N')=0$. Denote by $\mathcal{N}$ the collection of all $(\mu,\Sigma)$-null sets. Let $\Sigma^*$ be the collection of subsets $E$ of $S$ for which there exist $F,G \in \Sigma$ such that $F \subset E \subset G$ and $\mu(G\backslash F)=0$. For $E \in \Sigma^*$ and $F,G$ as above we define $\mu^*(E)=\mu(F)$.
Prove that $\Sigma^* = \sigma(\mathcal{N} \cup \Sigma)$.
I'm having trouble proving the $\subset$ inclusion. Let $E \in \Sigma^*$, then there exist $F,G\in \Sigma$ with $F \subset E \subset G$ and $\mu(G\setminus F)=0$. From here I just can't see how to show that $E$ is in the $smallest$ $\sigma$-algebra containing $\mathcal{N} \cup \Sigma$.
Any tips in how I should reason?
Answer: To show that $E$ is in the smallest $\sigma$-algebra containing $\mathcal{N} \cup \mathcal{\Sigma}$ it is enough to show that it is generated from elements of $\mathcal{N} \cup \mathcal{\Sigma}$ under the operations of countable union, countable intersection, and complementation.  You have already found some relevant elements of $\mathcal{\Sigma}$, namely $F$ and $G$.  Hint: find a null set whose union with $F$ is $E$.
Comment: My first intuition would be to take the union of $\bigcup\{N \in S: N \subset G \setminus F\}$ with F, but the problem is this left set isn't necessarily a countable union so it doesn't have to be in $\mathcal{N}$.
Comment: The definition of the class $\mathcal{N}$ of null sets gives another way to find null sets, namely as subsets of sets in $\Sigma$ with $\mu$-measure zero.  You already found the relevant set in $\Sigma$ with $\mu$-measure zero; now find the subset that you want to add to $F$.


How do I sort a date field in views without the time?

Question: Drupal 7
I have a view that sorts on three fields so the ORDER BY statement looks like:
ORDER BY
node_status ASC,
field_data_field_date_field_date_value DESC, field_data_field_sort_order_field_sort_order_value ASC
I need the sort of the date field to not be granular to the time. I just want it sorted by the date so that the sort order field will take it from there. When I run the query against the database itself, I see that the date field returned is showing the full value like: 2016-06-19 08:48:12, but some of the values are different by a second, causing the "incorrect" (not the desired) sort order.
How can I get it to sort on the date field (date field module) without the "full date" field?
EDIT:
(adding screen shot of view)
Answer: you can change the granularity of the sort under the settings for the sort criteria:
Comment: I don't see the settings to click on to get that. I added a screen shot of my view to my question. I do have it for the filter on date.
Comment: If you're using the [Date](https://www.drupal.org/project/date) Module, you can set the granularity in the Field Settings for that particular field
Comment: It is a date field with the date module and the field is defined as only collecting month, day, and year. I wish I knew why I wasn't seeing what you see for those settings.
Comment: We have now done a work-around. We have rules applied when these items are published to set the date. It was getting set with "now" and I have changed it to "today" and it is just setting the field with the midnight time.
Comment: well, if it works... you aren't seeing what I posted because you didn't specify you were using the Date Field module, the image I posted is for core Post Date Field
Answer: D7 only provides granularity for the core fields not added fields.
D8 provides granularity for the core and added fields.
I have added D7 functionality as a patch to the module views_date_format_sql. See this patch.
Views_date_format_sql can also do custom formats as well.
Note:

The D8 patch is only for core date fields so far (e.g. node updated).


Does the domain of the real logarithm need to be "extended" when dealing with even exponents in the argument?

Question: Consider $f(x)=\log(x^2)$. Clearly, the domain of $f$ is $D_f=\mathbb{R}-\{0\}$, since $x^2>0$ for any $x<0$. However, by the fundamental properties of logarithms:
$$
f(x)=\log(x^2)=2\log(x)\equiv g(x)
$$
where I abuse notation to give separate names $f$ and $g$ to two equivalent (but different in appearance) expressions. Clearly $f(x)\equiv g(x)$ but the domain of $g$ is $G_g=\{x\in\mathbb{R} : x>0\}\neq G_f$. How is this possible? What am I missing in the definition of a logarithm?
Note that this comes from a high-school exercise book on derivatives, so I don't think it should involve the definition of $\log(z)$ for $z\in\mathbb{C}$.
My take is that we define:
$$
\int\frac{1}{x}dx = \ln (|x|) + c
$$
so one must consider the argument of the logarithm as positive and/or enclosed in an absolute value operation. However, this doesn't look rigorous to me.
I have not found any similar question on this website, even though it's hard to believe no one asked it before. If I missed any useful threads, I will be happy to be redirected.
Apologies for the abuse of notation and for poor language; I am not a native English speaker and I am relatively new to mathematical concepts. Thanks in advance for your kind answers.
Comment: Since $\sqrt{x^2}=|x|$ it follows that $\log(x^2)=2\log|x|$.
The function $\log(x^2)$ is the composition of 'square(x)' and logarithm, in this order; so the domain of $\log(x^2)$ is $\mathbb{R}\setminus\{0\}$.
Comment: To answer the question, you need to state the definition of "log" to be used.  Different definitions, used in different circumstances, may yield different answers to the question.
Comment: @Antonio thank you for the clarification, it's been very helpful.
Comment: @GEdgar what other definition of logarithm can exist in $\mathbb{R}$ though?
Answer: The property $$\log(a^b)=b\log(a)$$ is only valid for $a>0$, precisely because $\log(a)$ may not even be defined.
For this reason, $f(x)=\log(x^2)$ and $g(x)=2\log(x)$ are not the same function, but they do agree on the set $\mathbb{R}^+$ (which is the domain of $g$).
Comment: Surprisingly simpler than I thought. Many thanks!
Comment: A secondary question: why do you say $f$ and $g$ as above defined are not the same function? Aren't they equivalent in every aspect? To me, it sounds like stating "$x\cdot x$" and "$x^2$" are different... What am I missing? Thanks in advance!
Comment: $f$ and $g$ don't even have the same domain, so they can't be equal (informally, you can plug values to $f$ that you cannot plug to $g$). The relation between both is that $g$ is the restriction of $f$ to $\mathbb{R}^+$.
Comment: thank you very much!


Test Match abandon Conditions?

Question: How many Overs (minimum) are required to have a result (draw or win) in a test match so that match abandon law doesn't apply?
Answer: None. In general, an abandonment is not a result which is covered by the Laws of Cricket; an abandonment can happen only if an agreement is made under Law 13.1.2 ("Number of innings") as referred to by Law 16.4:

Matches in which there is an agreement under Law 13.1.2
For any match in which there is an agreement under Law 13.1.2 (Number of innings), if the result is not determined in any of the ways stated in 16.1, 16.2 or 16.3, then the result shall be as laid down in that agreement.

The Test Match Playing Conditions do not contain any such agreement under Law 13.1.2, so an abandonment is not a possible result of a Test Match. (The ODI and T20 playing conditions do contain such an agreement, so an abandonment is possible there).
One case in which a Test Match could (in theory) result in a win without a ball being bowled would be if one side refused to take the field; the umpires would then award the match to the other side in accordance with Law 16.3.1:

a match shall be lost by a side which
[...]
in the opinion of the umpires refuses to play.  If so, the umpires shall award the match to the other side.
Comment: @EdwinThomas Yes, unless some suitable authority eventually decides to treat the match as never having happened (the laws only govern how the match proceeds, not how statisticians or contracts deal with the outcome).
Comment: so in that case if a test match with only one over bowled will be considerd to be drawn?

Test Match abandon Conditions?


How to do select from where x is equal to multiple values?

Question: I am debugging some code and have encountered the following SQL query (simplified version):
SELECT ads.*, location.county
FROM ads
LEFT JOIN location ON location.county = ads.county_id
WHERE ads.published = 1
AND ads.type = 13
AND ads.county_id = 2
OR ads.county_id = 5
OR ads.county_id = 7
OR ads.county_id = 9

I'm getting very strange results from the query and I think its because the first OR is negating the AND operators that are found before it.
This results in getting results back for ads of all types and not just for the type 13.
Each time the query is called there may be a differnt amount of county entities that need to be looked up.
Any help on the correct way to go about this would be appreciated.
Answer: Put parentheses around the "OR"s:
SELECT ads.*, location.county
FROM ads
LEFT JOIN location ON location.county = ads.county_id
WHERE ads.published = 1
AND ads.type = 13
AND
(
    ads.county_id = 2
    OR ads.county_id = 5
    OR ads.county_id = 7
    OR ads.county_id = 9
)

Or even better, use IN:
SELECT ads.*, location.county
FROM ads
LEFT JOIN location ON location.county = ads.county_id
WHERE ads.published = 1
AND ads.type = 13
AND ads.county_id IN (2, 5, 7, 9)

Comment: I think the IN version is easier to read and less likely to return unexpected results.
Comment: it's also ***substantially*** faster, at least on MySQL
Comment: In my case the values in the `IN` are coming from the result of another select query, how do I handle that?
Comment: what about "not equal to" for multiple properties separated by OR operator?
Answer: You can try using parentheses around the OR expressions to make sure your query is interpreted correctly, or more concisely, use IN:
SELECT ads.*, location.county
FROM ads
LEFT JOIN location ON location.county = ads.county_id
WHERE ads.published = 1
AND ads.type = 13
AND ads.county_id IN (2,5,7,9)

Answer: And even simpler using IN:
SELECT ads.*, location.county
  FROM ads
  LEFT JOIN location ON location.county = ads.county_id
  WHERE ads.published = 1
        AND ads.type = 13
        AND ads.county_id IN (2,5,7,9)


Is $a^n b^n$ context free even if we take strings instead of characters?

Question: Let a and b be 2 strings . Does the set {$a^nb^n$ , $n\geq0$} still form a context free language?
Intuitively, I feel that should be the case since in this case I'm just storing strings instead of characters in my stack for the Pushdown automata but I am not able to prove anything. Any help would be appreciated !
Comment: As stated in @HallaSurvivor 's answer, the closure under homomorphisms confirms your feeling. In the other direction, the language can even become simpler. If, for example, a=01 and b=0101, then the language is regular: $(010101)^+$. More general: the language is regular if a and b have the same primitive root.
Answer: Yes.
As a hint, recall the homomorphic image of a context free language is context free.
Can you see why your language is a homomorphic image of the context free language
$\{ x^ny^n \} \subseteq \{x,y\}^*$?

I hope this helps ^_^


Matrix Factorization and Overfitting

Question: I recently came accross the algorithm of Matrix Factorization for a recommendations system.
One of the tutorials I followed can be found  here.
According to it given the initial matrix $R$ and the goal to factor it into two matrices $P$ and $Q$ with $k$ latent features the error for each known entry is calculated using the following formula in order to avoid overfitting :
$$e_{ij}^2 = (r_{ij} - \sum_{k=1}^K{p_{ik}q_{kj}})^2 + \frac{\beta}{2} \sum_{k=1}^K{(||P||^2 + ||Q||^2)}$$
What I don't understand is :

Why add the $\frac{\beta}{2} \sum_{k=1}^K{(||P||^2 + ||Q||^2)}$ part to the squared error? It seems a bit arbitrary

How does it prevent overfitting?
Comment: The basic idea is that constraining the solution to have smaller magnitude weights gives us a dial that we can turn up or down control the extent of any overfitting. See: https://stats.stackexchange.com/questions/188092/why-do-smaller-weights-result-in-simpler-models-in-regularization
Answer: The idea prevalent in recommender systems is to find a low rank approximation of your matrix. The matrix factorization you describe gives rise to a low-rank approximation (at least when $k$ is relatively little of course...) . From this paper (and references therein) you can learn of the different steps leading to this $||P||^2 + ||Q||^2$ regularization. It comes as an equivalent form of the nuclear norm, which is a convex surrogate of the rank (in fact its convex envelope on bounded matrices). To help you further, you can note this other reference, which gives a proof (Lemma 1)

Matrix Factorization and Overfitting


Prove tower property of conditional expectation $\mathbb{E}[\mathbb{E}[X|Y,W]| Y = y] = \mathbb{E}[X|Y = y]$

Question: I am using Sheldon Ross 9th edition as a reference and all I am given is the definition of conditional expectation:
$$E[X|Y = y] = \sum\limits_x x \Pr[X = x| Y = y]$$
I am required to prove the tower property of conditional expectation:
$$\mathbb{E}[\mathbb{E}[X|Y,W]| Y = y] = \mathbb{E}[X|Y = y]$$
I am very lost and need assistance. First, we recognize that $\mathbb{E}[X|Y,W]$ is a random variable that is a function of $Y,W$
We first write:
$$\mathbb{E}[X|Y=y,W=w] =  \sum\limits_x x \Pr[X = x| Y = y,W = w],$$
then,
\begin{align*}\mathbb{E}[\mathbb{E}[X|Y,W]| Y = y] &= \mathbb{E}[\sum\limits_x x \Pr[X = x| Y = y,W = w]|Y = y]\\ &= \sum\limits_y \sum\limits_w \sum\limits_x x \Pr[X = x| Y = y,W = w] yw\Pr[Y = y,W = w|Y = y]\\ & = \sum\limits_y \sum\limits_w \sum\limits_x x \Pr[X = x| Y = y,W = w] yw\frac{\Pr[Y = y,W = w]}{\Pr[Y=y]} \\ &= \sum\limits_y \sum\limits_w \sum\limits_x x  yw\frac{\Pr[X = x,Y=y,W=w]}{\Pr[Y=y]} \end{align*}
The problem is at this stem, all I get is: $\dfrac{1}{\Pr[Y=y]}$.
I strongly suspect:
\begin{align*}\mathbb{E}[\mathbb{E}[X|Y,W]| Y = y] = \sum\limits_y \sum\limits_w \sum\limits_x x \Pr[X = x| Y = y,W = w] yw\Pr[Y = y,W = w|Y = y] \end{align*} is incorrect. But it makes intuitive sense to me. We are taking the expectation of two jointly defined random variables $Y,W$, so the probability is $\Pr[Y = y,W = w|Y = y]$.
Can someone please point me to the right direction?
Comment: In the first equation after "then", what you are writing in the RHS is not $$\mathbb{E}[\mathbb{E}[X|Y,W]| Y = y]$$ but $$\mathbb{E}[\mathbb{E}[X|Y=y,W=w]| Y = y]=\mathbb{E}[X|Y=y,W=w]$$ Recall that each $$\mathbb{E}[X|Y=y,W=w]$$ is simply a *number*, not a random variable.
Comment: Perhaps more at the heart of your problem, you seem to have a definition of $E(X\mid Y=y)$ and $E(X\mid Y=y,W=w)$ at your disposal, but not of $E(X\mid Y,W)$. Is that so?
Answer: I've adapted the following definition of $\mathbb E [X \vert W, Y]$ from the discussion in Probability with Martingales by Williams, section 9.6.
Define the function $g$ by
$$g (w,y) = \mathbb E[X \vert W = w, Y = y]. $$
We define $\mathbb E [X \vert W,Y]$ to be the random variable $g(W,Y)$. Note this is different from the expectation of $X$ conditional on the event $\{W=W, Y=Y\}$, which is clearly the unconditional expectation of $X$.
We can thus make the following calculation:
\begin{align*}
\mathbb E [ \mathbb E [X \vert W,Y] \vert Y= y ] &= \mathbb E [g(W,Y) \vert Y = y] \\
&= \sum_{w,y^\prime} g\left(w,y^\prime \right) \Pr \left[\left.W = w, Y = y^\prime \right\vert Y = y\right] \\
&= \sum_w g(w,y) \Pr [W = w \vert Y = y] \\
&= \sum_w \mathbb E [X \vert W=w,Y=y] \Pr [W = w \vert Y = y] \\
&= \sum_w \left[ \sum_x x \Pr [X=x \vert W=w,Y=y] \right]\Pr [W = w \vert Y = y] \\
&= \sum_{w,x} x \Pr[X=x, W=w \vert Y = y] \\
&= \sum_x x \Pr[X = x \vert Y = y] \\
&= \mathbb E[X \vert Y=y]
\end{align*}
The third equality follows from the fact that $\Pr \left[\left.W = w, Y = y^\prime \right\vert Y = y\right]$ is $\Pr[W = w \vert Y= y]$ for $y^\prime = y$ and $0$ otherwise. The sixth equality comes from Bayes' rule. The rest should follow from definitions.
Comment: Why the first identity? This seems to identify $$\mathbb E [X \vert W,Y]$$ with $$  \sum_x x \Pr [X=x \vert W, Y=y ]$$ which is wrong. If this is appealing to another property of conditional expectation, it seems mandatory to explain this property.
Comment: @Did thanks for the comment. I've edited my answer. Is that better, or does it need more detail?
Comment: Actually, my second comment on main seems to apply here as well: do you have a *definition* of $E(X\mid Y,W)$ at hand?
Comment: @Did Yes. It is the random variable $Z$ (measurable wrt $\sigma(W,Y)$) that satisfies $E \left[ \mathbb I_A Z \right] = E\left[ \mathbb I_A X \right]$ for every $A \in \sigma(W,Y)$. Employing this particular definition does not seem helpful here, at least in terms of answering the OP. Do you have a more useful suggestion?
Comment: Sorry but how can one solve this question without relying on a definition of $E(X\mid Y,W)$? If you are using another definition, once again, please provide it. To sum up, my suggestion would be to start from a definition of $E(X\mid Y,W)$ to solve the exercise (preferably the one in your comment or an equivalent form), rather than shoehorning without justification an identity basically equivalent to the conclusion in an early step of the proof.
Comment: @Did yes, of course one needs a definition for $E[X \mid W,Y]$. I did not claim that one was unnecessary or useless. To clarify, I was asking if you had an alternative definition that might be more suited for the simpler discrete setting than the one in my previous comment.
Comment: I doubt there is one.
Comment: @Did I've tried to work with a simpler definition for this setting, as edited above. I'd be interested to hear your thoughts on it.
Comment: The new version is sound. Bravo! (I corrected a small typo.)


if else statement with two condition

Question: This maybe trivial but I have this code
if(condition 1 & condition 2){
// apply some code
}
else{
// apply other code
}

my question is: When is else applied?
Is it applied when both conditions are false or is it enough for one condition to be false?
Comment: This is absolutely trivial to try yourself (or just look up the documentation...).
Answer: First off, you are using bitwise and which I don't think does what you want.
In order to use logical and (&&) change if(condition 1 & condition 2){ to if(condition 1 && condition 2){.
Secondly, if one condition is false then the else will evaluate.
When using && in if statements the if logic evaluates if and only if both sides of the && evaluate to true.
if evaluates when:
true && true

else evaluates when:
false && true
true && false
false && false

Comment: In java `&` will work any place that `&&` works (as `boolean & boolean -> boolean`), given the difference that it will eagerly evaluate both expressions. That is, *`&` is only bitwise when applied to an integral type* such a long or int: `integraltype & integraltype -> widendedintegraltype`.
Comment: Thanks, I didn't know that. I think it's still a relevant point considering OP did just put `condition 1` and `condition 2` without indicating the variable type. It may work in this case, and it may not. If the OP is new enough to programming to be working on figuring out if statements though, it's safe to say that there may be some difficulty figuring out why `&` is behaving oddly.
Comment: @user2864740 Sorry, didn't understand correctly. So if `condition1` is `false`, with `&&` will go to `else` here? and `&` will check both unconditionally? If this the case, in which scenarios do an `&` is useful to use if you know that will be false even if I evaluate `condition2`?
Comment: That is correct: `&` forces both expressions to be evaluated (as there is *no* 'short-circuit' behavior). However the result (barring side-effects of the second expression) are the same; in some cases this is desirable but it usually is not which is why `&&` should be preferred - the short-circuiting logical-AND `&&` form also allows chained checks like `x != null && x.y == z` . (A side-effect in a condition, which may warrant a 'clever' `&`, usually indicates a design that can be improved.)
Comment: "..However the result (barring side-effects *and dependencies* of the second expression) are the same.."
Answer: You will need a little logic here. Check the Truth table here: https://en.wikipedia.org/wiki/Truth_table
if(condition 1 && condition 2){ will enter the else if the condition of the if (condition 1 && condition 2) is false. So the condition is false if:

condition 1 is false
OR
condition 2 is false

In that case, it's the else block that will be executed.
Also, check the difference between bitwise operators since && and & are not the same thing.

if else statement with two condition


Comparing predictors in a logistic regression with different degrees of freedom

Question: I have a logistic regression for which different predictors have different degrees of freedom (for example, a categorical variable with 10 categories and a continuous variable).
I would like to compare the different predictors in terms of their "predicting power". I computed and compared their corresponding deviance (using anova function in R). Is their a way to account for the  different degrees of freedom of each predictor? Should I divide the explained deviance by the number of degrees of freedom?
Answer: There are two approaches that I like.  One is to use AIC (in R type AIC(fit1); AIC(fit2)) which is roughly described as a method to tell you which of the two models is more likely to cross-validate with better log-likelihood.  This penalizes the $\chi^2$ of a model by twice the number of degrees of freedom (parameters) needed to achieve the likelihood ratio $\chi^2$.  Secondly, I often use the Wald or likelihood ratio $\chi^2$ statistic for a variable minus the degrees of freedom for that test.  This is a "chance correction", as the expected value of the $\chi^{2}_{p}$ statistic is $p$ under the null hypothesis that the $p$ coefficients are all zero.  When you use the R rms package and run plot(anova(fit)) you get $\chi^{2} - p$ by default, using Wald statistics.