java: Printing odd even numbers using 2 threads

Question: I am trying to print odd and even numbers using 2 different threads alternately. I was able to achieve it using wait, notify and synchronize block but now i want to evaluate if we can achieve it without using wait, notify and synchronize.
Following is the code i have but its not working:
public class OddEvenUsingAtomic {

AtomicInteger nm = new AtomicInteger(0);
AtomicBoolean chk = new AtomicBoolean(true);

public static void main(String args[]) {
    final OddEvenUsingAtomic pc = new OddEvenUsingAtomic();

    new Thread(new Runnable() {

        @Override
        public void run() {
            while (true) {

                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }

                if (pc.chk.compareAndSet(true, false)) {

                    System.out.println("Odd: " + pc.nm.incrementAndGet());
                }
            }

        }

    }).start();

    new Thread(new Runnable() {

        @Override
        public void run() {
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            while (true) {
                if (pc.chk.compareAndSet(false, true)) {

                    System.out.println("Even: " + pc.nm.incrementAndGet());
                }
            }

        }

    }).start();
}

}
Any ideas?
I created another version after suggestions from Bruno which seems to be working better:
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;

public class OddEvenUsingAtomic {

    AtomicInteger nm = new AtomicInteger(0);
    AtomicBoolean chk = new AtomicBoolean(true);

    public static void main(String args[]) {
        final OddEvenUsingAtomic pc = new OddEvenUsingAtomic();

        new Thread(new Runnable() {

            @Override
            public void run() {
                while (true) {

                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }

                    if (pc.chk.get() == Boolean.TRUE) {

                        System.out.println("Odd: " + pc.nm.incrementAndGet());
                        pc.chk.compareAndSet(true, false);
                    }
                }

            }

        }).start();

        new Thread(new Runnable() {

            @Override
            public void run() {
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                while (true) {
                    if (pc.chk.get() == Boolean.FALSE) {

                        System.out.println("Even: " + pc.nm.incrementAndGet());
                        pc.chk.compareAndSet(false, true);
                    }
                }

            }

        }).start();
    }
}

Comment: What exactly do you mean by "it is not working"? What results are you getting? Did you try to run your code in a debugger, or with some additional logging enabled?
Comment: *"Threads are mixing up the odd even values."* - please describe what is happening **clearly**.  "Mixing up" is not a clear description.
Comment: With above code i want one thread to print only even numbers and other thread to print only odd numbers. I want to achieve it just with Atomic Integer and its not happening. Threads are mixing up the odd even values.
Comment: Following is a sample output, you can see odd numbers in front of even numbers this is waht i am calling mixing up : Odd: 1
Even: 2
Odd: 3
Even: 4
Even: 6
Odd: 5
Odd: 7
Even: 8
Even: 10
Odd: 9
Odd: 11
Even: 12
Odd: 13
Even: 14
Even: 16
Odd: 15
Odd: 17
Even: 18
Even: 19
Odd: 20
Even: 22
Odd: 21
Odd: 23
Even: 24
Odd: 25
Even: 26
Odd: 27
Even: 28
Answer: The code is not correctly synchronized, that's the problem.
The following execution order is allowed in your code:

First thread sees chk == true, sets it to false and enters the if block.
Second thread sees chk == false, sets it to true and enters the if block.

Now, you have 2 threads both inside their if blocks, getting ready to:

incrementAndGet() the number
Print it.

Therefore, you have absolutely no control on what is going to happen.

You can have any of the threads call incrementAndGet(), therefore you can have thread "Odd" printing, first, an odd number, and later, an even number.
You can have the first thread print the number, loop, see that the condition is satisfied again (since the second thread has set chk to true again, print, all of this before the second thread had the chance to print).

As you can see, to achieve the result you want, you must have the following operations done atomically:

compareAndSet() the boolean
incrementAndGet() the number
print it

If the 3 operations are not atomic, then you can have the threads being scheduled to run the operations in any possible order, you have no control on the output. The easiest way to achieve this is to use a synchronized block:
public static void main(final String... args) {
  final Object o = new Object();
  // ... thread 1 ...
    synchronized(o) {
      if (boolean is in the expected state) { change boolean, get number, increment, print }
    }
  // ... thread 2 ...
    synchronized(o) {
      if (boolean is in the expected state) { change boolean, get number, increment, print }
    }
}

Comment: Perfect, this shld work... i have edited by code and seems to be working. Just one thing change boolean shld come after increment. Do you agree? Also if we move change boolean to after increment , then do we need synchronization? I dont think so
Comment: Your edit makes my answer completely invalid for those who read the new version of the question. I really think you should revert your edit, leave your first wrong version, and ADD your new, correct version in the end of your question, preferably after something clearly stating that you added that as an edit, after you got some answers. After that, I will comment on your new input and on your new version, and how it relates to what I answered. There's some etiquette around here.
Comment: Added the new version below the first version and apologies for earlier error. I am wondering if we really need synchronization.
Comment: Yes, you do need synchronization, since, as I explained, you need the have the operations been executed **atomically**. One way to ensure the set of operations is atomic is to use a `synchronized` block (which is, by far, the most common solution and most simple to read and maintain). Another way is to do what you did: it is a "non-standard" method to achieve synchronization, in this case completely equivalent (even in memory visibility aspects). In any case, I cannot see any reason other than "I want to try something completely different to study a bit" to do what you did in the 2nd version.
Comment: From Wikipedia: *Thread synchronization or serialization, strictly defined, is the application of particular mechanisms to ensure that two concurrently-executing threads or processes do not execute specific portions of a program at the same time*. You used one particular mechanism. I used a different one -- the standard.
Comment: Oh, and some extra info: you can use a `boolean` and an `int` instead of `AtomicBoolean` and `AtomicInteger` if you use `synchronized`. If you don't want to use `synchronized`, you can use your 2nd version with a `volatile boolean` and a `volatile int` instead of the `Atomic*` classes. All of these options achieve the same thing, and are all correct.
Comment: You are right , i was trying to just study if this can be achieved without locking. Volatiles should do the job here.
Comment: Lokesh, one more thing: if you are trying to avoid locking because you've heard that "locking is evil" (ie, it makes things slow, etc), that kind of information is very, *very* old. Using "synchronized" in Java nowadays is very good. For instance, it won't lock right away if it can't obtain the lock, but it will loop and retry some times before giving up. Also uncontended locking is *very* fast. Anyways, it is very good to exercise the kind of thing you asked about.
Answer: Here are two threads printing odds and evens with no wait, notify, or synchronized (at least not in the code you can see):
import java.util.concurrent.*;

public class ThreadSignaling {
    public static void main(String[] args) {
        BlockingQueue<Integer> evens = new LinkedBlockingQueue<>();
        BlockingQueue<Integer> odds = new LinkedBlockingQueue<>();
        ExecutorService executorService = Executors.newFixedThreadPool(2);
        executorService.submit(() -> takeAndOfferNext(evens, odds));
        executorService.submit(() -> takeAndOfferNext(odds, evens));
        evens.offer(0);
    }

    private static void takeAndOfferNext(BlockingQueue<Integer> takeFrom,
                                         BlockingQueue<Integer> offerTo) {
        while (true) {
            try {
                int i = takeFrom.take();
                System.out.println(i);
                offerTo.offer(i + 1);
            } catch (InterruptedException e) {
                throw new IllegalStateException("Unexpected interrupt", e);
            }
        }
    }
}

Answer: class MultiThreading {

    Integer counter = 0;
    Thread even;
    Thread odd;
    boolean flagEven = true;
    boolean flagOdd;

    class ThreadEven implements Runnable {
        @Override
        public void run() {
            try {
                while (counter < 100) {
                    if (flagEven) {
                        System.out.println(counter);
                        counter++;
                        flagEven = false;
                        flagOdd = true;
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    class ThreadOdd implements Runnable {
        @Override
        public void run() {
            try {
                synchronized (even) {
                    while (counter < 100) {
                        if (flagOdd) {
                            System.out.println(counter);
                            counter++;
                            flagOdd = false;
                            flagEven = true;
                        }
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    public void start() {
        even = new Thread(new ThreadEven());
        odd = new Thread(new ThreadOdd());
        even.start();
        odd.start();
    }

}

}
call in the main method
new MultiThreading().start();


Vectors in XYZ Space with Negative Dot Product?

Question: This question is from a Linear Algebra textbook by Gilbert Strang. I got the answer, but don't understand it complete.
Can three vectors in the $xy$-plane have $\textbf{u} ⋅ \textbf{v} < 0$ and $\textbf{v} ⋅ \textbf{w} < 0$ and $\textbf{u} ⋅ \textbf{w} < 0$? I don't know how many vectors in the $xyz$-space can have all negative dot products. (Four of those vectors in the plane would certainly be impossible...)
I don't understand why 4 vectors in the same plane can't all have negative dot products with each other? Doesn't a negative dot product just mean that the angle between the vectors is less than 90 degrees? So wouldn't you be able to have an infinite amount of vectors in the same plane that all have negative dot products with each other? Thanks for the help.
Comment: Please see https://www.math.purdue.edu/pow/fall2012/pdf/solution1.pdf
Answer: The condition asks that any pairs out of your choice of vectors should have angle between them greater than $\pi/2$. This gives us certain geometric restraints on how vectors should be organized.
Let $v_1 \in \Bbb{R}^d \setminus \{0\}$ be our first choice and $H_1 = \{ u \in \Bbb{R}^d : u \cdot v_2 \geq 0 \}$. Then our next choice $v_2$ cannot be drawn from this region. But $H_1$ is a closed half-space, which means that half of the $\Bbb{R}^d$ becomes a forbidden region. And as you keep picking vectors, this forbidden region keep expanding. The problem says that when $d = 2$, if you pick 3 vectors in this way, the forbidden region covers the entire plane $\Bbb{R}^2$ and thus you cannot pick the fourth one.
Here is another explanation which is specific to the 2D case. Assume that you have four vectors. Pick any of them and label it $v_1$, and then label the others by $v_2, v_3, v_4$ as they appear in counter-clockwise order beginning from $v_1$. Then the angles $\angle v_1v_2$, $\angle v_2v_3$, $\angle v_3v_4$ and $\angle v_4v_1$ should sum up to $2\pi$. This means that at least one of them should be $\leq \pi/2$.
Answer: If $\vec u \cdot \vec v < 0$, then $$\big| \vec u \big| \cdot \big| \vec v \big| \cdot \cos \theta<0,$$ where $\theta$ is the angle between $u$ and $v$, which means the angle between $\vec u$ and $\vec v$ is greater than $90^\circ$. Now apply this to your situation.
Answer: since $u\cdot v=|u||v|\cos \theta_{u,v}$ and $\cos(\theta)$ is negative if $\pi/2<\theta<\pi$ this can indeed work for your case by placing the three vectors at equal angular separation.
Answer: A negative dot product means that the angle between vectors are larger than $90^{\circ}$. The available answers here solved it in 2D space and I am going to elaborate further in 3D space.
Lets start with a modified question: How many vectors in the $xyz$ space can have all zero dot products. The answer is straightforward -- six, one obvious vector set can be $+x$,$+y$,$+z$ and $-x$, $-y$, $-z$.
Now lets use $+x$ as a starting vector and try to solve the original question. To ensure negative dot product with $+x$, these vectors $+y$, $-y$, $+z$, $-z$ has to shift towards $-x$, and we know that among themselves one vector has to go to get negative dot product. Also, when they shift towards $-x$, $-x$ has to go away because the angle is smaller than $90^{\circ}$ now.
Consequently, only 4 vectors in $XYZ$ space can have all negative dot product.
Comment: For the 2nd paragraph, I suppose you want to find how many vectors are pair-wise orthogonal in $xyz$ space. For example, your vectors $+x$ and $-x$, if defined as let's say (1,0,0) and (-1,0,0) have a dot product $\ne 0$, namely -1 (similarly for $+y, -y$ and $+z, -z$. In any $\mathbb{R}^n$, you can have $n$ pair-wise orthogonal vectors.


Java - Merge sort array

Question: I'm making an algorithm for a shop. I have made an array which contains customer information. Now I want to implement a merge-sort on this array and sort it on age. This is my code for the customer class:
public class Customer{

private int customerID;
private String name;
private int age;
private char gender;
private String email;

public List<Customer> customerList = new ArrayList<Customer>();

public Customer(String name, int age, char gender, String email) {
    this.customerID = customerList.size();
    this.name= name;
    this.age= age;
    this.gender= gender;
    this.email = email;
    customerList.add(this);
}
public int getCustomerID() {
    return customerID;
}

public void setCustomerID(int customerID) {
    this.customerID = customerID;
}

public String getName() {
    return name;
}

public void setName(String name) {
    this.name= name;
}

public int getAge() {
    return age;
}

public void setAge(int age) {
    this.age = age;
}

public char getGender() {
    return gender;
}

public void setGender(char gender) {
    this.gender = gender;
}

public String getEmail() {
    return email;
}

public void setEmail(String email) {
    this.email = email;
}

}
This is my merge-sort:
    private int[] helper;
private int number;

public void sort(Klant[] values) {
    this.customerList= values;                      <---Error
    number = values.length;
    this.helper = new int[number];
    mergesort(0, number - 1);
}

private void mergesort(int low, int high) {
    // check if low is smaller then high, if not then the array is sorted
    if (low < high) {
        // Get the index of the element which is in the middle
        int middle = low + (high - low) / 2;
        // Sort the left side of the array
        mergesort(low, middle);
        // Sort the right side of the array
        mergesort(middle + 1, high);
        // Combine them both
        merge(low, middle, high);
    }
}

private void merge(int low, int middle, int high) {

    // Copy both parts into the helper array
    for (int i = low; i <= high; i++) {
        helper[i] = customerList[i];
    }

    int i = low;
    int j = middle + 1;
    int k = low;
// Copy the smallest values from either the left or the right side back
    // to the original array
    while (i <= middle && j <= high) {
        if (helper[i] <= helper[j]) {
            customerList[k] = helper[i];
            i++;
        } else {
            customerList[k] = helper[j];
            j++;
        }
        k++;
    }
    // Copy the rest of the left side of the array into the target array
    while (i <= middle) {
        customerList[k] = helper[i];
        k++;
        i++;
    }

}

On the line with:
this.customerList = values; I get an error: incompatible types Customer[] cannot be converted to List
My question is how can I fix this error and is my merge-sort correct this way?
Edit 1:
@Jens
Your first option:
    this.customerList= Arrays.asList(values);
fixed the error. But now I'm getting an error on this line:
            helper[i] = customerList[i];

It says: array required, but List found
Does anybody know how to fix this?
Comment: `public List customerList = new ArrayList();` This is a list. You're passing a `Klant[]` array. Arrays and ArrayLists are different. You were probably looking for `Customer[] customerList;`
Comment: You can either cover your list to an array or use a list through out !
Answer: You can`t assign a Array to a list.
Try
 this.customerList= Arrays.asList(values);

or Change the method parameetr to List<Customer>
public void sort(List<Customer> values) {

Answer: Why not to use Collections.sort() method? It also uses merge sort algorithm.
List<Klant> list = Arrays.asList(values);
Collections.sort(list);

Or you can use Arrays.sort() as well, but it does not use merge sort.
But keep in mind that will you need it to implement Comparable interface for your Klant class.
UPDATE:
In case if you need to implement merge sort algorithm by yourself, probably you need to change customerList variable type from List to array of Customer[]. If you would like to use the list you can do as Jens suggested, but use add() method of List and not assign the value via =.
Comment: Well I assume the task is to create a mergesort, so sorting it using a collections class is not really accomplishing the task with a mergesort.

Java - Merge sort array


type 'Future' is not a subtype of type 'Route'

Question: I got the the following  error for below code. I was attempting to navigate to the next page. I was able to navigate just once and then I got the error mentioned above. Please do help me on this. I tried even using await but await is not supported for  builder: (BuildContext context) => SubmitArticles()).
class UserSubmitOption extends StatefulWidget {
  @override
  _UserSubmitOptionState createState() => _UserSubmitOptionState();
}

class _UserSubmitOptionState extends State<UserSubmitOption> {
  @override
  Widget build(BuildContext dynamic) => MaterialApp(
      debugShowCheckedModeBanner: false,
      home:SafeArea (
          child: Scaffold(
            backgroundColor: Colors.indigo[800],
            resizeToAvoidBottomInset: false,
            appBar: AppBar(
                toolbarHeight: 60,
                backgroundColor: Colors.indigo[900],
                automaticallyImplyLeading: false,
                title: Text("What do you want to submit?",style:TextStyle(color:Colors.white,fontWeight:FontWeight.bold)),
                centerTitle: true,
                leading: IconButton(
                    icon: Icon(Icons.arrow_back,color:Colors.black,size:25,),
                    onPressed: () => Navigator.push(context,
                        MaterialPageRoute(builder: (context) => UserMenu())))),
            body: SafeArea(
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.center,
                children: <Widget>[
                  Padding(
                    padding: const EdgeInsets.all(60.0),
                    child: Center(
                      child: Wrap(spacing: 50, runSpacing: 50.0, children: <Widget>[
                        GestureDetector(
                            onTap: () {
                              SubmitQuiz();
                              setState(() {

                              });
                            },
                            child: SizedBox(
                              width: 200.0,
                              height: 200.0,
                              child: Card(
                                color: Colors.indigo,
                                borderOnForeground:true,
                                shadowColor: Colors.white,
                                elevation: 20.0,
                                shape: RoundedRectangleBorder(
                                    borderRadius: BorderRadius.circular(100.0)),
                                child: Center(
                                    child: Padding(
                                      padding: const EdgeInsets.all(50.0),
                                      child: Column(
                                        children: <Widget>[
                                          Icon(
                                            Icons.vpn_key_outlined,size:60,color:Colors.black,
                                          ), //     Image.asset("assets/todo.png",width: 64.0,),
                                          SizedBox(
                                            height: 7.0,
                                          ),
                                          Text(
                                            "Quiz",
                                            style: TextStyle(
                                              color: Colors.black,
                                              fontWeight: FontWeight.bold,
                                              fontSize: 17.0,
                                            ),
                                          ),
                                          SizedBox(
                                            height: 5.0,
                                          ),
                                        ],
                                      ),
                                    )),
                              ),
                            )),
                        GestureDetector(
                            onTap: () async {Navigator.push(context,
                                MaterialPageRoute (
                                    builder: (BuildContext context) => SubmitArticles())
                            );},
                            child: SizedBox(
                              width: 200.0,
                              height: 200.0,
                              child: Card(

                                color: Colors.indigo,
                                elevation: 20.0,
                                shadowColor:Colors.white,
                                shape: RoundedRectangleBorder(
                                    borderRadius: BorderRadius.circular(100.0)),
                                child: Center(
                                    child: Padding(
                                      padding: const EdgeInsets.all(45.0),
                                      child: Column(
                                        children: <Widget>[
                                          Icon (
                                            Icons.article_outlined,size:60,
                                          ),
                                          //    Image.asset("assets/note.png",width: 64.0,),
                                          SizedBox(
                                            height: 7.0,
                                          ),

                                          Text(
                                            "Articles",
                                            style: TextStyle(
                                                color: Colors.black,
                                                fontWeight: FontWeight.bold,
                                                fontSize: 17.0),
                                          ),
                                          SizedBox(
                                            height: 5.0,
                                          ),

                                        ],
                                      ),
                                    )),
                              ),
                            )),
                                           ]),
                    ),
                  ),
                ],
              ),
            ),
          )));
}

Comment: We need more code. I think that your method SubmitArticles returns a Future and no Route. If it returns a route, you have to add await before the call: await SubmitArticles()
Answer: You are trying to access route in the wrong way
use instead:
Navigator.push(context,MaterialPageRoute(
builder : (context) => SubmitArticles())
);

i hope it work with you.
happy coding!
Comment: And above line is causing error on                                  return MaterialApp(  of  following code
     void main() async {
    WidgetsFlutterBinding.ensureInitialized();
    await Firebase.initializeApp();
    runApp(MyApp());
  }

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(context) {
    return MaterialApp(
      debugShowCheckedModeBanner:false,
      home: AuthService().handleAuth(),
    );
  }

}
Comment: This is the error
                The following _TypeError was thrown building Builder(dirty):
type 'Future' is not a subtype of type 'Widget'


Calculate sum entry by entry (and displaying each step) in a table that contains multiple different items

Question: I have a process where multiple items in multiple iterations are being stored  into a storage. I am creating a entry for each item that is being moved to the storage, but now I have to make a self refreshing report which the workers can use to see in where they have stoped before they got distracted, went to a break, etc..
Here is a simplified example of what my table looks like:
<code>╔═══════════╦══════╦════════╦══════════╗
║ Timestamp ║ Item ║ Loaded ║ Expected ║
╠═══════════╬══════╬════════╬══════════╣
║        10 ║ A1   ║      1 ║       14 ║
║         9 ║ A2   ║      1 ║        8 ║
║         8 ║ A1   ║     11 ║       14 ║
║         7 ║ A1   ║      1 ║       14 ║
║         6 ║ A1   ║      1 ║       14 ║
║         2 ║ A2   ║      6 ║        8 ║
╚═══════════╩══════╩════════╩══════════╝
</code>
In the report/sql procedure I wan to make it look like this:
<code>╔═══════════╦══════╦════════╦══════════╗
║ Timestamp ║ Item ║ Loaded ║ Expected ║
╠═══════════╬══════╬════════╬══════════╣
║        10 ║ A1   ║      4 ║       14 ║
║         9 ║ A2   ║      7 ║        8 ║
║         8 ║ A1   ║     13 ║       14 ║
║         7 ║ A1   ║      2 ║        4 ║
║         6 ║ A1   ║      1 ║       14 ║
║         2 ║ A2   ║      6 ║        8 ║
╚═══════════╩══════╩════════╩══════════╝
</code>
The current value for each line entry (ordered by the timestamp, desending) is the predecessor items value plus the value that was moved in the current row.
Is there any way to make this happen?
Comment: I don't understand the definition of your result set I'm afraid. Could you elaborate further? Thanks.
Comment: Is there possibly a type-o in your expected results?
Comment: your example makes no sense but look at RunningValue() https://learn.microsoft.com/en-us/sql/reporting-services/report-design/report-builder-functions-runningvalue-function
Answer: Solved it with this (by using the first apporach): https://sqlperformance.com/2014/01/t-sql-queries/grouped-running-totals


super slow egress after migrating server mirror to GCE

Question: Migrated a Windows 2008 R2 instance using Cloud Endure to GC.  Everything looks great, network rules are set up correctly.
I can remote into the box from behind the firewall and everything is snappy.  But when the system is accessed from outside the firewall it's only getting about .5mb of egress speed (RDP/Web).  Running speedtest.net locally on the box it's getting 300mb download (bad) and it's only getting .5mb upload, typically this is around 1.4gb.
The network (ip4) settings have no legacy dns settings in them, everything is set to auto.  Ipconfig shows no legacy ips attached.  netstat -ano shows no activity trying to get to the prior network.  Checking network activity via taskmgr shows there isn't any network activity at all.
It's really strange as I did a test run with Cloud endure a few months back without issue.
I even tried spinning up a new box that didn't have 4 extra dedicated IP's configured as this one does and it's the same issue.
Been working on this all day and I'm out of ideas at this point!
Thanks in advance for any ideas!
Mike
Answer: Some instances migrated by Cloud Endure may be configured with a non appropriate MTU and it may cause latency and packet overhead by fragmentation that affects the network performance. [1]
Use the following command to check the configured MTU in the Windows instance:
$ netsh interface ipv4 show subinterfaces
If the value is higher than the recommended (1430), change it and repeat the tests, as its quite possible that this is related to your issue.

[1] https://cloud.google.com/compute/docs/troubleshooting#packetfragmentation
Comment: Did you also try to recreate the same instance in GCP from scratch just to verify the connectivity? Are you still having the issue?
Comment: Hi Lozano, thanks for the feedback.  However that didn't help.  They were set to 1500, changed to 1427.  Also wouldn't this affect the server regardless of accessing it outside/inside the firewall.  The egress is great behind the firewall, it's only outside we have trouble.  Either way thanks again!
Answer: It's been noted that windows 2008 and 2012 migrations been facing very slow upload (egress) speed after migration with Cloudendure. For example here and here
This is because of this know issue
There is a fix that works most of the time:
To change your MTU setting in Windows Server 2003 or 2008 use the following steps:
Open regedit as an administrator account on the server in question. (Click start , Run then regedit)
Navigate to HKLM\System\CurrentControlSet\services\Tcpip\Parameters\Interfaces[Choose the interface in question] (Do this by checking the correct IP address is in the settings under this key for the adapter you are configuring OR the one that has local IP and gate way settings inside it )
Once you are in the correct key for your interface, right-click and select new DWORD value (32 bit).
Call it MTU
Give this a decimal value equal to 1460 (measured in bytes).
I hope this helps if you have issues with cloud endure.


How To go Previous page using C# in asp.net that display all previous details

Question: Is it Possible to store Previous Page with Gridview data and all other details and can go back and Display All previous Details. I am using following code but Gridview Data lost because of page post back.
 ViewState["RefUrl"] = Request.UrlReferrer.ToString();

Comment: Viewstate is only for one page/form, You can use session or querystring to use data through one form to another
Answer: Just save your datatable in session and use it in another form
session["Data"]=dt ;
while retriving data:
DataTable table = Session["Data"] as DataTable;

Answer: I have Used This. we doesn't loose data of previous page data.
if (!IsPostBack)
        {
            btnBack.PostBackUrl = Request.UrlReferrer.AbsoluteUri;
         }


Verificar se uma string é composta por digitos

Question: Quero verificar se as minhas strings (que estão guardadas numa matriz), são inteiros ou não por exemplo a para a quarta linha da matriz tenho o seguinte código.
#include <stdio.h>
#include <locale.h>
#include <string.h>
#include <locale.h>
#include <stdlib.h>

struct informacaoFicheiroInput{
int id;
int acompanhantes;
char tipo[13];
int entrada;
int saida;
int servico;

};

void toString(struct informacaoFicheiroInput info){

   if(strcmp("Visitante",info.tipo) == 0){

   printf("ID: %d | ",info.id);
   printf("%s | ",info.tipo);
   printf("Entrada: %d | ", info.entrada);
   printf("Saida: %d | ",info.saida);
   printf("Serviço: %d\n",info.servico);

   }else{
   printf("ID: %d | ",info.id);
   printf("Acompanhantes: %d | ",info.acompanhantes);
   printf("Tipo: %s | ",info.tipo);
   printf("Entrada: %d | ", info.entrada);
   printf("Saida: %d | \n",info.saida);
   }
}

int validacaoVisitante(char dados[5][20]){

if(atoi(dados[0]) == 0  ){ //validação do ID
    return 0;
}

    //Validação da entrada
if(!isDigit(dados[2]) || atoi(dados[2])>24 || atoi(dados[2])<0){
     return 0;
}
    //Validação saida
if (!isDigit(dados[3]) || atoi(dados[3])>24 || atoi(dados[3])<=0){
     return 0;
}

    //validação do serviço
if(!isDigit(dados[4]) && dados[4] == 0){
     return 0;
}
return 1;

}

int isDigit(char *string){
char *p;
int firstDigit = 0; // A princípio, nenhum dígito foi encontrado.
int lastDigit = 0;  // A princípio, nenhum dígito foi encontrado.
int result = 1;     // A princípio, considera-se verdadeiro, que é digito.

p = string;

while (*p){
    if (*p >= '0' && *p <= '9'){
        p++;
        firstDigit = 1;
    }
    else if (*p == ' ' && !firstDigit){
        p++;
    }
    else if (*p == ' ' && firstDigit && !lastDigit){
        lastDigit = 1;
        p++;
    }
    else if (*p == ' ' && lastDigit){
        p++;
    }
    else{
        result = 0;
        break;
    }
}

return firstDigit && result;
}

void lerFicheiroInput(){
struct informacaoFicheiroInput informacao[20];
int tokenCount=0;
FILE* file;
file = fopen("input.txt","r");

if(file == NULL){
    printf("Não foi possivel abrir o arquivo.\n");
}

char line[100], *token, dados[5][20];
int info = 0;

while(fgets(line, sizeof line, file) != NULL){
    int count=0,i=0;
    token = strtok(line," ; ");

    while(token != NULL && count < 15){

        strcpy(dados[count++], token);
        token = strtok(NULL, " ; ");
        i++;
        tokenCount++;
    }

    // Mete os dados lidos da info-esima linha
    // em informacao.
    if(strcmp("Visitante", dados[1]) == 0 && validacaoVisitante(dados)==1){
       informacao[info].id = atoi(dados[0]);
       strcpy(informacao[info].tipo, dados[1]);
       informacao[info].entrada = atoi(dados[2]);
       informacao[info].saida = atoi(dados[3]);
       informacao[info].servico = atoi(dados[4]);
       info++;
    }else if (atoi(dados[0])!=0 &&(strcmp("Diretor",dados[2])==0 ||
strcmp("Funcionario",dados[2])==0)) {
       informacao[info].id = atoi(dados[0]);
       informacao[info].acompanhantes = atoi(dados[1]);
       strcpy(informacao[info].tipo, dados[2]);
       informacao[info].entrada = atoi(dados[3]);
       informacao[info].saida = atoi(dados[4]);
       info++;
   }
    count++;
}

fclose(file);
for(int j = 0; j< info; j++){
   toString(informacao[j]);
}

}

void main(){
setlocale(LC_ALL,"");
lerFicheiroInput();

}

Comment: Sim tenho tudo, posso atualizar o código em cima, mas ainda são algumas linhas de código
Comment: Poderia dar um exemplo de entrada ?
Comment: Eu tenho um ficheiro com linhas do genero
2 ; 12 ; Funcionario ; 10 ; 5
E estou a divida-las desta maneira (" ; "), contando os espaços antes e depois do ";" depois queria fazer essa verificação para saber se por exemplo num parâmetro que deveria ter um inteiro tenho uma string ou um float, por exemplo
Comment: faltou informar a linguagem que está utilizando.
Comment: está na tag, em baixo
Comment: Tira todos os `for (int i = 0; i < 20; i++)` e deixa só o "recheio" dos `for` porque não estás a iterar sobre `dados`, ou seja, não estás a usar o índice `i` para nada. No mais, põe `atoi(dados[4]) == 0`, no último `if` da função, no lugar de `dados[4] == 0`
Comment: Ah sim faz sentido! E sim tbm já reparei no ==
Como faço para percorrer todas as linhas e comparar o Id de cada uma?
Comment: Tens que usar uma estrutura que tenha todas as informações de todas as linhas. Tens algo assim?
Answer: Você pode usar a função isdigit() da biblioteca padrão ctype.h. Veja só:
#include <ctype.h>
#include <stdio.h>

int isDigit( const char * str )
{
    if(!str) return 0;     /* Se string for NULL, retorna 0 */
    if(!(*str)) return 0;  /* Se string for VAZIA, retorna 0 */

    while( *str )
        if( !isdigit( *str++ ) )
            return 0;

    return 1;
}

int main( void )
{
    printf( "%d\n", isDigit( "1234567890" ) );
    printf( "%d\n", isDigit( " 123" ) );
    printf( "%d\n", isDigit( "987 " ) );
    printf( "%d\n", isDigit( "1234aeiou" ) );
    printf( "%d\n", isDigit( "  ABC1234567 " ) );
    printf( "%d\n", isDigit( "" ) );
    printf( "%d\n", isDigit( NULL ) );
    return 0;
}

Saída:
1
0
0
0
0
0
0

Caso você queira ignorar os espaços em branco contidos antes e/ou depois dos digitos, você pode combinar as funções isdigit() e isblank():
#include <ctype.h>
#include <stdio.h>

int isDigit( const char * str )
{
    int ret = 0;

    if(!str) return 0;
    if(!(*str)) return 0;

    while( isblank( *str ) )
        str++;

    while( *str )
    {
        if( isblank( *str ) )
            return ret;

        if( !isdigit( *str ) )
            return 0;

        ret = 1;

        str++;
    }

    return ret;
}

int main( void )
{
    printf( "%d\n", isDigit( "1234567890" ) );
    printf( "%d\n", isDigit( " 123" ) );
    printf( "%d\n", isDigit( "987 " ) );
    printf( "%d\n", isDigit( " 567 " ) );
    printf( "%d\n", isDigit( "0 1 2 3 4 5 6 7 8 9 0" ) );
    printf( "%d\n", isDigit( " 0 1 2 3 4 5 6 7 8 9 0 " ) );
    printf( "%d\n", isDigit( "1234aeiou" ) );
    printf( "%d\n", isDigit( "  ABC1234567 " ) );
    printf( "%d\n", isDigit( "" ) );
    printf( "%d\n", isDigit( NULL ) );

    return 0;
}

Saída:
1
1
1
1
1
1
0
0
0
0

Comment: como uso o atoi para passar de string para inteiros, a função original isDigit diz que NULL é = a 0. o que para o meu programa infelizmente não me é util
Comment: A função `atoi()` não detecta erros e retorna `0` sempre que falha! Se você passar um valor `NULL` para `atoi()`, ele se comporta de maneira **indefinida**, provavelmente acasionando em uma desastrosa falha de segmentação!
Comment: Se o seu intento é fazer com que a função `isDigit()` proposto na minha resposta retorne algo diferente de `0` caso a entrada seja `NULL`, basta alterar a linha `if(!str) return 0;`. Veja os comentários no código.
Comment: `isDigit("0 1 2 3 4 5");` retornaria 1
Comment: @MarceloUchimura: ops! Resolvido!
Comment: `isDigit("987 ");` não retorna 1.
Comment: @MarceloUchimura: ufff, agora sim está resolvido!
Answer: int isDigit(char *string)
{
    char *p;
    int firstDigit = 0; // A princípio, nenhum dígito foi encontrado.
    int lastDigit = 0;  // A princípio, nenhum dígito foi encontrado.
    int result = 1;     // A princípio, considera-se verdadeiro, que é digito.

    p = string;

    while (*p)
    {
        if (*p >= '0' && *p <= '9')
        {
            ++p;
            firstDigit = 1;
        }
        else if (*p == ' ' && !firstDigit)
        {
            ++p;
        }
        else if (*p == ' ' && firstDigit && !lastDigit)
        {
            lastDigit = 1;
            ++p;
        }
        else if (*p == ' ' && lastDigit)
        {
            ++p;
        }
        else
        {
            result = 0;
            break;
        }
    }

    return firstDigit && result;
}

Uso:
for (i = 0; i < 20; i++)
{
    if (!isDigit(dados[3][i]))
    {
        return 0;
    }
}
return 1;

Comment: Funcionou perfeitamente! Se encontrar algum erro peço um esclarecimento, mas tem sido uma grande ajuda neste projeto!
Comment: Marcelo como passaria o ponteiro da string dados[3] por exemplo?
Comment: Marcelo para as linhas de visitantes fiz a seguinte função: validaçãoVisitante, editei no código em cima, agora já não me está a guardar nenhum visitante, o que estou a fazer mal?
Comment: Para saber se é um registro de visitante, não basta comparar `dados[1]` com `" Visitante "`?
Comment: Sim essa parte já está, mas temos várias validações para fazer, são considerados dados inválidos os seguintes:
 Linhas com informação insuficiente.
 Linhas com informação em excesso.
 Linhas com dados de tipos inválidos.
 Linhas com pessoas cuja representação seja inválida.
 Não se sabe quantas entradas existem no ficheiro.
 Não pode existir mais de uma entrada por pessoa.
 O visitante não pode visitar um serviço cujo funcionário ainda não entrou.
As pessoas, sejam elas visitantes ou funcionários, com o número 5 e/ou 10 não podem entrar
Comment: Falta apenas fazer a validação se o ID é igual ou nao
Comment: Comentei na tua pergunta, vê lá.
Answer: #include <stdio.h>
#include <string.h>
int verifica(char *nome);

int main(int argc, char** argv)
{
  char nomes[4][100];
  int tam, resultado;
  for(int i = 0; i < 4; i++)
  {
    scanf("%s", nomes[i]);
  }
  for(int i = 0; i < 4; i++)
  {
     tam = strlen(nomes[i]);
     resultado = verifica(nomes[i]);
     if(resultado == tam) //se o tamanho for igual o ao que função retornar ele só contem numeros
     {
        printf("%s\n", nomes[i]);
     }
  }
   return 0;
}

int verifica(char *nome)
{
  int tam = strlen(nome), cont = 0;
  for(int i = 0; i < tam; i++)
  {
     if(nome[i] >= '0' && nome[i] <= '9') // se ele for numero, o contador e incrementado
     {
        cont++;
     }
  }
  return cont;
}


Setting up different static error pages in IIS for different domains

Question: I have got a single IIS website that will host multiple sites (using a CMS).
Each site has its own domain and will have its own theme, so I want the error pages (404 and 500) to be specific to each site as well.
Normally I would set up the error pages using the httpErrors section in the web.config, but I think that only works for a single set of error pages?
The idea I had in my head was to use the URL Rewrite module to rewrite the static file URL to my site-specific file, but that doesn't seem to work:
<httpErrors errorMode="Custom" existingResponse="Replace">
  <remove statusCode="404" />
  <error statusCode="404" path="/404.html" responseMode="ExecuteURL" />
  <remove statusCode="500" />
  <error statusCode="500" path="/500.html" responseMode="ExecuteURL" />
</httpErrors>

And the rewrite rules:
<rule name="Rewrite Error Pages - Site 1" enabled="true" stopProcessing="true">
  <match url="^(\d{3}).html$" />
  <conditions logicalGrouping="MatchAny">
      <add input="{HTTP_HOST}" pattern="^mysite1.com$" />
  </conditions>
  <action type="Rewrite" url="{R:1}-mysite1.html" />
</rule>
<rule name="Rewrite Error Pages - Site 2" enabled="true" stopProcessing="true">
  <match url="^(\d{3}).html$" />
  <conditions logicalGrouping="MatchAny">
      <add input="{HTTP_HOST}" pattern="^mysite2.com$" />
  </conditions>
  <action type="Rewrite" url="{R:1}-mysite2.html" />
</rule>

So I have a few static HTML files for each site as well:

404-mysite1.html
500-mysite1.html
404-mysite2.html
500-mysite2.html

The rewrite rules work fine when I go to http://mysite1.com/404.html for example, as it will rewrite it correctly and return the content of 404-site1.html.
But when I go to a non-existing URL (e.g. http://mysite1.com/foo) it will return a blank page. I can see in the request trace (enabled through Failed Request Tracing in IIS) that it correctly tries to request /404.html (as is in my httpErrors section), but it won't then rewrite it to /404-site1.html.
Does anyone know if this is even possible? Or are there other ways to set up static HTML error pages for different domains in the same IIS site?
Answer: In the end I figured it's not possible using URL Rewrite rules, so am now using a simple .aspx page that will check the host name and render the correct error page content.
So I removed the URL Rewrite rules mentioned in the question, and change the httpErrors to this:
<httpErrors errorMode="Custom" existingResponse="Replace">
  <remove statusCode="404" />
  <error statusCode="404" path="/404.aspx" responseMode="ExecuteURL" />
  <remove statusCode="500" />
  <error statusCode="500" path="/500.aspx" responseMode="ExecuteURL" />
</httpErrors>

And in the 404.aspx file I do the following:
<%@ page trace="false" validateRequest="false" %>

<%-- set correct site name based on request domain --%>
<% string siteName = ""; %>
<% string hostName = Request.Url.Host; %>

<% if (hostName == "mysite1.com") { siteName = "mysite1"; } %>
<% if (hostName == "mysite2.com") { siteName = "mysite2"; } %>

<%-- return file content with a 404 status code --%>
<% Response.StatusCode = 404; %>
<% if (!string.IsNullOrEmpty(siteName)) { Response.WriteFile("404-" + siteName + ".html"); } %>

This seems to work fine for what I want it to do.


Is a forward pass measured relative to the passer or the pitch?

Question: In Rugby, if the ball carrier is running at high speed, and then passes the ball to a player behind them, the ball might still actually travel forwards due to the the momentum of the passer, but end up behind them, and the recipient still be behind them when they receive it.
If this happens, is this considered a forward pass? i.e. does the referee look at the flight of the ball relative to the pitch, or relative to the player who passed the ball?
And if it's the passer, what if the passer stopped running when they released the ball? Now it would appear to move forward relative to them, and appear as a forward pass even though the pass would be the exact same if they had continued running.
Answer: For Union, "Forward" is defined in the definitions of the Laws:

Forward: Towards the opposition's dead-ball line.

The relevant law is then 11.7 Throw Forward:

A player must not intentionally throw or pass the ball forward. Sanction: Penalty.

From this, it is clear that any pass which is towards the opposition's dead ball line is a forward pass, so "relative to the pitch" in your terminology.
League simply defines "Forward Pass" in the glossary:

Forward Pass is a throw towards the opponent's dead ball line.

Again, note no reference to the player, it is all to the pitch.
Comment: The definitions section of the laws of the game of rugby union state.  Throw forward: When a player throws or passes the ball forward i.e. if the arms of the player passing the ball move forward.  See https://www.world.rugby/the-game/laws/definitions#laws_let20
Answer: NB: This answer is based around Rugby Union

While it seems pretty clear-cut in the Laws, as pointed out in Philips's anwser, there is actually some contention around this - with referees appearing to make the decision based on whether the ball leaves the passer's hands backwards.
This is because, as you pointed out in the question, the pass could be made backwards relative to the passer and receiver, but travel forwards because of player momentum.
Additionally, in a seeming contradiction of their own Laws, World Rugby have a video on their official YouTube channel explaining this:

This video is admittedly a little old (from 2011), however in an article on World Rugby's website, published before the Quarter Finals of the 2019 World Cup, referee Wayne Barnes says:

[...] the forward pass is the most straightforward to explain. As English referee Wayne Barnes, [...] put it: "It's not about the direction that the ball eventually ends up, it's about the direction it's travelling in as it leaves the hands. So, when a TMO comes in, the referees are looking at the hands and the ball."
Comment: As mentioned in my comment below the definitions now state Throw forward: When a player throws or passes the ball forward i.e. if the arms of the player passing the ball move forward.  So it's the direction of travel of the hand.


Rhythm notation for lyrics?

Question: Are there any good notations for rhythm in song lyrics? Usually when I'm writing lyrics with pen and paper, I underline emphasis, which works for rap, but probably misses a lot of nuance for sung lyrics. Are there any good methods for notating emphasis, speed, and rhythm in general?
Pen-and-paper or software based answers are all acceptable. I'd be especially interested in any ASCII-based solutions.
Comment: Does it make sense to write down the rhythm if you don't write down the melody? Someone who knows the melody will know the rhythm, and someone who doesn't won't be able to sing it anyway...
Comment: In hip-hop, melody can be irrelevant. Also, it can be useful for other melodic styles if the melody hasn't been decided on yet, I think.
Comment: I'm thinking rhythm slashes and/or "X" note heads on a standard score, with the latter being the way I've seen unpitched vocals notated many times. When you're writing, you could just put a line under or above the lyrics and put rhythm slashes on the line.
Comment: Use normal notation. It's exactly what it's designed for. End of.
Answer: A very common way to notate lyrics where pitch doesn't matter is to just use a single line staff to note the rhythmic hits. In this system everything is the same except there are not distinct pitches per note.
Here's an example of this system used to notate The Aggressive Bee:
]1
Comment: Looks like some drum notation - clear, precise, and easily legible.
Comment: An alternative that I've seen omits the (solid) noteheads and the staff line, so your notes look like |. |' | | and so on.  Of course, minims and semibreves (half/whole notes) need the noteheads to differentiate them from the others.
Answer: I've certainly seen some notation being used for chords that can be used for lyrics, too. Basically, you add the bars, and then you divide each bar into an equal number of intervals, usually 2, 4 or 8. If then a syllable is longer that this basic unit, you add -- after it.
To give an example:
| Yes-ter-day -- | -- | -- -- All my | trou-bles seemed so | far -- a-way | --
| -- -- Now it | looks as though they're | here -- to stay, | -- oh
| I -- be-lieve | -- in | yes- -- ter-day. | -- |

Note that for convenience, we divide each bar of the song in two bars (i.e., 2/4 rather than 4/4). The syncopation, if occurs a lot, can be marked in another way, too:
| Yes-ter-day -- | -- | -- -- All my | trou-bles seemed so | far a- <| way
| -- -- Now it | looks as though they're | here to <| stay, oh
| I be- <| lieve in | yes-ter- <| day. |

It's not particularly useful or visible here since the song doesn't really have syncopation, but I hope the idea is clear.
Comment: this is kind of like guitar tab
Comment: This is quite good, because it's really easy to scribble down quickly with pen and paper. It would be good to have an additional method of being able to notate syllables that are shorter than beats.
Answer: Personally, I prefer as simple notation as possible. Every line will start on the first beat by default. I separate anacrusis (pickup) with the character | (example, line 1 & 3). For rests (usually representing 1/4) I use the character -. Rests can be used to indicate more accurately when the line starts (example, line 3). If needed, you can emphasize the beats by underlining or bolding the right syllables but, personally, I'm too lazy to do this.
Oh | yeah, well so it goes
Yeah so it goes
- - - Oh | - that sweet heirloom
Them abbey stones

If you're presenting your music to other musicians you should stick with some standard notation or make sure they understand what your notes mean. I wholeheartedly support using custom notations so that the standard notation doesn't shape your work or lessen your creativity. Every now and then, it's wise to take a step back and think whether your notation is meaningful to yourself.
Comment: @naught101 Wow I haven't run into this before! You can use bolding and underlining for that if it feels necessary. Also, wrapping text in different braces (`(, {, [, <`) might do the trick. Just keep to your own notation. I think it's worth noting that one line notation should always be preferred because then it doesn't rely on the character spacing of the font.
Comment: This is cool, but how would you capture faster rhythms, e.g. syllables as a triplet or something?
Comment: Agreed for computer-based methods. And nice solutions. I think multi-line, or at least annotated-line methods are quite nice for pen-and-paper though.
Answer: The standard method for classical Western music is, to integrate it into a score notation, as can be seen here in Lilypond notation manual. If the melody is inexistent or can be assumed to be known, the single pitch or drum-like notation suggested in other answers will do.
Actually this does not cover which syllables are to be stressed (one can put an accent on the note, but it remains unclear, whether it also applies to the lyrics), but there are good reasons for it:

Singers prefer to have their degree of freedom
If the text is carefully adjusted to the melody (or vice versa), it is clear anyway

If you want it nevertheless, proven methods are either underlining or uppercasing the stressed syllable.

Rhythm notation for lyrics?


Alternative to deprecated onExceededDatabaseQuota()

Question: My app is executing some Javascript code in a WebView which creates a database. In some situations when the database grows past a certain size I am getting this Javascript error:

there was not enough remaining storage space, or the storage quota was reached and the user declined to allow more space

The historical workaround for this has been to override WebChromeClient.onExceededDatabaseQuota() which allows the native app code to increase the quota as needed. This has been deprecated since API level 19, though, and is no longer called. The Javadoc says:

WebView now uses the HTML5 / JavaScript Quota Management API.

Is this new Quota Management API accessible to my Android app code? Is there an alternative way for me to tell my WebView to increase the storage quota?
Comment: As per android document `WebView now uses the HTML5 / JavaScript Quota Management API`. For Quota Management API check https://developers.google.com/web/updates/2011/11/Quota-Management-API-Fast-Facts?hl=en
Answer: It turned out there was actually insufficient space left on the emulator's internal storage. After I edited the AVD to give it more space, the error disappeared.


Popup map block

Question: I'm trying to get a map to appear in a modal but haven't worked out a solution yet.
I have a list of items and I would like a map with their locations to appear when I click a 'view map' button.
I'm using Leaflet maps and Zurb Foundation, although I'm not sure if this affects the solution.
I can get this to sort of work if I include the map block in a the hidden modal div, but I would really only like the map to be loaded on request.
(Also there seem to be map resizing issues when it is placed in a modal)
Another approach I tried was to register a path (of a views page) with hook_menu and then load this URL into the modal. This worked BUT included the site header & footer in the modal.
So I guess one solution is how to have just the unthemed views content attached to a path.
Any ideas?
Many thanks,
Chris
Comment: This question appears to be off-topic because it is about code you wrote, for which you want to write better code, or you want to understand why it doesn't work, but you didn't show the code you are using, or the part of the code that is relevant for the question. See [Help Center](http://drupal.stackexchange.com/help/on-topic).
Comment: @Mołot No code, this is all through Drupal UI using off the shelf modules. I am just trying to find an approach to get a views created map to load into a modal when a button is pressed. So, please can someone offer some help rather than just trying to pick holes in the question...
Comment: possible duplicate of [Drupal 7 - How to get AJAX response displayed in a ctools modal?](http://drupal.stackexchange.com/questions/40150/drupal-7-how-to-get-ajax-response-displayed-in-a-ctools-modal)
Comment: @FelixEve not at all! Firstly, I don't want to use ctools, although if that is a possible solution I'll definitely consider it.
Secondly, it isn't really an issue with getting an AJAX response to work - it's using an ajax load.
My main problem is getting the content of a block (or just a map) to load into a modal (which at this point is not cTools)
Comment: We are not "picking holes". We are trying to understand what you actually did and what you really want, to give you answer you may feasibly use. We need to know what was the results of your [search, and research](http://drupal.stackexchange.com/help/how-to-ask) to avoid answering with things you already fount not working, for example...
Comment: @Mołot I've clarified the question as much as I think I can within reason
Comment: @ChrisLeather : are you familiar with the https://www.drupal.org/project/ip_geoloc module? I wonder if that would help you somehow ...
Comment: @ChrisLeather http://drupal.stackexchange.com/questions/138063/location-map-in-colorbox
Answer: I know this post is old, but for anyone else looking for a quick solution and working in Drupal 8...
Try creating a View Page with the map and markers. Then link to that page with a Modal Link, like so...
View Map

If contextual filters are needed within the view, just add that contextual filter to the href, just as you would that page.
View Map

Popup map block


partial eta squared

Question: Would it please be possible to help me with a statistics query. I have asked for the partial eta squared on the output of a one-way within subjects ANOVA from SPSS and it has given me the value .137. According to Cohen (1992) the classifications for effect sizes should be; r=.10 small, r=.30 medium and r=.50 large (I am unsure whether these classifications can be attributed to partial eta squared?)
I appreciate this is a basic question but please may I clarify my value falls in the small effect category? Additionally, does this suggest that the proportion of variance explained by the IV on the DV and not explained by other variables in the analysis is 13.7%?
Any help would be greatly appreciated!! Thank you!
Comment: Partial Eta-squared of an effect is SSeffect/(SSeffect+SSerror) and, for quantitative IV (a covariate), equals partial r-squared.
Comment: This might help you:

http://stats.stackexchange.com/questions/15958/how-to-interpret-and-report-eta-squared-partial-eta-squared-in-statistically
Comment: Cohen never intended his proposals for guidelines for quantifying effect sizes to be used as definite categories.
Answer: According to Richardson (2011), Cohen (1969, pp.278-280) provides partial eta squared values of .0099, .0588, and .1379 as benchmarks for small, medium, and large effect sizes, respectively.
Literature:
Richardson, J.T.E. (2011). Eta squared and partial eta squared as measurements of effect size in educational research. Educational Research Review, 6, 135-147.
Cohen, J. (1969). Statistical power analysis for the behavioural sciences. New York: Academic Press.
Comment: Consider the whole section from Richardson (2011) you refer to. You get wrong exactly what they're talking about there in the very next sentence.
Comment: "Further confusion surrounds the benchmarks suggested by Cohen (1969, pp. 278–280) to define small, medium, and large effects. As was explained earlier, these were based upon values of f that correspond to values of partial $\eta^2$ of .0099, .0588, and .1379, respectively. ...
Comment: .. Nowadays, researchers often quote the latter values without explaining their derivation from values of f, which suggests a spurious degree of precision and makes them sound even more arbitrary than Cohen had originally intended. They are quoted as benchmark values for both partial $\eta^2$ and classical $\eta^2$, despite the fact that the former is typically greater than the latter."
(p. 142)
Comment: I disagree: see the last sentence from the paragraph you cited above, as well as Table 3 in the paper of Richardson.
Answer: I think these categorical values are depending on the research field, and 0.01, 0.06, and 0.14 as the small, medium, and large may be useful for education studies but for biological research such as poultry nutrition. Based on my experience, those values for poultry nutrition studies could be defined as 0.1, 0.5, and 0.8, similar to Cohen's category.

partial eta squared


JQuery Required TextBox Validation and Error Message in MVC

Question: I apologize in advance if this seems like a stupid question but after doing quite a bit of searching around I either can't put the right pieces together or simply haven't found the right answer.  Anyways, I've got this model:
public class Resort
{
    public int ID { get; set; }
    public String Name { get; set; }
    public int BlackDiamond { get; set; }
    public int BlueSquare { get; set; }
    public int GreenCircle { get; set; }
    public int TerrainPark { get; set; }
}

And I've got a view that creates TextBoxes as the input for each of those variables.  What I need to do is set up some JQuery validation to ensure that each TextBox has a value in it, and more specifically that the TextBoxes for the int has numbers in it.
After doing a little research I'm just not sure how I can even go about setting up the script for the view or if I should rely on Data Annotations in the model??  Any help is appreciated even if it is simply to point me in the right direction of research, I am here to learn.  Thank you.
Answer: If it's a required field, add the RequiredAttribute to the field:
[Required]
public int BlackDiamond { get; set; }

If you also want a custom message, add it to the attribute:
[Required(ErrorMessage="Please enter a number")]
public int BlackDiamond { get; set; }

If you want built-in jQuery validation, make sure you use the strongly-typed helper:
@Html.TextBoxFor(m => m.BlackDiamond) // you can also use EditorFor

You will need to also include script references to the UnobtrusiveValidation and jQuery Validate plugins to get the automatic validation.
Just FYI, this seems like a good place to start, if you are unfamiliar with validation in MVC: http://msdn.microsoft.com/en-us/VS2010TrainingCourse_ASPNETMVC3FormsandValidation
EDIT: Just to make this answer a bit more complete, as noted in the comments: to see the error messages associated with each control, you need to add the validation helpers: @Html.ValidationMessageFor(m => m.BlackDiamond)
Comment: These ones right:
Comment: So this does work, it stops me from being able to submit anything that is empty but my ErrorMessages don't show up at all...  Is there supposed to be anything else in the View that forces the ErrorMessages through?
Comment: @Jared To see the error messages, you need to add the validation helpers: `@Html.ValidationMessageFor(m => m.BlackDiamond)`, for instance.
Comment: Ahhh, I was thinking that might be the problem.  Thank you again!


Custom font not showing up in SwiftUI

Question: I've followed all the steps in Apple's tutorial to add custom fonts:
I've added the font files under a folder called fonts:

I've registered the fonts by adding them to Info.plist:

However Xcode cannot use them/find them:
Button(action: {}){
                Text("View profile")
                    .font(Font.custom("seravekBold.tff", size: 20.0))

I've also tried testing this method:
for family in UIFont.familyNames.sorted() {
    let names = UIFont.fontNames(forFamilyName: family)
    print("Family: \(family) Font names: \(names)")
}

in my AppDelegate to print out all the UI fonts and the fonts I added (seravek) do not show up.
Any idea what the problem is?
Comment: I've added the same font that you are using and used a custom font from a previous project. The other font is working but the seravek one is not. I'm not sure why but it seems like the font you want to use is not supported by iOS or something like that.
Comment: Check the Build Phases in the Copy Bundle Resources if it's in that list.

And as far as I know, there is no need to add the .tff in the Font.custom("").
Comment: Not sure what `Build Phases in the Copy Bundle Resources` is? And I tested without the `.ttf` and still doesn't work unfortunately
Comment: I've made a preview on how to find it. [here](https://imgur.com/a/XBXUPSN)
Comment: Thanks it is in that list: https://i.imgur.com/XXtUVVb.png But just noticed that the folder is not actually inside my project directory - it's on my desktop. Could this be the problem?
Comment: Thanks for testing. Very weird - i'll have to use another font.
Answer: Here is my steps (demo prepared & tested with Xcode 12 / iOS 14):

taken font for demo from  http://fdempreendimentos.com.br/assets/fonts/Seravek-Bold.ttf

drag & drop into project & mark checkbox to include to app target

Registered font with Info.plist

Demo content view

struct TestSeravekFont: View {
    var body: some View {
        Text("Hello, World! Specific Qij")
            .font(Font.custom("Seravek Bold", size: 40))
    }
}

Output

Here is how font looks in Font Manager, so we see that this is it. Done.
Answer: In my case, after make empty .xib file and put some labels with custom font,
SwiftUI's .custom(font_name) and UIFont.familyNames works well.
I thinks that there are some missing bundle for custom fonts with out UIKit Resources.
At iOS 14.5, Xcode 12.5.
Answer: Apply bellow process

Drag and drop your font file, must include copy item if needed and target project.

Register your font in info.plist(must include extension .ttf or .otf)

Verify the Font Names: It's important to verify the exact font names that SwiftUI expects. Open the custom font files in Font Book (on macOS) or Font Viewer (on Windows), and make a note of the PostScript name or the font family name.

Custom font not showing up in SwiftUI


How can I calculate this integral? $\int_{-\infty}^{\infty} \Phi (a + bX) \phi (c + eX) dx$

Question: Suppose we have the density and distribution of the standard normal. How can one calculate the integral:
$\int_{-\infty}^{\infty} \Phi (a + bX) \phi (c + eX) dx$
Note this is not included in the Wikipedia list of integrals of Gaussian functions.
Further, this is not the same as How can I calculate $\int^{\infty}_{-\infty}\Phi\left(\frac{w-a}{b}\right)\phi(w)\,\mathrm dw$ because that solution only works for a standard normal second term, i.e. $\phi (X)$ whereas this problem includes a coefficient and additional term. One cannot put into the same form as that case because $c$ and $e$ cannot be brought out of the normal density due to their involvement in the exponential component.
Comment: Not sure if this helps, but we know that

$$\int_{-\infty}^{\infty}\Phi(a+bX) \phi( X ) dX=\Phi\left(\frac{a}{\sqrt{1+b^2}}\right)$$
Comment: @Glen_b In which case it really ought to be migrated to [math.se], because it's about changing variables in integration. :-)
Comment: @ZERO Thanks, I am familiar with that integral and have seen short proofs on here, but unfortunately dealing with the second linear term is still unclear.
Comment: Are you sure it has an analytical closed form?
Comment: It was suggested to me that it does, but I am not sure.
Comment: I think that if the OP doesn't see how the other one answers this one (as was already established), then it's not really a dupe, since the question needs as an answer the explanation that connects one to the other.
Comment: @whuber I am in two minds about that; there's an extent to which the context means it's on topic (otherwise the original arguably should be migrated there as well; it's simply an integration problem). And on a similar basis ("it's really a mathematics question - it's just integration/differentiation/matrix algebra/change of variable...") a lot of the questions here would migrate. There's not a very clear dividing line about when it really counts as sufficiently statistical in context to count here. What I think just tips it over here is that the answer on which it relies is here.
Comment: Question: does this integral perchance calculate the probability that a random variable that obeys one Gaussian distribution takes on a value that is less than a second random variable that obeys another (different) Gaussian?
Answer: But if you know the form discussed in comments
$$\int_{-\infty}^{\infty}\Phi(a+bx) \phi( x ) dx=\Phi\left(\frac{a}{\sqrt{1+b^2}}\right)$$
it's quite straightforward!
Just do the substitution $Z = c+eX$  (don't forget the Jacobian), and use the fact there that you already know (but in $z$ rather than $x$).


Writing Permission to linux apache on windows folder

Question: We have a ubuntu 10.04 with apache 2 and samba. We set apache2 /var/www/ to be on a Windows Directory over the network using samba. It's all working but I can't seem to find a way to give writing permission on this directory. I've tried both on linux and windows. Any tips?
Answer: What version of Windows are you using and have you looked at NTLM as the cause?
http://technet.microsoft.com/en-us/library/cc960646.aspx
I've had issues on Windows Vista and 7 when trying to authenticate with Samba, I had to change the windows registry key "HKEY_LOCAL_MACHINE\System\CurrentControlSet\Control\Lsa\LMCompatibilityLevel" to "1".
What do your logs tell you?
Comment: It's a Windows Server 2008. I don't really know what a NTLM is. But I can see the directory, it's readable but i need to change the permission to writeable.
Comment: In the samba configuration file for that path you need to add writable = yes
Answer: Have you been running SWAT already? It's a graphical front-end for Samba, using a web interface so it shows up on http:localhost/901 on the Ubuntu-machine.
Manually editing samba-configuration files and setting permissions may be daunting, but with SWAT it's really easy.
https://help.ubuntu.com/community/Swat


Android align textview and edittext

Question: In the following xml file.i am trying to align the contents.i.e, first textview followed by the edittext and so on in the next line.But tight now the text is imposed one on another how to resolve this issue.
 <?xml version="1.0" encoding="utf-8"?>
  <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
      android:layout_width="fill_parent"
      android:layout_height="fill_parent"
      android:orientation="vertical" >

      <RelativeLayout
          android:layout_width="match_parent"
          android:layout_height="wrap_content"
          android:layout_weight="0.70" >

          <TextView
              android:id="@+id/hostname"
              android:layout_width="wrap_content"
              android:layout_height="wrap_content"
              android:layout_alignBaseline="@+id/ip"
              android:layout_alignParentLeft="true"
              android:text="hostname" />

          <EditText
              android:id="@+id/ip"
              android:layout_width="wrap_content"
              android:layout_height="wrap_content"
              android:layout_alignParentLeft="true"
              android:layout_alignParentTop="true"
              android:layout_marginLeft="39dp"
              android:ems="10"
              android:inputType="textEmailAddress" >

          </EditText>

   <TextView
              android:id="@+id/username"
              android:layout_width="wrap_content"
              android:layout_height="wrap_content"
              android:layout_alignBaseline="@+id/ip"
              android:layout_alignBottom="@+id/ip"
              android:layout_alignParentLeft="true"
              android:text="Hostname" />
          <EditText
              android:id="@+id/username"
              android:layout_width="wrap_content"
              android:layout_height="wrap_content"
              android:layout_alignLeft="@+id/editText1"
              android:layout_below="@+id/ip"
              android:layout_marginLeft="45dp"
              android:layout_marginTop="42dp"
              android:ems="10" />

           <TextView
              android:id="@+id/password"
              android:layout_width="wrap_content"
              android:layout_height="wrap_content"
              android:layout_alignBaseline="@+id/hostname"
              android:layout_alignBottom="@+id/username"
              android:layout_alignParentLeft="true"
              android:text="Password" />
          <EditText
              android:id="@+id/password"
              android:layout_width="wrap_content"
              android:layout_height="wrap_content"
              android:layout_below="@+id/password"
              android:layout_centerHorizontal="true"
              android:layout_marginTop="47dp"
              android:ems="10"
              android:inputType="textPassword" />

      </RelativeLayout>

  </LinearLayout>

Comment: Dude.. Instead of RelativeLayout use TableLayout... and put TextView and EditText pair in each row.. Simple..:-)
Comment: Your trying to show text on the edit text right?
Answer: Another way to do it, that worked well for me, is, in your xml file, to add a parent <LinearLayout> that specifies android:orientation="horizontal" to encompass your TextView and EditText.
This parent LinearLayout has to be inside your very first LinearLayout that has to specify a android:orientation="vertical" :

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:paddingLeft="15sp"
    android:paddingRight="15sp"
    android:paddingTop="15sp"
    android:paddingBottom="15sp" >

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:paddingTop="15sp">
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Poids :"
            android:textSize="15sp"
            android:textStyle="bold" />
        <EditText
            android:id="@+id/btn_poids"
            android:inputType="numberDecimal"
            android:hint="Entrez votre poids"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" />
    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:paddingTop="15sp">
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Taille :"
            android:textSize="15sp"
            android:textStyle="bold" />
        <EditText
            android:id="@+id/btn_poids"
            android:inputType="numberDecimal"
            android:hint="Entrez votre taille"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" />
    </LinearLayout>

</LinearLayout>

Here's the result (the warning signs are because of the hardcoded strings for the hints and text...) :
Comment: The above code is good if `TextView`'s  length are equal, if not they won't be vertically aligned
Answer: I had the same issue trying to target android 4.X. I solved it by using android:gravity="center_vertical"
<LinearLayout
        android:orientation="horizontal"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <TextView
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:ems="10"
            android:id="@+id/itemNameLabel"
            android:text="@string/entry_item_label"
            android:textSize="@dimen/baseTextSize"
            android:layout_weight=".15"
            android:gravity="center_vertical" />

        <EditText
            android:layout_width="0dp"
            android:layout_weight=".85"
            android:layout_height="wrap_content"
            android:inputType="textPersonName"
            android:ems="10"
            android:id="@+id/itemName"
            android:textSize="@dimen/baseTextSize"
            android:hint="Food, Video Game, etc..." />
    </LinearLayout>

Comment: Got the hint to handle my own case here
Answer: Your using the same id for multiple views, and then multiple views are using layout_below using the same id, that's why there are some that are on top of each other. Make them unique ids. Also the id you are using for some align_left arnt even there, like editText1 for example.
Short answer: use unique ids for each view and check what your referencing for alignments and positioning etc.
Your next problem is that you shouldn't try and layer your views like this, there is something called android:hint="hint text" this is what I think you want. The text will hide once the user starts to input text, but other then that its like there is a text view on top of it...
Answer: None of these solved my problem. What I do is I add
android:textAlignment="center" to the textView in XML. the edit text is centered by default.
Both the TextView and the EditText are in a horizontal LinearLayout.
Answer: Add this attribute to EditText:
android:layout_below="@+id/hostname"

Answer: The Best way is remove all the textview and set andoid:hint to edit text .
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <EditText
        android:id="@+id/ip"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:ems="10"
        android:hint="HostName"
        android:inputType="textEmailAddress" >
    </EditText>

    <EditText
        android:id="@+id/username"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:ems="10"
        android:hint="HostName" />

    <EditText
        android:id="@+id/password"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:ems="10"
        android:hint="Password"
        android:inputType="textPassword" />

</LinearLayout>

Comment: This doesn't answer the question.  What if one wants to show pre-filled data in some of the EditTexts?  The hint would not be useful to describe what the user is seeing in that case.

Android align textview and edittext


Rendering fields with node display settings

Question: I would like to take advantage of the settings I can set under admin/structure/types/manage/node_type/display when i render my custom fields in node--node_type.tpl.php but using the following code I just get some sort of default display setting:
<?php
  print render( field_view_field('node', $node, 'field_date', array('label' => 'hidden')) );
?>

This prints my date in the long format, but under /display I already set it to medium.
Also I have already set the label as hidden under the display settings.
How can I use those settings and only override them if I want to? Or is field_view_field() not the right function?
Answer: The content array should already contain an element for each field with the display settings applied. You can just print that directly:
<?php print render($content['field_date']); ?>

Comment: That's the one. Fantastic. Thanks for the quick answer.


Hermite problem formula

Question:
Consider the Hermite problem $$p^{(r)}(x_i)=y_i^{(r)},\ i=1,2 ;\
 r=0,1,2$$ with $p(x)$ a polynomial of degree $\leq 5$.
a - Give a Lagrange type of formula for $p(x)$.
b - Give a Newton divided difference formula and also derive an error formula.

Attempt at a solution:
What I know up to this point is for the basis functions $l(x_2)=l'(x_2)=l''(x_2)=0$, I will then have to use $l(x)=(x-x_2)^3g(x)$, where $g(x)$ is of degree $\leq 2$, then I will have to find $g(x)$.
Answer: Your notation is confusing to me, so I used something that makes more sense to me, please forgive that.
The Lagrange Polynomial is given by:
$\tag 1 \displaystyle P(x) = f(x_0)L_{n,0}(x) + \cdots + f(x_n)L_{n,n}(x) = \sum_{k=0}^{n} f(x_k)L_{n,k}(x), \text{where}$
$\tag 2 \displaystyle L_{n,k}(x) = \frac{(x-x_0)(x-x_1)\cdots (x-x_{k-1})(x-x_{k+1}) \cdots (x-x_n)}{(x_k - x_0)(x_k - x_1) \cdots (x_k-x_{k-1})(x_k-x_{k+1}) \cdots (x_k-x_n)} = \prod_{i=0, i \ne k}^n \frac{(x-x_1)}{(x_k-x_i)}$
for each $k = 0, 1, \cdots, n.$
So, for the three values of $r$, we have:

$\tag 3 \displaystyle L_{2,0}(x) = \frac{(x-x_1)(x-x_2)}{(x_0-x_1)(x_0-x_2)}$ and we can calculate $L_{2,0}'(x)$
$\tag 4 \displaystyle L_{2,1}(x) = \frac{(x-x_0)(x-x_2)}{(x_1-x_0)(x_1-x_2)}$ and we can calculate $L_{2,1}'(x)$
$\tag 5 \displaystyle L_{2,2}(x) = \frac{(x-x_0)(x-x_1)}{(x_2-x_0)(x_2-x_1)}$ and we can calculate $L_{2,2}'(x)$

The Hermite polynomials are given by:
$\tag 6 H_{2n+1}(x) = \sum_{j=0}^{n} f(x_j)H_{n,j}(x) + \sum_{j=0}^{n} f'(x_j) \hat H_{n,j}(x)$, where
$\tag 7 H_{n,j}(x) = [1 - 2(x-x_j)L'_{n,j}(x_j)]L^2_{n,j}(x)$, and
$\tag 8 \hat H_{n,j}(x) = (x - x_j)L^2_{n,j}(x).$
Using all of this information, we can write a Lagrange type formula as (the function-values, $f(x_k)$) below represent the six data points you have, that is, three values each for $f(x_k)$ and $f'(x_k)$:
$\tag 9 \displaystyle H_5(x) = f(x_0)H_{2,0}(x) + f(x_1)H_{2,1}(x) + f(x_2)H_{2,2}(x) + f'(x_0) \hat H_{2,0}(x) + f'(x_1) \hat H_{2,1}(x) + f'(x_2) \hat H_{2,2}(x).$
From the above, you can see that this is a complete description of the Hermite polynomials, however, we needed to determine and evaluate the Lagrange polynomials and their derivatives, which is tedious, even for these small values of $n$.
An alternative method for generating the Hermite approximations is to use the Newton interpolatory divided-difference formula for the Lagrange polynomials at $x_0, x_1, \ldots, x_n:$
$\tag {10} \displaystyle P_n(x) = f[x_0] + \sum_{k=1}^{n} f[x_o, x_1, \ldots, x_k](x-x_0) \cdots (x-x_{k-1})$
We can write out a divided-difference table to find all of the coefficients as (you can fill out the three missing columns):
$$\begin{array}{c|c|c}
\text{z} & \text{f(z)} & \text{1st divided differences} & \text{2nd divided differences}\\
\hline
\\z_0 = x_0 & f[z_0] = f(x_0) &   &
\\  &  & f[z_0, z_1] = f'(x_0) &
\\z_1 = x_0 & f[z_1] = f(x_0) &  & f[z_0, z_1, z_2] = \frac{f[z_1, z_2]-f[z_0,z_1]}{z_2-z_0}
\\ &  & f[z_1, z_2] = \frac{f[z_2]-f[z_1]}{z_2-z_1} &
\\z_2 = x_1 & f[z_2] = f(x_1) &  & f[z_1, z_2, z_3] = \frac{f[z_2, z_3]-f[z_1,z_2]}{z_3-z_1}
\\ &  & f[z_2, z_3] = f'(x_1) &
\\z_3 = x_1 & f[z_3] = f(x_1) &  & f[z_2, z_3, z_4] = \frac{f[z_3, z_4]-f[z_2,z_3]}{z_4-z_2}
\\ &  & f[z_3, z_4] = \frac{f[z_4]-f[z_3]}{z_4-z_3} &
\\z_4 = x_2 & f[z_4] = f(x_2) &  & f[z_3, z_4, z_5] = \frac{f[z_4, z_5]-f[z_3,z_4]}{z_5-z_3}
\\ &  & f[z_4, z_5] = f'(x_2) &
\\z_5 = x_2 & f[z_5] = f(x_2) &  &
\end{array}$$
We can now form $H_5(x) = P(x)$ using the values in this table with the Newton divided-differences formula.
I'll leave it to you to derive the error term, all you need to do is look at the Lagrange and Newton error term with a slight change.
Hope that all makes sense and too bad we didn't have real data to play with and actually solve.
Comment: @user60514: You are very welcome! Have fun!
Comment: It does, thank you so very much! :)
Comment: Amzoti, for the error I obtained $$f(x)-p_{2n-1}(x)=(x-z_1)...(x-z_{2n})f[z_1,...,z_{2n},x]$$ am I right on this part?
Comment: Wow, you put a lot of "heart and soul" into this!! +1
Answer: I'm wondering, for this Hermite problem it seems that you are given 2 nodes and the polynomial must interpolate through the second derivates.
I could be wrong but wouldn't we need to have a formula that is different than the usual hermite problem with just going through the first derivative?

Hermite problem formula


Calculate variance as $n \to \infty$ using the covariance

Question: Consider $X_1, ..., X_n,...$  independent random variables for which $\text{Var}(X_i) = \sqrt{i}$. Let $Y_i=f(X_i, X_{i+1}), f:R^2\to R$. Show that $cov(Y_i,Y_j)=0$ for $|i-j|>2$ and then show that the variance of $\frac{1}{n}\sum\limits_{i=1}^{n}Y_i$ converges to $0$ as $n\to\infty$.
I have:
$Cov[Y_i,Y_j]=E[Y_i,Y_j]-E[Y_i]E[Y_j]$. As $Y_i$ is a transformation of the random variables $X_i, X_{i+1}$, the covariance can be rewritten as (omitting constants):
$=E[(aX_i+bX_{i+1} ),(cX_j+dX_{j+1} )]-E[(aX_i+bX_{i+1} )]E[cX_j+dX_{j+1}]$.
Take $|i-j|>2$ and use the independence of $X_1,...,X_n$, it follows that the covariance can be rewritten as:
$=E[(aX_i+bX_{i+1})]E[cX_j+dX_{j+1} ]-E[(aX_i+bX_{i+1} )]E[cX_j+dX_{j+1}]\\=E[Y_i]E[Y_j]-E[Y_i]E[Y_j]=0$
I guess this is correct, but I suppose this is not the kind of proof they are asking for. Can anyone give me a hint to give a better proof?
For the second part, I suppose that $\lim_{n \to \infty}\frac{1}{n^2}\sum\limits_{i=1}^{n}Y_i= \lim_{n \to \infty}\frac{1}{n^2}\sum\limits_{i=1}^{n}\sum\limits_{j=1}^{n}Cov[Y_i,Y_j]\neq  \lim_{n \to \infty}\frac{1}{n^2}\sum\limits_{i=1}^{n}\sum\limits_{j=1}^{n}0$, as the second part also assumes the case that $|i-j|\leq2$. Could anyone give me a hint there too?
Answer: Part 1: When $|i -j|\geq 2$ the Random Variables $Y_i,Y_j$ depend on are independent of each other. For example, $$Y_1 = f(X_1, X_2), Y_3 = f(X_3, X_4)$$  This implies that $Y_i$ and $Y_j$ are independent and therefore have no correlation.
Part 2:
\begin{eqnarray*}
    \text{Var}\left(\frac{1}{n}\sum_{i=1}^n Y_i\right) &=& \frac{1}{n^2} \sum_{i=1}^n \sum_{j=1}^n \text{Cov}(Y_i, Y_j) \\
    &=& \frac{1}{n^2} \left(\sum_{i=1}^n \text{Var}(Y_i) + 2\sum_{i=1}^{n-1} \text{Cov}(Y_i, Y_{i+1})\right) \\
    &\leq& \frac{1}{n^2} \left(\sum_{i=1}^n \text{Var}(Y_i) + 2\sum_{i=1}^{n-1} \sqrt{\text{Var}(Y_i)\text{Var}(Y_{i+1}})\right) \\
\end{eqnarray*}
The third line follows because $\text{Cov}(X, Y) \leq \sqrt{\text{Var}(X)\text{Var}(Y)}$.
Comment: I was studying the third line, but I don't understand why that holds. The variance of $X_i=\sqrt{i}$, so how comes that all $Y_i$ are i.d.?
Comment: @Holograph  I did read the question as saying they where identically distributed.  I'll think more on it.
Comment: That was given in the excersise, I should have written that at the start of this question. But then I suppose that inequality still is true as $Cov[X,Y]\leq \sqrt{Var(X)Var(Y)}$, right?
Comment: @Holograph  Yes, that inequality is still true.  Do you know anything about what the function $f$ looks like?  You seemed to think it was affine in your partial solution.  (Feel free to uncheck this as the answer, I did read it incorrectly).
Comment: No, I assumed $f(X_i,X_j)$ should be some combination of $aX_i+c+bX_{i+1}+d$


Uso de string dá erro

Question: No inicio do código eu declaro a variável nome como char e quando tento pegar a variável nome lá em baixo no código dá erro, eu já tentei de várias formas e dessa forma que esta ai em baixo até dá certo, mas as vezes quando aparece a pergunta pro usuário " Deseja continuar ? " e ele responde s (sim), às vezes pula direto pro campo "digite o salario do funcionário:", ou seja. pula a parte em que pergunta o nome do funcionário
int cont, tinss;

char s, resp, nome[50];

float sal, novosala, val;

cont = 1;

do
{
    printf("\n digite o nome do funcionario; ");
    scanf("%s",&nome);
    printf("\n digite o salario do funcionario: ");
    scanf("%f",&sal);

    if(sal <= 500)
        {
            novosala = sal - ((sal / 100) * 8);
            val = (sal / 100) * 8;
            tinss = 8;
        }
    else
    if(sal > 500 &&  sal <= 1000)
        {
            novosala = sal - ((sal / 100) * 10);
            val = (sal / 100) * 10;
            tinss = 10;
        }
    else
    if(sal > 1000)
        {
            novosala = sal - ((sal / 100) * 12);
            val = (sal / 100) * 12;
            tinss = 12;
        }

    printf("\n Nome: %s \n",nome);
    printf("\n Salario bruto: %f \n", sal);
    printf("\n Taxa de INSS: %d% \n", tinss);
    printf("\n Valor de INSS %f \n", val);
    printf("\n Salario liquido: %f \n", novosala);

    printf("\n deseja continuar ? \n");
    resp = getch();
    cont = cont + 1;
}
while(resp == 's');

Comment: Note que, no seu programa em concreto, `else if(sal > 1000)` pode ser substituído por apenas `else`.
Comment: Alguma lhe ajudou mais? Precisa que algo seja melhorado?
Comment: Seu código está em C e não C++. Troque scanf("%s",&nome); por scanf("%s", nome);, pois nome já é o endereço da posição inicial do array, e também reveja o uso da função getch. Verifique se o buffer de entrada não está ficando com sujeira após a leitura de resp.
Answer: Primeiro, você pode até estar usando um compilador C++ mas você está programando em C. E está usando uma função que não deveria ser usada mais. Elimine a getch() e o problema será resolvido.
Tem outras funções que podem ser usadas mas eu usaria o scanf() até para não ficar esquisito hora ter que dar o ENTER, hora não.
Então ficaria assim:
#include <stdio.h>

int main() {
    char resp;
    do {
    int cont = 1, tinss;
    char s, nome[50];
    float sal, novosala, val;
    printf("\n digite o nome do funcionario; ");
        scanf("%s",&nome);
        printf("\n digite o salario do funcionario: ");
        scanf("%f",&sal);
        if (sal <= 500) {
            novosala = sal - ((sal / 100) * 8);
            val = (sal / 100) * 8;
            tinss = 8;
        } else if (sal > 500 &&  sal <= 1000) {
            novosala = sal - ((sal / 100) * 10);
            val = (sal / 100) * 10;
            tinss = 10;
        } else if (sal > 1000) {
            novosala = sal - ((sal / 100) * 12);
            val = (sal / 100) * 12;
            tinss = 12;
        }
        printf("\n Nome: %s \n",nome);
        printf("\n Salario bruto: %f \n", sal);
        printf("\n Taxa de INSS: %d% \n", tinss);
        printf("\n Valor de INSS %f \n", val);
        printf("\n Salario liquido: %f \n", novosala);
        printf("\n deseja continuar ? \n");
        scanf("%s",&resp);
        cont = cont + 1;
    } while (resp == 's');
}

Veja funcionando no ideone. E no repl.it. Também coloquei no GitHub para referência futura.
Versão mais C++:
#include <iostream>
#include <string>
using namespace std;

int main() {
    string  resp;
    do {
        int cont = 1, tinss;
        string s, nome;
        float sal, novosala, val;
        cout << endl << "digite o nome do funcionario: ";
        cin >> nome;
        cout << endl << "digite o salario do funcionario: ";
        cin >> sal;
        if (sal <= 500) {
            novosala = sal - ((sal / 100) * 8);
            val = (sal / 100) * 8;
            tinss = 8;
        } else if (sal > 500 &&  sal <= 1000) {
            novosala = sal - ((sal / 100) * 10);
            val = (sal / 100) * 10;
            tinss = 10;
        } else if(sal > 1000) {
            novosala = sal - ((sal / 100) * 12);
            val = (sal / 100) * 12;
            tinss = 12;
        }
        cout << endl << "Nome: " << nome << endl;
        cout << "Salario bruto: " << sal << endl;
        cout << "Taxa de INSS: " << tinss << endl;
        cout << "Valor de INSS " << val << endl;
        cout << "Salario liquido: " << novosala << endl;
        cout << endl << "deseja continuar ? " << endl;
        cin >> resp;
        cont++;
    }
    while (resp == "s");
}

Veja funcionando no ideone. E no repl.it. Também coloquei no GitHub para referência futura.
Dá para fazer melhor mas já está mais organizado.

Uso de string dá erro


Pass form input value to URL

Question: Total new guy to HTML here.
I'm looking to create a search box that passes the typed search term into the URL field.
This is my input form:
<form name="search" action="/search/" method="post">
    <input type="text" name="topic" value="">
</form>

I'd like the search term to go after the /search/ in the URL. How can this be done?
Thanks.
Answer: Use the GET form method:
<form name="search" action="/search/" method="GET">
    <input type="text" name="topic" value="" />
</form>

EDIT:
To get the form to send the user to a url like /search//, you can use a javascript function like this:
function submitForm(){
    var url = '/search/';
    url += document.search.topic.value + '/';
    // repeat the above line for any other fields you may want to add
    window.location.href = url;
}

You can then use this function as an onClick handler on a submit button or on the form's onSubmit.
Comment: Perfect, although the result in the URL bar is url.com/search/?topic=

How could i just have it /search//  ?
Comment: @user1742284 To do that, you would need to write some custom javascript.  I'm updating my original post with an example now.
Comment: @G-Nugget sorry to be such a newbie, but how exactly would i write that in my PHP file? what do you mean by onClick handler? I don't have a button for the form, just relying on user pressing enter
Answer: you can remove the method="post" since the default is GET method

Pass form input value to URL


Entity query for distinct field

Question: I have an entity line_item with the following fields:

id
uid (entity reference)
product (entity reference)
...

I would like to get all distinct products (product ids) for a specific user.
I tried with entity query:
<code>$query = $this->entity_query->get('line_item');
$query->condition('uid.entity.name', $username);
$entity_ids = $query->execute();
</code>
Unfortunately this results in all line_items from the given user, with multiple times the same product. But what I am interested in is just getting all different products for the given user.
Answer: I don't think it's possible to write a single entity query to accomplish this. You could take your $entity_ids result, use loadMultiple to load all the line_item entities, and then iterate through them to get all the products. Something like this:
<code>$line_items = $this->entity_type_manager->getStorage('line_item')->loadMultiple($entity_ids);

$products = [];
foreach ($line_items as $line_item) {
  $product = $line_item->getProduct();
  if ($product && !isset($products[$product->id()])) {
    $products[$product->id() = $product;
  }
}
</code>
Another possibility would be to use the database service to construct a select query with actual database table names and fields (\Drupal\Core\Database\Connection).
See:
https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Database%21Connection.php/function/Connection%3A%3Aselect/8.2.x
and for the list of methods you can use to construct the select:
https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Database%21Query%21SelectInterface.php/interface/SelectInterface/8.2.x

Entity query for distinct field


Excel Formula - Compare two tables (If match is found in name, calculate difference in charges.)

Question: I am trying to figure out a formula to find and calculate the difference in charges from two tables which has matching facility names. If facility name does not have a match then leave blank or if NA in calculation cell.
Comment: Can you post what you've tried so far?
Comment: `VLOOKUP()`? What have you tried? Questions like this are asked probably once a week, if not more often, here on SO. Have you searched for anything?
Answer: Looking at your screenshot I'm assuming the first row after the header is on row 7. You can try to paste this to cell J7:
=IFNA(VLOOKUP(CONCATENATE(RIGHT(F7,2)," - ", G7),B:D,2,FALSE)-H7,"")

What it does is using vlookup function to get the data from the other table. But since they don't have the common value, I use CONCATENATE(RIGHT(F7,2)," - ", G7) to generate common value assuming column B has a unique value.
Answer: If I understand your question correctly, this is what you are trying to do:

This is the formula to enter from cell J6 and you can drag it to K6 as well:
=IFERROR(INDEX(C$6:C$12,MATCH("*"&$G6&"*",$B$6:$B$12,0))-H6,"")

Basically, the trick is to use wildcard * to perform this search.  Try and let me know if this is what you are looking for.


Derive tempo value from the unit pattern length

Question: A guitar instrumental music was played with 4/4 timing and tempo of 86 bpm settings. One pattern consist of 6 notes ( or beats). On audacity, a unit strumming pattern ( = 1 bar)  takes roughly 2.78sec. How do I derive the bpm theoretically from this pattern length correctly? Or in other words how do I get a figure close to 86bpm from this unit pattern length of 2.78 (approx) sec?
Answer: It's given that one measure lasts 2.78 seconds.
Since one measure lasts 2.78 seconds, there can be 60/2.78 measures per minute.
It's also given there are four beats per measure. Since there are four beats per measure, the tempo is (60 / 2.78) * 4 bpm.
Therefore, the tempo is approximately 86.33 bpm.