Maze solver won't backtrack in Python

Question: There are a couple of maze questions similar to this one but none of them ever really go into the why it won't work.
I don't need precise answers. I just need to know why this particular thing doesn't work.
This is the bit of my class Maze that I need help with.

ysize in my example is 10
xsize is 10
xend is 20 (changing it to 19 messes with the results and doesn't draw anything)
yend is 10 (changing it to 9 does this too)

class Maze:
    def __init__(self):
        self.maze = []
        self.xstart = None
        self.ystart = None
        self.xend = None
        self.yend = None
        self.xsize = None
        self.ysize = None

    def read_maze(self, filename):
        maze_list = []

        f_maze = open(filename)

        size = f_maze.readline().split()                #
        start = f_maze.readline().split()               #
        end = f_maze.readline().split()                 #

        self.xstart = int(start[1])
        self.ystart = int(start[0])

        self.xend = (int(end[1])*2)
        self.yend = (int(end[0])*2)

        self.xsize = (int(size[1])*2)
        self.ysize = (int(size[0])*2)

        lines = f_maze.readlines()

        for line in lines:
            maze_list.append(list(line[:len(line)]))

        self.maze = maze_list                           # Assigns to class

    def __str__(self):
        return ("".join(''.join(line) for line in self.maze))
    def solve(self, x, y):

        if y > (self.ysize) or x > (self.xsize):
            print("1")
            return False

        if self.maze[y][x] == self.maze[self.yend][self.xend]:
            print("2")
            return True

        if self.maze[y][x] != " ":
            print("3")
            return False

        self.maze[y][x] = "o" # MARKING WITH o for path already taken.

        if self.solve(x+1,y) == True:

            return True
        elif self.solve(x,y+1) == True:

            return True
        elif self.solve(x-1,y) == True:

            return True
        elif self.solve(x,y-1) == True:

            return True

        self.maze[y][x] = " " # ELSE I want it to be replaced with space

        return False

This is the current result.
 ---------------------
 |ooooooooooooo| |   |
 |-+-+-+ +-+-+o+ + +-|
 |   |   |   |o|     |
 | +-+-+ + +-+-+-+ + |
 |       | | |     | |
 |-+-+ + + + +-+ +-+-|
 |     |             |
 |-+ +-+-+-+-+-+ +-+ |
 |     |         |   |
 ---------------------

I want it like this:
---------------------
|ooooooo      | |   |
|-+-+-+o+-+-+ + + +-|
|   |  o|   | |     |
| +-+-+o+ +-+-+-+ + |
|      o| | |     | |
|-+-+ +o+ + +-+ +-+-|
|     |ooooooooooooo|
|-+ +-+-+-+-+-+ +-+o|
|     |         |  o|
---------------------

I don't know how to fix the indentation format here I apologize. That is my whole code. These are my test statements:
maze = Maze()
maze.read_maze(filename)
maze.solve(maze.xstart, maze.ystart)
print(maze)

The files go in this format saved as .txt files.
 5 10
 1 1
 5 10
 ---------------------
 |             | |   |
 |-+-+-+ +-+-+ + + +-|
 |   |   |   | |     |
 | +-+-+ + +-+-+-+ + |
 |       | | |     | |
 |-+-+ + + + +-+ +-+-|
 |     |             |
 |-+ +-+-+-+-+-+ +-+ |
 |     |         |   |
 ---------------------

Comment: The function looks OK to me. The boundary sizes seem suspicious since it looks like many more `o`s are drawn than 10x10. Can you post a [mcve] that reproduces the problem?
Comment: This still isn't a MCVE. I should be able to copy and paste the code, click "run" and see the problem you're seeing. What does the file look like?
Comment: Please don't vandalize your question. Improve yes, but vandalize no, as you'll make all answers invalid.
Answer: The problem is that as your file stands, xend, yend is (10, 20). To debug why it's not working, you can print(self.maze[self.yend][self.xend]) which returns a dash "-". Now, when your recursive call's (x, y) pair reaches its first dash, it tests True for the line
if self.maze[y][x] == self.maze[self.yend][self.xend]:

and thinks it has solved the maze. Rather, we want to test
if (y, x) == (self.yend, self.xend):

That is, test the coordinates, not the value of the square.
Another point: examining the actual location of the goal, we see that it's here:
+-+ +-+ |
    |   |
--------- <= this corner is the goal!

Which is unreachable if moving in strictly cardinal directions. Moving the goal a square up or to the left would put it within bounds of the solver algorithm.
This was sufficient to get the code working for me and hopefully is enough to get you moving again.

Maze solver won't backtrack in Python


Para que serve aquela linha vertical e horizontal quando clica no Form?

Question: Eu queria saber para que serve aquela linha vertical e horizontal quando você clica no formulário e fica lá, aí dps quando dá mais outro click, aparece mais outra linha. E tbm como eu posso tirar essas linhas?
Answer: Essas linhas são as definições de linhas e colunas de um Grid, e server para organizar o layout da aplicação (Ver Imagem). Você pode adiciona-las clicando na parte mais externa do componente (Irá aparecer uma linha laranja onde a linha será adicionada), e pode remove-la dando dois cliques sobre o ponto inicial da linha (aquela seta pra baixo).
Também é possível remove-las pelo código XAML:
<Grid>
    <Grid.RowDefinitions>
        <RowDefinition Height="79*"/>
        <RowDefinition Height="240*"/>
    </Grid.RowDefinitions>
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="142*"/>
        <ColumnDefinition Width="375*"/>
    </Grid.ColumnDefinitions>
</Grid>


Image uploading using Java Servlet with Multipartrequest

Question:  package imageUplaod;

    import java.io.File;
    import java.io.IOException;
    import java.io.PrintWriter;

    import javax.servlet.ServletContext;
    import javax.servlet.ServletException;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import com.oreilly.servlet.MultipartRequest;
    import com.oreilly.servlet.multipart.DefaultFileRenamePolicy;
    import java.util.Enumeration;

     public class UploadImage extends HttpServlet {
       private static final long serialVersionUID = 1L;

    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {

    final int permitedSize = 314572800;  //~ 300 MB in bytes

    PrintWriter out = response.getWriter();
    response.setContentType("text/html;charset=UTF-8");
    response.setHeader("Cache-Control", "no-cache");
    response.setHeader("Pragma", "No-cache");
    response.setDateHeader("Expires",0);

    try{
       String type = "";
       String name = "";
       String originalFilename = "";
       String extension1 = "";
       String extension2 = "";
       String filename = "";

       String strDirectory = "files";
       ServletContext sc=getServletContext();
       String uploadPath = sc.getRealPath("//WEB-INF//"+strDirectory+"//");

       MultipartRequest multipartRequest = new MultipartRequest(request, uploadPath, permitedSize, "ISO-8859-1", new DefaultFileRenamePolicy());

       Enumeration<String> files = multipartRequest.getFileNames();

          while (files.hasMoreElements())
             {
                 name = files.nextElement();
                 type = multipartRequest.getContentType(name);
                 filename = multipartRequest.getFilesystemName(name);
                 originalFilename = multipartRequest.getOriginalFileName(name);

                 extension1 = filename.substring(filename.length() - 4, filename.length());
                 extension2 = originalFilename.substring(originalFilename.length() - 4, originalFilename.length());

                 //return a File object for the specified uploaded file
                 File currentFile = multipartRequest.getFile(name);
                 InputStream inputStream = new BufferedInputStream(new FileInputStream(currentFile));
                 if(currentFile == null) {
                      out.println("There is no file selected!");
                      return;
                    }

                 //checking the file extensions according to the MIME types
                 if((type.equals("text/plain") || type.equals("image/gif") || type.equals("image/pjpeg")
                   || type.equals("image/x-png") || type.equals("image/jpeg"))) {
                     //show a few details about the uploaded file
                     out.println("file: "+filename);
                     out.println("type: "+type);
                     out.println("size: "+currentFile.length());
                   } else {
                            out.println("\n Invalid format!");
                          }
                 }

       }catch (Exception exception)
          {
      response.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED);
      } finally { if(out != null) {out.close();} }
    }

    public UploadImage() {
        super();
        // TODO Auto-generated constructor stub
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        processRequest(request, response);

    }

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        processRequest(request, response);

    }
    }

       this is my index page:

    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><%@page
    language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>

    <title>index</title>
    <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">

O'Reilly COS Upload

      <form enctype="multipart/form-data" action="UploadImage" method="POST">
       Select the file to upload:
       <input type="file" name="userfile">
       <input type="submit" value="Upload">
    </form>

when I run it I get following error:
      Error 404: javax.servlet.UnavailableException: SRVE0203E: Servlet [UploadImage]:
     imageUplaod.UploadImage was found, but is missing another required class. SRVE0206E:

This error typically implies that the servlet was originally compiled with classes which cannot be located by the server. SRVE0187E: Check your class path to ensure that all classes required by the servlet are present.SRVE0210I: This problem can be debugged by recompiling the servlet using only the classes in the application's runtime class path SRVE0234I:
  Application class path=[C:\Program Files (x86)\IBM\SDP\runtimes\base_v7\java\lib;C:\Program Files (x86)\IBM\SDP\runtimes\base_v7\java\lib\dt.jar;C:\Program Files (x86)\IBM\SDP\runtimes\base_v7\java\lib\htmlconverter.jar;C:\Program Files (x86)\IBM\SDP\runtimes\base_v7\java\lib\ibmorbtools.jar;C:\Program Files (x86)\IBM\SDP\runtimes\base_v7\java\lib\jconsole.jar;C:\Program Files (x86)\IBM\SDP\runtimes\base_v7\java\lib\tools.jar;C:\Program Files (x86)\IBM\SDP\runtimes\base_v7\profiles\was70profile1\classes;C:\Program Files (x86)\IBM\SDP\runtimes\base_v7\classes;C:\Program Files (x86)\IBM\SDP\runtimes\base_v7\lib;C:\Program Files (x86)\IBM\SDP\runtimes\base_v7\lib\EJBCommandTarget.jar;C:\Program Files (x86)\IBM\SDP\runtimes\base_v7\lib\IVTClient.jar;C:\Program Files (x86)\IBM\SDP\runtimes\base_v7\lib\OTiSConvertTime.jar;C:\Program Files (x86)\IBM\SDP\runtimes\base_v7\lib\activation-impl.jar;C:\Program Files (x86)\IBM\SDP\runtimes\base_v7\lib\aspectjrt.jar;C:\Program Files (x86)\IBM\SDP\runtimes\base_v7\lib\bootstrap.jar;C:\Program Files (x86)\IBM\SDP\runtimes\base_v7\lib\bsf-engines.jar;C:\Program Files (x86)\IBM\SDP\runtimes\base_v7\lib\cimgr.ops.jar;C:\Program Files (x86)\IBM\SDP\runtimes\base_v7\lib\commandlineutils.jar;C:\Program Files (x86)\IBM\SDP\runtimes\base_v7\lib\commons-discovery.jar;C:\Program Files (x86)\IBM\SDP\runtimes\base_v7\lib\databeans.jar;C:\Program Files (x86)\IBM\SDP\runtimes\base_v7\lib\ffdcSupport.jar;C:\Program Files (x86)\IBM\SDP\runtimes\base_v7\lib\htmlshell.jar;C:\Program Files (x86)\IBM\SDP\runtimes\base_v7\lib\installver.jar;C:\Program Files (x86)\IBM\SDP\runtimes\base_v7\lib\installxml.jar;C:\Program Files (x86)\IBM\SDP\runtimes\base_v7\lib\iscdeploy.jar;C:\Program Files (x86)\IBM\SDP\runtimes\base_v7\lib\ivblogbr.jar;C:\Program Files (x86)\IBM\SDP\runtimes\base_v7\lib\j2ee.jar;C:\Program Files (x86)\IBM\SDP\runtimes\base_v7\lib\jNative2ascii.jar;C:\Program Files (x86)\IBM\SDP\runtimes\base_v7\lib\jacl.jar;C:\Program Files (x86)\IBM\SDP\runtimes\base_v7\lib\jrom.jar;C:\Program Files (x86)\IBM\SDP\runtimes\base_v7\lib\jsf-nls.jar;C:\Program Files (x86)\IBM\SDP\runtimes\base_v7\lib\launchclient.jar;C:\Program Files (x86)\IBM\SDP\runtimes\base_v7\lib\lmproxy.jar;C:\Program Files (x86)\IBM\SDP\runtimes\base_v7\lib\mail-impl.jar;C:\Program Files (x86)\IBM\SDP\runtimes\base_v7\lib\nif.jar;C:\Program Files (x86)\IBM\SDP\runtimes\base_v7\lib\pc-appext.jar;C:\Program Files (x86)\IBM\SDP\runtimes\base_v7\lib\pmirm4arm.jar;C:\Program Files (x86)\IBM\SDP\runtimes\base_v7\lib\rrd-appext.jar;C:\Program Files (x86)\IBM\SDP\runtimes\base_v7\lib\rsadbutils.jar;C:\Program Files (x86)\IBM\SDP\runtimes\base_v7\lib\rsahelpers.jar;C:\Program Files (x86)\IBM\SDP\runtimes\base_v7\lib\serviceadapter.jar;C:\Program Files (x86)\IBM\SDP\runtimes\base_v7\lib\setup.jar;C:\Program Files (x86)\IBM\SDP\runtimes\base_v7\lib\startup.jar;C:\Program Files (x86)\IBM\SDP\runtimes\base_v7\lib\tcljava.jar;C:\Program Files (x86)\IBM\SDP\runtimes\base_v7\lib\urlprotocols.jar;C:\Program Files (x86)\IBM\SDP\runtimes\base_v7\lib\wses_dynaedge.jar;C:\Program Files (x86)\IBM\SDP\runtimes\base_v7\lib\wsif-compatb.jar;C:\Program Files (x86)\IBM\SDP\runtimes\base_v7\installedChannels;C:\Program Files (x86)\IBM\SDP\runtimes\base_v7\web\help;C:\Program Files (x86)\IBM\SDP\runtimes\base_v7\deploytool\itp\plugins\com.ibm.etools.ejbdeploy\runtime;C:\Program Files (x86)\IBM\SDP\runtimes\base_v7\deploytool\itp\plugins\com.ibm.etools.ejbdeploy\runtime\batch.jar;C:\Program Files (x86)\IBM\SDP\runtimes\base_v7\deploytool\itp\plugins\com.ibm.etools.ejbdeploy\runtime\ejbdeploy.jar;C:\Program Files (x86)\IBM\SDP\runtimes\base_v7\deploytool\itp\plugins\com.ibm.etools.ejbdeploy\runtime\ejbmapvalidate.jar;C:\Program Files (x86)\IBM\SDP\runtimes\base_v7\derby\lib\derby.jar;C:\Program Files (x86)\IBM\SDP\runtimes\base_v7\installedConnectors\sib.api.jmsra.rar;C:\Program Files (x86)\IBM\SDP\runtimes\base_v7\profiles\was70profile1\installedConnectors\wmq.jmsra.rar;C:\Program Files (x86)\IBM\SDP\runtimes\base_v7\profiles\was70profile1\installedConnectors\wmq.jmsra.rar\com.ibm.mq.commonservices.jar;C:\Program Files (x86)\IBM\SDP\runtimes\base_v7\profiles\was70profile1\installedConnectors\wmq.jmsra.rar\com.ibm.mq.connector.jar;C:\Program Files (x86)\IBM\SDP\runtimes\base_v7\profiles\was70profile1\installedConnectors\wmq.jmsra.rar\com.ibm.mq.headers.jar;C:\Program Files (x86)\IBM\SDP\runtimes\base_v7\profiles\was70profile1\installedConnectors\wmq.jmsra.rar\com.ibm.mq.jar;C:\Program Files (x86)\IBM\SDP\runtimes\base_v7\profiles\was70profile1\installedConnectors\wmq.jmsra.rar\com.ibm.mq.jmqi.jar;C:\Program Files (x86)\IBM\SDP\runtimes\base_v7\profiles\was70profile1\installedConnectors\wmq.jmsra.rar\com.ibm.mq.jmqi.local.jar;C:\Program Files (x86)\IBM\SDP\runtimes\base_v7\profiles\was70profile1\installedConnectors\wmq.jmsra.rar\com.ibm.mq.jmqi.remote.jar;C:\Program Files (x86)\IBM\SDP\runtimes\base_v7\profiles\was70profile1\installedConnectors\wmq.jmsra.rar\com.ibm.mq.jmqi.system.jar;C:\Program Files (x86)\IBM\SDP\runtimes\base_v7\profiles\was70profile1\installedConnectors\wmq.jmsra.rar\com.ibm.mq.jms.admin.jar;C:\Program Files (x86)\IBM\SDP\runtimes\base_v7\profiles\was70profile1\installedConnectors\wmq.jmsra.rar\com.ibm.mq.pcf.jar;C:\Program Files (x86)\IBM\SDP\runtimes\base_v7\profiles\was70profile1\installedConnectors\wmq.jmsra.rar\com.ibm.mqjms.jar;C:\Program Files (x86)\IBM\SDP\runtimes\base_v7\profiles\was70profile1\installedConnectors\wmq.jmsra.rar\com.ibm.msg.client.commonservices.j2se.jar;C:\Program Files (x86)\IBM\SDP\runtimes\base_v7\profiles\was70profile1\installedConnectors\wmq.jmsra.rar\com.ibm.msg.client.commonservices.jar;C:\Program Files (x86)\IBM\SDP\runtimes\base_v7\profiles\was70profile1\installedConnectors\wmq.jmsra.rar\com.ibm.msg.client.jms.internal.jar;C:\Program Files (x86)\IBM\SDP\runtimes\base_v7\profiles\was70profile1\installedConnectors\wmq.jmsra.rar\com.ibm.msg.client.jms.jar;C:\Program Files (x86)\IBM\SDP\runtimes\base_v7\profiles\was70profile1\installedConnectors\wmq.jmsra.rar\com.ibm.msg.client.matchspace.jar;C:\Program Files (x86)\IBM\SDP\runtimes\base_v7\profiles\was70profile1\installedConnectors\wmq.jmsra.rar\com.ibm.msg.client.provider.jar;C:\Program Files (x86)\IBM\SDP\runtimes\base_v7\profiles\was70profile1\installedConnectors\wmq.jmsra.rar\com.ibm.msg.client.ref.jar;C:\Program Files (x86)\IBM\SDP\runtimes\base_v7\profiles\was70profile1\installedConnectors\wmq.jmsra.rar\com.ibm.msg.client.wmq.common.jar;C:\Program Files (x86)\IBM\SDP\runtimes\base_v7\profiles\was70profile1\installedConnectors\wmq.jmsra.rar\com.ibm.msg.client.wmq.factories.jar;C:\Program Files (x86)\IBM\SDP\runtimes\base_v7\profiles\was70profile1\installedConnectors\wmq.jmsra.rar\com.ibm.msg.client.wmq.jar;C:\Program Files (x86)\IBM\SDP\runtimes\base_v7\profiles\was70profile1\installedConnectors\wmq.jmsra.rar\com.ibm.msg.client.wmq.v6.jar;C:\Program Files (x86)\IBM\SDP\runtimes\base_v7\profiles\was70profile1\installedConnectors\wmq.jmsra.rar\dhbcore.jar;C:\Program Files (x86)\IBM\SQLLIB\java\db2jcc.jar;C:\Program Files (x86)\IBM\SDP\runtimes\base_v7\universalDriver\lib\db2jcc_license_cu.jar;C:\Program Files (x86)\IBM\SDP\runtimes\base_v7\profiles\was70profile1/properties;C:\Program Files (x86)\IBM\SDP\runtimes\base_v7/properties;C:\Program Files (x86)\IBM\SDP\runtimes\base_v7/lib/startup.jar;C:\Program Files (x86)\IBM\SDP\runtimes\base_v7/lib/bootstrap.jar;C:\Program Files (x86)\IBM\SDP\runtimes\base_v7/lib/jsf-nls.jar;C:\Program Files (x86)\IBM\SDP\runtimes\base_v7/lib/lmproxy.jar;C:\Program Files (x86)\IBM\SDP\runtimes\base_v7/lib/urlprotocols.jar;C:\Program Files (x86)\IBM\SDP\runtimes\base_v7/deploytool/itp/batchboot.jar;C:\Program Files (x86)\IBM\SDP\runtimes\base_v7/deploytool/itp/batch2.jar;C:\Program Files (x86)\IBM\SDP\runtimes\base_v7/java/lib/tools.jar;C:\Users\drunkendeath\IBM\rationalsdp\workspace\UploadImage\WebContent\WEB-INF\classes;C:\Users\drunkendeath\IBM\rationalsdp\workspace\UploadImage\WebContent]

So what is wrong here, can anybody explain?
I have included all the .jars. There is no error in code.
Comment: possible duplicate of [How to upload files to server using JSP/Servlet?](http://stackoverflow.com/questions/2422468/how-to-upload-files-to-server-using-jsp-servlet)
Comment: its not a dulicate,read the error
Comment: If you read the question/answer, it shows how to upload a file using a multipart request and that's what you are asking. If you use this method (that I particularly haven't seen anywhere in the net) then keep it, but there must be a good reason why that answer has all those votes on favor.
Comment: I have read it, it is not solving my problem. Please read my error. it says: Error 404: javax.servlet.UnavailableException: SRVE0203E: Servlet [UploadImage]: imageUplaod.UploadImage was found, but is missing another required class. SRVE0206E: This error typically implies that the servlet was originally compiled with classes which cannot be located by the server. SRVE0187E: Check your class path to ensure that all classes required by the servlet are present.SRVE0210I:
Answer: The error is telling you that one of your imports is not being found by Websphere. The only classes you are using are the O'Reilly ones and standard Java ones. It is highly unlikely that it is one of the Java classes that are not being found.
Make sure that the O'Reilly jar is in your WEB-INF/lib directory or place it into Websphere's classpath. If it is there, restart Websphere (standard fix it solution in the product I was on while I was at IBM).


How to stop using Hindi number in Arabic translation of products

Question: When using English version of website, price is shown in Arabic number (common one). But when using Arabic version of website, price is shown in Hindi number.
I don't want price to be shown in Hindi Numbers.
English view of products (Arabic Numbers)

Arabic view of products (Hindi Numbers)

How to force using Arabic Numbers in both versions.
Answer: Subscribe to the NumberFormatDefinitionEvent ("commerce_price.number_format") and change $definition['numbering_system'] to 'latn' for your locale.
Comment: Seems to be the solution, but I couldn't figure out how to do that, do I have to implement a hook in my custom module or theme.
Comment: You'll have to learn about event subscribers in general. Yes, they are implemented in modules.
Answer: I think your theme use this font, you must change font used in price, for test, use inspect element in chrome browser and change font and see result.
Comment: no, it's not in the theme. the characters translated in commerceguys/intl library.


solving cubic eq without using derivatives

Question: enter image description here
Hi, I had this question, but I'm unable to solve it without using derivatives, though I have the answer (which is $15.7$ approx). I would appreciate it if you could help me out how to get the answer without using derivatives. Thanks a lot.
Question:  The profit of a company can be modelled by the polynomial function $p(t)= -4t^3+10t^2+8t-6$, where $p$ is the profit, in thousands of dollars, and $t$ is the time in years. When will the company make their maximum profit of $18 000 $ $?
Comment: Why without derivatives ??
Answer: The answer, believe it or not, is actually $2$.
What you (probably) did was get the equation $-4t^3+10t^2+8t-6 = 18000$. However, this is not correct, because of the caveat in the problem statement. It says "$p$ is the profit in thousands of dollars."
So we express $18000$ as $18$, since we are in thousands of dollars. The equation is therefore $$-4t^3+10t^2+8t-6=18.$$
This simplifies to $4t^3-10t^2-8t+24.$ Note that we can divide by $2$ to get $2t^3-5t^2-4t+12$.
To solve this, use the Rational Root Theorem. Checking $1, -1, 2, -2, \dots$ note that $t = 2$ is a solution by RRT.
Dividing $2t^3-5t^2-4t+12$ by $t-2$ gets $2t^2-t-6$. The two solutions to this are $t = 2$ and $t = -\frac{3}{2}$.
So the company will make their maximum profit in $2$ years.
Comment: Thanks a lot, ma G you da best!
Answer: Hint:
Use the rational root theorem to solve $$-4t^3+10t^2+8t-24=0.$$
Comment: right thank you so much !!


Authentication mode=windows not working

Question: I am newbie to ASP.NET. I have an ASP.NET MVC 4 application from which I am trying to get the current loggedOn user using HttpContext.
this is not running under IIS, but under FileSystem (as in running locally from Visual Studio 2012).
I have set
<authentication mode="Windows"></authentication>

and still I do not get the loggedOn user.
Then I tried with:
<deny users="?"/>

Gives me access denied error, even though I have admin rights on my computer.
can somebody help in getting loggedOn userName through HttpContext?
Comment: AFAIK this only works with IIS and NOT when running locally...
Answer: found the solution in the settings of the project created.
also found that, by default for a MVC 4->Single Page/Internet/Mobile Application the Anonymous Authentication will be enabled and Windows Authentication is Disabled.
Changing the settings for Anonymous Authentication as Disabled and Enabling Windows Authentication did the trick.
(seriously, this was dumb behavior at its best :'( )

Authentication mode=windows not working


Operator precedence between await and ternary

Question: I tried this with Chrome console:
const foo = async () => 1;
const bar = async () => 2;
(await 1) ? foo() : bar();

The result is 1.
Can you explain this please? Isn't it suppose to return a Promise?
Comment: What version of chrome, when I try `var x = (await 1) ? foo() : bar();`, I get a Promise in x as expected.
Comment: Interesting. When I try your operation I also receive x as a Promise. But without the assignment it returns 1.
Comment: I see what the question is now (it's not reproducible from your original code without adding semicolons), since it is interpreted as `(async () => 2)(await 1)` without a semicolon after the 2, unless it is entered line by line.
Comment: Yes thanks for the correction. I only tried this on Chrome console.
Answer: await coerces non-promise operands to a promise by calling Promise.resolve(operand).  So
 (await 1)

becomes
 (await Promise.resolve(1))

and Promise.resolve(1) returns a promise fulfilled with the value 1.
After await returns (asynchronously - after executing a job in the promise job queue*) the ternary expression is evaluated as
 1 ? foo() : bar()  // calls foo()

The precedence of the await operator appears to be the same as that of other unary operators.
*Note await never continues execution in the same call out from the event loop even if the promise it is waiting on is already fulfilled: it always returns in another call out from the event loop.
Comment: I missed the keyword async on foo and bar when I created the question. Already updated it. Sorry about the confusion. The return of `foo()` is a promise.
Answer: It seems the chrome console did something under the hood which is not the concern of this question. The result of the operation is as expected.

Thanks to Paulpro
Comment: The chrome console is breaking standards "under the hood"! The code should throw a syntax error because `await` is only recognised as an operator within an async function.
Comment: @traktor53 They added that it a pretty recent release: https://developers.google.com/web/updates/2017/08/devtools-release-notes#await . Note that the REPL doesn't claim to run in the global scope, so it could easily be eval'd within an async function.
Answer: await expects async function as an argument and it halts the operation until the promise in async function is returned. In your case 1 is the expression and hence it is returned immediately. Now your ternary operator takes 1 as an expression which is true in JavaScript's logic. This will trigger your first function i.e. foo
So your result will be 1


Drawing a border around a custom LinearLayout

Question: here is a quick description of my screen layout.
<CustomLayout>
    <CardView>
        <CustomTextView />
        <CustomTextView />
        <CustomTextView />
    </CardView>
    <CustomTextView />
    <CustomTextView />
</CustomLayout>

I coded it so that CardView extends LinearLayout and CustomTextView extends TextView. Everything works fine except I want to draw a border line at the bottom of the CardView and at the bottom of the second CustomTextView. To do so, I use the same method for my CardView and my CustomTextView:
@Override
protected void onDraw(Canvas canvas) {
    super.onDraw(canvas);
    getLocalVisibleRect(mRect);
    if (mDrawBottomBorder)
        canvas.drawLine(mRect.left, mRect.bottom, mRect.right, mRect.bottom, mBorderPaint);
}

That method gets called in both cases, i.e. for my CardView and CustomTextView but it doesn't draw the border for my CardView! I suspect it's because it extends LinearLayout and not TextView but shouldn't it work anyway?
Answer: Ok I figured it out. My 3rd CustomTextView in my CardView layout was covering the border beneath it so the line wasn't visible.


DCG(again) creating abstrac tree in semantic actions

Question: Here is some gramma wich represents tree
<tree> -> *
<tree> -> (<tree><tree>)

where * means leaf and couple of trees in parentheses describes root that sons are trees in parentheses.
i Have to rewrite that gramma to dcg and add semantic actions which will create abstrac tree of that tree whith leaf/0 and node/2 example node(node(leaf,leaf),node(leaf,leaf))
for any idea or source i will be gratefull.
Answer: This works in my SWI-Prolog:
leaf_rule(leaf) --> "*".
tree_rule(X) --> leaf_rule(X), !.
tree_rule(node(X,Y)) --> "(", tree_rule(X), tree_rule(Y), ")".

In order to parse a string you need to call phrase predicate, for example:
phrase(tree_rule(X), "((**)*)", Rest).

Prolog will unify X with abstract representation of tree from string.
Comment: No need for the cut! And no need for leaf_rule//1.
Comment: cut makes it deterministic but yes leaf rule is not need but semantic actions are in { } that is just additional Logic Variable wich will uniy on the end


Is there a name for "slapping" a hammond organ?

Question: Just wondering if there was a technical name for the keyboard "slap" technique found here at around 4:00ish:

Thanks!
Answer: Not really.  Organs aren't touch sensitive, so there's no effect to the sound, it's just this guy's way of getting extremely short staccato notes.
Comment: Thinking about this again, I still agree with you although I think there is an important distinction -- his "short, staccato" notes aren't necessarily intentionally selected notes, they're somewhat random hits on the keyboard without regard for the notes, which creates a more percussive, rhythmic sound to me. An analogous concept to this I think would be guitar damping/scratching. See http://en.wikipedia.org/wiki/Damping_%28music%29 and a sample: http://youtu.be/Prh2Jkt1nLE


Spring Integration Mail: Send email after all database inserts

Question: Hello I have an integration flow that splits a file line by line, transforms each line into a POJO and then inserts that POJO into a db via JDBC outbound gateway.
I want to be able to send a single email once the process of the file has completed.
I currently am sending to smtpFlow channel after my jdbcOutboundGateway, however this is sending an email after every db insert.
Here is my current flow DSL
IntegrationFlow ftpFlow() {
    return IntegrationFlows.from(
            ftpSource(), spec -> spec.poller(Pollers.fixedDelay(5, TimeUnit.SECONDS)))
            .split(splitFile())
            .transform(this::transformToIndividualScore)
            .handle(jdbcOutboundGateway(null))
            .channel("smtpFlow")
            .get();

How do I get this flow to only send one email after all files have been processed in the jdbcOutboundGateway?
Here is my splitFile() method
@Bean
FileSplitter splitFile() {
    FileSplitter fs = new FileSplitter(true, false);
    fs.setFirstLineAsHeader("IndividualScore");
    return fs;

Here is my transformToIndividualScore method
@Transformer
private IndividualScore transformToIndividualScore(String payload) {
    String[] values = payload.split(",");
    IndividualScore is = new IndividualScore();
    is.setScorecardDate(values[0]);
    is.setVnSpId(values[1]);
    is.setPrimaryCat(values[2]);
    is.setSecondaryCat(values[3]);
    is.setScore(Integer.parseInt(values[4]));
    is.setActual(values[5]);
    return is;
}

Answer: So a solution to my problem, (kind of).
Marking iterator to false on my FileSplitter now allows the sequencing headers.
the updated splitFile() is below
@Bean
FileSplitter splitFile() {
    FileSplitter fs = new FileSplitter(false, false);
    fs.setFirstLineAsHeader("IndividualScore");
    fs.setApplySequence(true);
    return fs;
}

My intuition is telling me that the default .aggregate() release strategy must be that the message header sequenceSize == the list of messages aggregated.
When creating the FileSplitter with iterator set to true the sequenceSize is set to 0 which will never fulfill the release strategy of the default .aggregate()
However, this makes the FileSplitter use a List to store all lines of the file in memory. The aggregator is also storing another ArrayList of lines in memory..
Is there a better solution to creating a custom aggregator that handles the END FileMarker for allowing for usage of the iterator for splitting a file?
Answer: with the help of @ArtemBilan
I was able to use the publishSubscribeChannel() and chain 2 subscribe() methods in sequence below is the new IntegrationFlow
 @Bean
IntegrationFlow ftpFlow() {
    return IntegrationFlows.from(
            ftpSource(), spec -> spec.poller(Pollers.fixedDelay(5, TimeUnit.SECONDS)))
            .publishSubscribeChannel(channel -> channel
                    .subscribe(
                        a -> a
                                .split(splitFile())
                                .transform(this::transformToIndividualScore)
                                .handle(jdbcMessageHandler(null)))
                    .subscribe(
                        b -> b
                                .transform(this::transformToSuccessEmail)
                                .handle(emailHandler()))
            )
            .get();

Answer: Add .aggregate() after the handle to assemble the results of the splits back into a single message.
Comment: @ArtemBilan yes! it's making sense now to me. I am very new to integration and it's a great framework.
Comment: i will update my code and post a new message with a solution shortly.
Comment: Another way is to use a `publishSubscribeChannel()` with a `split()` and `jdbcOutboundGateway()` as one subscriber sub-flow and `Mail.outboundAdapter()` as another one. It is really impossible to do what you are asking for all the files at once: there is just no an flag to check that all the files are done. What if a new file arrive during processing existing?.. Consider to change your logic to be based on per-file basis. Or as Gary said: with some aggregator strategy to emit email message after some number of files or timeout.
Comment: Oh, right; sorry, I misread the question - the aggregator will send a mail for each file instead one for each insert; you need @ArtemBilan 's suggestion for one message for all files.
Comment: when i just drop ```.aggregate()``` after ```.handle(jdbcOutboundGateway(null))``` it doesn't complete the flow, it just hangs.
Comment: @GaryRussell I do want it to send it after each file, so i think your answer is correct.
Comment: `transformToIndividualScore` - perhaps you are dropping the sequence information headers; show your transformer; if you are returning a `Message`, you are responsible for propagating the inbound headers to the outbound message.
Comment: @ArtemBilan thank you for your help and sorry about the misunderstanding, I do want to send email after each file is done, not after "the process" (which could be n number of files) is completed.
Comment: @GaryRussell added ```transformToIndividualScore```
Comment: So, `publishSubscribeChannel()` is the way to go and you don't need to worry about sequence detail for an aggregator. And that `jdbcOutboundGateway` could be just as simple as `JdbcMessageHandler` - one-way to store in DB and forget. The second subscriber just with the `Mail.outboundAdapter()` will wait until the work is done in the first subscriber.
Comment: BTW the `FileSplitter` doesn't populate a `sequenceSize` header in case of `iterator` option. That's why an aggregator doesn't work. Looks like we still need to come up with the `FileMarkerAggregator` solution: https://jira.spring.io/browse/INT-4116


How to edit Ansible with default fail condition and customer fail condition

Question: I have an Ansible function, like
- shell: ...
  register: results
  failed_when: (default fail condition) or ("upgrade false" in results.stdout)

How do I fill (default fail condition)? Then this function is able to fail on normal fail condition and fail on customer condition (results contains string "upgrade false")
Answer: The default fail condition is simply fail on any exit code other than 0. You can do the same like this:
- shell: ...
  register: results
  failed_when: (results.rc > 0) or ("upgrade false" in results.stdout)

Comment: I haven't worked a ton with failure conditions. I'll test that later


Can a valid HTML comment tag contain an attribute-like syntax?

Question: I'm trying to discern if the attribute syntax characters (quoted key-value pairs) are valid within HTML comments:
I can't tell if this is valid.  I looked at:

http://dev.w3.org/html5/spec-author-view
http://www.w3.org/TR/html-markup/syntax.html

It appears that they probably are—except for a few references to "control characters".  I can't find a definition for control characters in the specification.
The specification only requires:

comment open ""

Most browsers and parsers support having a quoted key-value pair in a comment.  I've ran into a few issues with various open source libraries that can sometimes choke.
Comment: Comments are not tags and they should be completely opaque to an HTML parser. So apart from the restrictions meant to distinguish them you can put anything inside.
Comment: That refers to [Unicode control characters](http://www.aivosto.com/vbtips/control-characters.html#unicode).
Comment: That's what I believe too.  But I can't find the answer in the HTML spec. The spec states "open" + text + "close" and allows for everything but "control characters" in the "text".  But I can't find a definition for them.
Comment: Thanks!  That explains why i couldn't find the reference in the spec.
Comment: The two links are (effectively) broken. They both redirect to unspecific generic places.
Answer: No. Only elements have attributes,  and a comment is not an element.
That said, you can write many things in a comment. And you might to choose to call some of those things attributes. But in the context of parsing,  saying that is just confusing. In the context of HTML,  attribute has a specific meaning.

But why would you even want to do that? It seems you want to record some key-value pairs that you can parse later. HTML already has a feature for that: the meta element.
Comment: It might not need to be parsed as an attribute, but =-"' are valid characters within a comment.
Comment: @Jonathan You can put anything into a comment and call it an attribute if you wish; doesn't make it so in the spec.
Comment: I clarified the question.  I don't care about something parsing or interpreting key/value pairs as an attribute. I just want to know the validity of placing a quoted key/value pair in an HTML comment.
Answer: As long as the attribute-like syntax contains no instances of the character sequences that are expressly forbidden in the spec, it's perfectly valid and won't break your comment in spectacular ways. For reference, here's what it says in the second link in your question:

The text part of comments has the following restrictions:

must not start with a ">" character
must not start with the string "->"
must not contain the string "--"
must not end with a "-" character

This makes it easy to comment out most elements without having to change their content, unless they specifically contain the forbidden character sequences. For example, this is fine:

Because we're talking about comments, as you may have guessed it'll simply be harmlessly ignored by the browser, as with any other comment content. That does not make your comment invalid per se.
Comment: Thanks.  I had seen that part.   My confusion was because the first link listed "control characters" as forbidden, but there was no reference to them.  @Jon noted [in a comment] that they referred to Unicode Control chars.
Comment: Also, FWIW, this *should* never make it to a browser.  We're storing some structured content within html comments; it's replaced with HTML on the fly - but stored within a comment in the database.  This allows for it to simply disappear if something breaks.


Adding cx_Freeze msi to path

Question: I have an msi and when installed I want it to add the exe to path.
I have found this:

add_to_path    add the target directory to the PATH environment variable; the default value is True if there are any console based executables and False otherwise

From the documentation.
I have tried adding this to the setup script:
setup(  name = "cabbage",
        version = "0.1",
        description = "just a vegetable",
        add_to_path = True, # <-- Just here
        options = {"build_exe": build_exe_options},
        executables = [Executable("spam.py", base=base)])

This returns:

UserWarning: Unknown distribution option: 'add_to_path'

I also tried from the command line:
C:\Users\Simon\Desktop>python setup.py bdist_msi add_to_path=True
invalid command name 'add_to_path=True'

How do I add this option?
Comment: What are your Python version, cx_freeze version, and your PATH variable?
Comment: @Bachrc x32 bit Python 3.7.0 and cx_Freeze 5.1.1
Comment: Also I am confused by PATH variable, what do you mean exactly?  The path to the exe I package in the msi?  If so `C:\TestProgram\bin` @Bachrc
Answer: Add below lines in your setup.py script to make it work.
  if 'bdist_msi' in sys.argv:

        sys.argv += ['--add-to-path', 'True']

Your code should look like:
 if 'bdist_msi' in sys.argv:

        sys.argv += ['--add-to-path', 'True']

 setup(  name = "cabbage",
    version = "0.1",
    description = "just a vegetable",
    add_to_path = True, # <-- Just here
    options = {"build_exe": build_exe_options},
    executables = [Executable("spam.py", base=base)])

Run command: python setup.py bdist_msi

Adding cx_Freeze msi to path


Communicating with my system admin: SSL for Apache httpd, and for Tomcat

Question: I'm at the mercy of a sys admin who handles middleware config for an application I'm working on.  Long story short I asked for SSL to be enabled for the application.
The app is split up between a PHP layer being served from Apache httpd, and a set of REST services in Java, being served by Tomcat 8.5 (standalone) on port 8443.
After the sys admin told me "your SSL is fully configured", I hit the base app at:
https://www.example.com/myapp/

Comes up fine, no SSL warnings and green padlock.  However:
https://www.example.com:8443/myRestAPI/

still gives a warning on SSL.  So, is there a hint of some sort or guidance, link to a good how-to, or anything I can share with this person to get her some help to understand how to get this SSL working on that Tomcat/port ?
Answer: Tomcat SSL configuration is done in the server.xml The connector needs to be configured like this:
<Connector port="8443"
   protocol="org.apache.coyote.http11.Http11AprProtocol"
   secure="true"
   scheme="https"
   SSLEnabled="true"
   SSLCertificateFile="/path/to/ocsp-cert.crt"
   SSLCertificateKeyFile="/path/to/ocsp-cert.key"
   SSLCACertificateFile="/path/to/ca.pem"
   SSLVerifyClient="require"
   SSLVerifyDepth="10"
   clientAuth="true"/>

Tomcat SSL documentation
Another option would be to configure the Apache httpd as a reverse proxy in front of the Tomcat.
Comment: Yes, to this: "Another option would be to configure the Apache httpd as a reverse proxy in front of the Tomcat." The sysadmin might have already done that. Hopefully they did as that is more advisable. Its easier to maintain ongoing support for SSL changes if it can be configured in one place, at the reverse proxy. More control too.


D8 can't see module

Question: Using the drupal console I created a module in a /sites subdirectory - because I want that module to be available only during development.
The creation process worked.
I tried to create a controller using the console and it said there was no such module. I tried enabling the module: no such module. Using:
drupal debug:module --type=no-core

listed the one other module I've created which is in /modules.
(Yes, I cleared caches.)
Comment: If you created a module under /sites/SITE A/modules/ then it won't display in root drupal folder. You have to go under sites/SITE A and list down modules there.
Answer: The only valid places for modules to live are:

/modules
/sites/foo_site/modules/ (modules here will only be available when you list modules for that site specifically)
/profiles/foo_profile/modules (modules here will only be available when the site has been installed with this profile)

Anywhere else and Drupal won't find them. There's more information on the Installing Drupal 8 Modules page.
Disabling a module for a particular environment is something different, you handle it with configuration management rather than file system paths.
See How to prevent devel module to be installed on production enviroments? for the full picture.
Comment: This I know, and that's what "created a module in a /sites subdirectory" says. it's in a /sites/foo_site/modules directory.
Comment: OK. I looked it up. Got the picture.

D8 can't see module


Is there a lower bound of 15 mins for the Tomcat  value?

Question: Is there a lower bound for the Tomcat server configuration property <session-timeout> ? Because, if I set it to 5 minutes the sessions always expires after 15 minutes. I also tried 1 minute and it was the same.
This is my web.xml for my webapp deployed under tomcat:
    <session-config>
        <session-timeout>5</session-timeout>
        <cookie-config>
           <http-only>true</http-only>
           <secure>false</secure>
        </cookie-config>
    </session-config>

I didn't find anything on the documentation, e.g.
https://docs.oracle.com/cd/E13222_01/wls/docs81/webapp/web_xml.html#1017275
Any hint?
Answer: There is indeed no lower bound on this value. On a "hello world" web application deployed to Tomcat, you can observe that expiration works properly by looking at how often the JSESSIONID cookie value is refreshed in the browser.
If you set session-timeout to 1 minute and refresh the page after 1 minute, the value of JSESSIONID will be different. If you refresh it before 1 minute runs out, it will be the same. This proves that session expiration works as expected.
If in your case it's limited by 15 minutes, it might mean that your application itself does some additional session management.
The HTTP session is just a way to correlate the subsequent HTTP queries. By itself it has nothing to do with authentication or user being logged in / logged out. In case of Tomcat, the session-config configuration is related to the HTTP session management defined by the Servlet specification and supported by Tomcat as the servlet container.
The security framework that you use may take advantage of this Servlet HTTP session to attach authenticated user data, or it may create its own session for that. So expiration of Servlet HTTP session may not coincide with expiration of user login.
Comment: JSESSIONID is by definition the identifier of a session, so a new identifier means the old session was invalidated and a new one was created. How exactly do you determine that the session was not invalidated?
Comment: I've edited my answer and tried to explain a bit more about the difference.
Comment: I got your point @Sergei, thanks for your prompt response. I can see the `JSESSIONID` cookie is renewed after 5 mins, but what I am asking for is: Why the "session" is not killed/invalidated till 15 mins pass. Probably this is not at all about **session expiration**, but rather **session handling** ?
Comment: Basically, I do expect (but I'm probably wrong) the "session expired - logout banner" to appear after that a period of inactivity - longer than the `` value - is elapsed.
Comment: By "logout banner" I assume you use some kind of authentication framework? Do you use standard JavaEE security, Spring Security, something else? Different security frameworks may manage authentication in a different way, it may be flexibly configurable, and they also could have sessions independent from the one created by Tomcat.
Comment: Spring Security! But also Vaadin: indeed, this bit of information (https://stackoverflow.com/a/33541628/6466510) should help. However, I still don't get the difference between: the session **expires** and the `JSESSIONID` is renewed, the user is **logged out** by the security framework and finally, a certain time passed from the last heartbeat/non-heartbeat request.


How can I add custom styling?

Question: I am using the Quicktabs module, which has built-in styles for its tabs.
I would like to add my own custom styling. How can I do it?
Answer: You can do 1 of 2 things:

Patch the quicktabs module to include a css stylesheet for your custom style.
Select an already existing style that matches what you want the closest and then override the styles css.  For example, if you select the arrows style, override the <code>.quicktabs-style-arrows</code> class with whatever you need.

The 2nd option would be the quickest and easiest.
Comment: I would strongly advise against placing your custom style inside the module folder, i did it once and an update removed it.
Comment: If i rather the first approach how would i go about patching  the quicktabs module to include my css stylesheet?
Comment: Just glancing at the code, you'd just need to add your own `mystyle.css` to `/modules/quicktabs/quicktabs_tabstyles/mystyle/mystyle.css` and flush your caches
Comment: Off the top of my head, copy the arrows folder and paste the copy in the styles folder, where the arrows folder is. Quicktabs will recognize the arrows copy as a new style. Then just edit the css of the arrows copy file.
Comment: After an hour trying to edit the arrow with my custom css is not easy as i thought it would...need help in understanding arrow.css what class does
Comment: .quicktabs_main.quicktabs-style-arrows,                                      ul.quicktabs-tabs.quicktabs-style-arrows.

ul.quicktabs-tabs.quicktabs-style-arrows a,

ul.quicktabs-tabs.quicktabs-style-arrows li.active a,
ul.quicktabs-tabs.quicktabs-style-arrows li a:hover                 sorry for all the edits

How can I add custom styling?


Execute a script before fsstab is read

Question: For a netboot cluster, I'm creating a CentOS 6.5 root disk. The goal is to mount / read-only over NFS, and various other folders, such as /var/log, on the local disk.
Here's my first idea:

On boot, a script is executed as early as possible, which checks whether the local disk needs to be initialized or not;
If the disk needs initialization, the LVM volumes are created;
Normal boot continues, and the partitions are mounted whenever /etc/fstab is read.

However, other than modifying /etc/inittab or /etc/rc.d/rc.sysinit, which doesn't sound quite reasonable, I can't see how to execute a script before /etc/inittab is read.
As using local disks with a netboot setup seems to be a fairly common need, I wonder whether there is other solutions to achieve this behavior?
Comment: Have you tried pulling any of the live distros apart to see how they do it, most of those do a similar behavior to allow booting from the CD/DVD.
Comment: @shawty As far as I know, most live distros are mounting the local disk at boot time, with standard init scripts. In my case, I need to mount the disks as early as possible, so, for example, the boot log is written on the local disk and not in a tmpfs.
Comment: I have to admit, it's not something I've ever tried to do Pierre (Hey your a french version of me :-) ) but when you look at a lot of these live distros they seem to be able to do things like that.  You might also want to have a look at gentoo the source only linux, can't think of anything else off the top of my head, but I'll be sure to put some notes on here if I do.
Comment: Another thought, how about writing it as an init script, then numbering/naming it so that it runs before everything else as early as possible.
Answer: You'll probably want to do what you're looking for in a custom initrd. The initrd is used getting drivers loaded, getting software RAID up and going, etc. If you look around for diskless / stateless boot tutorials I suspect you'll be able to cobble together the pieces.

Execute a script before fsstab is read


Evaluate $3^{{7}^{11}}\bmod {10}$

Question: How should I approach solving $3^{7^{11}} \bmod {10}$? I understand how to do $a^x \bmod{n}$ type of problems, but taking on the same approach does not work in this case.
Comment: $(3^7)^{11}=3^{7\cdot 11}$
Comment: What is $3^2\bmod 10$?
Comment: @kamil09875 sorry for the confusion its (3)^(7^11)
Answer: Note that $$7^{11} \equiv (-1)^{11} \equiv -1 \equiv 3 \pmod 4$$
However, $$3^{4k+3} \equiv 3^3 \times (81)^k \equiv  27 \equiv 7 \pmod {10}$$
Answer: $3^1\equiv3 \mod10$
$3^2\equiv-1 \mod10$
$3^3\equiv-3 \mod10$
$3^4\equiv1 \mod10$
Therefore you only need to know the congruence modulo 4 of the exponent. For that, proceed similarly:
$7\equiv 3\mod 4$
$7^2\equiv 1 \mod 4$.
Therefore you only need to know the parity of the exponent. Then $7^{11}\equiv 3\mod 4$, and so $3^{7^{11}}\equiv -3\mod 10$.
Comment: $3^{7^{11}}\equiv -3\mod 10$ is true but I suspect $3^{7^{11}}\equiv 7\mod 10$ was wanted, to show the final decimal digit of $3^{7^{11}}$

Evaluate $3^{{7}^{11}}\bmod {10}$


Appropriate method to Predict Power and time in this set

Question: I am unsure what method to search for and most appropriate approach to solving the predictions of the missing ? values in the below data.
Can you demonstrate the best methodology to determine the predicted values?
[![Dependant    weight(kg)  distance(metres)    time(seconds)   time600 Speed 1 ms  Speed 2 ms  Force   Work Done 1     Work Done 2 Total Work  Power 1 Power 2 Average Power
1   59  1200    70.38   35.8    17.35   16.76   6.020408163 3612.244898 3612.244898 7224.489796 104.4605234 100.9006955 102.6806094
2   58  1200    69.95   34.9    17.12   17.19   5.918367347 3551.020408 3551.020408 7102.040816 101.3129931 101.7484358 101.5307144
3   57  1400    83.15   34.8    16.55   17.24   5.816326531 4653.061224 3489.795918 8142.857143 96.23704704 100.2814919 98.25926947
4   56  1600    95.2    35.4    16.72   16.95   5.714285714 5714.285714 3428.571429 9142.857143 95.5566173  96.85230024 96.20445877
5   58  1400    ?   ?   ?   ?   ?   ?   ?   ?   ?   ?   ?][1]][1]

Comment: Don't you want to add any background information? This looks like 4 time steps and you need a forecast for the 5th. This is really a small sample.
Comment: Thanks Richard the sample is small so its hopefully easier to demonstrate. Is there any background information that would be useful?
Comment: All background info would be useful How does weight play together with distance? And the small sample is not good: it is bad .. not speaking in statistical terms: how can we find a pattern if we just see that few examples?
Comment: First, it's probably just semantics, but there are a lot of ways to predict datapoints (in a timeseries or not) and as long as we do not know the true values of the '?' datapoints, there is no way of finding the best way of predicting these missings (i.e. the method which most closely predicts the true values). Second, do you want to predict all other values for dependant 58 at 1400meters (whatever those represent) or is this missing data in your dataset?
Comment: Well i had figured if i was able to predict the power then this would allow me to backwards solve other missing data.
Answer: You can use a linear model to infer data. In R, this would be:
x <- c(1200,1200,1400,1600,1400) # Taking the distance metric from your example
w <- c(70.38,69.95,83.15,95.2,NA) # Taking the weight metrics from your example

Note that in R, missing data are represented as NA.
model <- lm(w~x) # Define a linear model of x against w
pred <- predict(model,newdata=as.data.frame(x)) # Create a predicted w value for all x values in the data

Note that because you have a prediction for all of the dependent data, whether it is missing or not, you can estimate how accurate the inferred data are.
Comment: If i just use distance and time i dont include weight or other factors. Would this work similarly for power ?
Comment: @sayth: exactly the same principles for predicting, say power, are applicable.


Quickly prove monotonicity of an integral function

Question: How can one quickly show that the function
$$f(x) = e^{x^2/2}\int_x^{+\infty} e^{-s^2/2} ds$$
is monotonically decreasing for every $x \in \mathbb R$?
Differentiating I don't seem to get an easy inequality to solve.
Answer: Hint
Using Logarithmic derivative you get:
$$\frac{f^\prime(x)}{f(x)} = xe^{-x^2/2} - \frac{e^{-x^2/2}}{\int_x^{+\infty} e^{-s^2/2} ds} = e^{-x^2/2}\left(x - \frac{1}{\int_x^{+\infty} e^{-s^2/2} ds}\right).$$
As $f(x)>0$ on $\mathbb R$, you're left to prove that
$$x \int_x^{+\infty} e^{-s^2/2} ds < 1.$$
This is clear for $x \le 0$. And for $x > 0$ you have
$$x \int_x^{+\infty} e^{-s^2/2} ds \le \int_x^{+\infty} se^{-s^2/2} ds = e^{-x^2/2} < 1$$


How do I insert a   tag inside the   tag on my main menu

Question: I have asked exactly this question on Stack Overflow, but it makes more sense to ask it here.
I'm trying to make the text between my tag not display by wrapping it in a and then styling that.
I've added the following function to my template.php file, but I cannot see any difference on the front end; the span just does not appear. (I have cleared my cache.)
Am I using the right function? What am I doing wrong?
function my_theme_link($variables) {
  return '' . ($variables['options']['html'] ? $variables['text'] : check_plain($variables['text'])) . '';
}

Answer: Rather than building the anchor tag, and passing the result of url() to check_plain(), you should call l(), which builds the tag for you.
Remember to set $options['html'] to TRUE (where $options is the last parameter passed to l()), when the string you pass as first argument to l() contains HTML tags; by default the function assumes $options['html'] is FALSE.
Answer: Have a look at http://drupal.org/node/457740 / http://drupal.org/node/988842 and the devel / theme developer module might be useful too.
I think the function your using is for Links in general and is non specific to any menu..
function THEMENAME_links__system_MENUNAME_menu($variables) {
  $output = '';
  foreach ($variables['links'] as $link) {
    $output .= l(''. check_plain($link['title']) .'', $link['href'], $link);
  }
  return $output;
}

EDIT: included span.
Comment: You need also to report to [l()](http://api.drupal.org/api/drupal/includes--common.inc/function/l/7) that the first parameter contains HTML tags; this is done adding `'html' => TRUE` in the array passed as last parameter.
Comment: Thanks, I sort of follow what you are saying, but I think my issue is that I have to add the  tags **inside** the  tag, so that I can make the text in the  tag not appeary, but still have the hyperlink. So I need to override the function that actually ouputs the final html snippet.
Comment: Are you trying to make the text disappear simply for aesthetics, such as using an image button?
Comment: yes, that is exactly what I am trying to do.
Comment: Tried css text-indent:-9999em; ?
Comment: http://css-tricks.com/css-image-replacement/ - good resource for it
Comment: Thanks, kiamlaluno. Mark West solved my problem, but yours is the correct answer to the question that I asked. Would it not be better for you to submit an answer and then I can accept that as the definitive one? Sorry, Mark :-)
Comment: @Westie What would you do, if you need to override all menus to provide a ``?
Answer: I found the solution to this problem after a lot of searching. By the way this works to customize the output of the links of any specific menu.
Let me just say first that customizing the primary or main menu links is something essential to any theming, and the only reason I can think of why Drupal programmers made it so hard to do is so that professional Drupal themers can keep their jobs!
I saw solutions using the theme_link function : bad idea because this will alter the output of ALL your links, which will break your site's layout.
So my approach is to you override the theme_menu_link function. I add a condition to use the override only on the specific menu I want. In this example I chose the primary links. To know the name of the menu you want to theme you have to put dsm($variables) and usse the Devel module.
function yourtheme_menu_link(array $variables) {

  $element = $variables['element'];
  $sub_menu = '';

// Replace 'menu_link__menu_block__1' with the name of the menu you want to theme.
if ($element['#theme']['0'] == 'menu_link__menu_block__1') {
  if ($element['#below']) {
    $sub_menu = drupal_render($element['#below']);
  }

  $title = $element['#title'];

// I put the span tags in the title.
  $element['#title'] = '' . $title . '';
// I tell the l() function to keep the HTML tags.
  $element['#localized_options'] += array(
    'attributes' => array(),
    'html' => TRUE,
  );
  $output = l($element['#title'], $element['#href'], $element['#localized_options']);
  return '
' . $output . $sub_menu . "
\n";
}
// The function renders the links from all the other menus without modification.
if ($element['#below']) {
  $sub_menu = drupal_render($element['#below']);
}
$output = l($element['#title'], $element['#href'], $element['#localized_options']);

return '
' . $output . $sub_menu . "
\n";
}

Answer: This outputs the same result than the code shown by Taerno, and it works fine in Drupal 7.12.
function yourtheme_menu_link(array $variables) {
  $element = $variables['element'];
  $sub_menu = '';

  if ($element['#below']) {
    $sub_menu = drupal_render($element['#below']);
  }

  $element['#localized_options']['html'] = TRUE;
  $linktext = '' . $element['#title'] . '';

  $output = l($linktext, $element['#href'], $element['#localized_options']);
  return '
' . $output . $sub_menu . "
\n";
}

You could add in the following code, where "menu_link__menu_block__1" is the name of your menu.
if ($element['#theme']['0'] == 'menu_link__menu_block__1') {

}

I found the name of the menu by printing $element['#theme']['0'] for my menu.
I am trying to add the span to the parent link only, so I will post when I have done that.
Comment: I think this is the cleaneast solution so far, but two more things:

1. For security reasons you should use check_plain($element['title']) to sanitize the title before echoing it
2. You could use the hook yourtheme_menu_link__menu_block__1 to avoid the if condition
Answer: You might be interested in the Theme Developer module. It lets you click on elements of a Drupal page to discover which theme function/template generated them, what arguments were passed in, which alternatives are available, etc.
Comment: Thanks, I have that installed already. When I click on a menu item I get the following: parent links__system_main_menu and Function called: Them_link() - Hence me trying to override the link function.
Answer: Most of the cases where you would have needed an extra span before can now be solved with css only:
li {
  position: relative;
  padding-left: 25px;
}

li:before {
  content: "";
  position: absolute;
  left: 0;
  top: 0;
  width: 20px;
  height: 20px;
  background: url('../images/icons.png') no-repeat;
  background-position: 0 0;
}


Best way to read data from a file

Question:
Possible Duplicate:
Best way to read a text file

In Java I can open a text file like this:
BufferedReader reader = new BufferedReader(new FileReader("file.txt"));

My question is, how do you read from the following file? The first line is a number (830) representing number of words, and the following lines contain the words.
830
cooking
English
weather
.
.

I want to read the words into a string array. But how do I read the data first?
Answer: You're on the right track; I would treat the first line as a special case by parsing it as an integer (see Integer#parseInt(String)) then reading the words as individual lines:
BufferedReader reader = new BufferedReader(new FileReader("file.txt"));
String numLinesStr = reader.readLine();
if (numLinesStr == null) throw new Exception("invalid file format");
List<String> lines = new ArrayList<String>();
int numLines = Integer.parseInt(numLinesStr);
for (int i=0; i<numLines; i++) {
  lines.add(reader.readLine());
}

Answer: Unless you have some special reason, it's not necessary to keep track of how many lines the file contain. Just use something like this:
BufferedReader reader = new BufferedReader(new FileReader("file.txt"));

String line;
while ((line = reader.readLine()) != null) {
    // ...
}

Answer: If you're working with Java version greater than 1.5, you can also use the Scanner class:
Scanner sc = new Scanner(new File("someTextFile.txt"));
List<String> words = new ArrayList<String>();
int lines = sc.nextInt();

for(int i = 1; i <= lines; i++) {
    words.add(sc.nextLine());
}

String[] w = words.toArray(new String[]{});

Answer: Try the class java.io.BufferedReader, created on a java.io.FileReader.
This object has the method readLine, which will read the next line from the file:
try
{
    java.io.BufferedReader in =
        new java.io.BufferedReader(new java.io.FileReader("filename.txt"));

    String str;
    while((str = in.readLine()) != null)
    {
        ...
    }
 }
 catch(java.io.IOException ex)
 {
 }

Answer: You could use reflection and do this dynamically:
 public static void read() {

            try {
                BufferedReader reader = new BufferedReader(new FileReader(
                        "filename.txt"));

                String line = reader.readLine();

                while (line != null) {
                    if (Integer.class.isAssignableFrom(line.getClass())) {
                        int number = Integer.parseInt(line);
                        System.out.println(number);
                    } else {
                        String word = line;
                        System.out.println(word);
                    }

                    line = reader.readLine();
                }
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }

        }

Best way to read data from a file


Estimating the response variable distribution in bivariate simple linear regression

Question: So let's say I have a bunch of $IID$ samples $(X_n,Y_n)_n$ from some unknown distribution $p(x,y)$, where $Y$ is the response variable and $X$ is the explanatory variable.  And suppose I plotted these points and saw a pretty obvious positive linear relationship, (for instance maybe $X$ is amount of sunlight and $Y$ is sunflower height, or something like that).
Then suppose I wanted to try to get a good idea of what the distribution for $Y$ might be.  Well I could just look at the $Y$ coordinates from my samples and plot a histogram and then fit a curve to it, or something like that, but I believe that would only make sense under the assumption that the $Y_n$ are $IID$, when all I know is that they are identically distributed, and not necessarily that they are independent.
So instead what I do is plot the least-squares regression line $y=f(x)$ for my data, and then try to calculate the marginal distribution for $Y$:
$$p(y)=\int_{x\in\Omega}p(x,y)dx=\int_{x\in\Omega}p(y|x)p(x)dx.$$
Now what I do is assume there's some standard normal variability about my regression line, and so I set $p(y|x) = N(f(x),1)$.  However the problem in finding $p(x)$ is the same problem I have in finding $p(y)$, namely, my samples $X_n$ could very well not be independent.
Assuming I'm understanding the theory correctly, how do I go about resolving this?
Edit: Now I'm thinking maybe the $Y_n$ are independently sampled, but how would one go about proving this?
Answer: If the $\{(X_i,Y_i)\}_i$ are an iid samples from the distribution $p(x,y)$, then the $\{Y_i\}_i$ will be an iid sample from the marginal distribution $p(y)$.
To see this, write the joint distribution $p(y_1,\ldots,y_n)$ of $(Y_1,\ldots,Y_n)$ as $$p(y_1,\ldots,y_n)=\int_{x_1\in\Omega}\cdots\int_{x_n\in\Omega} \prod_{i=1}^n p(x_i,y_i)\ dx_1\cdots dx_n. $$
Then it follows that
$$p(y_1,\ldots,y_n)=\prod_{i=1}^n\int_{x_i\in\Omega}p(x_i,y_i)\ dx_i= \prod_{i=1}^n p(y_i),$$
showing that the $\{Y_i\}_i$ are iid with distribution $p(y)$.


Meaning of convergence of series in a radius

Question: I know this might sound quite an odd question but I'll try to explain myself. Previously in calculus I understood the meaning of a series to be "converging" like $\sum_{n=1}^\infty \frac{1}{n^2}$ because I understood what it meant, which is that if you keep on summing terms to terms like so $$\frac11+\frac 14+\frac 19+\frac{1}{16}+\dots$$ it would eventually converge to a number that is well known. But I've been learning now complex analysis and never really stopped to understand what it actually means that a series has a radius of convergence like $\sum_{n=0}^\infty z^n=\frac{1}{1-z}$ has the radius of convergence of 1, and that for $|z|<1$ it converges but for $|z|>1$ it diverges, what does it mean?
And yes, I have read several questions here but none satisfied myself fully, also other sources like my book don't really explain this well, they just focus on how to find that radius of convergence, not it's meaning
Comment: You typed $z_n$ for $z^{n}$.
Comment: It seems like you accidentally typed $\frac11+\frac12+\frac13+\frac14+\cdots$ instead of $\frac11+\frac14+\frac19+\frac1{16}+\cdots$.
Comment: You understand the meaning of "convergent series", but not the meaning of "divergent series"? Is that it?
Comment: $|z|=|re^{i\theta}|<1$ or $x^{2}+y^{2}=r^{2}<1$  the contour being the circumference :$|z|=1$ or $x^{2}+y^{2}=1$
Comment: @JoséCarlosSantos No, the user below in the post understood what I meant, I didn't grasp the idea how what it meant that a series only converged for a certain radius, now I understand that for the numbers inside that circle, the numerical series will converge as I'm used to understand with the usual numeric series like $\sum \frac{1}{n^2}$
Answer: The difference is that the series $$\sum_{n=1}^\infty \frac{1}{n^2}=\frac{1}{1}+\frac{1}{4}+\frac{1}{9}+\ldots$$ involves adding numbers, while $$\sum_{n=1}^\infty z^n=z+z^2+z^3+\ldots$$ does not. Because $z$ is not a number. It is a variable. So for the first series I mentioned above, you can ask "does it converge"? and that question makes sense with a single yes/no answer. For the series $\sum_{n=1}^\infty z^n$, you can ask "does it converge"? But that question doesn't make sense with one yes/no answer, because you could get different yes/no answers for different choices of $z$. For example, if we take $\sum_{n=1}^\infty z^n$, plugging in $z=1/2$ yields $$\frac{1}{2}+\frac{1}{4}+\frac{1}{8}+\ldots=1,$$ exactly as you understand convergence. But if we plug in $z=2$, we get $$2+4+8+\ldots,$$ which diverges. So for something like $\sum_{n=0}^\infty c_n(z-a)^n$, instead of asking "does it converge?", we ask "for which $z$ does it converge"? The answer to this question will be a set of $z$s. That set is always a disk centered at the point $a$, and so it makes sense to ask what is the radius of that disk. (The radius can be $0$, in which case the "disk" is really just the point $a$, and the radius can be $\infty$, in which case the "disk" is the whole complex plane).
When we write, for example, $$e^z=\sum_{n=0}^\infty \frac{z^n}{n!},$$ you may be confused about the meaning, because you are thinking of the terms being added until they "eventually converge" to a number (not a function). But all this means is that for each particular $z$ value within the disk of convergence, when I evaluate the series with that specific number, the right side will converge to the function on the left side evaluated at that point, eg $$e^2=\sum_{n=0}^\infty \frac{2^n}{n!}.$$ The right side is a series of numbers and it converges to $$1+\frac{2}{1!}+\frac{4}{2!}+\frac{8}{3!}+\ldots=e^2\approx 7.38905609893.$$
Answer: Let't first clear up what "converge" and "diverge" mean.
When a series converge, it means that as the upper bound of the summation approaches infinity, the summation will go towards some value. Rigorously, in terms of limits, if your summation is defined as $S_n=\sum_{k=1}^na_k$ for some sequence $a$, then $\lim_\limits{n\to\infty}S_n=L$ for some finite value $L$.
When a series diverges, it simply means that the limit defined above does not exist.
Now let's discuss about interval of convergence. What an interval of convergence of a series means is essentially: what numbers can be substituted into the summation in order to make the summation converge?
Let's take your geometric series example:
$$\sum_{n=0}^\infty z^n=\frac1{1-z}$$
Let's try setting $z$ to be a specific value, like $0.5$. So the series becomes:
$$\sum_{n=0}^\infty (0.5)^n$$
We can see that this converges in a variety of ways, but we can do an integral test for example, and see that since $$\int_0^\infty(0.5)^xdx=\frac1{\ln2}$$
i.e. the integral converges, then the corresponding series will also converge due to the integral test.
But now let's take $z=2$, for instance. Now the series becomes:
$$\sum_{n=0}^\infty 2^n$$
Because $\lim_\limits{n\to\infty}2^n$ does not exist (it tends towards infinity), we can say that this summation diverges due to the divergence test.
So we can see that for some values, such as $z=0.5$, the series will converge, while for other values, such as $z=2$, the series will diverge.
The interval of convergence is a range of $z$ values such that the series will converge. In this case, it can be found that the series will converge only if $|z|<1$, and will diverge for all other values of $z$. Because of reasons I won't go into here, it turns out that the interval of convergence for any series is either a single continuous interval, empty, or contains all real numbers. Specifically, it won't be a union of disjoint intervals.
As for the radius of convergence, it is essentially just the length of this interval divided by $2$. Because the interval of convergence won't be a union of disjoint intervals, it will always be possible to find some "center" of this interval, and from there, find the radius of the interval of convergence.


Show the following is logically equivalent

Question: Show that
$$p \leftrightarrow (q \land r) \equiv (\lnot q \lor \lnot r) \leftrightarrow \lnot p $$
I can't use a truth table.
I'm really confused. So if you could explain using the law.
This is what I got
LHS:
= $\lnot p \leftrightarrow \lnot(q  \land r)$
= $\lnot p \leftrightarrow (\lnot q  \lor \lnot r)$
Comment: Have you already proved that $p\leftrightarrow q\equiv\neg p\leftrightarrow\neg q$?
Comment: Is that one of the laws? I have a table here and I didn't see that but that seems to be equivalent
Comment: It isn't one of the equivalences that are usually considered basic laws, but it's not too hard to prove using the fact that $p\leftrightarrow q$ is equivalent to $(p\to q)\land(q\to p)$.
Comment: So like in this case, which side would be better to start with? Because I could easily change the left side $(q \land r)$ into the $(\lnot q \land \lnot r)$ but then after it gets confusing. Also how would I change the arrow to the or symbol.
Comment: My inclination would be first to prove that $(s\leftrightarrow t)\equiv(\neg s\leftrightarrow\neg t)$ as a general rule and then to let $s=p$ and $t=q\land r$; after that all you need is one application of De Morgan's law.
Comment: I edited the question to what I got so far, but after that I'm confused, I could be totally wrong too.
Comment: You have an extra negation: if you're going to use the equivalence that I suggested (which will still need to be proved), the lefthand side is equivalent to $\neg p\leftrightarrow\neg(q\land r)$, which is equivalent to $\neg p\leftrightarrow(\neg q\lor\neg r)$.
Answer: HINT for the revised question: Complete the calculation so that you end up with $(\neg q\lor\neg r)\to\neg p$:
$$\begin{align*}
p\to(q\land r)&\equiv\neg p\lor(q\land r)\\
&\equiv\neg p\lor\neg\big(\neg(q\land r)\big)\\
&\equiv\neg p\lor\neg(\neg q\lor\neg r)\\
&\equiv\ldots
\end{align*}$$
Comment: I think I made a error in my question, I meant to say $\to$ not $\leftrightarrow$
Comment: would that change the change the answer?
Comment: @Shawn: It makes it *much* easier. I've revised my answer to match; you should do the same to the question itself.
Comment: I dont get why you changed the $\to$ to $\or$, but the last calculation you did, all I have to do is the de Morgans law correct?
Comment: @Shawn: I assumed that you knew that $p\to q$ is equivalent to $\neg p\lor q$; you really do need that equivalence, so far as I can see. I've already made the one application of De Morgan's law that's needed; the last step (or two, depending on how fussy you're required to be) requires something else.


repeated measures anova using minitab

Question:
I have to analyze repeated measures data set where each subject's BMI is measured at several time points. I have two sets of subjects where some were given drug1 and another group of subjects is given drug2.
  With using repeated measures ANOVA first I am trying to analyze for the subjects who were given drug 1, how their BMI varies with time .After that  analyze for the subjects who were given drug 2, how their BMI varies with time.
I am using MINITAB 17 and using Stat -> ANOVA -> General Linear Model, I don't understand what should be put in Responses ? Should this be BMI. And for factors I included time.
Is this correct?  What should be included for covariates field?
Comment: Is there any 'fixed effect' or 'random effect' option in minitab panel there?
Comment: This page has similar task , though in a different program : http://www.statsdirect.com/help/default.htm#analysis_of_variance/two_way_replicate.htm%3FTocPath%3DAnalysis%2520of%2520variance|_____3S
Answer: In 'Responses' you need to use the BMI as it is your interest of study.
I'm not sure, how you coded Time as 1,2,3 but if it is a factor that affects the response (BMI) then it's okay to use. You may also have to use 'Drug' & 'subject' as factors.
Covariates are quantitative variables measured on either an interval scale or ratio scale. Examples include height, weight, age, temperature, volume, pressure and so on, in fact any valid, predictor or independent variable.
It is an optional input in Minitab. In your case, I do not see a continuous predictor. So, you can leave it as blank. Hope this helps!

repeated measures anova using minitab


Higher ramification groups

Question: I was wondering if someone could explain what higher ramification groups are used for? What information do they contain and why are they important?
Answer: Some more-or-less random things that come to mind:

There is the formula for computing the different of a field extension in terms of the sizes of the higher ramification groups.
The higher ramification groups correspond to naturally arising groups of local units; namely, their image under the Artin map are precisely the higher powers of the local 1-units.
In fact, historically more basic than the previous point is that the first very careful proofs of Kronecker-Weber (i.e., before class field theory existed) by Hilbert heavily involved the use of the higher ramification groups.
They turn out to provide the correct fix to Euler factors of L-functions at "bad" places (where "bad" depends on your context.)  This would require a rather long digression, so let me just mention the Hasse-Arf theorem and the Artin conductor.
Answer:
In basic Galois theory, to add to Cam's answers: they provide information on whether an extension is tame or wildly ramified and thus give a more complete picture
Sheaf theoretically: for example, higher ramification groups give an important invariant called the Swan conductor which is used in the Ogg-Shafarevich formula for computing Euler characteristics of curves. This formula has been generalized by Deligne, Laumon, and more recently Kato-Saito for higher dimensions.

Higher ramification groups


Como bloquear o teclado em jquery?

Question: Como bloquear o teclado todo em jquery, especialmente a tecla esc para tela cheia, quero que não saia do fullscreen quando apertar esc.
exemplo:
<code>$(document).keydown(function(e) {
    if (e.keyCode == 13) { return false; }
    if (e.keyCode == 27) { return false; }
});
</code>
É um cadastro de usuários e ele fica em um computador especifico só para o cadastro desses usuários, o pc não vai ter outra função a não ser essa.
Comment: Que navegador sai da tela cheia com ESC? Tentei o Chrome e o Firefox e ambos ignoram por padrão.
Comment: Todos saiem do fullscreen com ESC pelo que eu sei, pelo menos o internet explorer sai...
Comment: Já experimentou `$(document).keydown(function(e) { return false; });` ?
Comment: Ele continua saindo do fullscreen Sergio!
Comment: Provavelmente isso é independente do Browser, e sim uma função do OS. De qq maneira acho desaconselhável impedir o utilizador de sair de full-screen...
Comment: É um programa de cadastro e o usuario não pode sair da tela cheia, eu desabilitei o F1 com o cód: document.onhelp = function() { return(false); }
window.onhelp = function() { return(false); }
provavelmente tem alguma maneira de desabilitar o esc
Comment: Além de dar `return false;`, já tentou `e.preventDefault();`?
Comment: Já sim, e não deu certo...
Answer: Por questões de segurança, nenhum browser vai permitir que uma página qualquer tire do usuário os controles mais básicos - como minimizar a janela, trocar para outra, etc. Nada impede, por exemplo, o uso de Alt+Tab ou Ctrl+Alt+Del - e a partir daí o usuário provavelmente vai conseguir fazer o que ele quiser. Não conheço a fundo o modo fullscreen, mas sei que o usuário precisa dar autorização pra entrar em tela cheia, e estou certo que o browser não permite que você sobrecarregue o comando para sair dela, seja ele qual for.
Sugiro que você "dê um passo pra trás" e avalie exatamente que problema você está tentando resolver (e não somente a solução imaginada).

É um programa de cadastro e o usuario não pode sair da tela cheia...

Cadastro no que? Não pode sair da tela cheia por que? É para resolver algum problema técnico no seu site/serviço/aplicativo (e se for, qual?) ou por razões de segurança? Existem alternativas? É importante que esses detalhes sejam bem pensados - e a solução mais apropriada empregada (seja usando recursos nativos do browser, ou recorrendo a plugins e/ou funcionalidades específicas do SO). Pois no caso geral a única resposta correta pra sua pergunta é: "é impossível bloquear totalmente o teclado em jQuery".
Comment: @user3230262 Além disso, procure saber como utilizar o "modo kiosk" ([*kiosk mode*](http://en.wikipedia.org/wiki/Kiosk_software)) do seu sistema operacional - de modo a impedir de fato o usuário de sair/trocar de aplicativo usando os controles usuais. Assim você vai ter um aplicativo que só acessa uma única página, e que não pode ser trocado por usuários não privilegiados.
Comment: É um cadastro de usuários e ele fica em um computador especifico só para o cadastro desses usuários, o pc não vai ter outra função, estou pensando até em usar linguagens de software como Delphi para bolar esse sistema, preciso de sugestões...
Comment: @user3230262 Nesse caso, eu sugeriria investigar **browsers específicos pra um único site** ([*site-specific browser*](http://en.wikipedia.org/wiki/Site-specific_browser)). É uma funcionalidade que alguns browsers oferecem (dentre eles o IE9+ e o Google Chrome) para criar um atalho no desktop que abre uma janela do browser "simplificada" - sem menus, barra de endereço e coisas assim - restrita a acessar um único site ou domínio. Não posso indicar uma solução específica, pois não cheguei a usar nenhuma na prática, mas no site linkado (Wikipedia, em inglês) mostra algumas opções no fim da página
Comment: mgibsonbr, vou pesquisar sobre kiosk mode e site-specific-browser, obrigado!

Como bloquear o teclado em jquery?


Is a VPS with some resources the same as a Dedicated server with exactly same resources?

Question: Apologize if I shouldn't ask this here.
I want to acquire a VPS or a Dedicated. I read about VPS and Dedicated and the differences but I don't understand something...
Is a VPS with some resources (X CPU cores, Y RAM, Z Bandwidth etc) the SAME as a Dedicated with exactly the same resources (X CPU cores, Y RAM, Z Bandwidth etc)?
I saw VPSs are cheaper than Dedicated even with same resources. What is the difference? If there is a difference is it big (affecting the performance so much)?
Thank you very much!
Comment: I'm not going to add an answer, but one thing to consider is security - although somewhat rare, there are documented vulnerabilities for breaking out of virtualized containers. This means that if some other VPS customer's site has a vulnerability, someone could theoretically break into their site and pivot all the way up to controlling the server your VPS is on. It shouldn't be an issue if your host keeps everything updated and patched - but there are plenty of third-rate webhosts that take the lazy approach!
Answer: In the best case, it will be of similar performance (with a slight performance impact due to the virt overhead). In the worst case with a bad provider, you end  up in a "up to X" situation where the provider overcommits resources and if people start to use those resources, things get slow.
VPSs are cheaper because even a good provider can overcommit (selling more resources then he really has, because in reality, most servers idle most of the time) and also because there is a big overhead to run a physical server and it's much cheaper to run one powerful server that then runs a number of smaller VPSs instead of running the same number of physical servers.
Comment: Also on top, the OP Misses the most critical factor: IO bandwidth (IOPS). Often a problem in dedicated hardware, but once you have 20 VM's hitting the same discs.... better make sure the provider is using only SSD.
Comment: Thank you very much! @TomTom thank you, I really missed that.
Comment: OTOH, Somebody building a good server to carry VPSes has good reason to invest in a good I/O and storage subsystem, which can be to your advantage in peak load scenarios. A VMWare instance on a non-overloaded box with, say, an LSI9280+BBU (an older but honest RAID card) and VMWare's IMHO excellent drivers and decent disks will S M O K E a dedicated server equipped with "the cheapest bargain basement parts that we can sell as RAID" when it comes to I/O.
Comment: @rackandboneman: This is not what this question is about.
Comment: @Sven it is something that in that context, especially among claims that I/O is going to be a potential problem, need be said. NMNL.


Unfaithful husbands

Question: In a parallel universe when Neil Armstrong landed on the moon, he found it to be inhabited by a tribe of humanoids. He discovered that:

they were all married
the husbands of 10 of the wives were unfaithful
Each wife knew whether or not any other wife's husband was a cheater, but did not know whether or not her own husband was a cheater
No wife was allowed to tell any other wife that her husband was unfaithful or otherwise. Husbands also did not discuss this but otherwise gossip was gossip …
If a wife discovered her husband was unfaithful she had to throw him out of the house and onto the street at precisely 10am the following day, where he would be visible to all others in the tribe.

Foolishly Neil informed the entire tribe at 11am on the day that he landed that at least one of the husbands was unfaithful. What happened next?
Comment: Conspiraciy theorists may ask: Why does the problem require a parallel universe? Because in ours the moon is uninhabited or because in ours the moon landing was faked?
Comment: At noon, one of the wives finds a pair of frilly underwear behind the bed that isn't hers.  The next morning, her husband is out on the street.  The tribe returns to business as usual, and the 9 other cheaters breathe a sigh of relief.  (Or do they?)
Comment: In case anyone wonders whether (4) allows men to gossip with women about who is unfaithful: it does not.
Answer: That's the famous problem related to the concept of the common knowledge, and the solution is well-known though often leads to arguments of people who don't rely upon it. The hint it to solve the problem by induction: suppose that there is only one guy who is cheating and see what happens. Then think of two guys cheating and try reducing it to the previous case, etc.
See also a very similar problem about blue-eyed guys in my link. Also, here is a post of Terry Tao on this problem.
Since it's a CW post, I decided to do a bit of a search on MSE and found several more examples which talk about blue eyes.

Unfaithful husbands


Moving absolutely positioned image according to container div's position in the browser window

Question: I have a div with a relative position (div 1). It contains an image (shown as the green block) with an absolute position which by default is hidden way off to the left of the browser window.
I'd like to make it so that when div 1 is in the center of the browser window as the user scrolls down, the image is moved in slightly from the left and appears on the screen. As the user begins to scroll down past div 1, I'd like the image to move back to its original offscreen position.
I have attached a picture to try and make a bit more sense.

I have a feeling this is possible using JavaScript or jQuery but I'm not sure how. Any help would be greatly appreciated.
Ian
Comment: have a live example of the HTML structure?
Answer: You'll want to bind a handler to the scroll event of the window, and measure the ratio of how far down the page the user has scrolled - then, position the image accordingly. I built a rough prototype; you should be able to tweak sizes and positions to make it work for you.
The JS for the prototype, which depends on the HTML and CSS in the JSFiddle linked above, is as follows:
var $main = $('.main');
var $tgt = $('.targetMover');
var origLeft = $tgt.position().left;
var maxLeft = 200;

$main.scroll(function(ev){
    var ratio = $main[0].scrollTop / $main[0].scrollHeight;
    var newLeft = origLeft + ( (maxLeft - origLeft) * ratio);
    $tgt.css({left:newLeft});
});

Comment: The example is good, it just doesn't move back after it has scrolled past the div, but should be enough to guide the OP
Answer: You would want to position the image on scroll. You would basically check what the position of the div is, set the top of the image to the same as the div, and set the left to whatever you like. you could use jquery animate for this to make it "move" to that position. You then would have to manage to do an scrollstop event (which doesn't exist), and hide the image again. See: http://james.padolsey.com/javascript/special-scroll-events-for-jquery/ for scrollstop implementation (taken from the below post).
You might want to read through jQuery - fadeOut on Scroll / fadeIn on "scrollstop"


Task.ContinueWith and .wait(). ObjectDisposedException?

Question: I use a pattern including tasks in C# where I do
Task.Factory.StartNew( .something... )
            .ContinueWith(t=> {
                                 try{ t.Wait() }
                                 catch(Exception ex) ...
                               });

if something forexample includes WCF code or other exception throwing stuff. That way Im sure that the tasks have been waited for I dont get those finalizer exceptions and I can consistently log error messages.
Recently I have seen that t.Wait() throws ObjectDisposed exception. Is my pattern wrong or should I keep the continue with only on TaskContinuationOptions.NotOnRanToCompletion.
Answer: If the continuation is firing, it is pretty obvious that it has completed (one way or another); there is no need to Wait() on something that has finished. Just check how it finished (completion, cancellation (.IsCanceled), exception (.IsFaulted)), and access the result (.Result) if appropriate.
The ObjectDisposedException sounds like the notorious WCF "feature", where-by the Dispose() in WCF can throw the above (which is annoying). There are various ways proposed to wrap WCF to handle this, but this is unrelated to the task API. WCF thus swallows the actual error, and surfaces ObjectDisposedException. There are several stackoverflow questions that address this.
Comment: @svrist and the end of that message is "or accessing its Exception property"; so yes - checking the exception **does** mark it observed (I've just verified this in a console exe, too)
Comment: So you are saying that if I just access t.Exception I can avoid the finalizer exception
Comment: "A Task's exception(s) were not observed either by Waiting on the Task " like described here: http://stackoverflow.com/questions/7883052/a-tasks-exceptions-were-not-observed-either-by-waiting-on-the-task-or-accessi
Answer: You can use the following TaskContinuationOptions to see how your Task finished.
var t = Task.Factory.StartNew(...)
(....)
 t.ContinueWith(task => (..Ran to Completion.. + task.Result),   TaskContinuationOptions.OnlyOnRanToCompletion);
t.ContinueWith(task => (..Handle Exception .. + task.Exception),
       TaskContinuationOptions.OnlyOnFaulted);
t.ContinueWith(task => (.. Was cancelled..),
       TaskContinuationOptions.OnlyOnCanceled);

Comment: Thanks svrist, I oversaw that in a hurry!


Getting oldest record from SQL Server using T-SQL

Question: I have a T-SQL query where I need to find the oldest date record. I have written it like this:
SELECT
    T0.ItemCode, T0.OpenQty AS 'Qty', MIN(T1.DocDate) AS 'DocDate',
    T1.DocNum, T1.CardCode, T1.SlpCode AS 'Sales Person', T0.WhsCode
FROM
    RDR1 T0
INNER JOIN
    ORDR T1 ON T0.DocEntry = T1.DocEntry
WHERE
    T0.linestatus = 'O'
GROUP BY
    T0.ItemCode, T0.OpenQty , T1.DocNum, T1.CardCode, T1.SlpCode , T0.WhsCode

but it is not returning the oldest date record.
Data is shown in this screenshot:
Comment: What is the data type of DocDate? What output are you getting and what is your expected result?
Answer: You can use ROW_NUMBER() to rank the records by ascending T1.DocDate in a inner query, and then select the oldest in the outer query:
Select *
From (
    Select
        T0.ItemCode,
        T0.OpenQty as 'Qty',
        T1.DocDate,
        T1.DocNum,
        T1.CardCode,
        T1.SlpCode as 'Sales Person',
        T0.WhsCode,
        Row_Number() Over(Order By T1.DocDate) rn
    From RDR1 T0
    Inner Join ORDR T1 on T0.DocEntry = T1.DocEntry
    Where T0.linestatus = 'O'
) x
Where rn = 1

This will give you the oldest record in the table. If you need to get the oldest record per group, then you can add a PARTITION BY clause to the ROW_NUMBER() function.
Note: this also assumes that T1.DocDate is of a date-like datatype, which seems to be (and should be) the case by looking at your sample data.
Comment: Thanks for the response. I need a unique oldest record in each group. I tried Partition But it's not working. and yes its date type data type.
Comment: @AsifHameed: how do you define a group?
Comment: The values with the same itemcode and Qty are a group as highlighted in image. i want to pick the one with old date
Comment: @AsifHameed: ok so you would need `Row_Number() Over(Partition By T0.ItemCode, T0.OpenQty Order By T1.DocDate)`.
Answer: Why are you writing Self join ?  If you need to get 10 oldest record from table then just sort the table according date in ascending order and list top 10 rows.
For Example -
Select  top 10 T0.ItemCode, T0.OpenQty as 'Qty', T1.DocDate as 'DocDate', T1.DocNum, T1.CardCode, T1.SlpCode as 'Sales Person', T0.WhsCode
From RDR1 T0
Where T0.linestatus = 'O'
order by T1.DocDate