ng-click event not working with ocLazyLoad

Question: I have a basic Angular.js app which is using ocLazyLoad for loading the application files. I am using the skeleton of the sbAdminApp template.
My problem is that when I use a template with an ng-click event, the click event is not being fired. It is not a scope problem because when I print the function's content to the view it is shown.
Here is some of my code:
For loading the files using ocLazyLoad:
$stateProvider.state('dashboard.importLotteries', {
    templateUrl: '/Scripts/app/views/importLotteries.html',
    url: '/importLotteries',
    controller: 'LotteriesCtrl',
    resolve: {
        loadMyFiles: function ($ocLazyLoad) {
            return $ocLazyLoad.load({
                name: 'sbAdminApp',
                files: [
                    '/Scripts/app/scripts/services/lotteriesService.js',
                    '/Scripts/app/scripts/controllers/lotteries.js'

                ]
            })
        }
    }
}

This is the importLotteries.html template file:

                Import Lotteries

            {{importLotteries.toString()}}

                <input type="button" ng-click="importLotteries()"  value="Import"/>

and this is the controller's code:
'use strict';
angular.module('sbAdminApp')
  .controller('LotteriesCtrl', function ($scope, lotteriesService) {

      $scope.importLotteries = function () {

          alert("importing");
          $scope.importStatus = "Loading...";
      };

  });

The result view looks like this:

So as you can see, the function exists on the scope but the click event is not firing and I don't get any errors.
I tried to search for a solution online for sometime now and couldn't find one, so any help will be greatly appreciated!
After further investigating the issue, I see that the event function (importLotteries) is undefined in the scope, but when I change the value to a string instead of a function the scope value is correct.
Comment: possible for you to make a fiddle/plnkr of your problem?
Comment: @HanletEscaño No it shouldn't. You only add a prefix if you are using controllerAs syntax, which he isn't - and you probably wouldn't want to name it as $scope anyways.       Shai, how do you know it isn't firing? Have you set a breakpoint in it?
Comment: @Shai How do you know it's ocLazyLoad problem? Did you try to load the files(lotteriesService.js, lotteries.js) earlier rather than loading them with ocLoazyLoad?
Comment: @matmo , yes I set a breakpoint and I added an alert command which is not executed.
Comment: @ShaiAharoni I think you can share a plnkr or a fiddle of your problem, it will be easier to debug
Comment: @ShaiAharoni, can you include full html of your view, so that how you've implemented the controller in the view is clear.
Comment: I couldn't find a solution for this problem so I decided to remove ocLazyLoad from my project. Now everything is working ok
Answer: Try attaching a ng-href or href to the link and it'll be fired.
<input type="button" ng-click="importLotteries()" ng-href='#' value="Import"/>

Source:
[1] Angular ng-click with call to a controller function not working
Comment: But he's not using the link, but the input, it shouldn't have the href attribute or ng-href


Suppose that $A$ is $3\times 3$ and $\text{rank}(I-A) = 2$ and $\text{rank}(-I-A) = 1$. Then A is diagonalizable.

Question: I'm asked to determine the truth or falsity of the following statement:
Suppose that $A$ is $3\times 3$ and $\text{rank}(I-A) = 2$ and $\text{rank}(-I-A) = 1$. Then A is diagonalizable.
I think the answer is yes but I need help confirming this answer.
The most intuitive first step I could think of was given that that $\text{rank}(I-A) = 2 <3$ and $\text{rank}(-I-A) = 1 < 3$, this means that $\det(I-A) = \det(-I-A) = 0$ and thus we have eigenvalues $\pm 1$, with two distinct eigenvectors for $\lambda = -1$. I would think that because the matrix is $3\times 3$ and that we have three distinct eigenvectors, thus $A$ is diagonalizable.
I wasn't satisfied with this answer, because I thought the characteristic polynomial is not given, thus how does one know the algebraic multiplicity of the eigenvalues? Sure, if the eigenvalues were $-1,-1,1$ then it would be true. It would also work if there were a third distinct eigenvalue $\lambda \not= \pm 1$, but what if the eigenvalues were $1,1,-1$?
The fact that $\text{rank}(-I-A) = 1$ means that the columns of $A+I$ are all multiples of one another. Thus I'm guessing the matrix $A$ has to look something like
$$A=\begin{pmatrix}
h\cdot a_{11}-1 & k\cdot a_{11} & l\cdot a_{11} \\
h\cdot a_{21} & k\cdot a_{21}-1 & l\cdot a_{21} \\
h\cdot a_{31} & k\cdot a_{31} & l\cdot a_{31}-1 \\
\end{pmatrix}$$
for $h,k,l \in \mathbb{R}$.
Although taking the determinant might seem complicated at first, many terms end up cancelling and $\det(A) = h\cdot a_{11} + k\cdot a_{21} + l\cdot a_{31} -1$, and since I'm assuming the characteristic polynomial is $-(t-1)^2\cdot(t+1) = -t^3 + t^2 + t -1 = -t^3 + \text{trace}(A)t^2 + t +\det(A)$, $\det(A)=-1$. Thus $h\cdot a_{11} + k\cdot a_{21} + l\cdot a_{31} =0$, but $\text{trace}(A) = h\cdot a_{11} + k\cdot a_{21} + l\cdot a_{31} - 3 = 1$, while also $h\cdot a_{11} + k\cdot a_{21} + l\cdot a_{31} = 4$ and we have a contradiction. Thus we can't have the case where the eigenvalues are $1,1,-1$ and $\text{rank}(-I-A) = 1$.
Am I missing something? I guess if my answer is complete, my question is, is there a quicker way to get the conclusion building on the concept of $\text{rank}(-I-A)=1$? Skipping the calculations above.
Any help is appreciated (:
Comment: The rank of $-I-A$ is $1$ implies that the nullity of $-I-A$ is $2$. Therefore $-1$ is an eigenvalue of $A$ of *geometric* multiplicity $2$. Likewise $1$ is an eigenvalue of $A$ of geometric multiplicity $1$.
Answer: Your idea is correct, you mentioned that $\lambda=-1$ has two distinct eigenvectors and $\lambda=1$ has only one eigenvector.
Call $\gamma_\lambda$ the geometric multiplicity of $\lambda$ and $\mu_\lambda$ its algebraic multiplicity, then the following inequality holds for every eigenvalue:
$$1\leq \gamma_\lambda\leq\mu_\lambda\leq3,$$
or in general $n$ when we have an $n\times n$ matrix. If one eigenvalue had algebraic multiplicity $3$, say $\lambda=-1$, then its geometric multiplicity would also be 3 and thus $\lambda=1$ would not have any geometric multiplicity.
You also ask, what would happen if there was a different eigenvalue, but it's impossible for there to be another eigenvalue. As the matrix is $3\times 3$, it can have at most three eigenvalues and the sum of their multiplicities should be less than or equal to $3$. If $\lambda$ was another eigenvalue, then $\gamma_\lambda$ is at least $1$ and summing
$$\gamma_\lambda+\gamma{-1}+\gamma_1\geq1+2+1=4$$
we get an impossibility. I'd rather not work with the determinant because most of this facts can be worked just using the dimensions of certain spaces.
If you'd like me to elaborate more, let me know :)
Answer: Yes.
From $\text{rank}(I-A)=2$ and $\text{rank}(-I-A)=1$, we can get $1$ and $-1$ are the eigenvalues of $A$.
Use $\text{Jordan-Form-Theory }$,we can get the number of Jordan block with -1 as the  diagonal elements is $2$ and the number of Jordan block with 1 as the  diagonal elements is $1$.
$A$  is  $3\times 3$,so  there exists an invertible matrix P such that $P^{-1}AP=\left( \begin{matrix}
 1&  0&  0\\
 0&  1&  0\\
 0&  0&  -1\\
\end{matrix} \right) $.


How do you add a custom field to a menu link in Drupal 7?

Question: I am currently using the menu module (Drupal 7 Core) to manage my menus. A menu link consists on only a title and a description. I would like to add an image field as well as another text field. I have considered using taxonomy rather than menu links, but I still want the capability to add a basic page to a menu.
I have looked into a module called Menu Attributes http://drupal.org/project/menu_attributes, but it doesn't add an image field.
Answer: Menu icons should do what you're after.

This module allows you to upload an image in the menu-item's configuration form.
After uploading the image, the icon data will be added to the menu link's
options array.
Comment: @tytho Nothing at the moment but it looks like [menu links will be entities in Drupal 8](http://drupal.org/node/916388) so you'll be able to attach fields to them at some point in 2013 ;)
Comment: My Android has FUBARed the formatting of this answer.  If someone could fix it I'd be grateful =)
Comment: This will do! Although, I would have liked to customize the min/max dimensions, but I does allow me to use an image style which is just fine. Bonus points for a module that will allow me to add more fields to a menu item (such as a field collection or text area)


web config string with a link asp.net webform

Question: I have a key in my webconfig
<add key ="ForgotPasswordPageNonMemberMessage" value ="You are not a full member and you will not be able to login. Please click here to discover more about full membership."/>

I would like click here to take me to my link e.g., www.abeprakash.com
Is this possible?
In the code I am simply using
lblFailureMessage.Text = ConfigurationManager.AppSettings("ForgotPasswordPageNonMemberMessage")

Comment: I think this question is pretty similar: https://stackoverflow.com/questions/16196680/is-it-possible-to-include-hyperlink-in-app-config-key-value.  One answer suggests a string replacement technique.  Not sure if there's something more elegant.
Comment: What type of control is `lblFailureMessage`?
Comment: label as i need to show some other messages based on various conditions.
Comment: I have seen that link, I don't think it is a elegant solution.
Comment: Why can't you just embed the hyperlink in the web.config? You'd just have to encode it.
Comment: I am not sure how to do it
Answer: For now this is what I have done
<add key ="ForgotPasswordPageNonMemberMessage" value ="You are not a full member and you will not be able to login. To discover more about full membership"/>

 <asp:Label ID="ForgotPasswordPageMessage" runat="server"></asp:Label>
                    <asp:Label ID="MyWebsite" runat="server">cilck here</asp:Label>

just simply show and hide MyWebsite based on the condition when ForgotPasswordPageMessage is shown.
Please suggest if you have any better way of doing this.


Forging a stack trace in Java

Question: When you use RMI in Java the remote stack trace of an exception will be prepended when you receive it, somewhat like this:
ERROR Client received error when doing stuff:
myapp.FooBarException: bla
 at server.myMethod()
 at rmi.callHandler() // and now, on the next line comes the client
 at rmi.sendCall();
 at client.doServerMethod()
 at Thread.run()

How is that kind of stacktrace "forgery" done?

What do I want it for (apart from just being iterested)? Well, it would help me if I could do this:
outer() {

  thread = new Thread(...
      inner();
      // inner() throws
      // RuntimeException
      //  at inner();
      //  at Runnable.run();
      //  at Thread.run();
      //  at outer();
      //  at lalalala();
      //  ...

  ).start();

  thread.join();

}

And make it so that an exception thrown in inner() would have outer() (and methods lower down the chain) in the stacktrace as well, for logging purposes.
Answer: It is kind of easy:
Throwable has methods getStackTrace() and setStackTrace().
From one of my projects (non open-source, but maybe I'll some day open the remote call engine):
    /**
     * Setzt den Stack-Trace zusammen. Das untere Ende (tiefer in der
     * Aufrufhierarchie, am Anfang des Arrays/der Ausgabe) ist das,
     * welches im Throwable schon drin ist, das obere Ende wird aus
     * dem aktuellen Stack genommen. Dazwischen
     * kommt ein "Remote-Aufruf-Markierer".
     */

Translated for your convenience:

Merges the stack trace. The lower end (deeper in the call hierarchy, at the
  end of the array/the output) is what already is in the stack, the upper end
  will be taken from the current stack. Between them we will put an
  Remote call marker.

    private void mergeStackTraces(Throwable error)
    {
        StackTraceElement[] currentStack =
            new Throwable().getStackTrace();
        int currentStackLimit = 5; // TODO: raussuchen
        StackTraceElement[] oldStack =
            error.getStackTrace();
        StackTraceElement[] zusammen =
            new StackTraceElement[currentStack.length - currentStackLimit +
                                  oldStack.length + 1];
        System.arraycopy(oldStack, 0, zusammen, 0, oldStack.length);
        zusammen[oldStack.length] =
            new StackTraceElement("══════════════════════════",
                                  "<remote call %" +callID+ ">",
                                  "", -3);
        System.arraycopy(currentStack, currentStackLimit,
                         zusammen, oldStack.length+1,
                         currentStack.length - currentStackLimit);
        error.setStackTrace(zusammen);
    }

(On the server side, I'm already cutting off the parts of the stack trace which do not relate to the method call itself, i.e. everything related to the message handling.)
This results in a combined stack trace like this:
java.lang.SecurityException: Das Passwort für Nutzer »Paul« ist falsch.
        at de.fencing_game.db.userdb.Db4oUserDB.login(Db4oUserDB.java:304)
        at de.fencing_game.server.impl.StandardServers$SSServer$1.run(StandardServers.java:316)
        at de.fencing_game.server.impl.StandardServers$SSServer$1.run(StandardServers.java:314)
        at java.security.AccessController.doPrivileged(Native Method)
        at de.fencing_game.server.impl.StandardServers$SSServer.login(StandardServers.java:313)
        at de.fencing_game.transport.server.ServerTransport$ConnectionInfo$4.login(ServerTransport.java:460)
        at ══════════════════════════.<remote call %2>()
        at $Proxy1.login(Unknown Source)
        at de.fencing_game.gui.basics.LoginUtils.login(LoginUtils.java:80)
        at de.fencing_game.gui.Lobby.connectTo(Lobby.java:302)
        at de.fencing_game.gui.Lobby$20.run(Lobby.java:849)
        at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:226)
        at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:647)
        at java.awt.EventQueue.access$000(EventQueue.java:96)
        at java.awt.EventQueue$1.run(EventQueue.java:608)
        at java.awt.EventQueue$1.run(EventQueue.java:606)
        at java.security.AccessController.doPrivileged(Native Method)
        at java.security.AccessControlContext$1.doIntersectionPrivilege(AccessControlContext.java:105)
        at java.awt.EventQueue.dispatchEvent(EventQueue.java:617)
        at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:275)
        at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:200)
        at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:190)
        at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:185)
        at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:177)
        at java.awt.EventDispatchThread.run(EventDispatchThread.java:138)

I suppose the RMI system does something quite similar (just without the ══════════════════════════).

Edit:
For your usecase, you would have to save the stack trace of the outer thread when the inner thread is started, then in the run method catch the exception and append the outer stack trace to the stack trace of the inner exception. I would really recommend putting some type of separator, though.
Comment: I would like the inner exception to have the stacktrace of the outer appended, even if it's caught by something deep in the inner thread. I guess that's not possible, since I can't apply a custom exception.
Comment: Your catching code has to do this (or the exception must do this itself before throwing, overriding fillInStackTrace or doing this in the constructor). Neither of this will work for unknown exceptions thrown and caught by unknown code.
Comment: I like that you have 3 languages in one code snippet - English, German and Java :)
Answer: You create a customized exception that extracts the stacktrace from one exception and adds it to another via setStackTrace().
It's useful for doing things like this or maintaining a stacktrace when you don't want to maintain a hard reference to the caused by exception.  This is handy when passing exception info from server to client where the root cause exception classes may not be present, thus causing serialization issues.
Answer: I would like to suggest an alternative solution, which isn't what the OP asked for, but may be better for some people that have a very similar question. Like me.
I suggest creating a throwable in outer and add the throwable from inner as the cause of the throwable from outer. This will also capture the point at which a thread switch was made... which may be useful to avoid confusion about the stack trace. Furthermore, thread information can be stored in this throwable created in outer that may help even more.
Here's some code.
public class StackCaptor {
    public static Runnable capture(Runnable runnable) {
        // Capture the stack
        final Throwable prison = new Throwable();
        // Wrap run method to create a new throwable representing the creator of the original Runnable.
        return new Runnable() {
            @Override
            public void run() {
                try {
                    runnable.run();
                } catch (Throwable originalThrowable) {
                    RuntimeException callingThreadsException = new RuntimeException(originalThrowable);
                    callingThreadsException.setStackTrace(prison.getStackTrace());
                    throw callingThreadsException;
                }
            }
        };
    }
}

Then use the code like this:
// This code has not be compiled or tested... You may need to use your
// smarts to get it working, but it should give you an idea.
public void outer() {
    Thread thread = new Thread(StackCaptor.capture(new Runnable() {
        public void run() { throw new RuntimeException("my ex"); }
    }));
    thread.start();
}

Forging a stack trace in Java


Debug help - ArrayIndexOutOfBoundsException

Question: My program compiles correctly but I get the same message when I try and run it:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1 error on my calendar program

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package displaycalendars;

import java.util.Calendar;
import java.util.GregorianCalendar;

public class DisplayCalendars {

  public static void main(String[] args){
    Calendar calendar = new GregorianCalendar
            (Integer.valueOf(args[1]),
            Integer.valueOf(args[0])-1,1);

    printHeader(calendar);
    printData(calendar);
  }

  public static void printHeader(Calendar calendar){

    int month = calendar.get(Calendar.MONTH)+1;

    String monthName = "";

    switch(month){
      case 1: monthName="January";
        break;
      case 2: monthName="February";
        break;
      case 3: monthName="March";
        break;
      case 4: monthName="April";
        break;
      case 5: monthName="May";
        break;
      case 6: monthName="June";
        break;
      case 7: monthName="July";
        break;
      case 8: monthName="August";
        break;
      case 9: monthName="September";
        break;
      case 10: monthName="October";
        break;
      case 11: monthName="November";
        break;
      case 12: monthName="December";
        break;
    }

    System.out.println(" "+monthName+ ", " +calendar.get(Calendar.YEAR));
    System.out.println("--------------------");
    System.out.println("Sun Mon Tue Wed Thu Fri Sat");
  }

  public static void printData(Calendar calendar){
    int dayinWeek=calendar.get(Calendar.DAY_OF_WEEK);

    for (int i = 1; i< (dayinWeek); i++)
    {
      System.out.print(" ");
    }
    for (int i = 1; i <
        (Calendar.DATE); i++){
      System.out.print("\n");
      calendar.add(Calendar.DATE,1);
    }
    System.out.printf("%4d",calendar.get(Calendar.DATE));
  }
}

Comment: The `main` method expects arguments. Are you providing them?
Comment: @Marvin Probably not since the code doesn't contain any other arrays.
Answer: Explanation
Check the stacktrace provided along the error message. It is pointing to the line where you write
Calendar calendar = new GregorianCalendar
        (Integer.valueOf(args[1]),
        Integer.valueOf(args[0]) - 1, 1);

An ArrayIndexOutOfBoundsException is thrown whenever you try to access an array at an index outside of its bounds. That means if the an array contains, let's say, 6 elements and you access the 7-th element. Or if you try to access the element number -1 (which of course does not exist). From its documentation:

Thrown to indicate that an array has been accessed with an illegal index. The index is either negative or greater than or equal to the size of the array.

In your case you are accessing
args[1]
// and
args[0]

and you get an exception since args does not contain an element at index 0 nor at index 1. It's probably empty. You can check this by using args.length like
System.out.println("The size is: " + args.length);

Command-line arguments
The args argument of a main method is automatically created by the JVM and the machine passes arguments you have provided at creation of your application, so called command-line arguments.
This is usually inside your console where you started the app with some kind of
java DisplayCalendars

command. You can then pass arguments like
java DisplayCalendars firstArgument secondArgument

After that the JVM automatically assigns args with the given arguments:
args[0] => firstArgument
args[1] => secondArgument

If you use an IDE you can probably also set some command-line arguments, somewhere in the settings (in Eclipse it's inside the run configuration settings).
More on this at the official Oracle tutorial.


Dot product of two vectors

Question: How does one show that the dot product of two vectors is $ A \cdot B = |A| |B| \cos (\Theta) $?
Comment: The question is unclear. Do you mean "How does one show that the dot product..."?
Comment: Yes same meaning, thanks.
Comment: Isn't this the *definition* of the dot product? Do you have another definition for the dot product in mind, and want to show that that definition is equivalent to this one? Because that's a more sensible question.
Answer: Think about a triangle with sidelengths $|\textbf{a}|,|\textbf{b}|,|\textbf{c}|$. Then we can use the law of cosines.
$$
\begin{align}
|\textbf{c}|^2&=|\textbf{a}|^2+|\textbf{b}|^2-2|\textbf{a}||\textbf{b}| \cos \theta \\
\implies 2|\textbf{a}||\textbf{b}| \cos \theta &= |\textbf{a}|^2+|\textbf{b}|^2-|\textbf{c}| = \textbf{a}\cdot \textbf{a} + \textbf{b} \cdot \textbf{b} - \textbf{c}\cdot \textbf{c}
\end{align}
$$
By the properties of the dot product and from the fact that $\textbf{c}=\textbf{b}-\textbf{a}$ we find that
$$
\begin{align}
  \textbf{c}\cdot \textbf{c} &=(\textbf{b}-\textbf{a}) \cdot (\textbf{b}-\textbf{a}) \\
  &=(\textbf{b}-\textbf{a})\cdot \textbf{b} - (\textbf{b}-\textbf{a}) \cdot \textbf{a} \\
  &= \textbf{b}\cdot \textbf{b} - \textbf{a}\cdot \textbf{b} - \textbf{b}\cdot \textbf{a} + \textbf{a}\cdot \textbf{a}.
\end{align}
$$
By substituting $\textbf{c}\cdot \textbf{c}$, we get
$$
\begin{align}
  2|\textbf{a}||\textbf{b}| \cos \theta &= \textbf{a}\cdot \textbf{a} + \textbf{b} \cdot \textbf{b} - (\textbf{b}\cdot \textbf{b} - \textbf{a}\cdot \textbf{b} - \textbf{b}\cdot \textbf{a} + \textbf{a}\cdot \textbf{a}) \\
  &=2 \textbf{a}\cdot \textbf{b}.
\end{align}
$$
Answer: One way of showing this requires taking a Geometric look at stuff:
Think of $\vec{a},\vec{b}$ as the vertices of a triangle with one corner in the origin
and sides of length $|\vec a|,|\vec b|,|\vec{a-b}|$. Now, use the Law of cosines, and inner product properties (over $\mathbb R$) to calculate $|\vec{a-b}|$:
The law of cosines gives you:
$$|\vec{a-b}|^2=|\vec{a}|^2+|\vec{b}|^2-2|\vec{a}||\vec{b}|\cos\theta(a,b)$$
Inner product gives:
$$|\vec{a-b}|^2=\langle\vec{a-b},\vec{a-b}\rangle=|\vec{a}|^2+|\vec{b}|^2-2\langle\vec{a},\vec{b}\rangle$$
from there on it's an easy proof (I left you the technical details).
Hope that helps
Comment: Wow, `\vec{a-b}` looks bad. Yet another reason to prefer either underline or bold to denote vectors (`\overrightarrow{a-b}` doesn't look quite right either)

Dot product of two vectors


Cannot Find a Symbol

Question: The CalculatorDemo1 class
package calc;
public class CalculatorDemo1{
  public static void main(String args){
    int integer1 = 1;
    int integer2 = 2;
    Calculator a = new Calculator(integer1, integer2);
    a.sum();

  }
}

The Calculator class
package calc;

public class Calculator{
  int left, right;

  public Calculator(int left, int right){
    this.left = left;
    this.right = right;

  }
  public void sum(){
    System.out.println(this.left + this.right);
  }
}

So these codes exist in different files. I tried to compile these two files. One with the constructor compiles, but the other doesn't. And, it spits these errors.
CalculatorDemo1.java:6: error: cannot find symbol
    Calculator a = new Calculator(integer1, integer2);
    ^
  symbol:   class Calculator
  location: class CalculatorDemo1
CalculatorDemo1.java:6: error: cannot find symbol
    Calculator a = new Calculator(integer1, integer2);
                       ^
  symbol:   class Calculator
  location: class CalculatorDemo1
2 errors

I don't think this was the problem of the return type. It didn't fix the problem. Also, I checked my identifiers whether I messed up my spelling or not, but there was not any of those. I didn't find any answer from commonly asked question neither. How should I fix this issue?
Comment: You've likely not added the Calculator class to the classpath. Try adding it with the `cp` option
Comment: I'm not sure problem related with @us the problem also related with your constructor declaration
Comment: Is current directory of console set to `calc` folder? Compiler (`javac`) needs to know location of *packages* holding classes you are using. You set it by `-classpath` or `-cp` parameter. So if you are inside `calc` you can try with `javac -cp .. CalculatorDemo1.java`, or move one directory above and call `javac -cp . calc/CalculatorDemo1.java`.
Comment: What command did you use to compile your code? From which location?
Comment: javac Calculator.java and javac CalculatorDemo1.java and Calculator.java compiled, but javac CalculatorDemo1.java caused the error above. I fixed the constructor problem a while ago, and it doesn't work still.
Comment: You are probably doing the build incorrectly.  When I do the build correctly the code compiles.  (It doesn't run because you still have an error in the code.  But you can work that out for yourself when you get to it!)
Comment: What if I erase package calc, and just put these two files at the same time with a folder called Java? Do I need to mention package necessarily just to make sure they are correlated?
Comment: DON"T EVER create classes without package. If you will want to distribute such classes as Jar files and you will want to use that Jar in your other projects, you wouldn't be able to `import` such classes there.
Answer: The problem  related with your constructor declaration. Constructors don't have any return type. So, your Calculator method is not a constructor. when you try the instantiate,
Calculator c = new Calculator(5,7);//can't find true ctor.
Calculator c1 = new Calculator();//it is ok
public  void Calculator(int left, int right){ //delete void
    this.left = left;
    this.right = right;
}

Comment: I deleted it, but it is still causing a problem.
Comment: CalculatorDemo1.java:6: error: cannot find symbol
    Calculator a = new Calculator(integer1, integer2);
    ^
  symbol:   class Calculator
  location: class CalculatorDemo1
CalculatorDemo1.java:6: error: cannot find symbol
    Calculator a = new Calculator(integer1, integer2);
                       ^
  symbol:   class Calculator
  location: class CalculatorDemo1
2 errors
Chanwooui-MBP:java chanwookim$

Cannot Find a Symbol


Problema ao comparar horas

Question: Na comparação de horários tenho na base de dados registado o horário de abertura e fechamento de uma estabelecimento. Estou a ter um problema na hora de comparar o horário para ver se o estabelecimento esta aberto ou fechado, está-me sempre a aparecer como aberto quando já passou a hora.
<?php
$horario = strtotime(date('H:i'));
$result_horario_estado=mysql_query("select * from horarios where id_mae='".$row->id."'");
$row_horario_estado=mysql_fetch_array($result_horario_estado);

$abertura   = strtotime($row_horario_estado['horario_abertura']);
$fechamento = strtotime($row_horario_estado['horario_fechamento']);

if($horario >= $abertura || $horario <= $fechamento) {
?>

Aberto

<?php
} else {
?>

Fechado Agora

<?php
}
?>

Comment: Eu pessoalmente prefiro trabalhar com `gmt` (`gmdate(...)`) e converter as horas conforme "a região" ou preferencia do usuário. Se você usar `date()` poderá ter muitos problema com fuso horários e servidores "mal configurados". Eu tenho um serviço VPS e houve alguns problema no upgrade, simplesmente tive problema com várias coisas, inclusive o horário. Me corrijam eu tiver falado algo errado.
Comment: Cara incluir isso: date_default_timezone_set('America/Sao_Paulo'); Dependendo da sua localização... tenta dar um `echo` na sua hora atual se está batendo direitinho.
Answer: Você precisa que as duas condições sejam atendidas:
if($horario >= $abertura && $horario <= $fechamento){
            //  VEJA --- ^^

O && no lugar do || garante isso. No seu código, basta uma das condições para que entre no if, causando a exibição de mais eventos do que você gostaria.
Comment: Use `echo date_default_timezone_get();` para ver o fuso horário do servidor.
Comment: Já tinha testado dessa forma mas agora assim fica-me sempre como fechado
Comment: Qual é o formato das datas no seu banco?
Comment: Formato está como Varchar(255)
Comment: estou a fazer por horário neste formato H:i
Comment: Coloquei uma imagem com a estrutura da base de dados dos horaios
Comment: É provável que o servidor trabalhe em UTC, mas as suas horas estão em outro fuso.
Comment: Fuso Horario Europe/Lisbon
Comment: Me enganei, como tudo usa `strtotime`, fica tudo no mesmo fuso horário. Devia funcionar, veja só: http://ideone.com/y71gaf (altere os horários de inicio/fim para testar)
Comment: Realmente ai no exemplo funciona direitinho não sei por que será eu também achei que estava tudo bem até que decidi por aqui para ver se encontramos o gato
Comment: Mas aqui estive a ver e não encontro nenhum erro continua a ficar sempre como fechado
Answer: cara, analisa seu código.
Você tem abertura as 14 e fecha as 2.
Você tem que considerar isso. 14 é maior que 2.
<?php
$horario = strtotime('1:00');
$abertura = strtotime('22:00');
$fechamento = strtotime('7:00');

if ((
        $abertura < $fechamento && $horario >= $abertura && $horario <= $fechamento
        ) || (
        $abertura > $fechamento && ($horario >= $abertura || $horario <= $fechamento)
        )) {
    echo 'aberto';
} else {
    echo 'fechado';
}

Comment: Funcionou certinho valeu pela ajuda de todos
Comment: É verdade, eu não havia prestado atenção nesses dados.

Problema ao comparar horas


Async/Await retornando Promise{}

Question: const url = 'http://files.cod3r.com.br/curso-js/funcionarios.json'
const axios = require('axios')

const busca = () =>{
        return new Promise((resolve, reject) =>{
            try{
                const funcionarios = axios.get(url).then(resp => resp.data)
                resolve(funcionarios)
            }
            catch(e){
                reject(e)
            }
        })
    }

    async function getFuncionarios(){
        const funcionarios = await  busca()
        return funcionarios
    }

    const fcs = getFuncionarios()
    //fc deveria vir carregado com todos os funcionarios da url, mas só vem o Promise{<pending>}.Simplesmente não tem como ?

Comment: Assim como você usou `await` em `await  busca()` você também deveria usar em `const fcs = await getFuncionarios()`, mas o lugar aonde chama também tem que ser async. Você pode usar then também, mas para isso é importante você entender como funciona callbacks https://pt.stackoverflow.com/q/45706/3635 e entender com funciona os promises: https://pt.stackoverflow.com/q/119907/3635
Answer: Primeiro, vamos tentar entender certos conceitos.
Como criar e usar Promises?
Em JavaScript, quando vai-se criar uma Promise utilizando o construtor padrão, você passa uma função que tem dois parâmetros:

resolve, que é a função a ser chamada quando a Promise foi concluída com sucesso, isto é, foi "resolvida";

reject, que é a função a ser chamada quando a Promise encontrou um problema e deseja lançar um erro, isto é, foi "rejeitada".

Assim, usando a "API original" das Promises, você lidaria com elas assim:

const myPromise = new Promise(function(resolve, reject) {
  // Tenta gerar um número aleatório de 1 a 20
  const randomNumber = Math.floor(Math.random() * 20 + 1);

  // Após 2 segundos...
  setTimeout(function() {

    // Se o número gerado for ímpar,
    // "resolve" (conclui) a Promise
    // passando o número gerado
    if (randomNumber % 2 == 1) {
      resolve(randomNumber);
    }

    // Se não for ímpar, rejeita a Promise
    // (gera um erro)
    else {
      reject(new Error('even number'));
    }

  }, 2000);
});

// Como não sabemos se a Promise vai
// ser concluída normalmente (resolvida),
// ou se ela vai gerar um erro (vai ser
// rejeitada), iremos esperar pelas duas
// coisas!

myPromise
  // Se ela concluir normalmente, mostramos
  // no console o número que ela nos forneceu
  .then((number) => console.log(number))

  // Se ela gerar um erro, nós jogamos
  // esse erro no console também
  .catch((err) => console.error(err));

Uma coisa a se observar é que, ao invés da chamada encadeada (o .then() seguido do .catch()), você pode chegar a ver algo assim, também:
myPromise.then(
  (number) => console.log(number),
  (err) => console.error(err),
);

Isto é, a passagem da função que lida com o erro, diretamente no .then(), que é algo também válido.
A questão do encadeamento se deve ao fato de o .then() também retornar uma Promise. Desse modo, você consegue até fazer isso:
myPromise.then(function (number) {
  return `Number is: ${number}`;
}).then(
  (text) => console.log(text)
);

Que seria o mesmo que:
const secondPromise = myPromise.then(function (number) {
  return `Number is: ${number}`;
});

secondPromise.then((text) => console.log(text));

Então, recapitulando:

Para criar uma Promise (usando o construtor padrão), você deve passar uma função que recebe como argumento:

Uma função resolve, que será chamada quando tudo ocorrer corretamente;
E uma função reject, que será chamada quando ocorrer algum problema.

Lembrando que, não é necessário ser exatamente esses nomes, isso é só uma convenção para deixar mais compreensível, mais "didático".

Para esperar pelo resultado de uma Promise, usando a API original, você pode simplesmente usar o método .then(), para estabelecer as funções que serão chamadas em resolve e reject, ou você pode usar o .then() para estabelecer a função de resolve e o .catch() para estabelecer a função de reject, através do encadeamento;

E o encadeamento se torna possível, porque o .then() também retorna uma Promise.

Porém, com a utilização dessa API, você pode enfrentar certos problemas na hora de criar funcionalidades que realizam diversas operações assíncronas. Isto é, que utilizam-se de diversas Promises. Vejamos um exemplo:
function getFilteredData(filter) {
  return new Promise(function(resolve, reject) {
    // Eu faço uma requisição a uma suposta API externa de recursos
    const response = fetch('https://example.com/api/resource?filter=' + filter);

    // Como o código irá se basear inteiramente na resposta
    // da API, eu irei colocar praticamente todo o código da
    // da função em si, no `.then()` ou no `.catch()`
    response
      .then((data) => data.json())
      .then(function (json) {
        Promise.all(
          json.map((piece) =>
            new Promise(function (res, rej) {
              const response = fetch(`https://example.com/api/rating?id=${piece.id}`);
              response
                .then((data) => data.json())
                .then((rating) => res({ ...piece, rating }))
                .catch((e) => rej(e));
            })
          )
        )
        .then((newJson) => resolve(newJson))
        .catch((err) => reject(err));
      })
      .catch((error) => reject(error));
  });
}

const filteredData = getFilteredData('some-filter');

filteredData
  .then((data) => console.log(data))
  .catch((err) => console.error(err));

Está vendo a quantidade de encadeamentos que foram feitos? E ainda, o "engarrafamento" que surgiu no código? Claro que, certas coisas (talvez) poderiam ser otimizadas, mas, foi só uma demonstração de como a API das Promises pode deixar as coisas um pouco "complicadas".
Assim, para facilitar a forma como você lida com Promises, foram criados o async e o await.
Uso de async e await
Você pode ver diversos posts aqui no SOpt que também falam sobre eles. Mas, basicamente, podemos dizer que:

O async permite que você marque uma função como uma "realizadora de operações assíncronas" e que, portanto, ela mesma se tornará uma operação assíncrona, o que significa que ela irá gerar uma Promise. Além disso, marcar uma função com async é o que permite a utilização do próprio comando await.

E o comando await é o que permite que você espere que uma Promise seja concluída, para então seguir com um certo código.

Vamos vê-los na prática, utilizando-os para recriar o código acima:
// Marcamos com `async`, então o retorno
// de `getFilteredData` será uma `Promise`
async function getFilteredData(filter) {
  try {
    // Esperamos o resultado da `Promise` gerada por `fetch`
    const response = await fetch('https://example.com/api/resource?filter=' + filter);

    // Esperamos o resultado da `Promise` gerada pelo método `.json()`
    const json = await response.json();

    const data = [];

    for (const piece of json) {
      // Novamente, esperamos o resultado da `Promise` gerada por `fetch`
      const response = await fetch(`https://example.com/api/rating?id=${piece.id}`);

      // E o resultado da `Promise` gerada pelo método `.json()`
      const rating = await response.json();

      data.push({ ...piece, rating });
    }

    // Após "tanta espera", retornamos o resultado final
    return data;
  } catch (err) {
    // Se um erro foi capturado, iremos lançá-lo novamente
    throw err;
  }
}

const filteredData = getFilteredData('some-filter');

// Falaremos sobre isso mais adiante

filteredData
  .then((data) => console.log(data))
  .catch((err) => console.error(err));

Você pode pensar: espera, se estamos lidando com várias Promises, por que só temos um único bloco catch ali?
A resposta é: porque, nesse caso, quando um erro for gerado, seja qual for a operação que o gerar, a execução normal do código será interrompida. Portanto, seja qual for o ponto que o erro for gerado, ele só será gerado 1 vez, porque todos os outros pontos que podem gerar erro já não serão executados. Vejamos mais de perto:
  try {
    // Se gerar erro, o restante não executa
    const response = await fetch('https://example.com/api/resource?filter=' + filter);

    // Se gerar erro, o restante não executa
    const json = await response.json();

    const data = [];

    for (const piece of json) {
      // Se gerar erro, o restante não executa
      const response = await fetch(`https://example.com/api/rating?id=${piece.id}`);

      // Se gerar erro, o restante não executa
      const rating = await response.json();

      data.push({ ...piece, rating });
    }

    return data;
  }

Ou talvez, um exemplo funcional:

let fetchFailsCount = 0;

// A cada vez que `fetch` conseguir
// ser chamado e uma nova `Promise`,
// então, for criada, o contador será
// incrementado
function fetch() {
  return new Promise(function(_, reject) {
    fetchFailsCount++;
    setTimeout(() => {
      reject(`Fetch falhou ${fetchFailsCount} vez(es)`);
    }, 1000);
  });
}

(async function () {
  try {
    // Como o primeiro `fetch` gera
    // um erro, o segundo `fetch` não
    // será chamado
    const response1 = await fetch();
    const response2 = await fetch();

    console.log('Operações bem-sucedidas!');
  } catch (err) {
    console.log('Erro: ' + err);
  }
})();

Portanto, nesse caso, como só ocorrerá 1 erro durante toda a execução do código da função, só se faz necessário 1 bloco catch, capturando, assim, qualquer um dos erros que forem gerados por qualquer uma das operações. Mas, se você quiser lidar com cada erro individualmente, tratando de forma específica, fique à vontade.
Porém, com isso tudo, podemos fazer uma analogia de que o comando await "substitui" o .then(), e o bloco try-catch "substitui" o .catch().

Mas aí, pode-se pensar ainda: e por que, ali no final, não utilizamos o comando await também?
Porque, até onde se sabe, ainda não é totalmente suportada a utilização do await de fora de funções assíncronas (aquelas marcadas com async). Ou seja:

// Por enquanto, ainda pode gerar um erro
const response = await fetch('http://example.com');

Mas, se você quiser realmente utilizar o await, você pode envolver a operação em uma função assíncrona anônima e, ao mesmo tempo, chamá-la, dessa forma:
(async function () {
  const filteredData = await getFilteredData('some-filter');
})();

Funciona como uma alternativa. Mas, já propuseram trazer isso para o ES. Só não sabemos se será, de fato, implementado e se será logo.
Analisando o código e tentando resolver o problema
Assim, vamos ao seu código:
const url = 'http://files.cod3r.com.br/curso-js/funcionarios.json'
const axios = require('axios')

const busca = () => {
  return new Promise((resolve, reject) => {
    try {
      const funcionarios = axios.get(url).then(resp => resp.data)
      resolve(funcionarios)
    }
    catch(e) {
      reject(e)
    }
  })
}

async function getFuncionarios() {
  const funcionarios = await busca()
  return funcionarios
}

const fcs = getFuncionarios()

Na função contida em busca, você "misturou" algumas coisas.
Como você utilizou a API original para esperar pela Promise do axios, já não daria certo utilizar o try-catch para capturar o erro retornado pelo mesmo. Pois, o try-catch só funcionaria de verdade quando você esperasse pela Promise utilizando await, que é quando o verdadeiro erro seria lançado.
Desse modo, se o axios retornasse um erro, você iria, na verdade, capturar o erro de UnhandledPromiseRejection, isto é, rejeição de Promise não capturada (em tradução livre), que corresponde exatamente ao problema de não ter passado a função a ser executada quando a Promise é rejeitada (a função a ser executada em reject).
Além disso, como vimos anteriormente, o .then() também retorna uma Promise. Portanto, aquele resolve está, na verdade, passando a Promise do .then(), e não o valor retornado por ela, para quem chamou a função busca. Ou seja, o chamador da função busca teria que lidar com duas Promises: a Promise gerada pela função busca e a Promise retornada pela função busca.
// Gera uma Promise
const promise1 = busca();

// Retorna outra Promise
const promise2 = await promise1;

// Só então retorna o valor
const resultado = await promise2;

E é essa a causa do problema. Quando você faz await busca(), você está obtendo como valor uma outra Promise. E assim, teria-se que mais uma vez esperar pela resolução dessa Promise retornada, para então obter o valor que se deseja. E isso não é algo muito "interessante" de se fazer.

Portanto, se você quer utilizar a API original, você pode fazer assim:
const url = 'http://files.cod3r.com.br/curso-js/funcionarios.json'
const axios = require('axios')

const busca = () => {
  // Reutilizamos a `Promise` do `axios`,
  // através do funcionamento do .then()
  return axios.get(url)
      .then(resp => resp.data);
}

async function getFuncionarios(){
  try {
    const funcionarios = await busca();

    return funcionarios;
  } catch (err) {
    console.log(err);
    return [];
  }
}

getFuncionarios().then((fcs) {
  // faz alguma coisa com o resultado
});

Ou, se quiser utilizar o async/await, você pode fazer assim:
const url = 'http://files.cod3r.com.br/curso-js/funcionarios.json'
const axios = require('axios')

const busca = async () => {
  try {
    const response = await axios.get(url);
    const funcionarios = response.data;

    return funcionarios;
  } catch(e) {
    throw e;
  }
}

async function getFuncionarios(){
  try {
    const funcionarios = await busca();

    return funcionarios;
  } catch (err) {
    console.log(err);
    return [];
  }
}

(async function() {
  const fcs = await getFuncionarios();
})();

Conclusão
Note que, em ambos os códigos, utilizamos o bloco try-catch, na função getFuncionarios, para lidar com a Promise gerada pela função busca. Isso porque, seja utilizando a API, seja utilizando async/await, a Promise da função busca pode ser rejeitada. E como em getFuncionarios estamos utilizando o await, essa rejeição se tornaria, de toda forma, um erro a ser lançado. Portanto, nós precisamos lidar com esse erro também.
Outra observação é que, da mesma forma que lidamos com "Promises simultâneas" da primeira vez, utilizando a API, poderíamos também fazê-lo com async/await. Você pode ver isso na resposta desse post, que demonstra a utilização do método .map() junto com o construtor alternativo Promise.all.
E sim, existem outros "construtores" para Promise, além do construtor padrão. Alguns deles são:

Promise.resolve(value), que serve para criar uma Promise que imediatamente conclui (resolve), retornando o valor passado para o parâmetro value.
Promise.reject(reason), que serve para criar uma Promise que imediatamente é rejeitada com o motivo passado para o parâmetro reason.
E o Promise.all(iterable), citado acima, que serve para criar uma Promise que resolve quando todas as outras contidas em iterable, são resolvidas, ou que é rejeitada quando pelo menos uma delas é rejeitada.
Answer: Em um projeto que estava fazendo verifiquei que, utilizando fetch(), o que era retornado era uma Promise {state: 'pending'}. Para resolver isso eu usei await deste modo:
fetch(url, {method:'POST')
   .then(async(p) => {
   var data = await p.json()
   console.log(data)
   //retorna o resultado esperado...
}

Não sei se é o mais correto, mas funcionou. Se alguém tiver alguma objeção, escreva abaixo.
Answer: axios.get(url) retorna uma Promise, você está passando uma Promise para outra Promise, e depois chama uma função assíncrona, esperando que o resultado seja síncrono.
Acho que você não entendeu como funciona Promise direito, tem esses artigos que explicam como funciona Promise
https://developer.mozilla.org/pt-BR/docs/Web/JavaScript/Reference/Global_Objects/Promise
https://developers.google.com/web/fundamentals/primers/promises?hl=pt-br
Para que getFuncionarios funciona-se de forma síncrona, o código deveria ficar:
const url = 'http://files.cod3r.com.br/curso-js/funcionarios.json'
const axios = require('axios')

const busca = () =>{
    return new Promise((resolve, reject) =>{
        try{
            const funcionarios = axios.get(url).then(resp => resp.data)
            resolve(funcionarios)
        }
        catch(e){
            reject(e)
        }
    })
}

async function getFuncionarios(){
    const funcionarios = await  busca().then(resPromise => await resPromise)
    return funcionarios
}

const fcs = await getFuncionarios()

Ou o código poderia ser simplificado para:
const url = 'http://files.cod3r.com.br/curso-js/funcionarios.json'
const axios = require('axios')

function getFuncionarios(){
    return axios.get(url).then(resp => resp.data)
}

try {
    const fcs = await getFuncionarios()

} catch(e) {
    // Faz outra alguma coisa se der erro
}

Comment: Acho que você também não entendeu amigo, nenhum de seus códigos sequer compilam.

Async/Await retornando Promise{}


Jquery to scroll down to top of each section with button press

Question: This is my code: Js Fiddle
As you can see I have several sections on top of each other with 100% height. I want to know how I can get it so when the user clicks on "learn more" they scroll to the next section, so the top of the section is at the top of the page.
Normally it would be quite simple as I could do this:
$('body').animate({
scrollTop:$(document).height()
});

However this won't work if the user has already scrolled halfway down on of the sections and then hits the button. It would also be good if I could use the same function for each button press, instead of having three different functions, one for each different section.
I guess the code would be something like (in pseudo): scroll to top sectiona + 1
Comment: u expecting it to behave this way http://jsfiddle.net/niranjan_borawake/9uxGq/11/  ?
Comment: Should the section move to the top of the page on click or the section should scroll to the top of the view port?
Comment: why you need to jquery? use anchor tag name in your url, to point out the particular section.
Comment: That works fine but I was hoping to have a smooth transition
Answer: with jQuery and smooth scrolling
 $('a').click(function(){
        var nextSection = $(this).closest('section').next('section');
        $('html, body').animate({
            scrollTop: $(nextSection).offset().top
        }, 2000);
    });

Comment: This is a nice clean answer, but how do I get it to work in my fiddle? http://jsfiddle.net/9uxGq/20/
Comment: 1. you have unclosed elements in your document.
2. your id's are not unique
3. in your case it would be easier to define classes to navigate without anchors

http://jsfiddle.net/9uxGq/22/
Answer: Why not you pass id's to each section and in href refer to that id like

  Move to section two

  Move to section one

Comment: Use This

$("html, body").animate({ scrollTop: $('#sectionNo').offset().top }, 1000);

http://stackoverflow.com/questions/6682451/animate-scroll-to-id-on-page-load
Comment: this will scroll you to the top of that specific section with a speed of 1 sec. 1000 is the speed of animation in Milli seconds.
Comment: But that would need a different function for each button, in order to hard code the next section number?
Comment: i don't know how to do it in a loop ... but i thnk it would be needed hard coding :(
Answer: You can also try the following.
var amount_to_scroll_by = $(document).scrollTop() + element_to_scroll.getBoundingClientRect().top);

$(document).scrollTop(amount_to_scroll_by); // animate this scroll

Hope this helps :)
Comment: I appreciate that but I'm not really sure how to implement that
Answer: Using jquery, you can smoothly scroll to the target.
Here is a SAMPLE
JS:
$("a").click(function(e) {
    e.preventDefault();
    var target = $(this).attr('href');
    $('html, body').animate({ scrollTop : $(target).offset().top + "px"});
});

Answer: You should first fix up your anchors and use the hash fragments to allow for native navigation between anchors.
I have created a very simple demo for you to understand this (not using your markup to keep it simple).
Demo: http://jsfiddle.net/abhitalks/9uxGq/15/
(another demo with your markup: http://jsfiddle.net/abhitalks/9uxGq/19/)
You need two anchors, one as click link and the other to mark the position of target as anchor.
For example:

Sub Heading 2

        Some text content here

    Learn More

Note: Of course instead of using a second anchor as a marker, you could use the div (or in your case section) with an id. But, an a is better because it is more semantic for content navigation and it means an anchor.
Once done, this becomes a fallback for you. Now you can easily implement animations using jQuery etc.
It would be as simple as this:
// bind click on anchors (use selectors as per your requirements)
$("a").on("click", function(e) {
    e.preventDefault(); // prevent the default behaviour
    var nextAnchor = this.hash.replace("#", ""); // get the next marker anchor
    var gotoPoint = $("#" + nextAnchor).position().top; // get the position of marker
    $('body').animate({ scrollTop: gotoPoint }, 'normal'); // animate the body
});

Alternatively:
// bind click on anchors (use selectors as per your requirements)
$("a").on("click", function(e) {
    e.preventDefault(); // prevent the default behaviour
    var nextAnchor = $(this).attr('href'); // get the next marker anchor
    var gotoPoint = $(nextAnchor).position().top; // get the position of marker
    $('body').animate({ scrollTop: gotoPoint }, 'normal'); // animate the body
});

Now applying this to your use case, the demo becomes: http://jsfiddle.net/abhitalks/9uxGq/19/
Hope that helps, and you can work it out in your markup and use-case.
.


Apache httpd mod_proxy POST issue on home page like abc.com

Question: I have apache server 2.4.18 on centos as a web server in the front end. Now I have multiple websites which are deployed on tomcat 8.0.33 as webapps in the default webapps folder of tomcat.
Configuration on apache end:
<VirtualHost 184.108.40.206:80>
    ServerName abc.com
    ServerAlias www.abc.com

    ProxyPass / http://localhost:8079/abc/
    ProxyPassReverse / http://localhost:8079/abc/
</VirtualHost>

<VirtualHost 22.214.171.124:80>
    ServerName def.com
    ServerAlias www.def.com

    ProxyPass / http://localhost:8079/def/
    ProxyPassReverse / http://localhost:8079/def/
</VirtualHost>

Two .war files by the name, abc.war & def.war are deployed to tomcat webapps folder.
abc.com works absolutely fine, as it is just an html site.
but def.com is a dynamic site & it has a login form on home page. The home page after successful login should load user profile page which is:
login page url -> def.com
user profile page -> def.com/profile.htm
Note that the home page loads successfully (means GET is executing successfully) on browser but when user tries to login(which is a POST request), it somehow tries to load:
def.com/def/profile.htm
Also note that if I change configuration to :
<VirtualHost 220.127.116.11:80>
    ServerName def.com
    ServerAlias www.def.com

    ProxyPass /def/ http://localhost:8079/def/
    ProxyPassReverse /def/ http://localhost:8079/def/
</VirtualHost>

then I am successfully able to open def.com/def/ & I can also successfully able to login & open def.com/profile.htm but I want my home page to be on def.com
Answer: Most probably you need an added directive for the def page, as you mention there is login page and probably cookies, check how they are set at the backend.
My thoughts is you may need something like:
ProxyPassReverseCookiePath /  /def/

and perhaps maybe something similar with ProxyPassReverseCookieDomain.
Review the mod_proxy docs if not for all the options you have
This is an interesting topic so if this is not your solution I would appreciate if you add your answer once you get to solve it.


Apache+Passenger == HAProxy + Mogrel Servers (M/M/C Queue)

Question: I recently read a great blog post made by SoundCloud Team. The Article talks about the Software Architecture Evolution.
http://backstage.soundcloud.com/2012/08/evolution-of-soundclouds-architecture/
In the section "Load distribution and a little queue theory" Sean Treadway, talks about queue theory and how to better use the queue.
He Wrote:

We wanted a system that never queued, but if it did queue, the wait
  time in the queue was minimal. Taking the M/M/c model to the extreme,
  we asked ourselves "how can we make c as large as possible?"
To do this, we needed to make sure that a single Rails application
  server never received more than one request at a time
We added HAProxy into our infrastructure, configuring each backend with a maximum connection count > of 1 and added our backend processes across all hosts, to get that wonderful M/M/c reduction in > resident wait time by queuing the HTTP request until any backend process on any host becomes available

Apparently, they are using HAProxy + Rails Servers ( Maybe Mongrel ).
Ok, HAProxy enqueing incoming requests and only dispatching to Mogrel/Thin when it is available.
Maybe could I be completely wrong ;), but Apache + Passenger do the same thing, right ?
One queue ( Apache handling incoming requests ) and C Workers ( Child Process )
Answer: Apache + Passenger does indeed distribute incoming requests to rack backends (unless the requests refer to static resources, which apache handles by itself).
This model works as long as one single host can run all (!) the rack instances. When you need more instances, apache can't handle it anymore and you would have to put something on top (often HAProxy). But then, apache's functionality is much bigger than just serving rack based apps. So it makes sense to replace it with something more lightweight (for example nginx), especially because you deploy it once for every host you have.
I hope that helps a little.
Comment: What I meant is that I don't know of a way to make apache distribute incoming requests to different hosts. Passenger is handling this for a single host and a few rack apps (meaning that the passenger pool is on the local host) but it doesn't relay to different hosts (AFAIK).
Comment: Thanks @mosch. "when you need more instances, apache can't handle it anymore and you would have to put something on top" means that apache will purge incoming requests when there is no available child in passenger Pool ? Did apache do not enqueue ?


Let $V$ be a finite-dimensional vector space and let $W_{1}$ and $W_{2}$ be subspaces of V.

Question: Let $V$ be a finite-dimensional vector space and let $W_{1}$ and $W_{2}$ be subspaces of $V$.

if $W_1 \cap W_2= 0,\dim W_1+ \dim W_2= \dim V$. How to show that $V=W_1 \oplus W_{2}$?

$\dim(W_1+W_2)=\dim W_1+\dim W_2-\dim(W_1 \cap W_2)=\dim W_1+\dim W_2-\dim(0)=\dim W_1+\dim W_2 =\dim V $

Can I conclude that $V=W_1+W_2$?

if so, then $V=W_1+W_2,W_1\cap W_2=0\Rightarrow V=W_1 \oplus W_2?$
Any suggestions? Thanks in advance.
Answer: If you already know that $\dim W_1+\dim W_2 = \dim V$, applying the rank-nullity law $$\dim (W_1+W_2) + \dim (W_1\cap W_2) = \dim W_1+\dim W_2$$yields$$\dim (W_1+W_2) + \dim (W_1\cap W_2) = \dim V,$$and it follows that $W_1+W_2 = V$ if and only if $W_1\cap W_2 = \{0\}$, in which case $V = W_1\oplus W_2$.
But if your assumption is that $W_1\cap W_2 = \{0\}$...
Comment: aha, so $dim(W_1\cap W_2)=0\therefore dim(W_1+W_2)=dimV. $ However, do we have $ dim(W_1+W_2)=dimV\Leftrightarrow W_1+W_2=V $?
Comment: Yes, provided the dimension of $V$ is finite. Then the only subspace of $V$ with dimension equal to the one of $V$ is $V$ itself.


spring3 mvc @Valid annotation cannot be found

Question: I try to use @Valid annotation, but eclipse always gives the "Valid cannot be resolved to a type" error. I m using the spring3 library.
I have imported hibernate-validator-4.1.0.Final.jar into my WEB-INF/lib directory. however, this does not solve the problem.
Any help is appreciated!
Comment: Is `Valid.class` inside the JAR?
Answer: @Valid belongs to JSR-303. You can get it via maven using this dependency:
<dependency>
  <groupId>javax.validation</groupId>
  <artifactId>validation-api</artifactId>
  <version>1.0.0.GA</version>
</dependency>

Or you can download it from this page.
Comment: thank you for u reply. yes. i got it work. i just find that there are two types of @Valid annotation. the first type is method level @Valid which is imported from Hibernate Validator jar. The second type is argument level @Valid which is imported from validation-api jar. To use both, just add them in the WEB-INFO/lib.   Thank you again!!!!
Comment: There is no need to add it directly, since JSR-303 implementation is needed anyway, and it has transitive dependency to the API.
Answer: I had the same issue(Maven project). I followed below and it worked:

Added below dependency in pom.xml

<dependency>
    <groupId>javax.validation</groupId>
    <artifactId>validation-api</artifactId>
</dependency>

Save and Maven will automatically download dependency jar files

Restart application

Note: Did not have to mention version as it was already defined in Spring Boot Dependencies. Otherwise below should work:
<dependency>
    <groupId>javax.validation</groupId>
    <artifactId>validation-api</artifactId>
    <version>2.0.1.Final</version>
</dependency>

Source: https://mvnrepository.com/artifact/javax.validation/validation-api/2.0.1.Final
Answer: As far as I remember the @Valid annotation is part of the validation-api JAR which you can find in the lib directory of the Hibernate Validator, as you have already downloaded the Hibernate implementation. The @Valid is a part of the javax.validation annotation API. You can add this JAR to your class path to be able to properly reference the annotation.


Bloquear navegação até validar login com token, usando Spring, AngularJS e JavaScript

Question: Tenho uma questão.. implantei uma validação de login usando JWT.
Ele funciona tudo certo, gera o token dentro das requisições.
Porém, na página de login, se na URL eu colocar a proxima página o sistema deixa ir.
Login COntroller
@RestController
public class LoginController {

    @Autowired
    private EntidadesAdministradoresService eaService;

    @RequestMapping(value = "/autenticar", consumes = MediaType.APPLICATION_JSON_VALUE, method = RequestMethod.POST)
    public LoginResponse autenticar(@RequestBody Entidades_administradores entidadesAdministradores) throws ServletException {

        //verifica se foram digitados o login e senha no front end
        if (entidadesAdministradores.getUsuario_administrador() == null
                || entidadesAdministradores.getSenha_administrador() == null) {
            throw new ServletException("Nome ou senha obrigatório");
        }

        // busca no banco de dados
        Entidades_administradores entAdministradoresAutenticado = eaService
                .buscarPorNome(entidadesAdministradores.getUsuario_administrador());

        if (entAdministradoresAutenticado == null) {
            throw new ServletException("Usuário não encontrado");
        }

        // compara a senha vinda do banco de dados com a senha vinda da tela
        if (!entAdministradoresAutenticado.getSenha_administrador()
                .equals(entidadesAdministradores.getSenha_administrador())) {
            throw new ServletException(" Senha inválida");
        }

        String token = Jwts.builder().setSubject(entAdministradoresAutenticado.getUsuario_administrador())
                .signWith(SignatureAlgorithm.HS512, "digi2fred")
                .setExpiration(new Date(System.currentTimeMillis() + 1 * 60 * 1000)).compact();

        return new LoginResponse(token);
    }

    private class LoginResponse {
        public String token;

        public LoginResponse(String token) {
            this.token = token;
        }

        public String getToken() {
            return token;
        }
    }
}

RequestMapping
public class HomeController {
    @RequestMapping("/home")
    public String irParaHome(){

        return "home";
    }

    @RequestMapping("/login")
    public String irParaLogin(){

        return "login";
    }

    @RequestMapping("/escolherSistema")
    public String irParaEscolherSistema(){
        return "escolherSistema";
    }

    @RequestMapping("/inicio")
    public String irParainicio(){
        return "inicio";
    }

    @RequestMapping("/saude")
    public String irParaSaude(){
        return "saude";
    }

    @RequestMapping("/localTrabalho")
    public String irParalocalTrabalho(){
        return "localTrabalho";
    }

}

LoginCOntroller.js

app.controller("loginController", function($scope, $http, $location) {
    $scope.entidadesAdministradores = {};
    $scope.token = "";

    $scope.autenticar = function() {

        $http.post("/autenticar", $scope.entidadesAdministradores).then(
                function(response) {
                    $scope.token = response.data.token;
                    localStorage.setItem("userToken", response.data.token);
                    $location.path("/home"); // alterei
                    window.location.reload(true); // alterei
                },

                function(response) {
                    console.log(response);

                });

    };

});

Answer: Uma solução que encontrei foi fazer um comando javaScript no arquivo home.js
if(localStorage.getItem("userToken")==null){
        $q.when();
        $location.path("/login");
        window.location.reload(true);
    }

Quando alguém tentar fazer uma requisição via http para a pagina home o comando verifica se existe o token, se não existir ele volta para a página login.


SSL off for a specific URL Nginx

Question: This configuration was working before, and now it is not.
I should mention this is Django, Gunicorn, and Nginx.
We are trying to make https://toontowninfinite.com/rpc/ use http and not https (SSL) and the rest of the site still uses SSL.
This is the config:
server {
            listen 80;
            # Force HTTPS!
            server_name toontowninfinite.com;

            # Well, excluding the RPC server. (thanks chan!)
            location /rpc/ {
                    proxy_set_header Host $host;
                    proxy_pass http://toontowninfinite;
            }
            location / {
                    rewrite ^  https://$server_name$request_uri? permanent;
                    add_header Access-Control-Allow-Origin *;
            }
    }

I do not see anything wrong here, any suggestions as to why it is forcing SSL still?
Comment: Permanent redirects are supposed to be cached by your browser, which will make changes difficult to pick up. Did you stop your web browser/clear your cache/use an anonymous window?
Comment: Show config for https part. Does it use strict-transport-security header?
Comment: In addition to my earlier remark about cached headers: your domain is behind the CloudFlare CDN, which also [caches HTTP headers](https://support.cloudflare.com/hc/en-us/articles/200168326-Are-301-and-302-redirects-cached-by-CloudFlare-) or a redirect to SSL might be [configured there](https://support.cloudflare.com/hc/en-us/articles/200170536-How-do-I-redirect-all-visitors-to-HTTPS-SSL-) as well
Comment: There currently is no page rules set at Cloudflare, i also purged everything over at cloudflare, and also clear my browser cache, and it still misbehaves. I do not hae "strict-transport-security" header in my SSL portion either. Is that needed?
Answer: Because the directives after your location /rpc/ continue to be interpreted.
You will find the following answer helful to your case.
I suggest you to try with:
server {
        listen 80;
        # Force HTTPS!
        server_name toontowninfinite.com;

        # Well, excluding the RPC server. (thanks chan!)
        location ^~ /rpc/ {
                proxy_set_header Host $host;
                proxy_pass http://toontowninfinite;
        }
        location / {
                rewrite ^  https://$server_name$request_uri? permanent;
                add_header Access-Control-Allow-Origin *;
        }
}

Comment: That did not work i added the ^~ before it and restarted nginx, and it still does not behave properly.

SSL off for a specific URL Nginx


Update 10.0 to 10.1

Question: What is the procedure for safe use of version 10.0 to 10.1 MariaDB?
I tried to locate a manual for this update and did not find any information or someone who did.
Comment: Welcome to StackOverflow! I am fraid that your question is off topic here. For more information, take a look here: https://stackoverflow.com/help/on-topic
Answer: MariaDB has official instructions here.
In case of Ubuntu 14.04, I just had to change

deb http://nyc2.mirrors.digitalocean.com/mariadb/repo/10.0/ubuntu trusty main
deb-src http://nyc2.mirrors.digitalocean.com/mariadb/repo/10.0/ubuntu trusty main

to

deb http://nyc2.mirrors.digitalocean.com/mariadb/repo/10.1/ubuntu trusty main
deb-src http://nyc2.mirrors.digitalocean.com/mariadb/repo/10.1/ubuntu trusty main

in my /etc/apt/sources.list, and run:
sudo apt-get update
sudo apt-get upgrade

Update 10.0 to 10.1


Markov Chain Initial Distribution

Question: Suppose $\{X_0,X_1,X_2,\dots\}$ is a discrete-time Markov chain taking values in a finite set $\{1,\dots,N\}$ with initial distribution $p_i(0) = P(X_0 = i)$ for $i\in\{1,\dots,N\}$ and transition probability matrix P where the $ij$-th entry $p_{ij} = P(X_k = j \mid X_{k-1} = i)$ for $k\geq 1$ and $i,j\in\{1,\dots,N\}$.
In order for the Markov chain to be well-defined, must we have that $P(X_0 = i)>0$ for all $i\in\{1,\dots,N\}$? If this were not true, then some elements of matrix $P$ would be undefined since the following definition is only valid for $P(X_0 = i)>0$.
$$ p_{ij}=P(X_1 = j \mid X_0 = i) = \frac{ P(X_1 = j, X_0 = i) }{ P(X_0 = i) } $$
In some books dealing with discrete-time Markov chains, I have seen the author set the initial distribution to something like $p_i(0) = 1$ if $i=1$ and $p_i(0)=0$ if $i\neq 1$ to signify that the initial condition is known. Doesn't this cause the transition probability matrix $P$ to be invalid and the underlying probability space ill-defined?
Answer: This is a good question, and a nice point to bring up. The truth is that when dealing with a time-homogenous Markov chain, the transition matrix $P$ is supposed to be intrinsic to the Markov chain without reference to a particular initial distribution. That is, you can set up the transition matrix without reference to some initial distribution given in a particular situation. To do so, you define
$$
p_{ij} = P(X_1 = j~|~X_0=i)
$$
with the assumption that $P(X_0=i)=1$. In other notation, $p_{ij} = P_i(X_1=j)$. This gives you the transition probability of going from state $i$ to state $j$ in one step under the condition that your chain is currently in state $i$, which is what you want the $p_{ij}$ to represent.
Let $S = \{1, 2, ..., N\}$ be the state space of the Markov chain with transition matrix $P$ defined as above with $p_{ij} = P_i(X_1=j)$. For $t = 0, 1, ...$ let $p^{(t)}_{i j} = P_{i}(X_t = j)$. That is $p^{(t)}_{ij}$ gives the probability of starting in state $i$ and moving to state $j$ after $t$ steps. You can show that $p^{(t)}_{ij}$ equals $[P^t]_{ij}$, the $(i,j)$th element of the transition matrix raised to the $t$th power. Now, suppose you're handed an initial distribution, which I'll call $\nu = (\nu_1, ..., \nu_N)$ where we interpret $\nu_i = P(X_0=i)$. From here, let's divide up the state space $S = S_1 \cup S_0$ where $i \in S_1 \iff \nu_i \neq 0$ and $i \in S_0 \iff \nu_i=0$. Let's figure out how to calculate $P(X_t = k)$ using this information.
$$
P(X_t = k) = \sum_{i\in S} P(X_t=k,X_0=i) = \sum_{i\in S_1}P(X_t=k,X_0=i)+\sum_{j\in S_0}\overbrace{P(X_t=k,X_0=j)}^{=0} \\
=\sum_{i \in S_1} P(X_t=k|X_0=i)P(X_0=i)= \sum_{i \in S_1} p^{(t)}_{ik}\nu_i = \sum_{i \in S_1} p^{(t)}_{ik}\nu_i  + \sum_{j \in S_0} p^{(t)}_{jk}\cdot 0 \\
= \sum_{i \in S_1} p^{(t)}_{ik}\nu_i  + \sum_{j \in S_0} p^{(t)}_{jk}\nu_j
= \sum_{i \in S} p^{(t)}_{ik}\nu_i = \left[\nu P^t \right]_{k}
$$
where the last equality is $k$th element of the vector resulting from multiplying the row vector $\nu$ multiplying the matrix $P^t$.
The point is, we define $p_{ij} = P_i(X_1=j)$ and then we prove that the desired matrix equalities hold. At no point in time when deriving the formula, did we divide by zero!
Comment: If we use the notation $p_i(k) = P(X_k = i)$ and put these components in a row vector $p(k) = [ p_1(k), \dots, p_N(k) ]$, we can do the traditional Markov calculation $p(k) = p(0)P^k$ to find the marginal distribution on $X_k$. If we start with an initial distribution containing zeros, what do these calculations mean?
Comment: @CCL Another good question! I've updated the solution to answer your question here in the comments. Take a look and see if my work makes sense.
Comment: Very nice! The row-vector / matrix multiplications still give the correct result even though the logic to get there is different. Thank you much!
Answer: Find an arbitrary positive sequence $a_n$ such that $\sum a_n = 1$. Enforce $P(X_0 = i) = a_i$. You can now talk about conditional probability legitimately.

Markov Chain Initial Distribution


OpenVPN not functioning as expected when running over secured connection

Question: I have an OpenVPN server, hosted on an Azure VM.
I created an origin certificate on Cloudflare, and have imported the key and the certificate into OpenVPN successfully. The Origin CA was also copied to the VM. In the web server configurations, everything seems to be fine:

When I turn off the orange switch on Cloudflare (proxied - means that all traffic will securely go through CF now), the issuer is verified successfully and the pad on the browser shows as green. However, I got many weird redirections that eventually damage the server (both the VPN functionality and the HTML rendering):

If I turn off the orange switch, the site renders as expected, and the VPN functions as expected, however, the issuer becomes unknown (although traffic still encrypted):

What am I doing wrong?
Comment: What on earth is 'Orange switch'? What certificates do you have where? What is not working? OpenVPN *or* access to the http panel of your server? What are you trying to achieve? There's no information about your actual setup, and it's somewhat confusing what your problem is.
Comment: @vidarlo If you use Cloudflare you'll know what is it. It's the proxied DNS as stated in the parentheses. I mentioned that I created the certificates using Cloudflare itself ([origin certificate](https://developers.cloudflare.com/ssl/origin-configuration/origin-ca/)). The problem is stated clearly as well. What exactly confuses you?
Comment: I don't use CloudFlare, but I know a thing or three about both HTTP and DNS. And no, I don't think the problem is stated clearly at all. You have tagged this OpenVPN, and title is *OpenVPN not functioning as expected* - is it *OpenVPN **VPN*** that doesn't work, or the http(s) admin panel that doesn't work? If the latter (as indicated by your screenshots) - what HTTP error codes do you get? Why is relevant that you get a certificate warning when connecting direct, not going through CF?
Comment: @vidarlo Error codes are attached in the image above (many redirects, and failure to load `bootstrap.min.js`). Both functionality and the admin panel stop working when the connection is going through CF (however, in this case, the connection will be secured).
Comment: I'm not asking these questions to piss you off. I'm asking because It's information that I believe is lacking. Feel free to insist that I'm wrong, but that probably doesn't increase the chances that someone will answer your question.
Comment: @vidarlo Thanks for your efforts in trying to help me, I appreciate it. I edited my question, I hope it's clearer now (I'm not a DevOps/IT engineer, so I might be missing some information, please let me know if I still miss anything).
Answer:
When I turn off the orange switch on Cloudflare (proxied - means that all traffic will securely go through CF now)

Should this off be on since if you want to proxy your connection via Cloudflare, you should turn on the switch?

I can fix the trusted connection. But once I do that, the VPN functionality and the HTML rendering break (see details in my question).

Hence this part of the answer, should that off part of your question be on? Cloudflare proxied DNS entries should have orange switch enabled instead of disabled.

When I turn on the orange switch on Cloudflare (proxied - means that all traffic will securely go through CF now), the issuer is verified successfully and the pad on the browser shows as green. However, I got many weird redirections that eventually damage the server (both the VPN functionality and the HTML rendering)

If I turn off the orange switch, the site renders as expected, and the VPN functions as expected, however, the issuer becomes unknown (although traffic still encrypted)

One thing you should remember is that Cloudflare doesn't support forwarding OpenVPN protocol, only HTTP and HTTPS.
When you turn on the proxying feature of Cloudflare, your domain will point to Cloudflare servers instead of your server, so that all connections to the domain name will be handled by Cloudflare and forwarded to your server; hence why your OpenVPN won't work and website rendering failed.
When you turn off the proxying feature of Cloudflare, your domain will point to your server, so that all connections to the domain name are handled by your server; hence why your OpenVPN will work and your site will render just fine; but since you're using Cloudflare's Origin certificate (which is signed by Cloudflare Origin CA, which in turn is not trusted by any user-agent), your user-agent will warn you about untrusted certificate.

If I understand this correctly, then I'll have to bypass Cloudflare proxy?

Easy answer is yes, you should bypass Cloudflare and use other alternatives to do SSL/TLS, i.e. using Let's Encrypt (via its client implementations) or getting it from other SSL/TLS certificate vendors.
The harder answer is it depends: there's SRV discovery support baked in OpenVPN 2, but I have no idea if it's implemented on other OpenVPN clients. If you only use OpenVPN v2 clients, there's your alternative.
There's a patch for SRV discovery support but not yet merged to OpenVPN source.
Comment: I can fix the trusted connection. But once I do that, the VPN functionality and the HTML rendering break (see details in my question).
Comment: I've edited my answer.
Comment: Thanks for clarifying the issue. So I understand that it's best to turn proxying off and ignore the untrusted certificate (this is our own VPN server).
Comment: why not use Certbot or acme.sh to get Let's encrypt's TLS certificate?
Comment: If I understand this correctly, then I'll have to bypass Cloudflare proxy?
Comment: You ***have*** to bypass CF proxy to use OpenVPN.
Comment: Edited my answer to add info about SRV discovery.


How to set up a repeated "field set" with unlimited time and event?

Question: I am planning to set up a "patient visiting record" , the repeated "field set" is time and events, for instance, "2017-12-15, the first visit, patient has stomach pain", "2017-12-30, the second visit, patient has vomiting, has a rash on the left leg[image upload]"....every time when I click on "add item" the "time and event set" will pop up as one field. And the series "daily like" records will show on the patient record page, of course every patient will have their own page. The records of course are only accessible for admin. Is that possible to realize?
Answer: This is possible using the "double field" module (https://www.drupal.org/project/double_field) and using the "field permissions" module (https://www.drupal.org/project/field_permissions).
In the users' account settings add a double field, set it up as date/text combination, allow unlimited values. Use the field permissions setting to permit access to specific roles only.
This does't allow to use images to be used, unfortunately.
An alternative idea is using a paragraphs field (https://www.drupal.org/project/paragraphs), where you can define a paragraphs item with any fields you need. Again, set to unlimited allowed values and setting field permissions.
Comment: I've tried paragraphs module, it's perfect for my task!! Thank you very much marcmueller!

How to set up a repeated “field set” with unlimited time and event?


Make spring `login` filter available via GET

Question: We are using spring security version 4.2.3,
I want to configure that the login filter be available via GET. (By default calling http://127.0.0.1/login with GET http method returns 404. )
To do this I extend the UsernamePasswordAuthenticationFilter to configure my own filter and configure it as below
<beans:bean id="myUsernamePasswordAuthenticationFilter"
            class="foo.bar.MyUsernamePasswordAuthenticationFilter">
            <beans:property name="authenticationManager" ref="authenticationManager"/>
            <beans:property name="postOnly" value="false"/>
</beans:bean>

and also
<http entry-point-ref="authenticationEntryPoint">
        <custom-filter before="FORM_LOGIN_FILTER" ref="myUsernamePasswordAuthenticationFilter"/>
    ......

It is not working!
During debug I find that there is a hard coded line at UsernamePasswordAuthenticationFilter constructor which is as below:
public UsernamePasswordAuthenticationFilter() {
        super(new AntPathRequestMatcher("/login", "POST"));
    }

I think, this cause that the AntPathRequestMatcher.matches always return false
Well can I configure the login filter to be available via GET. So calling http://127.0.0.1/login/username=foo&bar=bar will be processed?! how ?
Comment: @dur it worked! Calling the `setRequiresAuthenticationRequestMatcher( new AntPathRequestMatcher("/login","GET") );` in `myUsernamePasswordAuthenticationFilter` constructor solved the issue. Please send it as answer so I can accept it!
Answer: You have to use postOnly:

Defines whether only HTTP POST requests will be allowed by this filter. If set to true, and an authentication request is received which is not a POST request, an exception will be raised immediately and authentication will not be attempted. The unsuccessfulAuthentication() method will be called as if handling a failed authentication.

and setRequiresAuthenticationRequestMatcher, see AbstractAuthenticationProcessingFilter:

This filter will intercept a request and attempt to perform authentication from that request if the request matches the setRequiresAuthenticationRequestMatcher(RequestMatcher).

with a RequestMatcher that matches HTTP GET. For example:
new AntPathRequestMatcher("/login", "GET")

see AntPathRequestMatcher:

Creates a matcher with the supplied pattern and HTTP method in a case insensitive manner.


Confused with probabilistic notation and precedence

Question: Is $P(A|B,C) = P(A|(B \cap C))$ or $P((A|B) \cap C)$?
In my book they do something like this in a proof regarding Markov models:
$P(A|B_{1:t+1}) = P(A|B_{1:t},B_{t+1}) = P(B_{t+1}|A,B_{1:t})*P(A|B_{1:t})$/$P(B_{1:t+1})$
And I'm totally confused. Could someone write this out with parenthesis and $\cap/\cup$?
edit: Removed the $\alpha$
Comment: The "invention" P((A|B)∩C) was already asked about some while ago, was it by you?
Comment: Nope, this is my first post here. Excuse my ignorance :(
Answer: Whenever $P(B\cap C)>0$ you have
$$
P(A\mid B,C)=P(A\mid B\cap C)=P(A\cap B\cap C)/P(B\cap C).
$$
The "quantity" $P((A\mid B)\cap C)$ is nonsense, since $A\mid B$ isn't a set.
Comment: Alright, that's what I originally thought, however the proof from my book made me unsure (probably irrationally, but either way), and still makes no sense to me. I don't understand how they get the third term.
Comment: I don't either since and probably won't until you define what $A,B_{1:t},B_{t+1},B_{1:t+1}$ and $\alpha$ is.
Comment: Sorry. I wasn't sure if that was standard notation. A is just a random variables, $B_{1:t}$ is a set of events from 1 to t, and $B_{t+1}$ is event t+1. $B_{1:t}$ and $B_{t+1}$ is just a partition of a set of events ranging from 1 to t+1. In my book they say they use Bayes' for the third step, but I don't understand how.  $\alpha$ is 1/$P(B_{1:t+1})$ I believe.
Comment: I probably should've just posted that second "problem" as it's own question with a little more thought put into the presentation...
Comment: Is $B_{t+1}$ and $B_1\cap\cdots\cap B_t$ independent? Furthermore, $A$ must be a set, not a random variable.
Comment: Yes, a is a set, my bad. All the B's are independent yes. They depend only on A.
Comment: Then I urge you try again with the right-hand side. Use the definition of conditional probability and use the independence assumption. Then you should be able to arrive at $P(A\mid B_{1:t},B_{t+1})$. When you have done that, you should post this as an answer here. Let me know if you're stuck.
Comment: I realize that I've probably screwed this up quite bad, so I'll just provide a picture of what's in my book: http://i.imgur.com/2I5WiBw.jpg I just tried to simply it for the question, but I suppose I just ended up obfuscating it. Sorry! I'm new to this.


Submit data into database

Question: I have read a great deal and trying to learn how to get data into a table in the db. I have the below code to test entering just the first name of someone and I am getting an error. I have tried to follow the examples.module but I am missing something. I would appreciate a nudge in the right direction...
<code>function ghost_form_form_submit($form, &$form_state) {
$entity_id = db_insert('field_data_field_first_name') // database table name
  ->fields(array(
    'field_first_name_value' => $form_state['values']['field_first_name_value'],
  ))
  ->execute();

drupal_set_message(t('Your form entry has been added'));
}
</code>
Here is the complete form code...
https://gist.github.com/anonymous/f6d8dc19a3eed0f56d59
The only error I get in watchdog is the $entity_id. However I am not sure what I am missing.
Thanks
Comment: You shouldn't attempt to manipulate field tables directly as it can lead to inconsistencies, relevant caches aren't flushed, and so on. Always use the API (`node_save()`, `field_attach_submit()`, etc)
Answer: This message is probably because you missed some database fields in your insert query (we do not know the field type and what exactly you are trying to achieve). Other than that, it is very odd that you attempt to insert a record directly in a Drupal field's table as this not how it is meant to be used. As per Clive's comment, this can lead to data inconsistencies, cache issues etc.
So I would strongly recommend you to take a good look at Drupal examples on how to define a custom table using Schema API, or even better take a look at this guide on using the Entity API, which you allow you to properly utilize Drupal Fields with your own custom module. Third option is to use the API of an existing module such as nodes, users etc. so that you properly save the field's value.
Comment: Thank you. The hard part is not being a developer with a huge background in php. I will go through the Guide above.

Submit data into database