MinMax Algorithm for Tic Tac Toe

Question: I'm trying to do the MinMax for the tic tac toe (Always computer win) but I can't get it to work.
All the successors simply return 0 (draw) as score and so the computer always chooses to move in the natural direction of the matrix.
PS: Matrix (class) is the board where they play, that contains an array of 9 positions.

| X | O | X | O | ... | like this.

Global Variable that handles the Tic Tac Toe board is called Main and is an instance of Matrix.
public void minMax(Matrix p) {
  Matrix bestvalue = maxValue(p);
  print(bestvalue);
  System.out.println(bestvalue.getScore());
  main = searchSucessorWithScore(p, bestvalue.getScore());
}

public Matrix maxValue(Matrix p) {
  if(endState(p)) { p.setScore(utility(p)); return p; } //always sets score to       0 but the method utility is correct...
  Matrix bestmove = new Matrix();
  bestmove.setScore(Integer.MIN_VALUE);
  LinkedList<Matrix> list = addSucessors(p, plays.PLAY_X);
  for(Matrix s : list) {
    Matrix move = minValue(s);
    if(move.getScore() > bestmove.getScore()) {
       bestmove = move;
    }
  }
  return bestmove;
}

public Matrix minValue(Matrix p) {
  if(endState(p)) { p.setScore(utility(p)); return p;}
  Matrix bestmove = new Matrix();
  bestmove.setScore(Integer.MAX_VALUE);
  LinkedList<Matrix> list = addSucessors(p, plays.PLAY_O);
  for(Matrix s : list) {
    Matrix move = maxValue(s);
    if(move.getScore() < bestmove.getScore()) { // <
      bestmove = move;
    }
  }
  return bestmove;
}

Auxiliar methods:

public LinkedList<Matrix> addSucessors(Matrix k, plays l) {
  LinkedList<Matrix> list = new LinkedList<Matrix>();
  for(int i=0; i<9; i++) {
  if(k.getRow(i).equals(plays.BLANK)) {
    Matrix p = k.clone();
    p.setRow(i, l);
    list.add(p);
  }
  }
return list;
}

/* RETURNS 0 FOR DRAW, 1 FOR PC WIN, -1 FOR USER WIN */
public int utility(Matrix p) {
  for(int i=0; i<9; i=i+3) {
    if(main.getRow(i).equals(plays.PLAY_X) && main.getRow(i+1).equals(plays.PLAY_X) && main.getRow(i+2).equals(plays.PLAY_X)) return 1;
    if(main.getRow(i).equals(plays.PLAY_O) && main.getRow(i+1).equals(plays.PLAY_O) && main.getRow(i+2).equals(plays.PLAY_O)) return -1;
  }
  for(int i=0; i<3; i++) {
    if(main.getRow(i).equals(plays.PLAY_X) && main.getRow(i+3).equals(plays.PLAY_X) && main.getRow(i+6).equals(plays.PLAY_X)) return 1;
    if(main.getRow(i).equals(plays.PLAY_O) && main.getRow(i+3).equals(plays.PLAY_O) && main.getRow(i+6).equals(plays.PLAY_O)) return -1;
  }
    if(main.getRow(0).equals(plays.PLAY_X) && main.getRow(4).equals(plays.PLAY_X) && main.getRow(8).equals(plays.PLAY_X)) return 1;
    if(main.getRow(2).equals(plays.PLAY_X) && main.getRow(4).equals(plays.PLAY_X) && main.getRow(6).equals(plays.PLAY_X)) return 1;
    if(main.getRow(0).equals(plays.PLAY_O) && main.getRow(4).equals(plays.PLAY_O) &&   main.getRow(8).equals(plays.PLAY_O)) return -1;
    if(main.getRow(2).equals(plays.PLAY_O) && main.getRow(4).equals(plays.PLAY_O) && main.getRow(6).equals(plays.PLAY_O)) return -1;
return 0;
}

public Matrix searchSucessorWithScore(Matrix p, Integer v) {
  for(Matrix s : addSucessors(p, plays.PLAY_X) {
  if(s.getScore() == v) return s;
  }
return null;
}

The method utility is correct, but inside recursion only returns 0 even for matrix's where there's a winner.
Help :D
Comment: I've recently played around with game theory algorithms and implemented 'Tic Tac Toe' and 'Connect Four'. Have a look at https://github.com/winterer/GameTheory
Comment: and you post the `setScore()` code to make sure that's correct?
Comment: It's correct. It's part of the class Matrix and just does: this.score = score;
Comment: well then how does this code ` p.setScore(utility(p));` always set the score to 0 if `utility()` is correct (so you say)
Comment: Because if I print the value of utility(p) and use a random p I made and test with the ones it fails during the algorithm. Utility always prints the correct result. Inside recursion, magic happens...
Comment: What do you see if you print out the contents of the matrix inside the utility function in the full program?
Comment: Shouldn't TicTacToe always end in a draw when both sides play optimally?
Comment: Yes, it should. I found the mistake in the utility, now it prints the correct result. What happens now is: whenever I play and computer understands he has no chance of winning he returns the final state, and ends. Still, he plays by the natural order of the cells. It's almost there, but not working yet. Any ideas?
Comment: Solved it. In case someone is wondering, the problem was the list where I was checking the score to pick a move, didn't had the score values because I was only saving them inside of the functions max and min. So I declared a global list that saved the moves and scores.
Answer: There is not enough code posted to correctly assess, but this almost never works.
Integer v
s.getScore() == v
You should be using Integer.intValue()
Comment: good catch.  It probably does work in this case since scores should only be -1, 0 and 1 which the JVM caches so boxed/unboxed Integers with those values should always be the same exact reference unless you use `new Integer(1)`

MinMax Algorithm for Tic Tac Toe


NullPointerException thrown by Charset.availableCharsets due to our Sybase JDBC driver

Question: I am running into a blocking issue with my install (JDK 1.7). Basically I have the following NPE:
10:19:17.548 [main] ERROR o.s.t.w.s.TestDispatcherServlet - Context initialization failed
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter': Instantiation of bean failed; nested exception is org.springframework.beans.BeanInstantiationException: Could not instantiate bean class [org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter]: Constructor threw exception; nested exception is java.lang.NullPointerException
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateBean(AbstractAutowireCapableBeanFactory.java:1007) ~[spring-beans-3.2.3.RELEASE.jar:3.2.3.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:953) ~[spring-beans-3.2.3.RELEASE.jar:3.2.3.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:487) ~[spring-beans-3.2.3.RELEASE.jar:3.2.3.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:458) ~[spring-beans-3.2.3.RELEASE.jar:3.2.3.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:289) ~[spring-beans-3.2.3.RELEASE.jar:3.2.3.RELEASE]
    at org.springframework.web.servlet.DispatcherServlet.createDefaultStrategy(DispatcherServlet.java:810) ~[spring-webmvc-3.2.3.RELEASE.jar:3.2.3.RELEASE]
    at org.springframework.web.servlet.DispatcherServlet.getDefaultStrategies(DispatcherServlet.java:779) ~[spring-webmvc-3.2.3.RELEASE.jar:3.2.3.RELEASE]
    at org.springframework.web.servlet.DispatcherServlet.initHandlerAdapters(DispatcherServlet.java:587) ~[spring-webmvc-3.2.3.RELEASE.jar:3.2.3.RELEASE]
    at org.springframework.web.servlet.DispatcherServlet.initStrategies(DispatcherServlet.java:444) ~[spring-webmvc-3.2.3.RELEASE.jar:3.2.3.RELEASE]
    at org.springframework.web.servlet.DispatcherServlet.onRefresh(DispatcherServlet.java:432) ~[spring-webmvc-3.2.3.RELEASE.jar:3.2.3.RELEASE]
    at org.springframework.web.servlet.FrameworkServlet.initWebApplicationContext(FrameworkServlet.java:525) ~[spring-webmvc-3.2.3.RELEASE.jar:3.2.3.RELEASE]
    at org.springframework.web.servlet.FrameworkServlet.initServletBean(FrameworkServlet.java:459) ~[spring-webmvc-3.2.3.RELEASE.jar:3.2.3.RELEASE]
    at org.springframework.web.servlet.HttpServletBean.init(HttpServletBean.java:136) [spring-webmvc-3.2.3.RELEASE.jar:3.2.3.RELEASE]
    at javax.servlet.GenericServlet.init(GenericServlet.java:160) [tomcat-servlet-api-7.0.37.jar:3.0.FR]
    at org.springframework.test.web.servlet.MockMvcBuilderSupport.createMockMvc(MockMvcBuilderSupport.java:53) [spring-test-3.2.3.RELEASE.jar:3.2.3.RELEASE]
    at org.springframework.test.web.servlet.setup.DefaultMockMvcBuilder.build(DefaultMockMvcBuilder.java:207) [spring-test-3.2.3.RELEASE.jar:3.2.3.RELEASE]
    at com.mycompany.ui.controller.ConnectionInfosControllerTest.setup(ConnectionInfosControllerTest.java:41) [test-classes/:na]
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.7.0_21]
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57) ~[na:1.7.0_21]
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.7.0_21]
    at java.lang.reflect.Method.invoke(Method.java:601) ~[na:1.7.0_21]
    at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:47) [junit-4.11.jar:na]
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12) [junit-4.11.jar:na]
    at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:44) [junit-4.11.jar:na]
    at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:24) [junit-4.11.jar:na]
    at org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:74) [spring-test-3.2.3.RELEASE.jar:3.2.3.RELEASE]
    at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:83) [spring-test-3.2.3.RELEASE.jar:3.2.3.RELEASE]
    at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:72) [spring-test-3.2.3.RELEASE.jar:3.2.3.RELEASE]
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:231) [spring-test-3.2.3.RELEASE.jar:3.2.3.RELEASE]
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:88) [spring-test-3.2.3.RELEASE.jar:3.2.3.RELEASE]
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:238) [junit-4.11.jar:na]
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:63) [junit-4.11.jar:na]
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:236) [junit-4.11.jar:na]
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:53) [junit-4.11.jar:na]
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:229) [junit-4.11.jar:na]
    at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61) [spring-test-3.2.3.RELEASE.jar:3.2.3.RELEASE]
    at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:71) [spring-test-3.2.3.RELEASE.jar:3.2.3.RELEASE]
    at org.junit.runners.ParentRunner.run(ParentRunner.java:309) [junit-4.11.jar:na]
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:174) [spring-test-3.2.3.RELEASE.jar:3.2.3.RELEASE]
    at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:50) [.cp/:na]
    at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38) [.cp/:na]
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:467) [.cp/:na]
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:683) [.cp/:na]
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:390) [.cp/:na]
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:197) [.cp/:na]
Caused by: org.springframework.beans.BeanInstantiationException: Could not instantiate bean class [org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter]: Constructor threw exception; nested exception is java.lang.NullPointerException
    at org.springframework.beans.BeanUtils.instantiateClass(BeanUtils.java:163) ~[spring-beans-3.2.3.RELEASE.jar:3.2.3.RELEASE]
    at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:87) ~[spring-beans-3.2.3.RELEASE.jar:3.2.3.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateBean(AbstractAutowireCapableBeanFactory.java:1000) ~[spring-beans-3.2.3.RELEASE.jar:3.2.3.RELEASE]
    ... 44 common frames omitted
Caused by: java.lang.NullPointerException: null
    at java.nio.charset.Charset.put(Charset.java:550) ~[na:1.7.0_21]
    at java.nio.charset.Charset.access$300(Charset.java:276) ~[na:1.7.0_21]
    at java.nio.charset.Charset$4.run(Charset.java:593) ~[na:1.7.0_21]
    at java.nio.charset.Charset$4.run(Charset.java:585) ~[na:1.7.0_21]
    at java.security.AccessController.doPrivileged(Native Method) ~[na:1.7.0_21]
    at java.nio.charset.Charset.availableCharsets(Charset.java:584) ~[na:1.7.0_21]
    at org.springframework.http.converter.StringHttpMessageConverter.<init>(StringHttpMessageConverter.java:66) ~[spring-web-3.2.3.RELEASE.jar:3.2.3.RELEASE]
    at org.springframework.http.converter.StringHttpMessageConverter.<init>(StringHttpMessageConverter.java:56) ~[spring-web-3.2.3.RELEASE.jar:3.2.3.RELEASE]
    at org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.<init>(AnnotationMethodHandlerAdapter.java:201) ~[spring-webmvc-3.2.3.RELEASE.jar:3.2.3.RELEASE]
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method) ~[na:1.7.0_21]
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:57) ~[na:1.7.0_21]
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45) ~[na:1.7.0_21]
    at java.lang.reflect.Constructor.newInstance(Constructor.java:525) ~[na:1.7.0_21]
    at org.springframework.beans.BeanUtils.instantiateClass(BeanUtils.java:148) ~[spring-beans-3.2.3.RELEASE.jar:3.2.3.RELEASE]
    ... 46 common frames omitted

I strongly suspect it is related to the following bug: see report here
I am desperately looking for a workaround. Note that I haven't touched the jdk installation. I haven't added or removed any charset...
Can anyone help?
edit 1: See other bug report here and notice the "for some reason"...
edit 2: I have further info regarding the above issue: I have added the following test case in a separate project:
package pack;

import java.nio.charset.Charset;
import java.util.Iterator;
import java.util.Set;

public class TestCase {
    public static void main(String[] args) {
        Set set = Charset.availableCharsets().keySet();
        for (Iterator iterator = set.iterator(); iterator.hasNext();) {
            String s = (String) iterator.next();
            System.out.println(s);
        }
    }
}

I noticed that the test case runs without any error!
Now when I add the very same test case to our project (built with maven), I run into the same NPE:
Exception in thread "main" java.lang.NullPointerException
    at java.nio.charset.Charset.put(Charset.java:550)
    at java.nio.charset.Charset.access$300(Charset.java:276)
    at java.nio.charset.Charset$4.run(Charset.java:593)
    at java.nio.charset.Charset$4.run(Charset.java:585)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.nio.charset.Charset.availableCharsets(Charset.java:584)
    at pack.TestCase.main(TestCase.java:9)

I therefore suspect it might be related to our config of maven. Any one has any clue of what could cause this Charset issue in a multimodule maven config?
edit 3:
The effective POM is too long. Here is the pastebin for it: pastebin here
edit 4:
I managed to pinpoint the problematic dependency. Here it is:
<dependency>
    <groupId>com.sybase</groupId>
    <artifactId>jconn4</artifactId>
    <version>7.07.GA</version>
    <scope>runtime</scope>
</dependency>

By removing this dependency, the TestCase executes properly and prints out all available charsets. However, we do need a database driver for our app. Any one has got any clue as to what is going wrong with sybase jdbc driver?
Comment: @all see edit 4: this is a sybase jdbc issue... I am not sure how to sort it though.
Comment: If you strongly suspect that it might be related to your maven config, it might be worth showing us what that config looks like.
Comment: Also, it would help if you could provide the source code for the spring bean (at least the constructor that's failing). Are you sure you are mocking the dependencies correctly?
Comment: @rimero I have added a pastebin of the effective pom.
Comment: @Vegard Note that the testcase fails without any spring bean being instanciated.
Comment: Gone from Spring for a while. The error happened in `StringHttpMessageConverter`, so maybe somewhere a charset is expected and something else is given (a language?). Maybe search the beans.
Comment: @JoopEggen Thanks! I actually managed to isolate the issue (see edit 2) and therefore I am 100% positive this has got nothing to do with Spring (beans). The issue is that `availableCharsets` throws a NPE given our current maven config.
Comment: I'm seeing this same issue, but do not have the Sybase driver.  Anyone have any thoughts how to troubleshoot this?
Answer: It turns out to be a bug in the Sybase JDBC driver as one can see here. To quote the disgruntled user of the Sybase JDBC driver from the above link:

Nothing should suprise me though, as the current Sybase driver is
  utterly broken, and has been for over a year! It contains a
  CharsetProvider, that returns a null iterator causing
  Charset.availableCharsets() to throw a nullpointer exception. A lot of
  frameworks such as Spring calls Charset.availableCharsets().

I am not sure how to report this bug to Sybase/SAP though...
Comment: If you have a Sybase support contract, you should be able to report the bug by calling support.
Comment: In case it helps anyone I was getting the error with jconn4 7.07 but not jconn4 7.0.
Answer: Not sure if anyone still looking for the answer or not...But yes, this is a bug in Sybase driver jar. There is a discussion and solution within this link Discussion of NPE with jconn4.jar in SAP. I just faced the same issue and got resolved by replacing with a newer jar(it turned out we were using the very old one.)


C# - How to pass generic type with type of "this" class

Question: I have a User class that has a GetQueryable method. Another method, Select(), calls GetQueryable().  I want to use the Select method without passing the type User to the Select method, because I have it in this but I can't use it.

Type type = this.GetType();
???
var x = this.GetQueryable< ??? >().ToList();

class Program
{
    static void Main(string[] args)
    {
        var acc = new User();
        acc.Select();
    }
}

public partial class User
{
    public DB_Test001Entities context;

    public User()
    {
        context = new DB_Test001Entities();
    }
    public void Select()
    {
        Type type = this.GetType();
        var x = this.GetQueryable< **???** >().ToList();
    }

    public IQueryable<TEntity> GetQueryable<TEntity>(List<string> includes = null) where TEntity : class
    {
        IQueryable<TEntity> items = context.Set<TEntity>();

        if (includes != null && includes.Any())
            includes.Where(i => i != null).ToList().ForEach(i => { items = items.Include(i); });

        return items;
    }
}

Comment: Take a look at this: http://stackoverflow.com/questions/232535/how-to-use-reflection-to-call-generic-method
Comment: Are you looking for `.OfType` ?
Comment: @Bart No, I want to use "this" to call a generic function. I can get the type of User class but i can't pass it to generic function.
Comment: mmm can't you just pass `type` instead of `this` ? or make it an extension method ?
Comment: @Bart no I can't pass type, I use a context property that can't access it from static methods and extension methods.
Answer: You can do it using reflection. The following sample works smoothly. In program you can use Clerk or Manager, just any instance derived from User to call Select. You can improve your program with this.
    class Clerk : User { }

    class Manager : User { }

    internal class User
    {
        public User() { }

        public string Name { get; set; }

        public void Select()
        {
            var list = new List<string>() {"Jack", "Martin"};
            Type thisType = GetType();
            MethodInfo method = thisType.GetMethod("GetQueryable").MakeGenericMethod(thisType);
            method.Invoke(this, new object[] {list});
        }

        public IQueryable<TEntity> GetQueryable<TEntity>(List<string> includes = null) where TEntity : User, new()
        {
            if(includes != null)
            {
                Console.WriteLine(typeof(TEntity));
                var entity = new List<TEntity>(includes.Count);
                entity.AddRange(includes.Select(item => new TEntity {Name = item}));
                return entity.AsQueryable();
            }
            return null;
        }
    }

    class Program
    {
        static void Main()
        {
            User usr = new Manager();
            usr.Select();
        }
    }

Comment: For an invoke, it is the developer who has to type cast it. You might need to make use of some more reflection here after invoke. Also, you must specify what you wish to do after Invoke, if you are returning TEntity then you must change the Select() method signature to accept generic parameter of type TEntity which again discards any use of invoke as you can directly call the GetQueryable method. This should bubble up to the topmost caller in general scenario when using generics.
Comment: tnx a lot. when i use invoke it returns object type, but i want returns IQueryable type. how can i convert it to IQueryable when i haven't TEntity?


SX1278 LoRa with Arduino cannot send or receive more than 1 byte

Question: I am making a project with LoRa which needs to control 4 servos but through LoRa communication so I sent it like for the first servo it should send values from 0-180 and for the next servo I sent 181 - 361 and goes on for 4 servos! But unfortunately it cannot send values fore that 255 which I guess is 1 byte and if I try to send more that 255 for example 256 it receives as 0 and 257 as 1 and goes on. Is there a commend or way to increase it by a initializing command? Because I know that Lora can send unto 63 bytes.I will attach the code below(Simplified with a simple code):
Sender code(TX)(Arduino UNO):
    #include <SPI.h>
    #include <LoRa.h>

    int val = 256;
    void setup() {
      Serial.begin(9600);
      while (!Serial);

      Serial.println("LoRa Sender");

      if (!LoRa.begin(433E6)) {
        Serial.println("Starting LoRa failed!");
        while (1);
      }
    }

    void loop() {
      Serial.print("Sending packet: ");

      // send packet
      LoRa.beginPacket();
      LoRa.print(val);
      LoRa.endPacket();

      delay(500);
    }

Receiver Code(RX)(Arduino Mega):
   #include <SPI.h>
   #include <LoRa.h>

   #define LORA_SS 53
   #define LORA_RST 9
   #define LORA_DIO0 8
   String val;

   void setup() {
     pinMode(LORA_SS, OUTPUT);
     digitalWrite(LORA_SS, HIGH);

     LoRa.setPins(LORA_SS, LORA_RST, LORA_DIO0);
     Serial.begin(9600);

     while (!Serial);

     Serial.println("LoRa Receiver");

     if (!LoRa.begin(433E6)) {
       Serial.println("Starting LoRa failed!");
       while (1);
     }
   }

   void loop() {
     // try to parse packet
     int packetSize = LoRa.parsePacket();
     if (packetSize) {
       // received a packet
       Serial.print("Received packet '");

       // read packet
       while (LoRa.available()) {
         val = LoRa.read();

       }

       Serial.print(val.toInt());
       // print RSSI of packet
       Serial.print("' with RSSI ");
       Serial.println(LoRa.packetRssi());
     }
   }

Output of the Receiver :
Received packet '0' with RSSI -5

Answer: Your val in the int val = LoRa.read(); has a scope only within the while loop. So when you access it outside of the scope, you get 0.
Move the declaration of the val outside of the while loop.
int val;
while (LoRa.available()) {
   val = LoRa.read();
}
Serial.print(val.toInt());

Comment: Your question is why you are getting 0 instead of the value you send, so forget about the servo and find out why you are getting 0 first.
Comment: Sorry for the inconvenience that was a mistake while copy pasting my code(Wrong code) please check it now!
Comment: `Lora.read()` does not return a String, it return an `int`. Do `Serial.print((char)Lora.read())` to see it yourself.
Comment: But when i give Serial.print((char)Lora.read()) how will i compare the input i need to write the incoming value to a servo


How to unlink image from folder?

Question: I am currently working on shopping cart.let me quick expain whats happening in product_info.php page.
in product info page products information in displayed such as name,price,image etc..
i have made small functionality in this page.i have put 10 small diffrent color images below the product main image and 2 text boxes to write something on main image using php Gd.
i have made ajax function which is called on onclick of image small images and on onkeyup of two text boxes with three parameter : selected color image's path and value of textboxes.Now when user will click on the one of the color image or Write text in the text box then this function will call and the response will go in the img.php file in which the dynamic image is created using GD and stored in the folder(not in databse) with random image integer name and this image. and from img.php it will get in product info page and display in main image.this new image's path will store in session for when user done checkout then it will store in table.
same process will repleat when user select diffrent color or eneter diffrent value in text box and every time new image will create and save in folder.
my question is how woulld i unlink the previous image from folder when new image will create? Thanx In Advance.
Comment: Try this: http://stackoverflow.com/questions/10006686/use-ajax-to-display-php-generated-image
Answer: Your question is very hard to read, but overall
unlink($imageName);

Will delete the image, as documented here.
Since the file is already sent to the client, you can unlink it right away when the image needs to be updated (in img.php if I understood properly?).
Answer: When saving your GD image for the user, you need to use a key that can be linked to the user and the image and the colour. The when you unlink the image, you can search for that key, colour and image combo and remove it.
For example, save the images with a name like this: uid_imgId_colourId.ext. If you want to add a small random id, that may help as well, but add it to the end of the file name (before the .ext).
Answer: Use unlink function to delete the image.
first check rather the file is there or not.
  unlink('\path\image_name1.png');

Answer: first check rather the file is there or not and after fetch image name in database
unlink("image path/imagename");
Comment: Highlight your code and press `Ctrl-K` to format it as code.

How to unlink image from folder?


Exchange Server 2016 Error MaxQueryStringLength when I try to open Admin Console

Question: So I have a 2012 R2 server with Exchange 2016 installed on it. This server is a part of a DAG. Of the three servers in this DAG, only one of them, we'll call it server1, cannot get to the EAC. I can get to the EAC for server2 and server3 from server1 (as well as other servers in other DAGs for that matter), but I cannot get to the one that belongs to server1. The IIS error page I get says:
<code>Server Error in '/ecp' Application (in big red letters)

The length of the query string for this request exceeds the configured maxQueryStringLength value
</code>
I've seen a couple of pages dealing with this, but it seems to be mostly from a programming standpoint. This would seem to be an IIS error and all the solutions to the link below involve making changes in either IIS Manager or to the web.config file directly.
Link 1
I've found this website, which led me to this website, which show how to edit the specified property.
I've set it to the max value and it takes a really long time, but it still fails. It kind of leads me to believe that I'm barking up the wrong tree. Anybody seen this issue yet with Exchange 2016?
Comment: Which Exchange 2016 Patch level are you using?
Comment: CU3. The rest of my servers are also on CU3. Now I can't get to the EAC for any of the servers in this particular DAG, either from the servers themselves or from other Exchange servers in my organization. I can get to other EACs on this and other servers.
Comment: Hm, one idea might be to backup the SharedWebConfig.config and copy it over from a working one as explained [here](http://www.admin-enclave.com/en/articles/exchange/373-resolved-exchange-2016-iis-not-usable-after-installation-from-cu5.html) it wouldn´t harm as you can switch back if still needed, but might be an option to check if the solution in the link might fix your issue as well. By the way, for security reasons your REALLY should upgrade to a higher CU!
Comment: Hmmm, no love there either. The error described in the link is not real close to what my issue is, though they are both IIS related, it seems.
Comment: yes its not exactly the error but please try the solution there and check if its solving your issues or not.
Comment: Right, "no love there" was meant to convey that the solution (copy a SharedWebConfig.config file) did not work either.
Comment: Let us [continue this discussion in chat](http://chat.stackexchange.com/rooms/59159/discussion-between-bastianw-and-joseph).
Answer: Check the IIS Bindings on server1 and other normal servers. Make sure the Bindings setting is correct on Default Web Site and Exchange Backend site.
Meanwhile, on server1, make sure the .NET CLR Version of MSExchangeECPAppPool is v4.0. If it is already v4.0, change it to v2.0, run IISReset, then change it back to v4.0. Run IISReset.
Comment: Hey Sue, thanks for your suggestion. Still no love, same error. The bindings look like they have the correct certificates and ports matched up, so as to say, they match what other servers have.
Comment: Oh... In this situation, I would recommend you upgrade this server to Exchange 2016 CU4 or CU5. As we know, upgrading would replace the configuration files and reinstall some components. That would help to resolve this issue.


How is this the Open Mapping Theorem?

Question: My book has this theorem which it has stated as the Open Mapping Theorem:

Suppose X and Y are Banach spaces and $T \in B(X,Y)$ is surjective.
Let: $L=\{T(x): x \in X \text{ and } \|x\|\le 1\}$,
with closure $\bar{L}$. Then:
(a) there exists $r >0$ such that $\{y \in Y: \|y\|\le r\}\subseteq
\bar{L}$;
(b) $\{y \in Y: \|y\| \le \frac{r}{2}\}\subseteq L$
(c) if, in addition, T is one-to-one then T is invertible.

But how does this say that an open set in X maps to an open set in Y? If I assume (c) then it holds, because then the inverse is bounded(and hence continuous), and then since T is the inverse of the inverse and a function is continuous iff open sets maps to open sets, we have the result. But what if T is not 1-1?
I tried something like this:
Let $V\subseteq X$ be open. Then we must show that T(V) is open. Let $y \in T(V)$ we must show that there exists an open ball: $B_y(\epsilon)\subseteq T(V)$ . Since T is surjective, there is an x such that $T(x)=y$. Since V is open there is an open ball such that $B_x(\delta)\subseteq V$. $B_x(\delta)=\{z \in X: \|x-z\|<\delta\}$. We also then have that the closed ball $B_x(\delta/2)\subseteq V$, $B_x(\delta/2)=\{z \in X:\|z-x\|\le\delta/2\}=\{z \in X: \|(z-x)\frac{2}{\delta}\|\le1\}$.
Now the set:
$\{z \in X: \|(z-x)\frac{2}{\delta}\|\le1\}$, reminds of $\{x \in X: \|x\| \le 1\}$(stated in the theorem). But I am not sure quite how to relate this, and how to finish my proof.
Can you please help?
Answer: I think the Theorem works better if we write $L=\{Tx:\ \|x\|<1\}$.
Note that $B_x(\delta)=x+B_0(\delta)=x+\delta\,B_0(1)$. So
$$
TB_x(\delta)=Tx+\delta\,TB_0(1)= y+\delta L.
$$
By the Theorem, there exists $r>0$ with $B_0(r)\subset L$. Then $$B_y(\delta r)=y+\delta B_0(r)\subset y+\delta L=TB_x(\delta).$$
So $V$ is open.

How is this the Open Mapping Theorem?


VBA Excel formatting numbers to strings

Question: In sheet 1 the value is 45 so I want in sheet RESULTADO the format like this: 0045
Worksheets("RESULTADO").Range("B" & row_counter) = Format(Worksheets(1).Range("B" & row_counter).Value, "0000")

Why this doesn't work?
I've tried also this, but neither it works:
Worksheets("RESULTADO").Range("B" & row_counter) = CStr(Format(Worksheets(1).Range("B" & row_counter).Value, "0000"))

Answer: You can do that in two(2) ways:

Set the number format first
With Worksheets("RESULTADO").Range("B" & row_counter)
    .NumberFormat = "@"
    .Value = Format(Worksheets(1).Range("B" & row_counter).Value, "0000")
End With

Use ' apostrophe
Worksheets("RESULTADO").Range("B" & row_counter) = "'" & _
    Format(Worksheets(1).Range("B" & row_counter).Value, "0000")

Answer: this doesn't work because in the first case you're trying to format a number n to 00n wich always return n, in the second case, you do exactly the same then you transtype the result to a string.
You have to convert n to a string first. So in your case :
Worksheets("RESULTADO").Range("B" & row_counter) = Format(CStr(Worksheets(1).Range("B" & row_counter).Value), "0000")

VBA Excel formatting numbers to strings


Cannot send UDP datagrams from Azure VM

Question: I am trying to send UDP datagrams from an Azure VM which has a public IP and a security group that has Outbound connections setup for UDP (actually for Any protocol) but I do not get the datagrams on the remote computer.
I can receive UDP datagrams on the VM with no issue.
Priority Name  Port     Protocol Source Destination Action
100      Any   1-65000  Any      Any    Any         Allow

To test I am using UDP Sender/Receiver.
How can I make this work?
Answer: You could check if the remote computer is listening on the same UDP port and binds with IP address 0.0.0.0. Also, the UDP and port should be allowed in the inbound rule in the firewall of remote computer. Please note that Azure supports the UDP networking protocol but does not support UDP broadcasting. You could get more explanation in this blog. You could also get more references in this answer.
Hope this information could help you.
Comment: Indeed, Azure is not supporting broadcasting nor multi-casting...

Cannot send UDP datagrams from Azure VM


GAM with categorical variables - interpretation

Question: I want to use GAM to analyze my experimental data. In my experiment, participants basically play a game for 40 experimental years. In total I have 6 different conditions and I have a between-subject design: one participant only experiences one condition.
I want to analyze a variable which is the output of participants' annual decisions. What I want to show is that:

Year has an impact on this output variable for all the conditions.
The path of this output variable over 40 experimental years is significantly different across 6 conditions.

To this end, I run the following model and get this result:

Abbr is my categorical variable which has 6 levels.
My question is mostly on the interpretation. The "Approximate significance of smooth terms" part of the table tells me that Year has a significant effect on pr in all conditions. Is it correct?
What does the "Parametric coefficients" part tell me?
How can I compare these 6 conditions and tell that the paths are significantly different?
And this is the plot of GAM:

Thank you for the great reply! It is much more clear now in terms of smooths.
What I try to do is to test that the smooths are significantly different from each other for my 6 categories. To this end, I followed your blog post and end up with ordered factors with the following model and the results, where OC is my ordered categorical variable:

Now, I can say that there is a significant difference between the smooths of F-G1P1 and F-G5P1.
And when I plot, I get the following:

The first plot gives me the smooth for my category F (reference category), while others are the difference smooths. How should I interpret them?
Now, I would like to extend this analysis to have a pairwise comparison between my 6 categories. To do this, I try to follow this post but I didn't succeed. Do all my categories need to have the same number of observations for these comparisons?
Answer: In a factor by variable smooth, like other simple smooths, the bases for the smooths are subject to identifiability constraints. If you just naively computed the basis of the required dimension, and given the defaults for s(), you'd get 2 basis functions that are in the null space of the smoothness penalty:

a flat, horizontal function, and
a linear functions

Both are perfectly smooth and not penalised by the smoothness penalty as a result. The flat function is the same thing as the model intercept. The identifiability issues arises because you could add any value to the estimated coefficient for the intercept (constant) term and subtract the same value from the coefficient for the flat, horizontal basis function, and get the same fit but via a new model. As there are an infinite set of numbers you could add to the intercept you have an infinity of models.
This is not good, so to alleviate the issue an identifiability constraint is used. There are several such constraints but the one that leads to good confidence interval coverage properties is the sum-to-zero constraint. Over the range of the covariate, the smooth is constrained to sum to zero. This means it is centred about zero and this means the flat function is deleted from the basis of the smooth.
Now, in the case of factor by variables, because each smooth is centred about zero, the smooth itself contains no easy way to control for differences between the levels in terms of the mean response; say samples from condition F were on average having larger values of pr than condition G1. We'd want the spline for F to be shifted up by some constant amount relative to G1. That's what the parametric terms are and they come from the + as.factor(Abbr) term in the model formula. The parametric terms represent the deviation of the indicated group from the mean of the reference group (in your case the level not listed, F). If you didn't include this term in the model, then the smooths may become more wiggly as they try to account for the mean shifts of the groups, which is not something you want.
The other main type of smooth you might use for this kind of model is the random factor smooth basis bs = "fs". This basis/smooth includes intercepts for each level of the grouping factor and as such doesn't need the parametric terms.
The approximate significance of the smooths actually represents a test that the indicated smooth is actually a flat, zero, function. Or put another way, it is the smooth equivalent of a t or Wald Z test of the null hypothesis that a coefficient in a linear model or GLM is equal to zero (i.e. has no effect). There is strong evidence against the null for each of your smooths, which is reflected in the strong non-linearity of the estimated smooths and that the confidence intervals for the smooths do not include 0 for most of the range of Year.
Comment: Thank you for the great reply! It is much more clear now in terms of smooths.


Move rows of data to columns, then delete the rows

Question: I have thousands of rows of data as shown in the Excel Sample #1 below. All data is currently in Column A. Each "Group" of data has six lines: name, dates, city, county, state and a blank line.  I need to move the data under each Name in Column A into Columns B through E as shown in Rows 1 and 2. I need to then delete the five rows below each name to bring the cells up so that the final output would look like the data currently in Rows 1 and 2.
EXCEL SAMPLE #1-
     A        B      C      D      E
 1 Name1    Dates1 City1 County1 State1
 2 Name2    Dates2 City2 County2 State2
 3 Name3
 4 Dates3
 5 City3
 6 County3
 7 State3
 8 <blank row>
 9 Name4
10 Dates4
11 City4
12 County4
13 State4
14 <blank row>

Here is the Excel 2010 macro I created to move the data. The problem is that I cannot figure out how to change the "ranges" so that it picks up the next Group of data. My formula only works on the data in the ranges specified in the macro.
Sub Move_Rows()
'
' Move_Rows Macro
' Moves cemetery row data for each grave into separate columns
'
' Keyboard Shortcut: Ctrl+q
'
    Range("A111:A115").Select
    Selection.Copy
    Range("B110").Select
    Selection.PasteSpecial Paste:=xlPasteAll, Operation:=xlNone, SkipBlanks:= _
        False, Transpose:=True
    Range("A111:A115").Select
    Application.CutCopyMode = False
    Selection.Delete Shift:=xlUp
End Sub

Comment: Since you're using Excel 2010, you may also want to check out the PowerQuery add-in if you have to do these sorts of manipulations often. It enables you to do these sorts of transformations without code. https://www.microsoft.com/en-us/download/details.aspx?id=39379
Answer: Strange that this was not answered yet. :)
All you need is to put your logic into a loop, I prefer using Do..While...loop, so here we go:
Sub Move_Rows()
'
' Move_Rows Macro
' Moves cemetery row data for each grave into separate columns
'
' Keyboard Shortcut: Ctrl+q
'
    Application.ScreenUpdating = False

    i = 111 'Initial row number
    Do While Cells(i, "A") <> ""
        Range(Cells(i, "A"), Cells(i+4, "A")).Select
        Selection.Copy
        Cells(i-1, "B").Select
        Selection.PasteSpecial Paste:=xlPasteAll, Operation:=xlNone, SkipBlanks:= _
            False, Transpose:=True
        Range(Cells(i, "A"), Cells(i+4, "A")).Select
        Application.CutCopyMode = False
        Selection.Delete Shift:=xlUp
        i = i + 1
    loop

    Application.ScreenUpdating = True
End Sub

Have a good luck with that!
Answer: Here's one that you should be able to run however many times you want, even if you add new data. I haven't tested it, so proceed with caution.
Sub Move_Rows()
    Dim ws As Worksheet
    Dim rRng As Range ' keep track of where we're gonna paste the results
    Dim sRng As Range, eRng As Range ' start-range, end-range

    Set ws = ThisWorkbook.Worksheets(1) ' <~~ Change to whatever you need

    For i = 1 To ws.UsedRange.Rows.Count
        ' Is this row valid as start of a range? If the cell in col B is populated, this means the current row is already correctly "formatted" and we need to skip it.
        If (ws.Range("B" & i).Value = "") And (sRng Is Nothing) Then
            Set rRng = ws.Range("B" & i)
            Set sRng = ws.Range("A" & i).Offset(1, 0) ' start-range set to the row below, we don't need to transpose the name.
        End If

        ' Is this row valid as end of a range? If the cell in col A is empty, the previous range will be the end of the area we want to copy.
        If ws.Range("A" & i).Value = "" Then
            Set eRng = ws.Range("A" & i).Offset(-1, 0) ' end-range set to the row above, we don't want to transpose the empty cell.

            ' The row was empty and we've set the reference to the content above. Now we can delete the empty row.
            ws.Range("A" & i).EntireRow.Delete
        End If

        If (Not sRng Is Nothing) And (Not eRng Is Nothing) Then ' You can also move this inside the previous If-loop. I prefer having it outside for readability.
            ' We have both a start-range and an end-range, we should do the copy-paste now
            Range(sRng, eRng).Copy
            rRng.PasteSpecial Paste:=xlPasteAll, Operation:=xlNone, SkipBlanks:=False, Transpose:=True

            ' Delete the now-superfluous rows
            Range(sRng, eRng).EntireRow.Delete

            ' Empty the range variables so we don't get wrong matches next iteration.
            Set rRng = Nothing
            Set sRng = Nothing
            Set eRng = Nothing
        Else
            ' One of the ranges are empty, so we'll do nothing. You can remove this line and the Else.
        End If
    ' Go to the next row
    Next i
End Sub

Comment: Thanks for the help. The Do..While...Loop worked with a bit of clean-up.  The "longer" macro that was not tested has a bug with "rowRng.PasteSpecial Paste:=xlPasteAll, Operation:=xlNone, SkipBlanks:=False, Transpose:=True".  I will do som efurther investigation on it, but the "shorter" macro worked fine!
Comment: Oops! I renamed a variable and apparently missed one instance. Change `rowRng` to `rRng` and it will work.


T-SQL Len function not working as expected

Question: I'm working with Microsoft SQL Server (2008 R2 if that matters)
When I execute
select LEN('test')

I get 4 as expected
But now try this:
declare @s varchar
set @s='test'
select LEN(@s)

And the result is ... 1
How does it actually work?
Answer: That is because if you were to
SELECT @s

it would return
t

only. You need to specify the length.
From char and varchar (Transact-SQL)

When n is not specified in a data definition or variable declaration
  statement, the default length is 1. When n is not specified when using
  the CAST and CONVERT functions, the default length is 30.

SQL Fiddle DEMO
Comment: Thanks! I would never expect this
Answer: When you define this:
declare @s varchar

you get a varchar of exactly one character length .
There's absolutely nothing wrong with LEN!
What you need to do is specify an explicit length when you define your varchar variable
declare @s varchar(20)
set @s='test'
select LEN(@s)

Now you should get back 4 from LEN  ...
Note: it is a recommend best practice to always specify a length when you use varchar - otherwise you'll run into these kind of surprises. ....
Answer: you have to declare it as nvarchar with more than 1 char
try this, it works:
declare @s nvarchar(100)


Progress bar em angulajs

Question: Preciso de uma progress-bar que seja a imagem de um cálice sendo enchido com AngularJs. Algo parecido com isso: http://franverona.com/loadgo/.
Alguém te algum exemplo possa me ajudar?
Ainda não tenho a imagem oficial, mas seria algo mais ou menos assim: Ao abrir uma página, o líquido do cálice (imagem 01) subiria até completar todo o cálice (imagem 02)
Comment: Você tem algum código, a imagem do cálice, em qual local do código é para acontecer isso?
Comment: O código te serviu Edinho?
Answer: Esse plugin não tem pra angular, tem que utilizar jquery ou não (acho mais simples com jQuery).
Exemplo minimo

var app = angular.module('app', []);
app.controller('ctrl', ['$scope',
  function($scope) {
    $scope.load = function() {
      $("#myImage").load(function() {
        $('#myImage').loadgo({
          'opacity': 0.5,
          'animated': true/*
          'image': 'https://i.stack.imgur.com/7uk8G.png'*/,
          'direction': 'bt'
        });
      }).each(function() {
        if (this.complete) $(this).load();
      });
    };
    $scope.go = function() {
      var _time = window.setInterval(function() {
        if ($('#myImage').loadgo('getprogress') == 100) {
          $('#myImage').loadgo('setprogress', 0);
          $("#btnExecutar").text('Executar');
          $("#btnExecutar").prop('disabled', false);
          window.clearInterval(_time);
        } else {
          var i = ($('#myImage').loadgo('getprogress') + 4);
          $('#myImage').loadgo('setprogress', i);
          $("#btnExecutar").text('Executando ...');
          $("#btnExecutar").prop('disabled', true);
        }
      }, 150);
    };
    $scope.load();
    //$scope.go(); // remover para funciona no inicio do carregamento
  }
]);

  <button id="btnExecutar" ng-click="go()">Executar</button>

Nesse exemplo foi utilizado um botão, mas, no final do script tem um comentário é só descomentar (//$scope.go();) que isso funcionará no carregamento da página. As imagens também me parecem diferentes n
Referencia: LoadGo

Progress bar em angulajs


Como inserir uma propriedade 'multiple' dentro de um Elemento HTML capturado pelo ID via Javascript

Question: Gostaria de inserir a propriedade 'multiple' via javascript, para meu código aceitar múltiplos arquivos:
file = document.getElementById('onetidIOFile');

<input type="file" name="fileupload0" id="onetidIOFile" class="ms-fileinput" size="56" title=
"Nome">

Neste código acima, ele só aceita somente um arquivo. Quero saber se é possível inserir a propriedade 'multiple', desta maneira: type='file' multiple
Answer: Achei uma maneira de inserir, via javascript, o atributo multiple usando o setAtribute:
file.setAttribute('multiple','multiple');

Desta maneira atendeu o que eu desejava:


In which fileshould I write style sheet(less) in roots starter theme of wordpress?

Question: I am new in roots starter theme of wordpress. In 'assets/less' folder, where should I write style sheet(There I found 4 files - _bootstrap.less,_global.less,main.less,_variables.less).Please anybody explain?
Answer: main.less is the file to edit.  The files with an _ prefixed are either dynamically generated or are static libraries which should not be amended.
You should use @import within main.less to add in additional code.
Answer: As you add more components and layouts to your theme, create new files for them and then add new @import's in main.less.


Converting points in arc to a bezier curve

Question: I have the coordinates of potentially any points within a 3D arc, representing the path an object will take when launched through the air. X is forward, Z is up, if that is relevant.
Using any of these points, I need to create a bezier curve that follows this arc. The curve requires the tangent values for the very start and end of the curve.
I can't figure out the formula needed to convert this arc into a bezier curve, and I'm hoping someone can help.
I've found plenty of resources discussing circular arcs, but the arc here is not circular.
Answer: Assuming that the arc is indeed a parabola, then the procedures outlined at Convert segment of parabola to quadratic bezier curve and http://www.ams.org/samplings/feature-column/fcarc-bezier should provide the appropriate calculations.
Comment: Ah, I'll look closer at those. I didn't think they applied here, since the formula given required A, B, and C variables without any definition given as to what those represented, so I was left to assume that they were unique to the calculation of a Parabola, and not applicable here. I've never taken Calculus, so I have a bit of a tenuous grasp on that.
Answer: Let $\mathbf{Q}$ be the start of the curve, let $\mathbf{V}$ be the initial velocity vector, and let $\mathbf{G}$ be the gravity vector. Then the equation of the trajectory is:
$$
\text{ParabolaFunction:}\quad \mathbf{P}(t) = \mathbf{Q} + t\mathbf{V} + \tfrac12 t^2\mathbf{G}
$$
I will assume that you have unitized the time scale so that the flight starts at $t=0$ and ends at $t=1$.
Compute three points on the curve:
\begin{align}
\mathbf{P}_0 &= \mathbf{P}(0)  \\
\mathbf{P}_m &= \mathbf{P}(\tfrac12)  \\
\mathbf{P}_3 &= \mathbf{P}(1)
\end{align}
and let $\mathbf{P}_c = \tfrac12(\mathbf{P}_0 + \mathbf{P}_1)$ be the mid-point. Compute
$$
\mathbf{P}_a = \mathbf{P}_c + 2(\mathbf{P}_m - \mathbf{P}_c).
$$
Then let
\begin{align}
\mathbf{P}_1 &= \tfrac23\mathbf{P}_a + \tfrac13\mathbf{P}_0  \\
\mathbf{P}_2 &= \tfrac23\mathbf{P}_a + \tfrac13\mathbf{P}_3
\end{align}
Then the control points of the cubic Bezier curve are
$\mathbf{P}_0$, $\mathbf{P}_1$, $\mathbf{P}_2$, $\mathbf{P}_3$.
Pseudocode is as follows. It assumes that addition and scalar multiplication of 3D points and vectors have been overloaded in the obvious way:
<code>p0 = ParabolaFunction(0)
pm = ParabolaFunction(0.5)
p3 = ParabolaFunction(1)

pc = 0.5*(p0 + p3)      // Point on chord
pa = pc + 2*(pm - cc)   // Apex point; intersection of tangents

oneThird = 1.0/3.0
twoThirds = 2*oneThird

p1 = twoThirds*pa + oneThird*p0
p2 = twoThirds*pa + oneThird*p3

result = CubicBezierCurve(p0, p1, p2, p3)
</code>
Comment: Hm... I'm really struggling with this one. It doesn't account for the Y-axis, so I had to put that in myself, which I attempted by just replicating the X-axis math on it. It also has some extraneous bits, since I already have the basic points in the parabola. My attempts so far have failed, though. I'm just getting a straight line as the bezier curve.
Comment: From your question, I got the impression that your parabola was just $z$ as a function of $x$, with $y=0$ everywhere. If that's not the case, then the approach will need to be modified. Please clarify.
Comment: Do you actually have the `ParabolaFunction` that I assumed? If so, what are its inputs and outputs?
Comment: I... don't think I have a ParabolaFunction. I'm using X, Y and Z. I was simply stating that Z in my case is the up axis, but saying X is forward may have been misleading. I forgot that I was actually using world coordinates.
Comment: What do you know about your "arc"? Do you know its equation? Do you have some points that lie on it? Can you calculate a point at any given "time" value? You're asking for a function that outputs a Bezier curve; you have to specify what inputs this function will receive.
Comment: It's calculating the path a physics projectile will take, so I'm performing a series of ray traces along an arc. The math used to determine where each point of the trace should be is a bit complex, but I can store any of them as a variable. Currently the arc spans 5 seconds of flight, with a point every 0.05 seconds, so a max of 100 points. I'm trying to use the bezier curve to visually represent the path plotted by these points.
Comment: For the actual math, I'm taking the initial location and velocity of the projectile as variables, as well as the Duration (5), Delta (0.05), and force of Gravity. Number of points in arc `(MaxIndex) = Duration / Delta rounded`.  Perform loop from 0 to MaxIndex. Inside loop, perform ray trace using `Location + (loop index * Delta * Velocity) + (loop index * Delta ^2 / 2 * Gravity)` I use this formula with normal loop index for the starting point of the trace, and loop index +1 to get the end point of the trace.


Notation to select a real number in a sequence

Question: Having $\lambda_{j}=\left\{ 0.9,0.3,0.01,0.02,0.001,0.002\right\} $ we want to select the first real that goes against the decreasing motion, in this case $0.02$. How I can mathematically notate this? I can give an explanation using a function, but I would prefer to find a more intuitive notation. Thank you,
Answer: I guess what you're looking for is
$$\lambda_{k_0},\,~\,~\,~k_0:=\min\{k:\lambda_k>\lambda_{k-1}\}\,.$$
Comment: @Jackozee Hakkiuz: I've revised the answer.
Comment: That selects the index. You want $\lambda_k$ at the left of the colon.
Edit: oh no I'm dumb.. Sorry.
Comment: Yeah I felt something was odd but pointed to the wrong thing haha :( i think it's quite clear now.
Comment: Excellent! @JackozeeHakkiuz


how to retrieve a node's file name

Question: I can't find the info through any search string I can think of. I need to retrieve the complete path including the filename for a file stored by a node.
public://module_name/filename.ext  I can get the public://module_name part but not the file name. I think I am having a basic misunderstanding on how Drupal stores files.  I have written a custom module and it puts the file where I specify: public://my_module.  If the file is an Image (jpg) there is no problem. I can display the file name with the generic file format. so I know that the information is available,  I just cant figure out how to access it.
can any one point me at an example, API description or tutorial that covers how to access a file in the current node?
Answer: This is not the 100% correct way of doing it because I'm accessing the property manually and I'm also generating the image html which can be automatically generated but maybe it can help as a simple example. In your theme's node.tpl.php write:
<code><?php
if (isset($node->your_field[LANGUAGE_NONE][0])) {
    $o_img = $node->your_field[LANGUAGE_NONE][0];
    $s_uri = $o_img['uri'];
    $s_url = file_create_url($s_uri);
    $s_html = "URI: {$s_uri} | URL: {$s_url}";
    print $s_html;
}
?>
</code>
Regards
EDIT: How to better read a field (I haven't tried with image fields). Notice you don't have to specify the language because everything is automatically handled by Drupal based on your language preference and fallback configuration.
<code>$aa_fields = field_get_items('node', $node, 'my_field');
foreach ($$aa_fields as $a_field) {
    $a_rendered_field = field_view_value('node', $node, 'my_field', $a_field);
    $s_html = $a_rendered_field['#markup'];
}
</code>
In order to avoid creating clutter in your node template file, it's better to move this code to your theme's template.php or, if you plan to use your code with other themes, to your own custom module.
Comment: as far as I can tell this generates entity missing bundle errors. I suppose I just don't comprehend it..i need to get a string back that goes something like "public://bigimage/file.zif " so I can pass it toi a custom file viewer. Still Thanks for your reply.
Comment: Where are you using the code? If you wanted to use the above code in your node template file (node.tpl.php) you should substitute $o_node by $node and 'my_field' by the actual name of the field for your image.

The error sounds to me like you don't have any image uploaded to that particular node or that the field you are indicating doesn't exist at all.

Also, keep in mind that if you put the above code in node.tpl.php, it will apply to all type of contents and your image field probably won't be found in some of them. So you would need to check if the field exists and contains any image.
Comment: My situation is that I have rewritten an existing module. I have to defined fields the I cal bigimage_image  and bigimage_zif The ZIF file is a modified big tiff that I need to send to java script viewer. I cant for the life of me get the filename to append to the path.  I'm not working with the theme template files. I'm trying to generate all the markkup in a function called function theme_bigimage($variables) which lives in my .module file. This function works for a different file structure I juist nee to convert it so that It can find a single file.
Answer: I looked at the functional code today and I find that the problen lies in the definition of $vaariables. In the functional code I can retrieve the path to the jpeg image  as $variable['filepath'] in the non functional code the path does not include the file name. So $varable is not being befined propperly in my new module. I will have to study up on it. I do have some references to the subject.
Thanks for the help and advise.

how to retrieve a node's file name


2nd and 3rd degree polynomial modular arithmetic questions

Question: I'm studying for a test and have 2 problems that I just can't figure out.
a) $3x^2+5x-2 \equiv 0 \pmod{12}$
I know that I have to seperate this to mod 3 and mod 4, but can't do much after.
b) $x^3+x+3 \equiv 0 \pmod{125}$
No idea. Probably something with $\pmod{5}$.
Please help :3
Answer: One approach to both problems is to start by looking at them modulo various divisors of the original modulus, with each subsequent divisor being multiple of the preceding one. Each step then provides further refinement of the information we have about the solutions; reducing the amount of work we need to perform.
For example, in the first case, we can proceed as follows:

Let's start by looking at the equation "modulo $3$". Trying out all three possible remainders of $x$ modulo $3$ tells us that only $x\equiv 1\pmod 3$ works.
This implies that once we move to "modulo $6$", the only possible values of $x\pmod 6$ will be $1$ and $4$. As it turns out, both of them work modulo $6$.
Finally, let's get up to "modulo $12$". Since we had two possible remainders modulo $6$, there are four candidates modulo $12$: $1, 4, 7, 10$. Of these, only $7$ and $10$ turn out to work; both being solutions of the original equation.

Of course, one doesn't need to restrict to primes; we could just as well start by looking at the equation modulo $4$ and check the four possibilities in order to find that $1$ and $2$ work; and then step up directly to "modulo $12$".
Alternatively, if one is more interested in the theory behind the problems, the first one is good example for the Chinese Remainder Theorem and the second one goes well with Hensel's Lifting Lemma.


Riccati Equation y'(t) = ay(t)^2+by(t)+c

Question: I am having trouble solving $y'(t) = -ay^2 + by + c$
I have been attempting to solve the simplified equation:
$\frac{dy}{ay^2+by+c} = dt$
I complete the square so I can integrate it into a $tan^{-1}$ function.  Within the $tan^{-1}$ solution, I have $(x\sqrt{a} + \frac{b}{2\sqrt{a}})$ which would mean the constant a would always need to be positive.  This does not seem to make sense to me (since a should be able to be both positive and negative) and my question is whether or not I am going in the right direction in solving this differential equation.
Answer: $$\frac{dy}{dt} = -ay^2 + by + c$$
You wrote  $\frac{dy}{ay^2+by+c} = dt$ which is not correct. This should be :
$$\frac{dy}{-ay^2+by+c} = dt$$
If you have trouble with the coefficient $-a$ which can be positive or negative, better write the equation on the form :
$$\frac{dy}{y^2-\frac{b}{a}y-\frac{c}{a}} = -a\,dt$$
Then there is no longer a problem of sign.


Abrir arquivo (.txt) e preencher os campos no form

Question: Estou fazendo uma aplicação de cálculos que contém Textbox, RadioButton e Combobox e necessito dessas seguintes opções:
1 - Preencher todos os campos e salvar em arquivo txt;
2 - Opção de abrir esse arquivo txt e preencher todos os campos com os dados salvos.
A opção de preencher e salvar os dados em arquivo txt eu já concluí com sucesso (verifiquei no arquivo e os dados preenchidos foram salvos com sucesso).
Mas estou com o problema de abrir o arquivo e preencher os dados nos campos, mas especificamente o RadioButton, ele duplica a opção que salvei no arquivo txt e desordena todos os itens seguintes.
Segue o print da tela com os dados salvos:

E os códigos de Salvar e Abrir:
        private void SaveTool_Click(object sender, EventArgs e)
        {
            try
            {
                SaveFileDialog dados = new SaveFileDialog();
                dados.Filter = "Arquivo texto (*.txt) | *.txt";
                dados.FilterIndex = 2;
                dados.InitialDirectory = @"C:\";
                dados.RestoreDirectory = true;

                if (dados.ShowDialog() == DialogResult.OK)
                {

                    Stream fileStream = dados.OpenFile();
                    StreamWriter sw = new StreamWriter(fileStream);

                    /
                    sw.WriteLine(txtSpeed.Text);
                    sw.WriteLine(txtOwnWeight.Text);
                    sw.WriteLine(txtOwnWeightCounterweight.Text);
                    sw.WriteLine(txtMaterialWeight.Text);
                    sw.WriteLine(txtMaterialWeightWithIncrustation.Text);
                    sw.WriteLine(txtRailGrad.Text);
                    sw.WriteLine(txtBeltTensionInput.Text); /
                    sw.WriteLine(txtBeltTensionOutput.Text);
                    if (rdbRolamento01.Checked)
                    {
                        sw.WriteLine(rdbRolamento01.Text);
                    }
                    if (rdbBucha3.Checked)
                    {
                        sw.WriteLine(rdbBucha3.Text);
                    }
                    sw.WriteLine(txtFriction.Text);
                    sw.WriteLine(txtGradientForce.Text);
                    sw.WriteLine(txtBeltStrength.Text);
                    sw.WriteLine(txtBearingFrictionF.Text);
                    sw.WriteLine(txtTotalForceReq.Text);
                    sw.WriteLine();

                    sw.WriteLine(txtNumberActive.Text);
                    sw.WriteLine(cmbWheelsDiameter.Text);
                    sw.WriteLine(txtFrictionWheelRail.Text);
                    sw.WriteLine(txtTotalReacReqDrivenWheels.Text
                    sw.WriteLine(txtMinReactReqEachDrivenWheel.Text);
                    sw.WriteLine(txtMinLoadDrivenWheel.Text);
                    sw.WriteLine(txtwLAct.Text);
                    sw.WriteLine();

                    sw.Close();
                    fileStream.Close();
                    MessageBox.Show("Data saved successfully!");
                }
            }

            catch(Exception ex)
            {
                MessageBox.Show("Sorry, an error occurred: " + ex.Message, "", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
         }

        private void OpenTool_Click(object sender, EventArgs e)
        {
            try
            {
                OpenFileDialog AbrirArquivo = new OpenFileDialog();

                AbrirArquivo.Filter = " All files | *";
                AbrirArquivo.FilterIndex = 2;
                AbrirArquivo.InitialDirectory = @"C:\";
                AbrirArquivo.RestoreDirectory = true;

                var result = AbrirArquivo.ShowDialog();

                if (result == DialogResult.OK)
                {

                    var NomeArquivo = AbrirArquivo.SafeFileName;
                    var Path = AbrirArquivo.FileName;

                    string[] args = Environment.GetCommandLineArgs();

                    using (StreamReader leitor = new StreamReader(AbrirArquivo.FileName))
                    {
                        txtSpeed.Text = leitor.ReadLine();
                        txtOwnWeight.Text = leitor.ReadLine();
                        txtOwnWeightCounterweight.Text = leitor.ReadLine();
                        txtMaterialWeight.Text = leitor.ReadLine();
                        txtMaterialWeightWithIncrustation.Text = leitor.ReadLine();
                        txtRailGrad.Text = leitor.ReadLine();
                        txtBeltTensionInput.Text = leitor.ReadLine();
                        txtBeltTensionOutput.Text = leitor.ReadLine(); /
                        if (rdbRolamento01.Checked) //
                        {
                            rdbRolamento01.Text = leitor.ReadLine();
                        }
                        else
                        {
                            rdbBucha3.Text = leitor.ReadLine();
                        }
                        txtFriction.Text = leitor.ReadLine();
                        txtGradientForce.Text = leitor.ReadLine();
                        txtBeltStrength.Text = leitor.ReadLine();
                        txtBearingFrictionF.Text = leitor.ReadLine();
                        txtTotalForceReq.Text = leitor.ReadLine();

                        txtNumberActive.Text = leitor.ReadLine();
                        cmbWheelsDiameter.Text = leitor.ReadLine();
                        txtFrictionWheelRail.Text = leitor.ReadLine();
                        txtTotalReacReqDrivenWheels.Text = leitor.ReadLine();
                        txtMinReactReqEachDrivenWheel.Text = leitor.ReadLine();
                        txtMinLoadDrivenWheel.Text = leitor.ReadLine();
                    }

                    MessageBox.Show("Data entered successfully!");
                }
            }

            catch (Exception ex)
            {
                MessageBox.Show("Sorry, an error occurred: " + ex.Message, "", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

Print da tela quando eu abro o arquivo e preencho os dados nos campos:

Obs.: Ele mostra a mensagem que foi inserido com sucesso, mas no RadioButton ele duplica a minha seleção, e desordena os dados do grupo 2.
Comment: `if (rdbRolamento01.Checked)` isso ta errado na leitura, pra escrever faz sentido mas pra ler deveria ver o que tem no arquivo texto e setar corretamente o radio
Comment: @RicardoPontual Sabe me dizer qual seria a maneira certa de escrever para fazer a leitura no arquivo text e setar no radio?
Comment: quando grava, está gravando o text do radio, assim por exemplo `sw.WriteLine(rdbRolamento01.Text);` então precisa comparar o valor gravado, algo como `var tipo = leitor.ReadLine(); if (tipo == "Rolamento") rdbRolamento01.Checked = true;`
Comment: @RicardoPontual Deu certo o RadioButton conforme você me disse, pore´´ma estou com um problema: no segundo grupo o primeiro Textbox (Quantidade), ele fica em branco e o valor deste textbox vai para o Textbox abaixo, alterando toda a sequencia, sabe me dizer o porque isso acontece? Pois, infelizmente não consegui achar o erro.
Answer: Após as ajudas, consegui achar o meu erro, segue as correções:
No evento de Salvar tirar os espaços entre as linhas sw.WriteLine(); para no momento de puxar os dados dos arquivos, ele saia da ordem.
E no evento de Abrir que era o problema ao invés de colocar o  if (rdbRolamento01.Checked). Era necessário colocar algo para comparar com o valor gravado no arquivo texto.
Segue o código alterado:
        private void SaveTool_Click(object sender, EventArgs e)
        {
            try
            {
                SaveFileDialog dados = new SaveFileDialog();
                dados.Filter = "Arquivo texto (*.txt) | *.txt";
                dados.FilterIndex = 2;
                dados.InitialDirectory = @"C:\";
                dados.RestoreDirectory = true;

                if (dados.ShowDialog() == DialogResult.OK)
                {

                    Stream fileStream = dados.OpenFile();
                    StreamWriter sw = new StreamWriter(fileStream);

                    /
                    sw.WriteLine(txtSpeed.Text);
                    sw.WriteLine(txtOwnWeight.Text);
                    sw.WriteLine(txtOwnWeightCounterweight.Text);
                    sw.WriteLine(txtMaterialWeight.Text);
                    sw.WriteLine(txtMaterialWeightWithIncrustation.Text);
                    sw.WriteLine(txtRailGrad.Text);
                    sw.WriteLine(txtBeltTensionInput.Text); /
                    sw.WriteLine(txtBeltTensionOutput.Text);
                    if (rdbRolamento01.Checked)
                    {
                        sw.WriteLine(rdbRolamento01.Text);
                    }
                    if (rdbBucha3.Checked)
                    {
                        sw.WriteLine(rdbBucha3.Text);
                    }
                    sw.WriteLine(txtFriction.Text);
                    sw.WriteLine(txtGradientForce.Text);
                    sw.WriteLine(txtBeltStrength.Text);
                    sw.WriteLine(txtBearingFrictionF.Text);
                    sw.WriteLine(txtTotalForceReq.Text);

                    sw.WriteLine(txtNumberActive.Text);
                    sw.WriteLine(cmbWheelsDiameter.Text);
                    sw.WriteLine(txtFrictionWheelRail.Text);
                    sw.WriteLine(txtTotalReacReqDrivenWheels.Text
                    sw.WriteLine(txtMinReactReqEachDrivenWheel.Text);
                    sw.WriteLine(txtMinLoadDrivenWheel.Text);
                    sw.WriteLine(txtwLAct.Text);

                    sw.Close();
                    fileStream.Close();
                    MessageBox.Show("Data saved successfully!");
                }
            }

            catch(Exception ex)
            {
                MessageBox.Show("Sorry, an error occurred: " + ex.Message, "", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
         }

        private void OpenTool_Click(object sender, EventArgs e)
        {
            try
            {
                OpenFileDialog AbrirArquivo = new OpenFileDialog();

                AbrirArquivo.Filter = " All files | *";
                AbrirArquivo.FilterIndex = 2;
                AbrirArquivo.InitialDirectory = @"C:\";
                AbrirArquivo.RestoreDirectory = true;

                var result = AbrirArquivo.ShowDialog();

                if (result == DialogResult.OK)
                {

                    var NomeArquivo = AbrirArquivo.SafeFileName;
                    var Path = AbrirArquivo.FileName;

                    string[] args = Environment.GetCommandLineArgs();

                    using (StreamReader leitor = new StreamReader(AbrirArquivo.FileName))
                    {
                        txtSpeed.Text = leitor.ReadLine();
                        txtOwnWeight.Text = leitor.ReadLine();
                        txtOwnWeightCounterweight.Text = leitor.ReadLine();
                        txtMaterialWeight.Text = leitor.ReadLine();
                        txtMaterialWeightWithIncrustation.Text = leitor.ReadLine();
                        txtRailGrad.Text = leitor.ReadLine();
                        txtBeltTensionInput.Text = leitor.ReadLine();
                        txtBeltTensionOutput.Text = leitor.ReadLine(); /
                        var tipo = leitor.ReadLine();
                        if (tipo == "Rolamento") rdbRolamento01.Checked = true;
                        txtFriction.Text = leitor.ReadLine();
                        txtGradientForce.Text = leitor.ReadLine();
                        txtBeltStrength.Text = leitor.ReadLine();
                        txtBearingFrictionF.Text = leitor.ReadLine();
                        txtTotalForceReq.Text = leitor.ReadLine();

                        txtNumberActive.Text = leitor.ReadLine();
                        cmbWheelsDiameter.Text = leitor.ReadLine();
                        txtFrictionWheelRail.Text = leitor.ReadLine();
                        txtTotalReacReqDrivenWheels.Text = leitor.ReadLine();
                        txtMinReactReqEachDrivenWheel.Text = leitor.ReadLine();
                        txtMinLoadDrivenWheel.Text = leitor.ReadLine();
                    }

                    MessageBox.Show("Data entered successfully!");
                }
            }

            catch (Exception ex)
            {
                MessageBox.Show("Sorry, an error occurred: " + ex.Message, "", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }


Bayesian updating with normal but incomplete signals

Question: Suppose I want to update my beliefs on a realization of vector $\theta = (\theta_{1},...,\theta_{d}) \in \mathbb{R}^{d}$ and for every one of these $\theta_{j}$, in each period I may receive signal $y_{jt} = \theta_{j} + \epsilon_{jt}$.
$\theta$ is normally distributed with mean $\mu_{\theta} \in \mathbb{R}^{d}$ and covariance matrix $\Sigma_{\theta} \in \mathbb{R}^{d\times d}$, the later allowing for positive correlation between the $\theta_{j}$'s. Further, $\epsilon_{jt}$ is an iid normal shock with mean 0 and variance $\sigma_{\epsilon}^{2}$. Because of these assumptions, $y_{t} \sim \mathbb{N}(\mu_{\theta},\Sigma_{\theta} + \sigma_{\epsilon}^{2} \mathbb{I}_{d})$.
If we observed all signals $y_{t} = (y_{1t},...,y_{dt}) \in \mathbb{R}^{d}$, then characterizing the mean and covariance of the posterior normal distribution is straightforward, assuming that prior $\pi(\theta)$ is exactly the distribution of $\theta$.
My question is the following: assume that for some reason we do not observe all signals, only a subset of $y_{t}$, is there a way to have an analytic expression for the posterior mean and covariance matrix as a function of the signals we do observe?
For example, assume that $d=3$ and you only observe signals $y_{1t}$ and $y_{3t}$. To derive $\pi(\theta|y_{1t},y_{3t})$, you would need to compute the likelihood $L(y_{1t},y_{3t} | \theta)$, which is going to be the marginal joint distribution of $y_{1t}$ and $y_{3t}$. However, I am having trouble deriving this likelihood for an arbitrary combination of signals we do observe.
If you assume that indicator vector $d_{t} \in \mathbb{R}^{d}$ is such that if $d_{jt} = 1$ then we observe signal $y_{jt}$, is there a way to characterize the posterior mean and variance as a function of this vector $d_{t}$?
Even if you do not know the answer, I would appreciate if you could point me to literature that might be useful. Thanks!
Answer: Let's drop the $t$ subscripts for simplicity of notation. I'm also going to use $\omega \in \{0, 1\}^d$ to denote the indicator vector of the observed vector (to avoid confusing it with the dimension of the space which we're calling $d$). So, in your example with $y_1$ and $y_3$ being observed and $y_2$ not being observed, we would have $\omega = (1, 0, 1)$. We're supposing that the indicator $\omega$ is given, so I'm not going to write it in every conditional.
Note that the observed vector $z$ is given by the entry-wise product $z = \omega \odot y$ where we are filling in all the non-observed $y_j$'s with the value $0$ so that we still have a vector in $\mathbb{R}^d$. These non-observed values now have deterministic values, which will preclude $z|\theta$ from having a density function with respect to the Lebesgue measure on $\mathbb{R}^d$. But with the right measure (the one ignoring the known, $0$-valued coordinates), this is not an issue: given $\theta$, we have $z \sim \mathcal{N}^* (\theta, \Omega)(z)$, a degenerate multivariate normal distribution with mean $\theta$ and ``covariance'' $\Omega = \text{Diag}(\omega /\sigma_\epsilon^2 )$ (quotes because $\Omega$ is not a full-rank matrix, and hence is not positive-definite like covariance matrices are required to be). Once you recognize this fact, the computation looks like the Bayesian update formula for a normal likelihood and a normal prior. Using Bayes' Theorem:
\begin{align}
p(\theta | z) & \propto p(z | \theta) p(\theta) \\
& = \prod_{\{ j \colon \omega_j = 1 \}} \mathcal{N}(\theta_j, \sigma_\epsilon^2)(y_j) \times \mathcal{N}(\mu_\theta, \Sigma_\theta)(\theta) \\
& \propto \exp\left( \frac{- \sum_{\{j \colon \omega_j = 1\}}(y_j - \theta_j)^2}{2\sigma_\epsilon^2} \right) \times \exp\left( \frac{-1}{2} (\theta - \mu_\theta)^T \Sigma^{-1} (\theta - \mu_\theta) \right) \\
& = \exp\left( \frac{-1}{2} \left( (y - \theta)^T \text{Diag}(\omega /\sigma_\epsilon^2 ) (y - \theta) + (\theta - \mu_\theta)^T \Sigma^{-1} (\theta - \mu_\theta) \right) \right) \\
& \propto \exp\left( \frac{-1}{2} \left( \theta^T (\Omega + \Sigma^{-1}) \theta - 2 (y^T \Omega + \mu_\theta^T \Sigma^{-1}) \theta \right) \right) \text{ , where } \Omega = \text{Diag}(\omega /\sigma_\epsilon^2 )\\
& = \exp\left( \frac{-1}{2} \left( \theta^T (\Omega + \Sigma^{-1}) \theta - 2 (\Omega + \Sigma^{-1})^{-1} (\Omega + \Sigma^{-1}) (y^T \Omega + \mu_\theta^T \Sigma^{-1}) \theta \right) \right) \\
& \propto \exp\left( \frac{-1}{2} \left( (\theta - \mu_1)^T (\Omega + \Sigma^{-1}) (\theta - \mu_1) \right) \right) \text{ , where } \mu_1 = (\Omega + \Sigma^{-1})^{-1} (y^T \Omega + \mu_\theta^T \Sigma^{-1})^T\\
& \propto \mathcal{N}(\mu_1, (\Omega + \Sigma^{-1})^{-1})(\theta)
\end{align}
So our posterior distribution looks essentially identical to the standard Bayesian update formula. You can now repeat for a sequence of observations indexed by $t$ and you can simplify this using the Woodbury matrix formula if you want, similar to the computation in the previous link, but I leave that as an exercise for you.
Comment: Thank you very much @ericperkerson ! However, I realized that my question wasn't exactly what I am looking for. The question that I had in mind is exactly the one in [here](https://stats.stackexchange.com/questions/421288/multivariate-bayesian-inference-learnig-about-the-mean-of-a-variable-by-observi/457218#457218), where every entry of the posterior mean is updated in a "hey I didn't observe a signal for 1 but I did for 2 and I know 1 and 2 are correlated to some degree" fashion. Any idea on how to do this?
Answer: Just a small correction to the previous solution. The correct expression for the posterior mean is given by:
\begin{align*}
\mu_{1} & =(\Omega + \Sigma^{-1})^{-1} (y^{T} \Omega + \mu_{\theta}^{T} \Sigma^{-1})^{T} \\
& = (\Omega + \Sigma^{-1})^{-1} (\Omega y +  \Sigma^{-1} \mu_{\theta})
\end{align*}
As for the generalization to an arbitrary sequence of incomplete signals as in here, the result is as follows (in case it's useful for someone):
\begin{align*}
\mathbb{E}(\theta | \{\omega_{i}\}_{i=i}^{N} ) & = \Big(\Sigma^{-1} + \sum_{i=1}^{N} \Omega_{i} \Big)^{-1} \Big(\Sigma^{-1} \mu_{\theta} + \sum_{i=1}^{N} \Omega_{i} y_{i} \Big) \\
\mathbb{V}(\theta | \{\omega_{i}\}_{i=i}^{N} ) & = \Big(\Sigma^{-1} + \sum_{i=1}^{N} \Omega_{i} \Big)^{-1}
\end{align*}
where of course, if $N=1$ then the general expression collapses to the one shown by ericperkerson. I used the Woodbury Matrix Formula for trying to simplify these expressions but it doesn't do much (contrary to the case in which $\Omega_{i} = \Omega \hspace{2mm} \forall i$) for the mean or covariance, so I leave them as above.


Type of study design:

Question: I have multiple dependant marketing variables measured on dichotomous scales and one independant variable with three levels (students, university personnel, both). I would like to define the type of study design in order to chose the correct statistical test for group differences. I want to see if the different marketing activities are different according to the main type of market (students, university personnel, both).
1) Between subject designs?
2) Within subject designs?
3) Mixed designs?
What actually worries  me is the category "Both". If not I would hae already classified it as "Between subject design"
Can you help me with some ideas and suggestions? Thank you in advance!
Comment: within group design is when you compare the performance of the same individual at different times, for example, pre and post-treatment. In this case there is only one assessment moment, is that right? So it does not matter whether you have people who share the share the characteristics of the other groups, they still represent another category.
Answer: It is a between subjects design, since you won't measure the same subject multiple times. And subjects cannot be in two groups (only students, only university, student and university), so they are still discrete.

Type of study design:


Logging to a file, prepending a timestamp to each line (Debian)

Question: I am trying to log output from some shell scripts of mine to a file, and I want the timestamp prepended to each line. From what I understood, that's what logger(1) is for, but I don't want the output to go to /var/log/messages, and I can't see that this is possible using logger. I'm using Debian by the way.
What is the best way to do this?
—Oliver
Comment: meta note: it's a duplicate of https://unix.stackexchange.com/questions/26728/prepending-a-timestamp-to-each-line-of-output-from-a-command
Answer: logger's function is actually to shunt messages to syslog; default configs will prepend a timestamp and write the logs out to /var/log/messages, but that doesn't mean that logger's purpose is to prepend a timestamp.
One way to handle this would be to modify your syslog configs such that your messages routed via logger go to a special file - use the "-p" flag to logger to stipulate a facility.priority pair (perhaps one of the user[1..7] facilities),  and configure your syslogd to log that facility to a special file.
Alternatively, you could whip up a quick shell function to simply prepend the timestamp:
Bodacious:~ james$ timestamp () {
> f=`date`
> echo $f $*
> }
You have new mail in /var/mail/james
Bodacious:~ james$ timestamp a line of logs
Tue 18 Jan 2011 22:40:24 EST a line of logs
Bodacious:~ james$

On my system, this is going to result in the shell forking /bin/date once per line of output. This is inefficient, but probably acceptable at small scales.
Comment: In attempting to provide an authoritative reference for my answer, I found out that I was a bit wrong.

"Facilities" are one of the ways syslog segments the messages it processes. There are 23 facilities defined - mostly for types of log messages that were common when syslog was created (lpr, ftp, cron), a couple to be generic buckets (messages, system) - but there are 8 facilities called local0 through local7 (not user1 through user7 as I originally stated) intentionally designed for local uses. See RFC5424 for the full list of facilities
Comment: Thanks for a good answer :) This was my original idea, but I thought "there has to be a program out there that does this already"… but clearly not! Or not one that's commonly used anyhow. Out of curiosity, what are the "user[1..7] facilities" you refer to?
Answer: I needed something like that, and google got me here.  Using something like syslog is definitely an overkill for just trying out to time something, and the printout-every-second is too inconvenient.
Here's a one-liner that seems to work fine:
cmd | { while read R; do echo "$(date +%s) $R"; done }

and a variant that prints the time it took to produce each line:
cmd | { T=$(date +%s); while read R; do T2=$(date +%s); echo "$((T2-T)) $R"; T=$T2; done }

(This is using seconds, probably not too hard to throw in %N in there, but at that level a shell solution is probably not the right tool anyway.)
Answer: You could use -t to tag each line, and then get your syslog server to filter to a different file based on that tag.
(Edited to take out incorrect reference to -f flag)
Comment: That's not what `-f` does. It uses the contents of the file as the message portion of the log entry.
Comment: My apologies! Misread the man page. However, the second part of the answer stands, so I've editted it to include just that.
Answer: Using the answer from Command to prepend string to each line?, I found this the easiest solution:
cmd | sed "s/^/`date +'%a %b %d %k:%M:%S'` /"

Comment: No, this is broken: it appends the same date to all lines.
Comment: Well, it's broken if you want to run an entire log-generating process through it. I'm using it as I generate each line.
Comment: If you're using it for a single line you don't need any pipe -- it's almost exactly the same as `date +...; cmd`.  The only difference is that you get a newline from `date` which you can remove in the usual ways.
Comment: The usual ways being sed?:-)
Comment: That would be one way ... but you're not using it.  Your line uses backticks in a way that already swallows the newline.  Here's a complete line that shows what I mean: `echo -n "$(date +%s) "; cmd` -- note that there are no pipes and no external subprocess other than `date`.
Comment: Cool, I just learnt something.
Comment: Well, you were using it -- maybe the `$(...)` is confusing -- it's the same as `\`...\`` except more convenient (including for these comments, which is why I used it).


Manually update core from 7.0 to 7.78 in one fell swoop

Question: I have recently become an admin for a site that has not been updated since 2011. there are broken links (internal links to the site's blog go to page not found, index error.) I think this is due to a bug, so I want to update the software. However this would be a manual update of Drupal Core and I'm wary of doing anything that might mess up the site's code, not being a coder myself.
Should I go somewhere in the middle of the 7.x updates, or should I go straight to the latest one? What issues may arise from my site from updating to the most recent available?
Comment: Rebuild from scratch with D9
Answer: The latest update contains all of the updates before so going straight to the latest one should be okay and is what is usually recommended. Be sure to backup your site and test the backup on a dev copy.
You should update your contributed modules at the same time as some of them may rely on updated versions of Drupal (core).
Lastly and very importantly, there have been numerous security releases since the 1st release and some of them are quite bad so I would say you should probably assume your site is compromised. That's 78(!) releases you've missed out on, including the infamous Drupalgeddon.


Solving a sum using Cauchy's sequence

Question: could I get some help proving that the sum of this expression is equal to $m$ using Cauchy's criterion?
$ 1+\frac{m-1}{m}+(\frac{m-1}{m})^{2}+(\frac{m-1}{m})^{3}+(\frac{m-1}{m})^{4}+....+(\frac{m-1}{m})^{n} $
Comment: Cauchy's criterion is a way of determining whether or not a series converges. It has nothing to do with actually computing the sum.
Comment: What $\;M\;$ do you mean?
Comment: @JoséCarlosSantos I see, thanks! so how could I compute this sum?
Comment: The limit of that sum (over $\;n\;$) is infinity and thus the limit doesn't exist finitely. Have you studied infinite series?
Comment: That's a geometrical series, right?! So…
Comment: Ah, right. Jose Carlos is right, I got confused with the $\;m,\,n\;$ . It is a geom. series with absolute value of ratio less than one and thus it converges...
Answer: With geometric series:
$1+\frac{m-1}{m}+(\frac{m-1}{m})^{2}+(\frac{m-1}{m})^{3}+(\frac{m-1}{m})^{4}+....+(\frac{m-1}{m})^{n} \to \frac{1}{1-\frac{m-1}{m}}=m$ as $ n \to \infty.$

Solving a sum using Cauchy's sequence


Dice problem, with image explanation.

Question: Four dice are rolled SIMULTANEOUSLY. $X_1$ is a random variable that represents how many 1's you get in a single roll. $X_2, ... , X_4$ are defined in the same fashion, like in the picture below.
Remember the rolls are NOT consecutive. Let Y = $X_1X_2X_3X_4$. What values Y can get? Get $E(Y)$
Answer: The variable $Y=0$ unless your four numbers are exactly $1,2,3,4$ in some order.  In that case $Y=1$, because $X_1=X_2=X_3=X_4=1$.
Comment: If each random variable can vary between 0,1,2,3 and 4 why did you assume they're all equal to one? Wouldn't the expected value of Y be the multiplication of each variable?
Comment: @matt_zarro, the variables are not independent.  If any one of them takes a value greater than $1$, then one of the others must take the value $0$, which makes their product $Y=0$.  (Oh, I answered this in part because I thought it was a comment to my answer!)
Comment: eureka!!!!! Thanks so much @BarryCipra !! Finally it makes sense, math is so beautiful!
Comment: Thanks to you too @vadim123 for the fast answer, but barry's also answered the expected value, wish i could mark both as wright..
Answer: $Y$ takes the values $0$ and $1$, the latter if and only if you have one each of $1,2,3$ and $4$, which occurs with probability $4!/6^4=1/54$, which is thus the value of $E(Y)$.

Dice problem, with image explanation.


Writing a piecewise function inside deff

Question: I am using deff to define piecewise functions in Scilab. I use if-else statements to define the function in different intervals. All of them seem to work except for this one.
This is my approach:
deff('a=f(p)', ["if(q >= -2 & q <= -1) then"; "a=1"; "elseif(q >= 1 & q <= 2) then"; "a=-1"; "else"; "a=0"; "end";])

The same approach worked on similar functions such as this.
eff('a=f(p)', ["if((p > 0 & p <= 2)) then"; "a=p/2"; "else"; "a=0"; "end";])

I have defined q as so:
q = -3:Ts:3;

where Ts is some floating point number. What am I doing wrong?
Comment: Can you validate the answer if it is ok for you ?
Answer: You cannot use your function as-is when the input is a vector. A possible workaround is to use feval:
a = feval(q,f)

Another (better) solution is to code f in a vectorized manner:
function a = f(q)
     a = 1*(q >= -2 & q <= -1) - 1*(q >= 1 & q <= 2)
end

the 1* are not necessary unless you need to change the values.


Equality between intersection of image of nested closed sets : $\bigcap_{n\in\mathbb{N}}f(F_{n}) = \bigcap_{n\in\mathbb{N}}\overline{f(F_{n})}$

Question: I'm trying to understand the following proof:
Theorem. Let $X$ and $Y$ be Hausdorff spaces. Let $f:X\rightarrow Y$ be a continuous mapping. Suppose that $\{F_{n}\}_{n\in\mathbb{N}}\subset X$ is a decreasing sequence of closed sets with compact intersection $K = \bigcap_{n\in\mathbb{N}}F_{n}.$ If for each open set $U$ in $X$,  $K\subset U$ implies that there exists some $m\in\mathbb{N}$ such that $F_{m}\subset U,$ then
$$f(K) = \bigcap_{n\in\mathbb{N}}f(F_{n}) = \bigcap_{n\in\mathbb{N}}\overline{f(F_{n})}.$$
Proof: For any $y\in\bigcap_{n\in\mathbb{N}}\overline{f(F_{n})}$, suppose that for each $x\in K$ there exists an open set  $U_{x}$ containing $x$ such that $y\notin \overline{f(U_{x})}.$ The collection $\{U_{x}\}_{x\in K}$ is an open cover of $K.$ Then the union of the $U_{x}$ in the subcover gives an open set $U\supset K$ with $y\notin\overline{f(F_{n})}$ for $n$ large, a contradiction since $F_{n}\subset U$  for $n$ large. So take $x\in K$ with $y\in f(V)$ for every open $V$ containing $x.$ If $f(x)\neq y,$  then take disjoint open neighborhoods $W$ of $f(x)$ and $T$ for $y.$ Let $V = f^{-1}(W)$ to get a contradiction.
I understand every part of the proof except "So take $x\in K$ with $y\in f(V)$ for every open $V$ containing $x.$" Why $y\in\bigcap_{n\in\mathbb{N}}\overline{f(F_{n})}$ satisfies the previous affirmation? Because of the above $y\in\overline{f(V)}$ for each open set containg $x,$ but is not clear that must be $y\in f(V).$
Of course, for an element $y\in f(V)$ for each $V$ open set containg $x,$ the last part of the proof above give us the seeking contradiction finishing the argument.
Any kind of help is thanked in advance.
Answer: It has something to do with $Y$'s Hausdorffness. Let me fill in the details of the proof.
Since $K = \bigcap_{n\in\mathbb{N}}F_{n}$, we have
$$f(K) =f(\bigcap_{n\in\mathbb{N}}F_{n}) \subseteq \bigcap_{n\in\mathbb{N}}f(F_{n})  \subseteq  \bigcap_{n\in\mathbb{N}}\overline{f(F_{n})}$$
Therefore, we need to prove
$$\bigcap_{n\in\mathbb{N}}\overline{f(F_{n})} \subseteq f(K)$$
Suppose that there exists a $y\in\bigcap_{n\in\mathbb{N}}\overline{f(F_{n})}$ such that $y \notin f(K)$, then for each $x \in K$, $f(x) \neq y$. Since $Y$ is Hausdorff, $f(x)$ and $y$ are separated by neighborhoods, thus there exists an open set  $U_{x}$ containing $x$ such that $y\notin \overline{f(U_{x})}$ because $f$ is continuous. The collection $\{U_{x}\}_{x\in K}$ is an open cover of $K$, then the union of the $U_{x}$ in the finite subcover gives an open set $U=\bigcup_{i=1}^nU_{x_i}\supseteq K$ with
$$y\notin \bigcup_{i=1}^n \overline{f(U_{x_i})}=\overline{\bigcup_{i=1}^n f(U_{x_i})}=\overline{f(\bigcup_{i=1}^n U_{x_i})} =\overline{f(U)} \supseteq \overline{f(F_{n})}$$
for $n$ large, a contradiction since $y\in \overline{f(F_{n})}$ for every $n \in \mathbb{N}$. This proves that $\bigcap_{n\in\mathbb{N}}\overline{f(F_{n})} \subseteq f(K)$. By the way, I don't think $X$ needs to be Hausdorff.
Comment: Very nice proof @Ricky! I really appreciate your help. Thanks.