Q:

iShidden always returning YES

using following code
-(IBAction)shareMenuBtnPressed:(id)sender
{
    [self.mainMenuView setHidden:YES];
    [self.tryOnView setHidden:YES];
    [self.d3View setHidden:YES];

    if ([self.shareView isHidden] == YES)
        [shareView setHidden:NO];
    else
        [self.shareView setHidden:YES];
}

on first Click it shows the menu i-e         [shareView setHidden:NO];
but if i click again it again runs the same seq. why is isHidden not changing to NO
EDIT: Ok it seems that i have placed this code
UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(hideAllViews)];
    //tap.cancelsTouchesInView = NO;
    [self.view addGestureRecognizer:tap];

with tap.cancelsTouchesinView it bevhaves strangely and [shareView setHidden:NO] gets called always. atm i have put commments but I can't remove tap.cancelsTouchesinView. what should be done?

A:

no need to write below code...
  if ([self.shareView isHidden] == YES)
    [shareView setHidden:NO];
else
    [self.shareView setHidden:YES];

instead write below code...
self.shareView.hidden = !self.shareView.hidden;

i think it will help you a lot...
Let me know it is working or not my friend!!!!!
Happy Coding....


Q:

How to install Oracle Express 11gR2?

I need a Step By Step guide for Installing Oracle Database Express Edition version 11g Release R2 on Ubuntu Desktop 12.04.1 LTS 64 bit Edition

A:

Uber ultimate guide to installing of Oracle 11g XE on modern Debian like distro you can find at (VERY HUGE with high amount of workarounds, that is why I can't paste article here):

https://forums.oracle.com/forums/thread.jspa?threadID=2301639

Another valuable sources (hey! these are not links from top 20 web search! I spend 3 evening on reading these blogs, they are really good, but mostly duplicate above forums.oracle.com link):

http://www.makina-corpus.org/blog/howto-install-oracle-11g-ubuntu-linux-1204-precise-pangolin-64bits
http://meandmyubuntulinux.blogspot.com/2012/05/installing-oracle-11g-r2-express.html
http://meandmyubuntulinux.blogspot.com/2012/06/trouble-shooting-oracle-11g.html
http://mikesmithers.wordpress.com/2011/11/26/installing-oracle-11gxe-on-mint-and-ubuntu/
http://www.len.ro/work/oracle-11g-release-2-xe-on-ubuntu-12-04/
http://mikesmithers.wordpress.com/2012/09/25/ora-00845-memory_target-error-installing-oracle-xe-on-mint-and-ubuntu/
http://blog.oracle48.nl/oracle-11g-amm-memory_target-memory_max_target-and-dev_shm/
http://d.hatena.ne.jp/t2y-1979/20111017/1318858143
http://sysadminnotebook.blogspot.com/2012/10/installing-oracle-11g-r2-express.html

One thing that kill a lot of my time is ORA-00845: MEMORY_TARGET not supported on this system error which I fixed by d.hatena.ne.jp blog tips:

$ sudo vi /u01/app/oracle/product/11.2.0/xe/config/scripts/init.ora
$ sudo vi /u01/app/oracle/product/11.2.0/xe/config/scripts/initXETemp.ora

#memory_target=418381824
pga_aggregate_target=200540160
sga_target=601620480

Another error that I fix and that doesn't mentioned by above links is:

  System parameter file is /u01/app/oracle/product/11.2.0/xe/network/admin/listener.ora
  Log messages written to /u01/app/oracle/diag/tnslsnr/desktop/listener/alert/log.xml
  Error listening on: (DESCRIPTION=(ADDRESS=(PROTOCOL=IPC)(KEY=EXTPROC_FOR_XE)))
  TNS-12555: TNS:permission denied
   TNS-12560: TNS:protocol adapter error
    TNS-00525: Insufficient privilege for operation
     Linux Error: 1: Operation not permitted

  Listener failed to start. See the error message(s) above...

when start listener by:

  /bin/su -s /bin/bash oracle -c '/u01/app/oracle/product/11.2.0/xe/bin/lsnrctl  start'

I fix it by commenting line:

#      (ADDRESS = (PROTOCOL = IPC)(KEY = EXTPROC_FOR_XE))

in /u01/app/oracle/product/11.2.0/xe/network/admin/listener.ora.
Next I read Getting Started to unlock HR test user which automatically created during installation of Oracle 11g XE...
Rest of the docs can be found at Database Express Edition Documentation

A:

I used this guide to install it on Ubuntu Server 12.04 and it worked perfectly.
http://meandmyubuntulinux.blogspot.ca/2012/05/installing-oracle-11g-r2-express.html


Q:

I have questions coming out the yin-yang about yin-yang phrases!

Yin Yang is the Chinese philosophy of Light and Shadow, often signifying the need for balance or that everything exists in balance.
But the (reasonably enjoyable to use) phrase

Up the Ying Yang

or

Out the Ying Yang

Doesn’t really make sense in this context (and it seems the spelling in the phrase has changed too) as it means to do something in the extreme, or to have a profusion of something. It sounds like it should be referring to a long river that someone has to travel up, connoting an extreme of something.
I can’t find an online etymology of this even after Googling and looking on Wiktionary amongst other online dictionaries, only a few ‘discussion’ here and poor explanation here.
Where did this phrase come from? Am I using it right?

A:

Um, your yin(g)-yang is a minced oath for one or another excretory orifice. So yes, you are using it “right”, although I would myself set it in lowercase, and possibly hyphenate it or fuse into a single word: ying-yang, yingyang.
It is similar to — really, equivalent to — up the wazoo, or any number of similar “nonsense” terms for the unmentionable parts. The somewhat reduplicative yingyang also gets used for the same thing that other reduplicatives like dingdong, dingaling, dongalong, pangwang, willydilly, wangerdanger, wangadoodle, and hoohoodilly all also do, and is similar in construction.  (Ramalamadingdong may or may not be related.)  Sometimes those have hyphens, and sometimes they don’t.
Here is one reasonably citable reference:

Take a term rendered in a foreign language, let’s say “yin and yang.” Have people start mispronouncing (and misspelling) it as “ying and yang,” bring in a slang term for what polite people call the buttocks—“she’s got talent out the ying-yang,” add a rap group called the Ying-Yang Twins, and pretty soon more people will think that “ying” is correct.
[...]
Not so “wazoo,” another reference to one’s posterior. As with “ying-yang,” the phrase “out the wazoo” means an abundance. One can also claim that something is a “pain in the wazoo,” and even people who don’t know what a “wazoo” is will understand.
Here, the venerable Oxford English Dictionary weighs in. While it professes not to know the origin of “wazoo”, it says that others suspect it may come from the French oiseau, or bird, through a Louisiana Creole term, “razoo”, for raspberry. (Those with particularly fertile dirty minds may be able to make the connection.) It’s almost exclusively American.

These are North American slang terms, which is probably why they seem “foreign” to you if you are in the UK.


Q:

How to have emacs-helm list offer files in fixed directories as options?

This is related to this question:
how-to-have-emacs-helm-list-offer-files-in-current-directory-as-options
but rather than add files from the current directory, I'd like to be able to have a fixed list of directories that helm-mini would always offer the files from. Ideally, I would like to be able to just have the files with a particular extension, and I'd like this to be done recursively (only one layer deep, in fact).

A:

Here is a slightly different take that prefilters for the org extension.
(require 'helm-cmd-t)

(defvar my-org-folders (list  "~/org")
  "my permanent folders for helm-mini")

(defun helm-my-org (&optional arg)
  "Use C-u arg to work with repos."
  (interactive "P")
  (if (consp arg)
      (call-interactively 'helm-cmd-t-repos)
    (let ((helm-ff-transformer-show-only-basename nil))
      (helm :sources (mapcar (lambda (dir)
                               (helm-cmd-t-get-create-source-dir dir))
                             my-org-folders)
            :candidate-number-limit 20
            :buffer "*helm-my-org:*"
            :input "org$ "))))

A:

Here you go.  I am using this code to list all org files in a particular directory.   If you want to list all the files, just remove the candidate-transformer line in the source, and remove the emagician/helm-ct-is-org-file.
You'll likely want to rename the source/variable/function too. ;)
edit: Fixed, thanks to peeking at helm-cmd-t
note: This is my first real crack at making a helm source, and this implementation likely sucks. It also specifically solves my problem (finding all org files in one directly only) rather then the more generalized problem  (building a helm source based on files from a particular directory).
(defvar emagician/helm-c-source-files
  `((name  . "Find Emagician Files")
    (header-name . (lambda (_)))
    (candidates . ,(lambda ()
                    (when (file-accessible-directory-p emagician-dir)
                      (directory-files emagician-dir t))))
    (match helm-c-match-on-file-name helm-c-match-on-directory-name)
    (keymap . ,helm-generic-files-map)
    (candidate-transformer . emagician/helm-ct-is-org-file)
    (help-message . helm-generic-file-help-message)
    (mode-line . ,helm-generic-file-mode-line-string)
    (type . file)))

(defun emagician/helm-ct-is-org-file (candidates)
  (remove-if-not (lambda (c)
                   (and (string= (substring c -4) ".org")
                        (not (string= (substring (file-name-nondirectory c) 0 2) ".#"))))
                 candidates))

(defun emagician/helm-emagician-dir ()
  "List all the org files in the Emagician dir"
  (interactive)
  (helm :sources emagician/helm-c-source-files
        :candidate-number-limit 40
        :buffer "*emagician-|-+-|-files*"))

(global-set-key (kbd "S-<f3>") 'emagician/helm-emagician-dir)


Q:

Difference between two dates in days

Why do I get the following outcomes?
today        = 2014-01-06
selected_day = 2014-01-06

Outcome is 0
today        = 2014-01-06
selected_day = 2014-01-07

Outcome is 0
today        = 2014-01-06
selected_day = 2014-01-08

Outcome is 1
DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
Date d1 = df.parse(today);
Date d2 = df.parse(selected_date);
Calendar c1 = Calendar.getInstance();
c1.setTime(d1);
Calendar c2 = Calendar.getInstance();
c2.setTime(d2);
long diff = c1.getTimeInMillis() - c2.getTimeInMillis();
System.out.println(diff / (24 * 60 * 60 * 1000));

A:

Because you are setting both dates to the same calendar instance
Calendar c2 = Calendar.getInstance();
c1.setTime(d2); // this is wrong :)

change the second c1 to c2 ;)


Q:

Combining lists and lists in dictionary

I have a dictionary where each value is a list of variables (all variables are floats):
d = {1:[a,b,c], 2:[d,e,f], 3:[g,h,i]}
and a list with the same number of elements as there are elements in the combined lists of the dictionary:
L = [1,2,3,4,5,6,7,8,9]
I want to combine the list into the dictionary, such that:
d = {1:[a+1,b+2,c+3], 2:[d+4,e+5,f+6], 3:[g+7,h+8,i+9]}
What is a good way to do this?

A:

Here is a way to do it.
As your question was unclear about what a, b and so on were supposed to be when you first asked your question, I used strings for simplicity. It would work all the same with floats.
d = {1:['a', 'b', 'c'], 2:['d', 'e', 'f'], 3:['g', 'h', 'i']}

L = ['1', '2', '3', '4', '5', '6', '7', '8', '9']

L_iter = iter(L)

new_d = {key: [val + next(L_iter) for val in sublist] for key, sublist in d.items()}

print(new_d)
# {1: ['a1', 'b2', 'c3'], 2: ['d4', 'e5', 'f6'], 3: ['g7', 'h8', 'i9']}

We create the new dict with a dict comprehension. Inside it, we create the new sublist with a list comprehension, iterating on L with the help of the iterator L_iter, which allows to get the next item of L each time.


Q:

Notion of Torsors

I am trying to read this paper by Lawrence Breen.
It starts with the definition of a torsor.

Let $G$ be a bundle of groups on a space $X$. The following definition of a principal space is standard, but note the occurrence of structural bundle of groups,rather than simple a constant one. We are in effect giving ourselves a family of groups $G_x$, parametrised by points $x\in X$, acting principally on the corresponding fibers $P_x$ of $P$.
Definition: A left principal $G$-bundle (or left $G$-torsor) on a topological space $X$ is a space $\pi:P\rightarrow X$ above $X$, together with a left group action $G\times_XP\rightarrow P$ such that the induced morphism $G\times_XP\rightarrow P\times_XP$ given by $(g,p)\mapsto (gp,p)$ is an isomorphism. We require in addition that there exists a family of local sections $s_i:U_i\rightarrow P$, for some open cover $\{U_i\}$ of $U$. The groupoid of left $G$-torsors on $X$ will be denoted by $Tors(X,G)$.

I do not understand: what does it mean to say a bundle of groups on a space? Does it mean that $G$ as a set is a disjoint union of groups indexed by elements of $X$?
I do not understand anything that is said in the first paragraph.
I do not understand the necessity of defining (considering) action of $G$ on $P$ as map $G\times_XP\rightarrow P$  and not just some continuous map $G\times P \rightarrow  P$.
I realise reading some other (equivalent) definition of torsors that they are just generalisations of principal $G$-bundles for some group $G$. Given a principal $G$-bundle $\pi:P\rightarrow M$ there is an open cover $\{U_i\}$ of $M$ and collection of local trivialisations $\phi_i:\pi^{-1}(U_i)\rightarrow U_i\times G$. This would give sections $s_i:U_i\rightarrow P$ given by $x\mapsto \phi_i^{-1}(x,e)$. I am guessing this is generalised to existence of sections in the definition of torsors (correct me if I am wrong).
Suppose we have a Lie group $G$ that acts on a manifold $M$. Then, we have a quotient space $M/G$ which does not have a smooth manifold structure in general. Then, we impose (with other mild conditions) that $G$ acts properly on $M$ i.e, the map $G\times M\rightarrow M\times M$ given by $(g,m)\mapsto (gm,m)$ is a proper map. Which will then confirm that the quotient space is a manifold and the obvious map $M/G\rightarrow M$ is a first example of a principal bundle.
In the definition of torsors they are asking for a similar map to be an isomorphism. I am guessing the above paragraph is the motivation for asking for such a condition to hold (correct me if I am wrong).
My question is: is  my understanding (as of now) of torsors correct? Is there anything else that I am missing? What are they really other than being a generalization of principal bundles?
On a lighter note, why can't authors specify everything clearly? Or Is this how one usually write a paper?
Edit :  I saw just now that he does say what he mean by bundle of groups.

Since the concepts discussed here are very general, we have at times not made explicit the mathematical objects to which they apply. For example, when we refer to “a space” this might mean a topological space, but also “a scheme” when one prefers to work in algebro-geometric context, or even “a sheaf” and we place ourselves implicitly in the category of such spaces, schemes, or shaves. Similarly, the standard notion of an $X$-group scheme $G$ will correspond in a topological context to that of a bundle of groups on a a space $X$. By this we mean a total space $G$ above space $X$ that is a group in the cartesian monoidal category of spades over $X$. In particular, the fibers $G_x$ of $G$ at points $x\in X$ are topological groups, whose group laws vary continuously with $x$.

A:

I do not understand what does it mean to say bundle of groups on a space? Does it mean that G as a set is disjoint union on groups indexed bybelements of X?

Presumably there's also a condition that the groups "vary continuously" in some sense, just like a vector bundle isn't any disjoint union of arbitrary vector spaces indexed by elements of a space.
The paper seems to give an example in example 1.3.

I do not understand the necessity of defining(considering) action of G on P  as map $G \times_X P \to P$

Well as you noted before G is a disjoint union of groups, so it's not going to be a group itself and therefore can't act on things.  Instead, you want individual actions of $G_x$ on $P_x$ which "vary continuously" in some sense, and that's what a fiber product gives you.

For general background on torsors, John Baez has a nice writeup in This Week's Finds which you can find with Google.  (I'm writing on mobile.)


Q:

Get the URL of the previous page even after history.back() event

Is there a way I can get the URL of the last page the user has been? document.referrer isn't what I want, because it only gets the referrer and it won't work if, for instance, the user clicks the back button.
I suspect this isn't possible, since you can't even get the URL of the forward page in the history.

A:

As indicated by @ctwheels, this seems to solve my problem: http://w3schools.invisionzone.com/index.php?showtopic=31256&p=169916
Quoting from the page:

get the url of just the last previous page? of your domain only, or
  all previous pages? of yours and external domains?
if you require last previous page, of your domain only, would storing
  url in javascript cookie work?
one cookie to store previous url, and another to store current, then
  next page, the current would become the previous.

EDIT: @DontVoteMeDown recommended to use localStorage instead of cookies.


Q:

Programmatically insert page break in vb.net

So I am trying to force a page break while printing directly from my VB.NET program. I am basically using this code from MSDN to print my document:
Private Sub printDocument1_PrintPage(ByVal sender As Object, _
    ByVal e As PrintPageEventArgs)

    Dim charactersOnPage As Integer = 0
    Dim linesPerPage As Integer = 0

    ' Sets the value of charactersOnPage to the number of characters
    ' of stringToPrint that will fit within the bounds of the page.
    e.Graphics.MeasureString(stringToPrint, Me.Font, e.MarginBounds.Size, _
        StringFormat.GenericTypographic, charactersOnPage, linesPerPage)

    ' Draws the string within the bounds of the page
    e.Graphics.DrawString(stringToPrint, Me.Font, Brushes.Black, _
    e.MarginBounds, StringFormat.GenericTypographic)

   ' Remove the portion of the string that has been printed.
    stringToPrint = stringToPrint.Substring(charactersOnPage)

    ' Check to see if more pages are to be printed.
    e.HasMorePages = stringToPrint.Length > 0

End Sub

This allows it to print fine, but I would like to put page breaks in specific spots. I've tried e.HasMorePages = true, but I don't understand how this allows me to break at specific locations. Say my stringToPrint is 5000 characters long, and I want to start a new page after 1000 characters, and then again after the next 2500 characters. How would I do this?
Also, changing linesOnPage and charactersOnPage to other values doesn't seem to change anything at all.
EDIT: I guess a little more info about what my program does will help. Basically what it's doing is the program will create about 4 full pages of data, and prints it to a .txt file. Now, I want to print the entire .txt file. The only way that I know how to do this is by printing a string, so I have it read the entire .txt file line by line and stores it all as one string (namely stringToPrint). Now, using the code above, I print stringToPrint.

A:

Your current code is based on printing to a rectangle: e.MarginBounds
For testing, I used this code:
Private pageNum As Integer

Private Sub Button1_Click(ByVal sender As Object, ByVal e As EventArgs) _
                          Handles Button1.Click
  Dim sb As New StringBuilder
  For i As Integer = 1 To 100
    sb.AppendLine(i.ToString & ") This is a line.")
  Next
  stringToPrint = sb.ToString

  pageNum = 0
  Using pvw As New PrintPreviewDialog()
    pvw.Document = printDocument1
    pvw.ShowDialog()
  End Using
End Sub

Then I changed your routine to use a smaller rectangle on the first page:
Private Sub printDocument1_PrintPage(ByVal sender As Object, _
                                     ByVal e As PrintPageEventArgs) _
                                     Handles printDocument1.PrintPage
  Dim charactersOnPage As Integer = 0
  Dim linesPerPage As Integer = 0

  pageNum += 1

  Dim printSize As Size = e.MarginBounds.Size
  If pageNum = 1 Then
    printSize = New Size(printSize.Width, printSize.Height / 2)
  End If
  e.Graphics.MeasureString(stringToPrint, Me.Font, printSize, _
      StringFormat.GenericTypographic, charactersOnPage, linesPerPage)

  ' Draws the string within the bounds of the page
  e.Graphics.DrawString(stringToPrint, Me.Font, Brushes.Black, _
    New Rectangle(e.MarginBounds.Location, printSize), _
    StringFormat.GenericTypographic)

  ' Remove the portion of the string that has been printed.
  stringToPrint = stringToPrint.Substring(charactersOnPage)

  ' Check to see if more pages are to be printed.
  e.HasMorePages = stringToPrint.Length > 0
End Sub

If you need to control the printing based on characters, you would have to ditch the code that prints the block of text and print everything on a line by line basis.


Q:

VB working with SQL DB - end of row count, keeps looping

I'm adding to a combo box an ID and a name that I'm pulling from a database. My problem is that for some reason my loop doesn't end once it reaches the end of the records in the database table. Here's my code:
    For intcount = 0 To dtOrders.Rows.Count - 1
        cmbSearch.Items.Add(dtOrders.Rows(intcount)("EmployeeID").ToString & " " &
           dtOrders.Rows(intcount)("EmployeeLastName").ToString & ", " &
           dtOrders.Rows(intcount)("EmployeeFirstName").ToString)
    Next

Shouldn't the .rows.count - 1 stop it once it reaches the last record? It loops 4 times through.

A:

Are you sure you're not getting back four times as many rows as you expect in dtOrders?
I'm guessing, from the name "dtOrders", that you're using a query that joins together customer and order information and therefore you will get the customer represented once for each order.


Q:

Returning a value early from a recursive function

I have a tree of nodes. While iterating this tree depth first, I need to return the list of all duplicate nodes from the root node to my current node.
Due to some business requirements the "already traversed" part of the tree is never the same. I do a lot of swap/replaces of branches in the already traversed part of the tree. So maintaining a list of traversed nodes might not work as it needs updates every time I finish traversing a node.
So whenever I need to answer getDuplicateNodesOfMyCurrentNode() I need to start from the top of the tree (rootNode) and search depth-first till my currentNode and return back a list<Nodes> that are duplicates of my currentNode.
private void getDuplicateNodesOfMyCurrentNode(Node parentNode, Node currentNode,List<Node> dupNodes){
  for(Node child: parentNode.getChildren()){
        if(child == currentNode){
            return;
        }
        if(child.getApp().equals(currentNode.getApp()){
            dupNodes.add(child);
        }
        getDuplicateNodesOfMyCurrentNode( child, currentNode, aDupNodes);

}
As you guys already know the issue with this code, return doesn't return back the control to the caller of this API since it recursively calls itself.
I want some way to exit out of this recursive loop once I get to my currentNode.
I probably can achieve this by maintaining some boolean state, but want to know the better way of solving this.

A:

Pass whether or not to abort your recursion back through the call stack via a boolean and abandon the current for loop if necessary at the point of the recursive call (also acknowledging Norbet van Nobelen's comment above that alludes to something similar):
private boolean getDuplicateNodesOfMyCurrentNode(Node parentNode, Node currentNode,List<Node> dupNodes){
    for(Node child: parentNode.getChildren()){
        if(child == currentNode){
            return false;
        }
        if(child.getApp().equals(currentNode.getApp()){
            dupNodes.add(child);
        }
        if (getDuplicateNodesOfMyCurrentNode( builtOn, currentNode, aDupNodes) == false){
            return false;
        }
    }
    return true;
}


Q:

Weighted Variance and Weighted Standard Deviation in C++

Hi I'm trying to calculate the weighted variance and weighted standard deviation of a series of ints or floats.  I found these links:
http://math.tutorvista.com/statistics/standard-deviation.html#weighted-standard-deviation
http://www.itl.nist.gov/div898/software/dataplot/refman2/ch2/weightsd.pdf (warning pdf)
Here are my template functions so far.  Variance and standard deviation work fine but for the life of me I can't get the weighted versions to match the test case at the bottom of the pdf:
template <class T>
inline float    Mean( T samples[], int count )
{
    float   mean = 0.0f;

    if( count >= 1 )
    {
        for( int i = 0; i < count; i++ )
            mean += samples[i];

        mean /= (float) count;
    }

    return mean;
}

template <class T>
inline float    Variance( T samples[], int count )
{
    float   variance = 0.0f;

    if( count > 1 )
    {
        float   mean = 0.0f;

        for( int i = 0; i < count; i++ )
            mean += samples[i];

        mean /= (float) count;

        for( int i = 0; i < count; i++ )
        {
            float   sum = (float) samples[i] - mean;

            variance += sum*sum;
        }

        variance /= (float) count - 1.0f;
    }

    return variance;
}

template <class T>
inline float    StdDev( T samples[], int count )
{
    return sqrtf( Variance( samples, count ) );
}

template <class T>
inline float    VarianceWeighted( T samples[], T weights[], int count )
{
    float   varianceWeighted = 0.0f;

    if( count > 1 )
    {
        float   sumWeights = 0.0f, meanWeighted = 0.0f;
        int     numNonzero = 0;

        for( int i = 0; i < count; i++ )
        {
            meanWeighted += samples[i]*weights[i];
            sumWeights += weights[i];

            if( ((float) weights[i]) != 0.0f ) numNonzero++;
        }

        if( sumWeights != 0.0f && numNonzero > 1 )
        {
            meanWeighted /= sumWeights;

            for( int i = 0; i < count; i++ )
            {
                float   sum = samples[i] - meanWeighted;

                varianceWeighted += weights[i]*sum*sum;
            }

            varianceWeighted *= ((float) numNonzero)/((float) count*(numNonzero - 1.0f)*sumWeights);    // this should be right but isn't?!
        }
    }

    return varianceWeighted;
}

template <class T>
inline float    StdDevWeighted( T samples[], T weights[], int count )
{
    return sqrtf( VarianceWeighted( samples, weights, count ) );
}

Test case:
int     samples[] = { 2, 3, 5, 7, 11, 13, 17, 19, 23 };

printf( "%.2f\n", StdDev( samples, 9 ) );

int     weights[] = { 1, 1, 0, 0, 4, 1, 2, 1, 0 };

printf( "%.2f\n", StdDevWeighted( samples, weights, 9 ) );

Result:
7.46
1.94

Should be:
7.46
5.82

I think the problem is that weighted variance has a few different interpretations and I don't know which one is standard.  I found this variation:
http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance#Weighted_incremental_algorithm
template <class T>
inline float    VarianceWeighted( T samples[], T weights[], int count )
{
    float   varianceWeighted = 0.0f;

    if( count > 1 )
    {
        float   sumWeights = 0.0f, meanWeighted = 0.0f, m2 = 0.0f;

        for( int i = 0; i < count; i++ )
        {
            float   temp = weights[i] + sumWeights,
                    delta = samples[i] - meanWeighted,
                    r = delta*weights[i]/temp;

            meanWeighted += r;
            m2 += sumWeights*delta*r;   // Alternatively, m2 += weights[i] * delta * (samples[i]−meanWeighted)
            sumWeights = temp;
        }

        varianceWeighted = (m2/sumWeights)*((float) count/(count - 1));
    }

    return varianceWeighted;
}

Result:
7.46
5.64

I also tried looking at boost and esutil but they didn't help much:
http://www.boost.org/doc/libs/1_48_0/boost/accumulators/statistics/weighted_variance.hpp
http://esutil.googlecode.com/svn-history/r269/trunk/esutil/stat/util.py
I don't need an entire statistics library, and more importantly, I want to understand the implementation.
Can someone please post functions to calculate these correctly?
Bonus points if your functions can do it in a single pass.
Also, does anyone know if weighted variance gives the same result as ordinary variance with repeated values?  For example, would the variance of samples[] = { 1, 2, 3, 3 } be the same as weighted variance of samples[] = { 1, 2, 3 }, weights[] = { 1, 1, 2 }?
Update: here is a google docs spreadsheet I have set up to explore the problem.  Unfortunately my answers are nowhere close to the NIST pdf.  I think the problem is in the unbias step, but I can't see how to fix it.
https://docs.google.com/spreadsheet/ccc?key=0ApzPh5nRin0ldGNNYjhCUTlWTks2TGJrZW4wQUcyZnc&usp=sharing
The result is a weighted variance of 3.77, which is the square of the weighted standard deviation of 1.94 I got in my c++ code.
I am attempting to install octave on my Mac OS X setup so that I can run their var() function with weights, but it is taking forever to install it with brew.  I am deeply into yak shaving now.

A:

float mean(uint16_t* x, uint16_t n) {
    uint16_t sum_xi = 0;
    int i;
    for (i = 0; i < n; i++) {
        sum_xi += x[i];
    }
    return (float) sum_xi / n;
}

/**
 * http://www.itl.nist.gov/div898/software/dataplot/refman2/ch2/weigmean.pdf
 */
float weighted_mean(uint16_t* x, uint16_t* w, uint16_t n) {
    int sum_wixi = 0;
    int sum_wi = 0;
    int i;
    for (i = 0; i < n; i++) {
        sum_wixi += w[i] * x[i];
        sum_wi += w[i];
    }
    return (float) sum_wixi / (float) sum_wi;
}

float variance(uint16_t* x, uint16_t n) {
    float mean_x = mean(x, n);
    float dist, dist2;
    float sum_dist2 = 0;

    int i;
    for (i = 0; i < n; i++) {
        dist = x[i] - mean_x;
        dist2 = dist * dist;
        sum_dist2 += dist2;
    }

    return sum_dist2 / (n - 1);
}

/**
 * http://www.itl.nist.gov/div898/software/dataplot/refman2/ch2/weighvar.pdf
 */
float weighted_variance(uint16_t* x, uint16_t* w, uint16_t n) {
    float xw = weighted_mean(x, w, n);
    float dist, dist2;
    float sum_wi_times_dist2 = 0;
    int sum_wi = 0;
    int n_prime = 0;

    int i;
    for (i = 0; i < n; i++) {
        dist = x[i] - xw;
        dist2 = dist * dist;
        sum_wi_times_dist2 += w[i] * dist2;
        sum_wi += w[i];

        if (w[i] > 0)
            n_prime++;
    }

    if (n_prime > 1) {
        return sum_wi_times_dist2 / ((float) ((n_prime - 1) * sum_wi) / n_prime);
    } else {
        return 0.0f;
    }
}

/**
 * http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance#Weighted_incremental_algorithm
 */
float weighted_incremental_variance(uint16_t* x, uint16_t* w, uint16_t n) {
    uint16_t sumweight = 0;
    float mean = 0;
    float M2 = 0;
    int n_prime = 0;

    uint16_t temp;
    float delta;
    float R;

    int i;
    for (i = 0; i < n; i++) {
        if (w[i] == 0)
            continue;

        temp = w[i] + sumweight;
        delta = x[i] - mean;
        R = delta * w[i] / temp;
        mean += R;
        M2 += sumweight * delta * R;
        sumweight = temp;

        n_prime++;
    }

    if (n_prime > 1) {
        float variance_n = M2 / sumweight;
        return variance_n * n_prime / (n_prime - 1);
    } else {
        return 0.0f;
    }
}

void main(void) {
    uint16_t n = 9;
    uint16_t x[] = { 2, 3, 5, 7, 11, 13, 17, 19, 23 };
    uint16_t w[] = { 1, 1, 0, 0,  4,  1,  2,  1,  0 };

    printf("%f\n", weighted_variance(x, w, n)); /* outputs: 33.900002 */
    printf("%f\n", weighted_incremental_variance(x, w, n)); /* outputs: 33.900005 */
}


Q:

referencing a main method in an imported module from a newbie to Python

Apologies if the thinking behind the question is wrong: just picking up Python as I go.
So I've written a python module that goes off to a database and gets a bunch of standard data that is used by lots of other modules, so I thought it would be good practise to build it as a reusable module.
So there is a class:
class TalkToOracle:

with an attribute
gres = None

a bunch of other functions, and a main function at the end
def main():

with a line I don't fully understand but seems to automatically run the main method when the class is referenced(?)
if __name__ == "__main__":
    main()

Main runs the functions in the class in order, and sticks the results in the attribute: gres
All runs great stands alone. The file is saves as GetOraData.py
I now want to reuse this code so.......
In another Python module
import GetOraData

class GetInstances:
    def oraInstanceData(self):
        log.info('Getting instance routing data')
        HAData = GetOraData.TalkToOracle()
        log.info('debug1')

All goes pear shaped from here.
I just want to run the other module, and access the results in the attribute gres.
I tried this (and every other variation I could think of) but no joy.
I feel I'm missing something fundamental.
HADATA.main()
log.info('debug2')
HADataSet = HAData.gres
log.info('debug3')
log.info('Query fetched ' + str(len(HADataSet)) + ' rows')

Any help would be gratefully appreciated.
After some work, here is the modified code that still throws an error
import logging
import time
import uuid
import GetOraData
from datetime import datetime

log = logging.getLogger()
log.setLevel('INFO')

class GetInstances:
    def oraInstanceData(self):
        log.info('Getting HA instance routing data')
        HAData = GetOraData.main()
        HADataSet = GetOraData.gres
        log.info('Query fetched ' + str(len(HADataSet)) + ' HA Instances to query')

def main():

    logging.basicConfig()
    start = time.time()

    #oracle routines

    oraInstances = GetInstances()
    oraInstances.oraInstanceData()

if __name__ == "__main__":
    main()

error:AttributeError: 'module' object has no attribute 'gres'

A:

You need to explicity call the main module attribute of GetOraData:
GetOraData.main()
GetOraData.gres

When you import a module, all of its attributes are in its namespace.

https://docs.python.org/2.7/tutorial/classes.html#a-word-about-names-and-objects
http://pyvideo.org/video/1749/namespaces-in-python,
http://pyvideo.org/search?models=videos.video&q=namespaces


Q:

Can I copy a Postgresql Large Object on the db server?

I've got data in a large object, now I want to make a copy of it so I can append to it while keeping the copy of the original.  Is there any JDBC call or SQL statement I can use to cause that to happen?
From every resource I have found, it seems I have to actually read all the data to my client and write it out again to get the copy.  I'd much prefer to save the round trip.

A:

A large object can be copied/cloned with two queries if you know its oid.
INSERT INTO pg_largeobject_metadata (lomowner, lomacl)
  SELECT lomowner, lomacl
  FROM pg_largeobject_metadata
  WHERE oid = <my_old_oid>
RETURNING oid AS my_new_oid;

INSERT INTO pg_largeobject (loid, pageno, data)
  SELECT <my_new_oid>, pageno, data
  FROM pg_largeobject
  WHERE loid = <my_old_oid>;

my_old_oid is the large object's known oid
my_new_oid is the oid returned by the first insert statement
pg_large_object reference
Object Type Identifier (oid) reference


Q:

Dual space and Metric tensor

So I know that the dual space is the set of all linear transformations that map a vector from a vector space to the field of the space itself (the real number line, complex, quaternions). From YouTube I saw that you can use the metric tensor to go from the vector space to the dual space.I have two questions about this. Why do we use the metric tensor as a map (don't we define tensors by the fact that they are invariant under general Lorentz transformations? And if this is the case that the metric tensor acts as a mapping from the vector space to the dual space then does this mapping specify the linear combination of the dual basis in terms of original basis?

A:

The vector space and its dual space are isomorphic. We can "identify" the spaces with any mapping (given the properties of the mapping are "nice" enaugh, like being 1-1). But they are not cannocically isomorphic, because there is no reason to prefer one mapping over another. In metric space, the metric is distinguished among all the existing mappings and thus we can use this mapping to build canonical isomorphism.
Metric tensor (or any tensor for that matter) is simply linear map from all the vectors and dual spaces into real numbers. So if we have vector space $V$ and dual space $V^*$, tensor $T^2_3$ is a linear map from $V^*\times V ^*\times V \times V\times V \rightarrow R$.
Notice that if you don't insert some of the vectors, you get linear map that waits for those vectors. If you dont insert one vector into metric, which is linear map $V\times V \rightarrow R$, you get linear map that waits for that vector to produce number, so $g(-,v)$ where g is metric and v vector in V, you get linear map from $V\rightarrow R$ which is exactly what dual space is.
To construct isomorphism between vector space and its dual, use prescription $(e^*)^i=g(-,e_i)$. But then the condition $(e^*)^i(e_j)=\delta_j^i$ for dual basis is not satisfied, because for timelike basis vector the norm gives $-1$.
Now the advantage of this identifiaction is in the fact that the dual vectors are not just random linear map of vector space, its the scalar product.
EDIT to further explain the connection between dual vectors, metric and lorentz transformation:
For any basis $e_i$ in $V$ we have dual basis $e^i$ given by the relation $e^i(e_j)=\delta^i_j$. This defines the isomorphism (map that identifies the two vector spaces) between $V$ and $V^*$. When we choose different basis in V, we get another dual basis and this also defines some isomorphism between $V$ and $V^*$. It can be shown that the two isomorphisms are not in general the same. That is, if first isomorphism creates identification $v_1 \leftrightarrow v^2$ where $v_1 \in V, v^2 \in V^*$, the second isomorphism will in general identify the same vector $v_1$ with different vector $v^3 \in V^*; v^3\ne v^2$.
So there is no natural way to associate vector $v_i \in V$ with some vector of dual space.
But if we have metric, we can fix isomorphism with already given prescription $(e^*)^i=g(-,e_i)$. Then, as i already pointed out, the linear map $v^i(v_j)=g(v_i,v_j)$ gives you the scalar product of vector $v_j \in V$ and vector $v_i \in V$ associated with the $v^i \in V^*$.
But since the scalar product in relativity is invariant under lorentz transformations (we can choose only such kind of metrics, otherwise they can't be physically meaningfull), this way of identifying $V$ and $V^*$ is also lorentz invariant and gives you great benefits.
EDIT 2, correction
I made a mistake: prescription $(e^*)^i=g(-,e_i)$ does not lead to $(e^*)^i(e_j)\equiv g(e_j,e_i) = \delta^i_j$, because f.e. $g(e_t,e_t) =-1$ in minkowski. So in fact, there is no orthonormal basis in GR as i wrote, because you cannot normalize timelike/null vectors to $1$ (in metric with signature -+++). There is only orthogonal basis, not orthonormal.
The corrections are written in italic.


Q:

Database name convention: DATETIME column

What is your naming convention for DATETIME columns (in my case, using MS SQL Server)
For a column that stores when the row was created CreatedDatetime makes sense, or LastModifiedDatetime.
But for a simple table, let's say one called Event, would you create columns called:
EventID,                 // Primary key
EventDatetime,           // When the event is happening
EventEnabled             // Is the event is on

or
ID,                      // Primary key
Datetime,                // When the event is happening
Enabled                  // Is the event is on

If you'd use neither convention: Please provide the column name you would use.

A:

I normally name DATETIME columns as ACTION_WORD_on: created_on, completed_on, etc.
The ACTION_WORD defines what the column represents, and the suffix (_on) indicates that the column represents time.
Other suffixes (or even prefixes) may be used to specify the data type (_at, _UTC, when_, etc).
Be descriptive. Be consistent.

A:

Why call it EventDateTime, when you don't also use EventIDInt, or EventEnbaledVarchar? Why inlcude the data type in the column name? (My rule of thumb is, if they're accessing data in a table, they better know what the column data types are, 'cause otherwise they don't know what they're working with.)
These days I prefer what I think of as descriptive column names, such as:
  CreateDate
  DateCreated
  CreatedAt
  CreatedOn (if there's no time portion)
  AddedOn (might be semanitcally more appropriate, depending on the data)
Picking a "label" and using it consistantly in every table that requires that kind data is also a good thing. For example, having a "CreateDate" column in (almost) every table is fine, because then you will always know which column in every table will tell you when a row was created. Don't get hung up with the "but they all have to have unique names" argument; if you're writing a query, you had better know which tables you're pulling each column from.
--Edit--
I just recalled an exception I've done in the past. If a DateTime (or SmallDateTime) column will contain no time portion, just the date, as a "reminder" I'd put "Date" in the column name, such as "BilledDate" instead of "Billed" or "BilledOn". This shouldn't apply when tracking when rows were added, since you'd want the time as well.

A:

The name should communicate what Business meaning of the data is in the column... "DateTime" is just the Type of the data. Is it when the event happened? when it was recorded? when it was stored in the DB? When the data was last modified?
If it efficiently communicates the meaning of what the column contains, the name is fine.  "DateTime" is not fine. "EventDateTime" is only very slightly better.  If the table holds events, then any datetime field in the table is an EventDateTime (It records some datetime related to the event). Although if there's only one datetime column in an "Events" table, then EventDateTime implies that it's when the event happened, so that's probably ok.
Choose or select the name so it communicates the meaning of the value...
Given edited question, some suggested names might be:
Occurred, or OccurredDateTime, or OccurredUTC, (or OccurredLocal), or, if events in your business model have duration, then perhaps StartedUtc, or BeganUtc, or InitiatedUtc, etc.


Q:

Alloy: define relation to only positive integers

I have a model with this sig:
sig Thing {}
sig World {
    quantities: Thing ->one Int,
}

I want to define a constraint on the quantities relationship such that the quantity of each Thing must be a positive int.
I am total beginner with Alloy (and I have no theory background to draw on, am just a Python programmer). I followed through the tutorial but I did not see a recipe for what I want to do.
I know how to:
fact {
    all w: World | w.quantities <something>
}

...but I am not clear how to address members of the right-hand-side of the relationship when writing a fact.
I have defined it as a relationship (rather than having a quantity property on the Thing sig) because I understood from the tutorial that this was necessary in a dynamic model where I want to update the quantity of Things via predicates.
I tried defining a:
sig PositiveInt extends Int {}

...but this is not allowed.

A:

updated
This kind of subtyping works (imho) best with set enumeration:
 let PositiveInt = { i : Int | i > 0 }
 sig Thing {}
 sig World { quantities : Thing -> one PositiveInt }

┌──────────┬──────────┐
│this/World│quantities│
├──────────┼──────┬───┤
│World⁰    │Thing⁰│7  │
│          ├──────┼───┤
│          │Thing¹│6  │
│          ├──────┼───┤
│          │Thing²│4  │
└──────────┴──────┴───┘


Q:

(Python Snake game) For loop doesn't draw snake

This is a small problem, been working on a snake game in python, it's not complete yet and there's just one thing I would like to know.  I originally had the code pygame.draw.rect(SCREEN, GREEN, (x_pos[i], y_pos[i], WIDTH, HEIGHT)) in the move_snake function.  The code drew the snake just fine while I had it like that, however now I'm trying to grow the snake, so I've moved it into the for loop in the grow_snake function.  It won't draw the snake anymore, however it still exists apparently as if I press the keys it will eventually hit a border and end the game.  Just want to know why it won't draw the snake anymore.  Thank you.  I'm a noob at programming so if you want to look through the code and give me tips on how to improve it, that would be much appreciated.  Keep in mind this is a work in progress so there are many obvious segments to the game that are missing that I will add in later.
# Snake game

import pygame
import random

pygame.init()
pygame.display.set_caption("Snake Game and AI")

WIDTH = 24
HEIGHT = 24
SCREEN = pygame.display.set_mode((500, 500))
RED = (255, 0, 0)
BLACK = (0, 0, 0)
GREEN = (0, 128, 0)
WHITE = (255, 255, 255)
SPEED = 25
x_head = 251
y_head = 251
direction = None
apple_x = random.randrange(26, 476, 25)
apple_y = random.randrange(26, 476, 25)
length = 0
x_pos = [x_head]
y_pos = [y_head]

def grid():
    for x in range(25, 500, 25):
        pygame.draw.rect(SCREEN, WHITE, (x, 25, 1, 450))

    for y in range(25, 500, 25):
        pygame.draw.rect(SCREEN, WHITE, (25, y, 450, 1))

def press_key():
    global direction
    global keys
    if keys[pygame.K_RIGHT] and direction != 'left':
        direction = 'right'
    if keys[pygame.K_LEFT] and direction != 'right':
        direction = 'left'
    if keys[pygame.K_UP] and direction != 'down':
        direction = 'up'
    if keys[pygame.K_DOWN] and direction != 'up':
        direction = 'down'

def move_snake():
    global x_head
    global y_head
    global SCREEN
    global WIDTH
    global HEIGHT
    if direction == 'right':
        x_head += SPEED
    if direction == 'left':
        x_head -= SPEED
    if direction == 'up':
        y_head -= SPEED
    if direction == 'down':
        y_head += SPEED

def eat_apple():
    global apple_x
    global apple_y
    global length
    if x_head == apple_x and y_head == apple_y:
        apple_x = random.randrange(26, 476, 25)
        apple_y = random.randrange(26, 476, 25)
        if direction == 'right':
            pass
        if direction == 'left':
            pass
        if direction == 'up':
            pass
        if direction == 'down':
            pass
        length += 1
    pygame.draw.rect(SCREEN, RED, (apple_x, apple_y, WIDTH, HEIGHT))

def grow_snake():
    move_snake()
    global x_pos
    global y_pos
    for i in range(length):
        pygame.draw.rect(SCREEN, GREEN, (x_pos[i], y_pos[i], WIDTH, HEIGHT))

def game_over():
    global is_running
    if x_head < 26 or x_head > 456 or y_head < 26 or y_head > 456:
        is_running = False

is_running = True
while is_running:
    pygame.time.delay(150)
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            is_running = False

    keys = pygame.key.get_pressed()
    press_key()
    move_snake()
    SCREEN.fill(BLACK)
    grid()
    grow_snake()
    eat_apple()
    game_over()
    pygame.display.update()

pygame.quit()

A:

You don't need x_head, y_head and length at all. The position of the snake is stored in the lists x_pos and y_pos, use it:
(zip() aggregates the elements of a list)
def grow_snake():
    for x, y in zip(x_pos, y_pos):
        pygame.draw.rect(SCREEN, GREEN, (x, y, WIDTH, HEIGHT))

If you want to know the length of the snake the you can get it by the length of the lists (e.g. len(x_pos).
To move the snake, compute the new position of the head, add the new position at the head of the lists and remove the tail of the list
def move_snake():
    global SCREEN, WIDTH, HEIGHT, x_pos, y_pos

    # compute new head
    x_head, y_head = x_pos[0], y_pos[0]
    if direction == 'right':
        x_head += SPEED
    if direction == 'left':
        x_head -= SPEED
    if direction == 'up':
        y_head -= SPEED
    if direction == 'down':
        y_head += SPEED

    # add new head at head of lists
    x_pos = [x_head] + x_pos
    y_pos = [y_head] + y_pos

    # delete tail of snake
    del x_pos[-1]
    del y_pos[-1]

If you eat an apple the add a new element at the tail of the snake:
def eat_apple():
    global apple_x, apple_y, x_pos, y_pos
    if x_pos[0] == apple_x and y_pos[0] == apple_y:
        apple_x = random.randrange(26, 476, 25)
        apple_y = random.randrange(26, 476, 25)
        x_pos.append(x_pos[-1])
        y_pos.append(y_pos[-1])
    pygame.draw.rect(SCREEN, RED, (apple_x, apple_y, WIDTH, HEIGHT))

Code without x_head, y_head and length:

# Snake game

import pygame
import random

pygame.init()
pygame.display.set_caption("Snake Game and AI")

WIDTH = 24
HEIGHT = 24
SCREEN = pygame.display.set_mode((500, 500))
RED = (255, 0, 0)
BLACK = (0, 0, 0)
GREEN = (0, 128, 0)
WHITE = (255, 255, 255)
SPEED = 25
direction = None
apple_x = random.randrange(26, 476, 25)
apple_y = random.randrange(26, 476, 25)
x_pos = [251]
y_pos = [251]

def grid():
    for x in range(25, 500, 25):
        pygame.draw.rect(SCREEN, WHITE, (x, 25, 1, 450))

    for y in range(25, 500, 25):
        pygame.draw.rect(SCREEN, WHITE, (25, y, 450, 1))

def press_key():
    global direction
    global keys
    if keys[pygame.K_RIGHT] and direction != 'left':
        direction = 'right'
    if keys[pygame.K_LEFT] and direction != 'right':
        direction = 'left'
    if keys[pygame.K_UP] and direction != 'down':
        direction = 'up'
    if keys[pygame.K_DOWN] and direction != 'up':
        direction = 'down'

def move_snake():
    global SCREEN, WIDTH, HEIGHT, x_pos, y_pos
    x_head, y_head = x_pos[0], y_pos[0]
    if direction == 'right':
        x_head += SPEED
    if direction == 'left':
        x_head -= SPEED
    if direction == 'up':
        y_head -= SPEED
    if direction == 'down':
        y_head += SPEED
    x_pos = [x_head] + x_pos
    y_pos = [y_head] + y_pos
    del x_pos[-1]
    del y_pos[-1]

def eat_apple():
    global apple_x, apple_y, x_pos, y_pos
    if x_pos[0] == apple_x and y_pos[0] == apple_y:
        apple_x = random.randrange(26, 476, 25)
        apple_y = random.randrange(26, 476, 25)
        x_pos.append(x_pos[-1])
        y_pos.append(y_pos[-1])
    pygame.draw.rect(SCREEN, RED, (apple_x, apple_y, WIDTH, HEIGHT))

def grow_snake():
    for x, y in zip(x_pos, y_pos):
        pygame.draw.rect(SCREEN, GREEN, (x, y, WIDTH, HEIGHT))

def game_over():
    global is_running
    if x_pos[0] < 26 or x_pos[0] > 456 or y_pos[0] < 26 or y_pos[0] > 456:
        is_running = False

is_running = True
while is_running:
    pygame.time.delay(150)
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            is_running = False

    keys = pygame.key.get_pressed()
    press_key()
    move_snake()
    SCREEN.fill(BLACK)
    grid()
    grow_snake()
    eat_apple()
    game_over()
    pygame.display.update()

pygame.quit()


Q:

Determine the number of connected acyclic graph with 10 vertices and 10 edges, how and why

Determine the number of connected acyclic graphs with 10 vertices and
  10 edges.

Please if someone can explain how and why, thank you.

A:

A connected acyclic graph is a tree.
A tree with $n$ vertices has $n-1$ edges.
Hence there are no connected acyclic graphs  with $10$ vertices and $10$ edges.


Q:

How to use AngularJS to build javascript widgets for public use?

I'm trying to build a JavaScript widget that will allow webmasters to just cut and paste a few lines of code to display some functionality and UI on their site.
I've seen a good example of doing this kind of thing in JQuery, but not Angular. I'm assuming the widget will need to download the angularjs javascript file conditionally (based on whether it has already been loaded).
Has anyone had experience doing this in Angular and can recommend whether or not to do it in Angular or just stick with jQuery?
e.g. FourSquare's widget code:

Save to foursquare
<script type='text/javascript'>
(function() {
   window.___fourSq = {"uid":"606"};
   var s = document.createElement('script');
   s.type = 'text/javascript';
   s.src = 'http://platform.foursquare.com/js/widgets.js';
   s.async = true;
   var ph = document.getElementsByTagName('script')[0];
   ph.parentNode.insertBefore(s, ph);
})();
</script>

A:

I believe AngularJS is a framework with is targetted towards Single Page Apps (SPA) and provides all the infrastructure around it. The use of widget within existing HTML pages is not a ideal use case for using AngularJS.
jQuery is more of a utility belt \ library and hence can be used anywhere.


Q:

jquery droppable is not working

Guys. I spent few hours just for checking my jquery, why it doesn't work well. Just confused why droppable function doesn't firing alert when the square div has dropped into box's div.
Here is my html

<title>jquery - draggable </title>
    <link rel="stylesheet" type="text/css" href="css/style.css">

And this is my style
#box {
    margin: 0 auto;
    background: #ecf0f1;
    border-radius: 10px;
    border-style: dashed;
    height: 100px;
    width: 100px;
}
#square {
    margin: 0 auto;
    background: #3498db;
    border-radius: 10px;
    height: 100px;
    width: 100px;
}

And this is my javascript
$(document).ready(function(){
    $("#square").draggable();

    $("#box").droppable({
        drop: handleDropEvent
    });

    function handleDropEvent(event, ui){
        alert('Hello');
    }

});

Any help would be appreciated. Thank you!

A:

Play with droppables tolerance option.

"fit": Draggable overlaps the droppable entirely.
"intersect": Draggable overlaps the droppable at least 50% in both directions.
"pointer": Mouse pointer overlaps the droppable.
"touch": Draggable overlaps the droppable any amount.

$(document).ready(function(){
    $("#square").draggable();

    $("#box").droppable({
        drop: handleDropEvent,
       tolerance:"pointer"
    });

    function handleDropEvent(event, ui){
        alert('Hello');
    }

});
#box {
    margin: 0 auto;
    background: #ecf0f1;
    border-radius: 10px;
    border-style: dashed;
    height: 100px;
    width: 100px;
}
#square {
    margin: 0 auto;
    background: #3498db;
    border-radius: 10px;
    height: 100px;
    width: 100px;
}

<title>jquery - draggable </title>
    <link rel="stylesheet" type="text/css" href="css/style.css">


Q:

Script# For Visual Studio 2008

I am working with Script# with Visual Studio 2010. But now I need to develop an application and my development machine runs Windows XP with Visual Studio 2008.
Is there a place where I can download the last version (0.7.4) of Script# for Visual Studio 2008 ???
If there is no option to download 0.7.4 for Visal Studio 2008 is there a place to download the last version that supports Visual Studio 2008 ???

A:

Are you able to use .NET4 - that is a minimum requirement for the script# compiler. Assuming yes, the only thing specific to VS2010 (at the moment) is project templates. In the future, there will be more VS2010 dependencies and support, but for now, you can probably create your project in VS2010 and then tweak it to open in VS2008.
Alternatively, can you use Visual Web Developer Express 2010?
Unfortunately 2008 is no longer supported, and the last version that did that is really really old. Lots of changes have gone into the project since.


Q:

Fortran 90 array subsets

I am trying to read some Fortran code but there is something I can't understand with array subsets operations like this one
Assume n = 3
And the arrays
INTEGER, PARAMETER :: dp = SELECTED_REAL_KIND(12)
REAL(KIND=dp)   :: P(n+1),P0(n)

what does this line exactly do?
DO i=1,n-1
  …..
  P(3:i+2) = P(3:i+2) - i*P0(1:i) / (i+1)
  ….
END DO

Is it a nested loop? Like j from 3 to i+2 for P and k from 1 to i for P0?
Thanks in advance.

A:

Take the line
P(3:i+2) = P(3:i+2) - i*P0(1:i) / (i+1)

and replace i with 1 (the first value it takes in the do loop)
P(3:3) = P(3:3) - 1*P0(1:1) / 2

On the lhs you have a slice (or section) of array P from element 3 to element 3, so in this case just one element -- but still an array slice not a scalar.  This is updated by subtracting 1 times the (same sized) slice of array P0 and divided by 2.
It's a bit more interesting in the next iteration, with i==2 and
P(3:4) = P(3:4) - 2*P0(1:2) / 3

where the array slices are now 2 elements each.  The operations on array slices are applied on corresponding elements from each array so this statement is approximately equivalent to the two statements
P(3) = P(3) - 2*P0(1) / 3
P(4) = P(4) - 2*P0(2) / 3

It's better to think of this in Fortran terms, as operations on array sections, than as some kind of syntactic sugar for nested loops.


Q:

MERGE: INSERT on MATCH

I am downloading data that will have duplicates with previously downloaded data.
I am successfully using a MERGE statement to throw away the duplicates based on transaction number.   Supposedly that is sufficient, but I would like to monitor if the detail ever changes on a particular transaction.
To that end I added a when matched clause on the merge with an additional insert that identifies the record as a duplicate.
This logic should not trigger very often so I am not too concerned that this method (if it worked) would report the same duplicate multiple times.
When I prepare this code I get this error message:
An action of type 'INSERT' is not allowed in the 'WHEN MATCHED' clause of a MERGE statement.

Is there a way to get the duplicate record to insert into this table or another table using the MERGE statement?
I am open to other solutions, but I would really like to find a way to do this with the MERGE statement because it would impact my code the least.
MERGE INTO dbo.TransactionDetail as t
USING (SELECT @TransNr --bigint
             ,@Detail  -- [VARCHAR](50) NOT NULL
      ) as s
      ([TranNr]
      ,[Detail]
      )
   on t.TranNr = s.TranNr and t.CHANGED_RECORD = 0
 when not matched then
      INSERT (CHANGED_RECORD
         ,[TranNr]
             ,[Detail]
             )
      VALUES(0, s.TranNr, s.Detail)
/* Adding this does not allow statement to be prepared....
 when matched and s.Detail <> t.Detail
 then
      INSERT (CHANGED_RECORD
         ,[TranNr]
             ,[Detail]
             )
      VALUES(1, s.TranNr, s.Detail)
*/
;

A:

You can use an INSERT statement, like this:
INSERT INTO dbo.TransactionDetail (CHANGED_RECORD,TranNr,Detail)
SELECT  CASE WHEN EXISTS (
            SELECT * FROM dbo.TransactionDetail
            WHERE TranNr=@TransNr AND CHANGED_RECORD=0 AND Detail<>@Detail
        ) THEN 1 ELSE 0 END AS CHANGED_RECORD,
        @TransNr AS TranNr, @Detail AS Detail
WHERE NOT EXISTS (
    SELECT * FROM dbo.TransactionDetail
    WHERE TranNr=@TransNr AND CHANGED_RECORD=0 AND Detail=@Detail
)

This will skip inserting if a row which has CHANGED_RECORD=0 has the same detail. However, if the same detail it's found in another row which has CHANGED_RECORD=1, a new duplicate would be inserted. To avoid that, remove the AND CHANGED_RECORD=0 condition from the WHERE NOT EXISTS subquery.
You may also want to create a unique filtered index, to ensure unicity for the rows which have CHANGED_RECORD=0:
CREATE UNIQUE INDEX IX_TransactionDetail_Filtered
ON TransactionDetail (TranNr) /*INCLUDE (Detail)*/ WHERE CHANGED_RECORD=0

The INCLUDE (Detail) clause could also marginally improve performance of queries that are looking for the Detail of the rows which have CHANGED_RECORD=0 (at the expense of some additional disk space and a small performance penalty when updating the Detail column of existing rows).


Q:

Load HTML document to populate HTMLPanel a good idea?

I want to load "pieces" of HTML to set HTMLPanels which will be dynamically modified by getting the id's as follows:
HTMLPanel dynContent = new HTMLPanel("<div id=\"test_id\"/>");
dynContent.add(new Label("This content is dynamically generated."), "test_id");

Can I serve HTML files to my client from a GWT app (It would be cool to just load the html files served at application startup)? Or do I have to create a call to the server to get the HTML (say RPC)? It sounds like JSP is the solution but I rather stay away from this for such a simple app.
Any suggestions are welcome!

A:

The answer is pretty neat! I first found this:
best way to externalize HTML in GWT apps?
Then tried this to load static data via Client Bundle:
public interface Resources extends ClientBundle {
    Resources INSTANCE = GWT.create(Resources.class);

    @Source("public/html/timesheet.html")
    TextResource synchronous();

}

Then I load the resources in my html panel:
 HTMLPanel dynContent = new HTMLPanel(Resources.INSTANCE.synchronous().getText());
 dynContent.add(new Label("This content is dynamically generated."), "dynContent");

 simplePanel.add(dynContent);

The content from the HTML file I have is fetched and populates the HTMLPanel as I wanted.


Q:

Does an implied tie exist

Is there such a thing as an implied tie? Like some kind of symbol or notation that would specify to hold a note through the duration of all the notes on a pitch as if they were tied together.
Edit: I am asking because I am wondering if there is a way to specify that instruments hold one tone (like a choir that is humming) instead of playing each note separately. The reason I am wondering is because I am using a notation program to write out some music, and then you can listen to it, and I want to hear it like a choir humming. I know about ties, but I just thought I'd check if there is such a thing in music.
Edit: By implied, I mean it isn't written in the music. In other words it is specified at the beginning of the part or something like that.
Edit: I am using Noteworthy Composer.

A:

If you want a long, sustained note, you could notate it in quite a few different ways. Below are some suggestions. Not all will actually save you time, by cutting notation, though! Each of these is only five bars long, so, obviously, you would only get any time benefit from using these techniques with longer notes.
BTW, I haven't used Noteworthy Composer before, so have no idea if they would work with that software. I used Sibelius7 for these, and all played back exactly the same (apart from the second line), i.e. with one sustained note per bar.

Standard Notation.
Similar notation using ties into rests; even though this doesn't require notes to be written, it would actually take more time to put in as the placement of the ties is fiddly. For instruments where the sound decays (eg. piano, guitar) you would usually use l.v. too.
Using repeat-bar marks can save a lot of time.
This notation is effectively the same, and plays back the same, but is less clear; it's not clear whether you attack the second note…
And of course, if in doubt, use text to make the intention clear in the score.

With this answer I've tried to show different kinds of notation for sustained notes that would be valid within a score. Not all of them would save time if all you actually want is to hear the music (or to create a MIDI file of it, for instance). If all you want is to create a long held pitch, as quickly and easily as possible, the notation below will create the necessary effect (well, again, it works in Sibelius7, but might not in other software). But it is certainly not correct notation!


Q:

TStringGrid OnHeaderClick event

I have a simple Android application consisting of TSringGrid and 2 columns, one of which is TColumn and the other TCheckColumn.  I can sort on each of the columns using TButton and appropriate code, but the TButtons take up valuable screen space that could be better used. Is it possible to determine which column is selected by using the OnHeaderClick event and calling the appropriate action from that event.
Many Thanks ...

A:

First, example of the event handler signature:
procedure TForm5.StringGrid1HeaderClick(Column: TColumn);

the Column parameter is the column whos header was clicked
There are many ways to detect which column was clicked, here are three:
Alternative one: check the Header property of the column
  if Column.Header = 'First column' then
    ShowMessage('First clicked')
  else
  if Column.Header = 'Second column' then
    ShowMessage('Second clicked');

Alternative two: check the Name property of the column
  if Column.Name = 'Column1' then
    ShowMessage('First clicked')
  else
  if Column.Name = 'CheckColumn1' then
    ShowMessage('Second clicked');

Alternative three: Assign values to the Tag property of each column
 at design time, and check Column.Tag value at runtime
  case Column.Tag of
    0: ShowMessage('First clicked');
    1: ShowMessage('Second clicked');
  end;

Of course you need to change the identifiers according to your actual grid.


Q:

Multiply image kernels

If I have 3 image kernels (edge detection, sharpen, box blur) and want to perform each to an image in that order. Can I multiply the 3 together in some way and apply them to my image in one go?
Here are examples of the kernels -> http://en.wikipedia.org/wiki/Kernel_(image_processing)
If it is possible, like 3d transformation matrices, how would I go about doing it?
Thanks

A:

In theory you can. The trick is to convolve the first filter with the first (as if the filter kernel was an image), then the result with the third (in the spatial domain), or to multiply the transforms (in the Fourier domain).
But in practice, this won't help you because

the edge detection filter is not a pure convolution (there is at least an absolute value); this is a nonlinear operation that will not commute with the other convolutions.
even if your package provides a way to convolve the kernels together, you will end up with a larger, general-purpose kernel, and the resulting filter will be much slower. You will lose the built-in optimizations of the predefined ones.

If the expected benefit is a speedup in processing, this is not the right approach in the general case with spatial domain filter implementations.
Assume filter sizes $p^2, q^2, r^2$; the combined filter will  have size $(p+q+r)^2$. The computational cost of the filter cascade is more attractive because
$$p^2+q^2+r^2<(p+q+r)^2.$$


Q:

Select a string with max length while using Group by in data table in r

My initial sample data was ambiguous so updating my data set
a <- data.table(name=c("?","","One","?","","Two"), value=c(1,3,2,6,5,2) , job=c(1,1,1,2,2,2) )

 name value job
1:    ?     1   1
2:          3   1
3:  One     2   1
4:    ?     6   2
5:          5   2
6:  Two     2   2

I want to group by the column "job" while finding the maximum in column "value" and selecting the "name" which has the maximum length.
My sample output would be
   name job value
1: One    1     3
2: Two    2     6

I think I want the equivalent of  How do I select the longest 'string' from a table when grouping in R

A:

We can group by 'job', get the index of the max number of characters (nchar) in 'name' and subset the dataset.
a[, .SD[which.max(nchar(name)) ], by = job]
#    name value job
#1:  One     3   1
#2:  Two     6   2

Or get the row index (.I) from which.max, extract the column with the index ("V1") and subset the dataset.
a[a[, .I[which.max(nchar(name))], by = job]$V1]

Update
Based on the new example, if the 'value' is not corresponding to the maximum number of character in 'name', we need to select it separately.
a[, .(value= max(value), name = name[which.max(nchar(name))]),
                      by = job]
#     job value name
#1:   1     3  One
#2:   2     6  Two


Q:

How to outline table column using JS/CSS/HTML

I need to select a table column on click. To show selection, I need to outline the table column.
I managed to outline each  in the column needed, see pic:

However, that doesn't suit me: I need to get rid of inner lines.
CSS (actually, LESS) I currently use:
  td.fd-selected
  {
    outline: 0.25em dashed rgb(79,115,176);
    background-color: rgba(79,115,176, 0.25);
  }

A:

Unfortunately you can't do it with outline. outline is basically used to highlight a focused element in its entirety (mostly form elements). In its default setting, it uses the outline provided either by the operating system or the web browser itself (IE as example for the former, Chrome as example for the latter).
The only reliable (and the least hacky) solution is, to use borders.
Here's how (logic):

Place left and right borders to all cells.
Place top border to the appropriate cell of the first row
Place bottom border to the appropriate cell of the last row

The example below also shows, how you could highlight the header too.
Example

table{
  border-collapse: collapse;
}

th {
  background-color: #efefef;
}

th, td {
  width: 60px;
  height: 30px;
  border: 1px solid #ccc;
}

td.outline {
  border-left: 2px dotted #06c;
  border-right: 2px dotted #06c;
}

tr:first-child > td.outline {
  border-top: 2px dotted #06c;
}

tr:last-child > td.outline {
  border-bottom: 2px dotted #06c;
}

/*how could it look like with the header*/

th.outline {
  background-color: #99ccee;
  border: 2px dotted #06c
}


Q:

Fill listboxes from XML-file

I have an XML file and a ListBox that shows the data of the file.
The XML file is:
<students>
  <student>
    <id>1</id>
    <data>
      <subject name="Geopraphy" status="passed" />
      <subject name="History" status="passed" />
    </data>
  <student>
<students>

What I want to show in the listbox1 is the id of the student, and if selected, I want in another ListBox (listbox2) to be shown all the subjects of that student. This is the codeI have so far:
XmlDocument xm = new XmlDocument();
string list = "//id";

xm.Load("data.xml");
XmlNodeList Xn = xm.SelectNodes(list);

foreach (XmlNode xNode in Xn)
{
    listBox1.Items.Add(xNode.InnerText);
}

How can I fill listbox2?

A:

private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
    XmlNode nodes = xDoc.SelectSingleNode(String.Format("/students/student[id={0}]/data", listBox1.SelectedItem));
    foreach (XmlNode node in nodes.ChildNodes)
    {
         if (node.Attributes["status"].Value == "passed")
             listBox2.Items.Add(node.Attributes["name"].Value);
    }
}


Q:

Reciting Boruch Dayan HaEmes on Shabbos

If someone's parent dies, one must recite Boruch Dayan HaEmes. What happens if this occurs on Shabbos? Is the customary Boruch Dayan HaEmes recited or not?

A:

The Bracha - Boruch ... Dayan HaEmes - is said on Shabbos. (Rokeiach Hilchos Aveilos 316 Minhagim, Shibolei HaLeket Hilchos Simchos 13, Tanya Siman 66, Sidur Bais Yaakov - Rabbi Yaakov Emdin, Chochmas Adam Klal 151 Siman 18)


Q:

Warning for missing statistics in execution plan

I have a situation that I can't understand. My SQL Server execution plan tells me that I have missing statistics on the table, but the statistics are already created:

But if we look at the table, we will see that there is a statistic that has been created automatically:

Can somebody help to understand how it can be?
Auto_Update and Auto_Create statistics is turned on on the current DB.
I am using SQL Server 2014.

A:

The warning does not always correspond to missing single-column statistics.
There is no easy way to precisely determine the exact statistic the optimizer went looking for and did not find in all cases, but it is almost always a multi-column statistic that would provide some correlation information across multiple equality predicates in the query.
Perhaps in your case it corresponds exactly with the predicates in the Filter following the scan where the warning appears.
It would be nice if SQL Server reported all columns for the 'missing statistic' warning, but that is not how it works today, unfortunately.
A certain amount of trial-and-error may be necessary to identify the multi-column statistic you need to create to remove the warning. Note that multi-column statistics cannot be created automatically. Despite the warning, you may or may not find the quality of the estimate improves even if the missing statistic is provided.

A:

Since it seems clear that a statistic already exists for the particular column, I offer two possibilities:

Object Explorer is pointed to a different database - I'm suspicious because the database has DEV in the name, so it's possible that in one case you're looking at dev and in another you're not.
The plan being used is from before the statistic was created (either it was generated earlier or, less likely, something prevented a recompile to be triggered when the statistic was created).

Please validate that the simple answer (1) is not the issue, and try issuing the same query with OPTION (RECOMPILE) to either confirm or rule out (2).

A:

I have just noticed that when you get such warnings about statistics,
if you run your query or procedure with the settings below:
SET SHOWPLAN_ALL ON

you can see what are the missing statistics:

and using the scripts here you can have a look at what stats are currently in place, and if missing you can add them.


Q:

.htaccess code to redirect HTTP requests to HTTPS

I recently migrated my website from HTTP to HTTPS. I read on various websites about redirecting all HTTP requests to HTTPS using .htaccess codes.
Lots of websites provide different codes and now I'm confused which code should I use.
Following are 4 codes found on various websites:
1st code:
RewriteEngine on
RewriteCond %{HTTP_HOST} ^yoursite.com [NC,OR]
RewriteCond %{HTTP_HOST} ^www.yoursite.com [NC]
RewriteRule ^(.*)$ https://www.yoursite.com/$1 [L,R=301,NC]

2nd code:
RewriteEngine On
RewriteCond %{HTTPS} !=on
RewriteRule ^/?(.*) https://%{SERVER_NAME}/$1 [R,L]

3rd code:
RewriteCond %{SERVER_PORT} 80
RewriteRule ^(.*)$ https://www.example.com/$1 [R,L]

4th code:
NameVirtualHost *:80
<VirtualHost *:80>
ServerName www.example.com
Redirect permanent / https://secure.example.com/
</VirtualHost>

<VirtualHost _default_:443>
ServerName secure.example.com
DocumentRoot /usr/local/apache2/htdocs
SSLEngine On
</VirtualHost>

Please guide me which code is perfect and I should put in my .htaccess file?

A:

For starters: the last configuration snippet is not even valid in .htaccess files...
(But since you shouldn't be using .htaccess files anyway if you're a system administrator that's not an issue.)
Redirecting http to https a text book example of when (as an admin) you should not need a mod_rewrite approach and use a simple redirect instead. So, if you do have access to the main server config, your last snippet with a simple redirect from the plain http VirtualHost is recommended.


Q:

How to defend vs. Image Remote File Inclusion, e.g. RFI using a .gif file (Apache/PHP)?

To defend versus Remote File Inclusion where attackers try to abuse image files, I usually recommend to never use include to include image files into PHP code.
Sometimes though, the avoidance of image includes may be not possible at all (for whatever reasons, doesn't matter).
In such case I usually pickup the images somewhere in the upload process and convert them to another image format (sometimes im combination with a lossy compression) to hopefully destroy any malicious code possibly contained in the original image.
This works, but I'm not quite satisfied with it. Mainly because of the additional server load such processing produces and possible image quality decreases that sometimes may happen.
Are the any smarter ways or best practices on that?
EDIT
To clarify: I'm talking about a siutation where the attacker injects PHP code into an image file to get the injected code executed on server side after uploading the image. Forums for example allow users to upload avatars (small image files) for personalisation.

A:

Your PHP code should never evaluate a data file. It may print out the content of an image file, but include()ing an image file is an insane use of code. I strongly assume that what you're doing is using PHP code to serve images, and because PHP doesn't evaluate anything that isn't between "<? ?>" tags, this works in most instances. That is definitely the wrong approach.
You may be looking for the readfile() function.
Other than that, don't write include statements that take external input.

A:

Using GD functions to convert is a nice way to solve the problem, but adds overhead as you noticed. Also why do you use include?
I guess you have done all the usual mitigations:

Only allow certain extensions and check against them
Use random file names
use getimagesize()
Check content-type

Other things you may try

disable execution of php files in the image upload directory
use a separate domain to upload the images or store them outside the webroot

A:

I struggle to think a scenario where the use of include(), to include and evaluate/execute an image file, as part of another PHP-file is a valid scenario, when do you need this?
Could you elaborate on the scenario?
If you need to include() a file, it will be evaluated. And since many image formats allow comments to be added, the file could contain valid PHP-commands. So the defense would be either to copy the contents/data of the image, and store it in a new file or strip the comments.
The lossy compression is most likely an overkill (Although I guess it should be possible to forge an image that contains opcode that will be interpeted as valid PHP upon including it while at the same time being a valid image; I don't know if it would survive a lossless image copy intact).

If you are talking about uploaded images that contain PHP code that is executed by the webserver upon serving the images, the defence is much easier:

Do not allow file extensions other than .php to be interpeted as PHP.
If you need dynamic PHP created .png-files, rename them .png.php and use URL rewriting to hide the .php on the client side.
Move the uploaded images (or any file for that matter) to a directory configured to be ignored by PHP.
Never store uploaded files under their original name.


Q:

jquery checking if an image exists in a folder

i am changing the source of an image using the following code:
var src = "/Content/Productimg/" + data.image +".jpg";
              $("#image").attr("src", src);

However, sometimes if data.img returns test and test.jpg does not exist in the Productimg folder a funny icon is displayed.
Is there a way i can check if the image is there before assigning the src?

A:

For checking if image exists or not , you can do:

$.ajax({
    url:'http://yourhost/someimage.ext',
    type:'HEAD',
    error: function()
    {
        //file does not exist
    },
    success: function()
    {
        //file exists do something here
    }
});

A:

$("#image").bind("error", function () {
    $(this).remove();
}).prop("src", src);

If this causes an error (as in javascript error) upgrade your jQuery or use the sinful:
$("#image").bind("error", function () {
    $(this).remove();
}).attr("src", src);


Q:

ARM64 - Linux Memory Write protection won't disable

i'm trying to disable the Memory Write protection on an ARM64 system from within an LKM. (Startet in the DOM0 of the Xen hypervisor)
I found the corresponding PTE to an virtual address by using the Linux Kernel Functions.
pgd_t *pgd;
pte_t *ptep, pte;
pud_t *pud;
pmd_t *pmd;
pgd = pgd_offset(init_mm, (addr));

if (pgd_none(*pgd) || pgd_bad(*pgd))
    goto out;
printk(KERN_NOTICE "Valid pgd 0x%lx\n",pgd);

pud = pud_offset(pgd, addr);
if (pud_none(*pud) || pud_bad(*pud))
    goto out;
printk(KERN_NOTICE "Valid pud 0x%lx\n",pud);

pmd = pmd_offset(pud, addr);
if (pmd_none(*pmd) || pmd_bad(*pmd))
    goto out;
printk(KERN_NOTICE "Valid pmd 0x%lx\n",pmd);

ptep = pte_offset_map(pmd, addr);
if (!ptep)
    goto out;
pte = *ptep;

After this I'm clearing the 7th Bit of the PTE which should, according to the ARM-ARM (Page 2066 - Attribute fields in stage 1 VMSAv8-64 Block and Page descriptors) disable the write protection as it allows write from EL1 (AP[2:1]==00)
Additioanlly im using the Linux Kernel function wo "make the pte writable" eventhough this Bit (Bit 51) is used for stage 2 translation (my work is with Stage 1)
printk(KERN_INFO "PTE before 0x%lx\n", pte);
printk(KERN_INFO "Setting PTE write\n");

pte = pte_mkwrite(pte);
pte = clear_pte_bit(pte, __pgprot((_AT(pteval_t, 1) << 7)));

printk(KERN_INFO "PTE after         0x%lx\n", pte);
flush_tlb_all();
printk(KERN_INFO "PTE nach flush    0x%lx\n", pte);

Because i still get a Kernel Panic when writting to the memory with memcpy, i call the function to disable write protection twice in order to check my settings. These are the outputs for two function calls:
[ 1804.078382] Valid pgd 0xffff000008e7d000
[ 1804.082397] Valid pud 0xffff800017ffe000
[ 1804.086374] Valid pmd 0xffff800017ffd200
[ 1804.090367] PTE before                       0xc0000040081793
[ 1804.094529] Setting PTE write
[ 1804.097562] PTE after                        0xc8000040081713
[ 1804.101637] PTE after flush                  0xc8000040081713
[...More outputs...]
[ 1804.117395] ROUND 2########################
[ 1804.149190] Valid pgd 0xffff000008e7d000
[ 1804.153207] Valid pud 0xffff800017ffe000
[ 1804.157178] Valid pmd 0xffff800017ffd200
[ 1804.161172] PTE before                       0xc0000040081793
[ 1804.165329] Setting PTE write
[ 1804.168366] PTE after                        0xc8000040081713
[ 1804.172443] PTE after flush                  0xc8000040081713

(difference is the 8 instead of an 0 on the second spot from left, and the 1 instead of a 9 on the second one from right)
As you can see, after call the function the second time, we would expect that the last PTE Value of the first round, is the same as the first one of the second round (Output NR: 1804.101637 != 1804.161172), which is not the case here.
I'm writing into the memory with this command:
static unsigned char replace_blr[4] = {0xD6,0x3F, 0x03,0xA0}; (global defined)
memcpy(el1_sync,replace_blr,4);

where el1_sync containts the virtuall address that I'm using for the pte finding.
Does anybody see, why my PTE configuration is not updated/is reset?
If somebody got an alternative to let me write directly into the kernel memory, i would also appreciate any other input. My goal is just to enable writing into the Page of the given virtual address. (Just like many of the x86 rootkits, but on ARM64)
KERNEL OOPS when writing: (Virtuall Address: 0xffff000008081a00)
  [   49.776343] Unable to handle kernel paging request at virtual address ffff000008081a00
[   49.784313] pgd = ffff800013d91000
[   49.787777] [ffff000008081a00] *pgd=0000000000000000[   49.792542]
[   49.794094] Internal error: Oops: 9600004f [#1] PREEMPT SMP
[   49.799721] Modules linked in: mod_init(O+) adv7511 kirin_drm drm_kms_helper dw_drm_dsi drm asix
usbnet ipv6
[   49.809610] CPU: 1 PID: 2328 Comm: insmod Tainted: G           O    4.9.0-hikey-139764-g3e36302a0
621-dirty #1
[   49.819580] Hardware name: HiKey Development Board (DT)
[   49.824876] task: ffff80001580b200 task.stack: ffff800015af8000
[   49.830864] PC is at init_module+0xf8/0x1f0 [mod_init]
[   49.836061] LR is at init_module+0xe8/0x1f0 [mod_init]
[   49.841259] pc : [<ffff000000b71568>] lr : [<ffff000000b71558>] pstate: 00000145
[   49.848716] sp : ffff800015afbc40
[   49.852099] x29: ffff800015afbc40 x28: 00000000024000c0
[   49.857474] x27: 0000000000000124 x26: ffff000008129f68
[   49.862851] x25: 0000000000000001 x24: ffff800014f5abc8
[   49.868227] x23: ffff000000b730d0 x22: ffff800014f5ad80
[   49.873604] x21: 0000000000000000 x20: ffff000000b72370
[   49.878981] x19: ffff000000b73380 x18: 0000000000000010
[   49.884357] x17: 0000aaaadb4f02b0 x16: 0000000000000012
[   49.889734] x15: 0000000000000006 x14: ffff000088e40a27
[   49.895110] x13: ffff000008e40a35 x12: 0000000000000007
[   49.900487] x11: 000000000000016d x10: 0000000005f5e0ff
[   49.905863] x9 : 000000000000016e x8 : 70752064656b6361
[   49.911240] x7 : 62207972746e6520 x6 : ffff000008e40a53
[   49.916616] x5 : 0000000000000000 x4 : 0000000000000000
[   49.921993] x3 : 0000000000000000 x2 : 00000000a0033fd6
[   49.927370] x1 : ffff000008081a00 x0 : 0000000000000000
[   49.932745]
[   49.934309] Process insmod (pid: 2328, stack limit = 0xffff800015af8020)
[   49.941073] Stack: (0xffff800015afbc40 to 0xffff800015afc000)
[   49.946885] bc40: ffff800015afbc60 ffff0000080830b8 ffff000000b71470 ffff800015af8000
[   49.954776] bc60: ffff800015afbcd0 ffff00000816521c ffff000000b73080 ffff000008d80000
[   49.962667] bc80: ffff000000b73080 ffff800014f5ad80 ffff000000b73080 ffff800014f5ab80
[   49.970558] bca0: ffff000000b730d0 ffff800014f5abc8 0000000000000001 ffff000008129f68
[   49.978450] bcc0: 0000000000000124 00000000024000c0 ffff800015afbd00 ffff00000812d454
[   49.986341] bce0: ffff800015afbe58 0000000000000001 ffff000000b73080 ffff800014f5ab80
[   49.994232] bd00: ffff800015afbe10 ffff00000812dd78 0000000000000000 0000000000000003
[   50.002124] bd20: 0000aaaadb4dd8d0 0000ffffaf31fcf4 0000000080000000 0000000000000015
[   50.010015] bd40: 0000000000000123 0000000000000111 ffff0000088c2000 ffff800015af8000
[   50.017906] bd60: 000000000003c788 ffff000008b3c088 ffff000000000072 ffff000000000064
[   50.025798] bd80: ffff80000000006e ffff000000b76000 ffff80001511a118 ffff000000b73250
[   50.033689] bda0: ffff0000088d24c0 ffff0000088d24b0 000000007fffffff 0000000000000003
[   50.041581] bdc0: 0000000000000123 ffff0000081dfa18 ffff800015afbe10 0000000000000000
[   50.049472] bde0: 0000000000000000 0000000000000000 0000000000000000 0000000000000000
[   50.057364] be00: 0000000000000000 0000000000000000 0000000000000000 ffff000008082ef0
[   50.065255] be20: 0000000000000000 0000000000000000 ffffffffffffffff 0000000000000000
[   50.073147] be40: ffff800015afbeb0 000000000003c788 ffff00000cb6d000 ffff00000cb6d000
[   50.081038] be60: 000000000003c788 ffff00000cba9088 ffff00000cba8f70 ffff00000cb8d838
[   50.088929] be80: 0000000000003000 0000000000003798 0000000000000000 0000000000000000
[   50.096820] bea0: 0000000000000bd0 0000001a00000019 0000000000000008 0000000000000005
[   50.104712] bec0: 0000000000000003 0000aaaadb4dd8d0 0000000000000000 0000000000000003
[   50.112603] bee0: 0000000000000000 000000000001fd31 0000000000000001 0000000000000001
[   50.120497] bf00: 0000000000000111 fefefefefefefeff 00000000ffffffff 0000000000000030
[   50.128386] bf20: 0000000000000004 0000000000000008 0000ffffaf259a94 0000ffffaf3a1588
[   50.136278] bf40: 0000ffffaf31fcd0 0000aaaadb4f02b0 0000ffffcb3fe1b0 0000aaaaf319f190
[   50.144169] bf60: 0000000000000000 0000aaaadb4dd8d0 0000000000000000 0000000000000002
[   50.152061] bf80: 0000aaaaf319e0d0 0000ffffcb3fe518 0000000000000000 0000000000000000
[   50.159952] bfa0: 0000000000000000 0000ffffcb3fe450 0000aaaadb4d3bd0 0000ffffcb3fe450
[   50.167843] bfc0: 0000ffffaf31fcf4 0000000080000000 0000000000000003 0000000000000111
[   50.175735] bfe0: 0000000000000000 0000000000000000 0000000000000000 0002000000000035
[   50.183624] Call trace:
[   50.186141] Exception stack(0xffff800015afba70 to 0xffff800015afbba0)
[   50.192644] ba60:                                   ffff000000b73380 0001000000000000
[   50.200536] ba80: ffff800015afbc40 ffff000000b71568 0000000000000006 0000000000000006
[   50.208428] baa0: ffff000008e42e4a 000000000000001c ffff000008e40000 ffff000008b39520
[   50.216323] bac0: ffff800015afbb60 ffff0000080ff5a0 ffff000000b73380 ffff000000b72370
[   50.224210] bae0: 0000000000000000 ffff800014f5ad80 ffff000000b730d0 ffff800014f5abc8
[   50.232102] bb00: 0000000000000001 ffff000008129f68 0000000000000000 ffff000008081a00
[   50.239993] bb20: 00000000a0033fd6 0000000000000000 0000000000000000 0000000000000000
[   50.247889] bb40: ffff000008e40a53 62207972746e6520 70752064656b6361 000000000000016e
[   50.255776] bb60: 0000000005f5e0ff 000000000000016d 0000000000000007 ffff000008e40a35
[   50.263668] bb80: ffff000088e40a27 0000000000000006 0000000000000012 0000aaaadb4f02b0
[   50.271564] [<ffff000000b71568>] init_module+0xf8/0x1f0 [mod_init]
[   50.277808] [<ffff0000080830b8>] do_one_initcall+0x38/0x128
[   50.283441] [<ffff00000816521c>] do_init_module+0x5c/0x1b8
[   50.288992] [<ffff00000812d454>] load_module+0x1a44/0x20b8
[   50.294540] [<ffff00000812dd78>] SyS_finit_module+0xd8/0xe8
[   50.300176] [<ffff000008082ef0>] el0_svc_naked+0x24/0x28
[   50.305554] Code: 58000802 52800000 f9400661 b9400042 (b9000022)
--[ end trace 13

A:

Found my error. I worked on the "local variable" instead of the point. This fixed it:
*ptep = clear_pte_bit(*ptep, __pgprot((_AT(pteval_t, 1) << 7)));

Rest of the code was correct


Q:

jQuery slider help

I am creating my own custom content slider and am wondering what the best way to go about it is using jQuery.
I want to have two buttons next/previous. When the user clicks next the current slide will slide to the left and the new slide will show.
How should I go about doing this in jQuery? I would use a plugin but they are so annoying when it comes to customization.
Code so far:

<button class="next">Next</button>

<button class="previous">Previous</button>

A:

This is my approach: http://jsfiddle.net/UpDcS/3/
What i am doing is (basically): All items are hidden by default and positioned absolutely in the viewport. I created two functions that wrap the logic of getting the next/previous element in the slideshow so it can be scrolled endlessly. The sliding is achieved by setting the new item to the left/right of the current item and moving both items by 100% to that side. After this, the (now) old item is hidden again. I hope you can figure out the details. This should be a pretty good starting point.


Q:

What exactly is D-Cinelike?

My DJI Mavic Air drone has the ability to shoot video footage in either standard mode or “D-Cinelike”.
Is D-Cinelike just a flatter colour profile with less contrast (to capture more detail in shadows and highlights)? What caveats should one be aware of when shooting in this mode or working with it in post-production?

A:

"Is D-Cinelike just a flatter colour profile with less contrast (to capture more detail in shadows and highlights)?" Yes.  It's closer to log color rather than linear.  The big thing to be aware of in post production is to make sure you grade it to where you want it to be and possibly use their LUT to convert back towards Rec 709 depending on what you are looking for.
If you don't want to have to work on your color, don't shoot D-Cinelike.  If you want the best recovery in highlights and more ability to adjust the tone, shoot D-Cinelike and spend the time to apply a color grade to your liking.  (D-cinelike isn't so great in shadow unfortunately).
Personally, I always shoot D-log on my Mavic 2 Pro, which is similar in concept to D-Cinelike, though it has better shadow recovery and a bit more balanced, though slightly less cinematic looking without more effort to tweak it, but last I knew, D-log isn't available on the Mavic Air.
If you want to see some good samples, this youtube video seemed like it had relatively good comparisons of the 3.


Q:

Creating a simple window with simple controls in c++ and OpenGL

How do i just create a window with just some controls like menus , check button , radio button , scroll bar ..just with c++ and OpenGL?

A:

It depends.
1) You can't use any external libraries.
In this case you would need to create whole framework for creating controls, handling events, hit tests, state changes... Shortly speaking, you would need to write a GUI library like Qt or wxWidgets, but with all controls drawing implemented in OpenGL.
2) You can use 3rd party libs.
Well, simply read the spec and use them. Examples:
GiGi
GLUI
Also, you may want to read this: OpenGL Forum
However, if you don't have to use OpenGL-based solution, I would suggest you use wxWidgets. I've been using it for years. It's my favourite cross-platform GUI library with solid support, quite big community and reliable, up-to-date online/offline documentation.


Q:

MYSQL Lookup Full Word against Part Word

Is it possible to do the following in myself for example with postcodes. I have the postcode AA1 2AA in my table there is a record AA1*. Is it possible to match this up? Reverse of the query below
SELECT * FROM destination WHERE postcode LIKE '%AA12AA%'

Records in table
ID Postcode
1  AA1*
2  AB1*
3  AB2*
4  AC1*

A:

I believe you are looking for:
SELECT *
FROM destination
WHERE 'AA12AA' like replace(postcode, '*', '%');

That is, reverse the like and use the correct wildcard for SQL.


Q:

Is the topology generated by the union of a chain of paracompact topologies paracompact?

Let $X$ be a set and let ${\frak T}$ be a collection of paracompact topologies on $X$ such that for any $\tau, \tau'\in {\frak T}$ we have $\tau\subseteq \tau'$ or $\tau'\subseteq \tau$. Let $\sigma$ be the topology having $\bigcup {\frak T}$ as a base.
Is $(X,\sigma)$ necessarily paracompact?
EDIT. Thanks to Tomek Kania for observing that $\bigcup {\frak T}$ need not be a topology.

A:

Here is an easy counterexample under the Continuum Hypothesis, where the union of the topologies generates a non-normal topology.
Take the upper half plane $\mathbb{H}$ (including $x$-axis) and enumerate $\mathbb{R}$ as $\langle x_\alpha:\alpha<\omega_1\rangle$.
Now let topology $\mathcal{T}_\alpha$ be generated by the normal topology plus the tangent disk neighbourhoods at all points $(x_\beta,0)$ for $\beta\le\alpha$.
Each topology $\mathcal{T}_\alpha$ is still separable and metrizable (regular with a countable base) but the union generates the Tangent Disk topology, which is not (even) normal.
This example can be made `real' as follows: take an injective sequence $\langle x_\alpha:\alpha<\omega_1\rangle$ of real numbers and consider the subset $X$ of $\mathbb{H}$ consisting of all points above the $x$-axis and the points $(x_\alpha,0)$ on the x-axis.
Perform exactly the same construction as above; the intermediate topologies are again separable and metrizable and their union generates the Tangent Disk topology on $X$. In this topology the set $\{(x_\alpha,0):\alpha<\omega_1\}$ is closed and discrete but there is no pairwise disjoint family $\{U_\alpha:\alpha<\omega_1\}$ of open sets such that $(x_\alpha,0)\in U_\alpha$ for all $\alpha$. So the space is not collectionwise Hausdorff and hence not paracompact.