convert string to values

Question: First of all I am not sure how correct my question is.
I want to upload data to MySQL database.
columns3=[]
for i in df.columns:
    i="row."+str(i)
    columns3.append(i)
for row in df.itertuples():
    mycursor.execute(insert into df2(rk, age, g, gs, mp, fg, fga) values(%s,%s,%s,%s,%s,%s,%s),(columns3))
mydb.commit()

output for columns3 is this:
['row.rk',
 'row.age',
 'row.g',
 'row.gs',
 'row.mp',
 'row.fg',
 'row.fga']

data is of string type, so it is imported to MySQL database like this:

columns3 should be row.rk, row.age,row.age and etc. (without quotes).
How can I convert these str values to desired values
Comment: what is your desired value
Comment: I want to conver 'row.rk', 'row.age', 'row.g' to row.rk, row.age, row.g (to remove quotes)
Comment: What type of data is `row.rk` if it is not a string?
Comment: type(row.rk)  is float (in dataframe column "rk" is of type float. type('row.rk') is str
Comment: So you want to insert the value of `row.rk` into the SQL database?
Comment: yes.  I want to insert it as row.rk (not as "row.rk")
Comment: I think `row['rk']` is what you want to retrieve the value of the column from the pandas df. Can you try that?
Comment: yes. That is what I want to get. I will try it
Answer: Let's say we have a pandas DataFrame df with some columns:
cols = tuple(df.columns)
num_cols = len(cols)
statement = "INSERT INTO df2 (" + ", ".join(cols) + ") VALUES (" + ", ".join("%s" for _ in range(num_cols)) + ")"
for row in df.itertuples():
    mycursor.execute(statement, row[-num_cols:])
mydb.commit()

The row is returned as a tuple with index/indices followed by column values. I'm slicing the last num_cols values from the tuple to get the column values to pass to the SQL database.
This should give you the desired results.

convert string to values


Keystone/Apollo/React: 1 useMutation for several creations issue

Question: I tried to create multiple products inside one single order creation.
Actually it works here manually through the GraphQL tool :
mutation {
    createOrder(
      data: {
        orderName: "Order 1"
        products: { create: [{ name: "Product 1" }, { name: "Product 2" }]}
      }) {
      id
      name
      products {
          name
      }
      }
    }

But I can't figure out how to write this in a useMutation hook from Apollo and how to pass the variables inside.
I tried something like this but it's still not complete, and I can't find so for any doc mentioning how:
const CREATE_ORDER = gql`
  mutation CREATE_ORDER(
    $orderName: String!
    $name: String!
  ) {
    createOrder(
      data: {
        orderName: $orderName
            products: { create: [{name: $name}, {name: $name}] }
      }
    ) {
      id
      orderName
      products {
          name
      }
      }
    }
  }
`;

And as a variable objects I would pass this:
const [createOrder, { data, loading, error }] = useMutation(CREATE_ORDER, {
    variables: {
      orderName: 'Order X',
      products: [{ name: 'Burger'}, { name: 'Pizza'}],
    }

Any idea?
Thanks for your help
Comment: prepare entire `$data:someCreateOrderInput` variable
Comment: Thanks for your feedback !
It helped me find the solution
Answer: I did this and it worked (and I pass an array of objects in the $data):
const CREATE_QUOTE = gql`
  mutation CREATE_QUOTE(
    $date: String!
    $total: Int!
    $data: [CartItemCreateInput]
  ) {
    createQuote(
      data: { date: $date, total: $total, cartItems: { create: $data } }
    ) {
      id
      date
      total
    }
  }
`;


Mean of ratio distribution with domain of denominator containing 0

Question: Consider a ratio distribution Z=X/Y. If 0 is in the domain of Y it seems intuitive that the mean of Z is undefined because Z itself will be undefined at many points.
However there are many results where the denominator distribution contains 0 and the resulting ratio has finite mean. I can't figure out why these ratio distributions would have finite means. Any help would be much appreciated.
Comment: See https://stats.stackexchange.com/questions/299722/.
Answer: The denominator distribution may contains 0, but the appearance of 0 is rare enough that it may not pose problem.

for continuous random variables : the probability of drawing exactly 0 is 0. So the probability of having a diverging ratio is zero. Having finite means is not that surprising.

Note that having finite means usually have to do with bahevior around diverging point and at infinity, as it is an integration problem :
$$ \mu_Z = E[Z] = \int_{-\infty}^\infty z f_Z(z)dz$$
So the question is more about the behavior of $f_Z$ around 0, and at +/-$\infty$. You may encounter both case where $zf_Z(z)$ is integrable around 0 or not.

for discrete random variables : the result may empirically hold because the value 0 wasn't drawn. It may not hold for bigger (or unluckier) draws.


Which test to use to check the difference between samples of percentages?

Question: I have data measured from 14 samples between two conditions. I want to check difference between them. But the data is normalised and is in terms percentage (0-100). For example
var.A = c(9.302325581, 42.85714286, 47.3880597, 6.93131695, 6.968517863,
9.535655058, 4.545454545, 10, 8.275862069, 17.5257732, 10.52631579,
7.865168539, 11.76470588, 11.84210526)

var.B = c(33.96226415, 58.21256039, 33.83084577, 10.61452514, 12.54752852,
9.371095377, 3.125, 20.21276596, 6.642066421, 11.62790698, 11.94029851,
14.28571429, 8.333333333, 10.71428571)

For variable-A, I am observing median value of 9.76 and for B its 11.78. I want to check for whether this is significant or not. Which test would be suitable in this case since all observations are on scale of 0-100 ?  Do I use prop.test from R ?
Comment: Do you have the denominators?
Comment: Yes I have. Each value is derived by dividing observed/total.
Comment: Are the data paired?
Comment: Hi Glen, Yes. data are paired.I am interested to know whether overall change (mean or median) is significant or not.
Comment: That's critical information that should be in your question.
Answer: The problem with the proportions is that they'll have non-constant variance ... but you need the denominators to work those variances out.
The more usual approach would be to work with the original counts (the numerators), and keep the denominators.
pair      A        B
        X   n    X   n
 1      4  43   18  53
 2      .
 3      .
 4      .
 ...
14

It's possible to construct a single chi-square test of the hypothesis of homogeneity within-pairs, by taking each pair's 2x2 chi-square and summing the statistics across pairs (giving a statistic that's approximately $\chi^2_{14}$ across all 14 pairs).
Alternatively, it would be possible to set this up as a GLM.
Comment: Yes, if I understand your aim correctly, that should work fine. For the p-values, you'd use `pchisq(sum.of.chisq.values,14,lower.tail=FALSE)`
Comment: Hi Geln, Thanks for the answer. Here is what I have done for 1st pair.

`Pair A.X A.n B.X B.n
1    4     43  18      53`

When I do `chisq.test` :
`chisq.test(matrix(c(4, 43-4, 18, 53-18), ncol=2))`

I gee a `p-value = 0.008934`

When I do `prop.test` :
`prop.test(c(4,18),c(43,53))`
I get the same `p-value = 0.008934`

Any how, whn you say summing the statistics across pairs, do you mean I sum up the p-values from all 14 samples ?? Sorry for being naive.
Comment: No, don't sum the p-values, sum the chi-square statistics.
Comment: That can then be compared with a chi-squared k (`pchisq` can be used for that) ... unless you want it done as a bunch of 2x2 tests of course
Comment: Hi Glen, thanks again. I did sum up the chi-squared statistics and used it to get a p-value for degrees of freedom 14. This should be enuf right ?
Answer: The values are rescaled - they should retain their basic statistical properties, provided they have been rescaled the same.
I'm a little confused about what you have - 14 samples, and 2 variables, or 2 samples with 14 observations? Is it a paired situation, where you have 14 cases and have observed them twice (like a pre and post test)? Either way, the data are non-normal, so a t.test shouldn't work, particularly with a small sample size like this. Prop.test isn't what you are after - although the values are proportions, prop.test is for comparing two proportions, not two vectors of proportions. Try the Wilcoxon Signed-Rank Test, wilcox.test. For the 2 samples, 14 observations case, I get:
> wilcox.test(var.A,var.B)

    Wilcoxon rank sum test

data:  var.A and var.B
W = 74, p-value = 0.2852
alternative hypothesis: true location shift is not equal to 0

For the 14 cases, 2 observations each case (i.e. paired), I get:
> wilcox.test(var.A,var.B,paired=T)

    Wilcoxon signed rank test

data:  var.A and var.B
V = 39, p-value = 0.4263
alternative hypothesis: true location shift is not equal to 0

Comment: Hi, Yes this data is from 14 paired samples before and after treatment (2 variables). I would like to check effect of treatment. As I mentioned in the question I am observing a median 9.6% and 11.8%. This increase of ~2% is significant or not, is the hypothesis I am trying test. I first thought of wilcoxon test but since data was normalized I hesitated to use.And in a recent paper where they do similar study, the mention they have used 'Proportion tests.' I am not sure what exact test they have used.
Comment: I'm sorry, I misunderstood what your original posting was presenting. Is there a reason you cannot pool all of the data together? You could treat each sample as a fixed or random effect, and if you know anything else about them, you could test whether they explain differences.
Comment: One other thing to consider: Chi2 and proportion tests are  sensitive to sample size, particularly a problem if you pool the results (however you do that). You should think about calculating effect sizes. For Chi2 that's simply square root of the standardized Chi2 stat (meaning calculate chi2 based on proportions in each cell, not counts).


Show that $\sum_{n=1}^\infty \frac{\sin (nx)}{n}$ converges uniformly on $[\pi /2 , 3\pi /2]$

Question: I must show that $\sum_{n=1}^\infty \frac{\sin (nx)}{n}$ converges uniformly on $[\pi /2 , 3\pi /2]$ - I know that it holds on $[\pi /2 , \pi ]$, which should also be sufficient as a proof, but I don't know how to prove it.
Answer: We want to be able to use Dirichlet uniform convergence test
So we need that
i)
1/n is monotonous decreasing function
ii)
1/n uniformly converges to 0 (which it does since it doesn't depend on variable x)
iii)
$$
(\exists M>0)(\forall n\in \mathbb{N})(\forall x\in [\pi/2,3\pi/2])
$$
$$
\left | \sum_{m=1}^{n} \sin(mx)  \right | \le M
$$
We can prove that by
$$
\left | \frac{1}{\sin{\frac{x}{2}}}\sum_{m=1}^{n} \sin{mx}\sin{\frac{x}{2}}  \right | = \left | \frac{1}{2\sin{\frac{x}{2}}}\sum_{m=1}^{n} (\cos{\frac{(2m-1)x}{2}}-\cos{\frac{(2m+1)x}{2}})  \right | =
$$
$$
\left | \frac{\cos{\frac{x}{2}}-\cos{\frac{(2n+1)x}{2}}}{2\sin{\frac{x}{2}}} \right | \le \left | \frac{1}{\sin{\frac{x}{2}}} \right |
$$
So when $x\in [\pi/2,3\pi/2])$ we know $\frac{x}{2} \in [\pi/4,3\pi/4]$
$$
\max_{x \in [\pi/4,3\pi/4]} \left | \frac{1}{\sin{\frac{x}{2}}} \right | = \frac{2}{\sqrt{2}}
$$
Hence using Dirichlet uniform convergence test we conclude that beginning function series uniformly converges on $[\pi/2,3\pi/2]$


Rails 4 ERB: consistent date format

Question: I have read several posts such as How to format time and date from db:datetime record in Rails 4? and Custom date time format in rails 4 and I feel like I am missing a puzzle piece.
In our project we have setup a conf variable for a date format and we use:
my_date_field.strftime(Rails.configuration.date_format_default)

Other suggestions are to setup an initializer and use:
my_date_field.to_s(format: :date_format_default)

Is there any way to make the output of a datetime field default to a format? In our project, unless we specify, we want a date to ALWAYS render the same way and it feels very un-DRY to have to constantly repeat strftime or to_s, both with their own parameters...
Answer: Set a default format in your translations:
en:
  time:
    formats:
      default: "%a %b %d, %Y at %I:%M %p"

Then use the translation helper in your ERb templates:
l some_model.created_at

Answer: You can use I18n (Rails Internationalization) to set a default date and time format
config/locales/en.yml
en:
  date:
    formats:
      default: "%d/%m/%Y"
  time:
    formats:
      default: "%d/%m/%Y %H:%M"

Rails 4 ERB: consistent date format


Python inline conditional in string concatenation

Question: I had this:
msg = time + b' - ' + Logger.LEVELS_WORD[msg_loglevel] + b': ' + msg.encode('utf-8') + b'\n'

Since sometimes msg was already bytes, I wanted to concat msg.encode('utf-8') if it was string or else just msg, so I did this:
msg = time + b' - ' + Logger.LEVELS_WORD[msg_loglevel] + b': ' + msg if isinstance(msg, bytes) else msg.encode('utf-8') + b'\n'

But it is not working as I expected, since now msg equals msg. (time + log level isn't getting added).
Should I do if/else instead?
Comment: What did you expect and what did it do?
Comment: @AmitGold concat msg.encode('utf-8') or msg depending on if it was already bytes.
Comment: instead of one of the `msg`s, change it to something similar like `_msg` and then do `msg = _msg`
Comment: The problem you have as stated in the answer provided is precedence, the if is taking the whole before expression. So you need to use parentheses in your conditional (msg if isinstance(msg, bytes) else msg.encode('utf-8'))
Answer: A conditional expression has a very low precedence; it is executed last only before a lambda. As such the expression, as written, choses between either time + b' - ' + Logger.LEVELS_WORD[msg_loglevel] + b': ' + msg or msg.encode('utf-8')) + b'\n'.
Put the conditional expression with the if and else branches in parentheses:
msg = time + b' - ' + Logger.LEVELS_WORD[msg_loglevel] + b': ' + (
    msg if isinstance(msg, bytes) else msg.encode('utf-8')) + b'\n'

Consider using duck-typing (test for hasattr(msg, 'encode')), and breaking up the expression into multiple lines for readability. If you are using Python 3.5 or newer, perhaps you want to use printf-style formatting:
if hasattr(msg, 'encode'):
    msg = msg.encode('utf-8')
msg = b'%s - %s: %s\n' % (time, Logger.LEVELS_WORD[msg_loglevel], msg)


Drupal admin themeing and customizations

Question: I am looking into how I might customize the backend, but re-themed is not the ultimate agenda. Say for instance, 'admin/content', where I have filter options for various content types. Below that I have a table of content sections.
I want to completely replace the table and render the list in the left region of my template and use the content area for a WYSIWYG editor -- this is a common UI for basic CMS and I figured would be a good advanced learning experience.
I started poking through the code and quickly discovered I have no idea what content/form/blocks are in which regions in the admin section.
I found the module that implements the menu for 'admin/content' but that wasn't very helpful.
My question is: In the admin portion of a drupal setup how would I position custom block module content in the right region of a template when using block admin seems only to affect the front-end of the site?
Answer:
Use https://drupal.org/project/admin_views
Go edit a view and add a new display: block.
Register a new path in system:
a) using hook_menu in your custom module OR
b) using https://drupal.org/project/empty_page
Place that new created block in a region (edit also the paths where block should be displayed)
I'm not sure what you mean by WYSIWYG editor in content area - do you want to edit node or what?
a) If you used hook_menu, point its page callback into a function which returns WYSIWYG editor OR
b) If you used a empty_page you must create another block with editoror inside, and place it into content region
Comment: Thanks for the reply. I'm not sure if admin_views is what I am looking for but will take a peak. :) To be honest I am not sure what I am trying to do (in the context of drupal) I guess I have read more.

Basically I want to replace the backend interface almost completely. Themes and some functionality, whilst still using Drupal as a framework.


Adicionar input button num select

Question: Quero um button para chamar outra pagina dentro de um select. O problema é que utilizando esse codigo, o button fica sempre fora do select.
<select>
  <option>teste</option>
  <option><input type=button value="Teste2"/></option>
</select>

Exemplo: http://jsfiddle.net/r82v3vxn/
Comment: "Idêntica" não sei, mas parecida é mesmo possível. Acho que essa sua sugestão daria uma resposta, @CesarMiguel ;)
Comment: Por um botão dentro de uma select não dá... Podes manipular a option da select com css para ficar idêntica a um botão
Answer: Os elementos <option> não aceitam HTML, somente texto. Se quer criar um dropdown com opções visualmente mais sofisticadas, terá de simular seu próprio <select> usando outros elementos HTML, mais JavaScript.
Talvez este plugin de jQuery resolva pra você: http://pioul.fr/jquery-simpleselect
Answer: Nao é possivel adicionar um<button> dentro de um select nativamente. Você consegue esse resultado com javascript simulando um select.

Adicionar input button num select


Understanding the GroupJoin and Join in Linq chaining syntax (Homework)

Question: I need help with understanding the fourth argument for GroupJoin. From what i understand so far GroupJoin takes 4 arguments: (1, 2) - the first one is the secondary list and argument two is a Func that returns the key from the first object type in other words from the first list in this case (people). (3, 4) A Func that returns the key from the second object type from the second list in this case (items), and one that stores the grouped object with the group itself (I can't understand the code for this part). Considering this and having the code below:
var products = new Product[]
{
    new Product { Id = 1, Type = "Phone", Model = "OnePlus", Price = 1000 },
    new Product { Id = 2, Type = "Phone", Model = "Apple", Price = 2000 },
    new Product { Id = 3, Type = "Phone", Model = "Samsung", Price = 1500 },
    new Product { Id = 4, Type = "TV", Model = "Samsung 32", Price = 200 },
};

var people = new Person[]
{
    new Person { Id = 1, Name = "Ivan Ivanov", Money = 150000 },
    new Person { Id = 2, Name = "Dragan Draganov", Money = 250000 },
    new Person { Id = 3, Name = "Ivelin Ivelinov", Money = 350000
}
};

var items = new Item[]
{
    new Item { PersonId = 1, ProductId = 1, Amount = 1 },
    new Item { PersonId = 1, ProductId = 4, Amount = 1 },
    new Item { PersonId = 1, ProductId = 5, Amount = 1 },
    new Item { PersonId = 1, ProductId = 7, Amount = 1 },
    new Item { PersonId = 2, ProductId = 2, Amount = 1 },
};

Query:
var productOwnerList = people
    .GroupJoin(
        items,
        o => o.Id,
        i => i.PersonId,
        (o, i) => new   <--- (**)
        {
            Person = o,
            Products = i
                .Join(products,
                    o1 => o1.ProductId,
                    i2 => i2.Id,
                 (o1, i2) => i2)          <--- (*)
                .ToArray()
        })
    .ToArray();

Just to mention I post only a few lines for the data. I need help to  understand what the 4th argument for the join method is performing here -> (*) (stores the grouped object with the group itself) ? When i watch the result i see it it puts all Person id's associate with the product keys and joined the two lists based on Items list (one to many). But i cannot get what exactly this line means (o1, o2) => i2). Its obvious what is doing (put all the items associated with the person id in a array (items[]) for every person. but what is "under the hood" here ? Also one question about (**) this line its creating new object, is this a anonymous class or if its not what is it.
Comment: Please note that peppering your text with triple-backticks makes it very hard to read. I'm not sure what formatting you were hoping to achieve, but it definitely wasn't helping the clarity.
Comment: [Linq to Entities join vs groupjoin](https://stackoverflow.com/a/15599143/2417602) might help....
Comment: @vikscool It helped a bit.
Comment: @Jon Skeet Sorry i didn't find appropriate formatting symbols for "underline" something. Can you give me a tip for what symbols to use ?
Comment: See https://stackoverflow.com/editing-help for formatting assistance, but I don't believe there's anything for underlining. Use bold or italics instead - but I'd suggest using them sparingly.
Answer: The fourth argument - which maps to the fifth parameter in the documentation (because the first parameter is the target of the extension method call) is just the result selector. It's a function accepting two parameters: the first is an element of the "outer" sequence (the people array in your case) and the second is a sequence of elements from the "inner" sequence (the items array in your case) which have the same key as the outer element. The function should return a "result" element, and the overall result of the method call is a sequence of those results.
The function is called once for each of the "outer" elements, so you'd have:

First call: person ID 1, and products with IDs 1, 4, 5, 7
Second call: person ID 2, and the product with ID 2
Third call: person ID 3, and an empty sequence of products

Your query is complex because you're using an anonymous type for your result, and constructing an instance of the anonymous type using another query. Here's a simpler query that might help to clarify:
var productOwnerList = people
    .GroupJoin(
        items,
        o => o.Id,
        i => i.PersonId,
        (person, items) => $"{person.Id}: {string.Join(",", items.Select(item => item.ProductId))}"
    .ToArray();

Comment: Great answer i followed the documentation that you provide me and your answer. It is pretty clear now but what it turns out is that the second part where i create a anonymous type for the result everything there is just to construct the object and its not related to the query itself ?
Comment: @BorisBorovski: I'm afraid I don't understand the question in your comment.
Comment: I mean i have a second query in the result for the GroupJoin method that maps  items from the Item data to the products in the product data.
Comment: @BorisBorovski: Yes - where you're calling `Join`, that's effectively a nested query which is executed for each group.


Unloading Java classes using CustomClassLoader

Question: I have been through many posts and questions but none of them had a absolute Java program to implement this.
Requirement : For some reasons my application loads the Common-codec 1.3.jar,
and later on ,within same jvm the process needs to use Common-code 1.10.jar  which is of different version.
But since the previous classes are loaded and they have same package name ,reloading them with a Java program  is not replacing the existing classes.
Here is the code (sample) i used to reload(replace) the existing keys,but found no luck as expected. Please let me know hoe this could be done by a Java example.
String pathToJar=/root/Desktop/commons-codec-1.10.jar";

            JarFile jarFile = null;
            try {
                jarFile = new JarFile(pathToJar);
            } catch (IOException e) {
                e.printStackTrace();
            }
            Enumeration<JarEntry> e = jarFile.entries();

            URL[] urls = new URL[0];
            try {
                urls = new URL[]{ new URL("jar:file:" + pathToJar+"!/") };
            } catch (MalformedURLException e1) {
                e1.printStackTrace();
            }
            URLClassLoader cl = URLClassLoader.newInstance(urls);

            while (e.hasMoreElements()) {
                JarEntry je = e.nextElement();
                if(je.isDirectory() || !je.getName().endsWith(".class")){
                    continue;
                }
                // -6 because of .class
                String className = je.getName().substring(0,je.getName().length()-6);
                className = className.replace(File.separatorChar, '.');
                String check="org.apache.commons.codec.binary.Base32";

                try {
                    Class c = cl.loadClass(className);   // Excepting it to replace old files,but thats not happening
                } catch (ClassNotFoundException e1) {
                    e1.printStackTrace();
                }

I was advised to write Custom class loader and unloading is possible via it.
Could some show some  relevant code or process of doing it.
Answer: Class "unloading" may only occur when both the Class and the ClassLoader that defined it are eligible for garbage collection. Furthermore, any given loader can only define a class of a specific name once. Therefore (save for exotic workarounds such as instrumentation or JDK implementation internals), there is no such thing as a "reloading-capable class loader" -- at least not in the true sense of the term; in order to obtain n distinct "versions" of a class, C, defineClass(C) must be invoked on n distinct ClassLoader objects.
Let's examine the following trivial use case: We have an app.jar, (unsurprisingly) containing a class declaring a main method; and two copies of a lib.jar, each having a single class, LibApiImpl, encapsulating a single method that just prints a version-dependent string to stdout. Our goal is to merely reference two copies of the "library" class from our main and see two different strings being output. The remainder of this post demonstrates just two of all the possible approaches to satisfy this requirement.
Approach #1 - Manually instantiating ClassLoaders
The straightforward solution is to simply create a new URLClassLoader every time a different LibApiImpl needs to be loaded. No custom class loader implementation is required, and the default parent-first delegation model serves both the application and the library well. A couple of things to note:

The library JARs must not sit on the classpath, in order to not be discoverable by the default application class loader. Otherwise the application class loader will "favor" one over the other, and, due to the default delegation model, standard URLClassLoader children of the application loader will not be able to override their parent's opinion on the matter.
To access the library class, the 3-argument Class::forName must be employed, specifying the manually-instantiated class loader. The single-arg version will delegate to the application class loader, which (as per the former point) is of course unaware of the existence of the corresponding .class file.
If the reflectively-obtained class is to be cast to an interface, as will be the case herein, the interface must, as opposed to the implementation, reside on the classpath.

Demo code
package com.example.app;

import java.net.URL;
import java.net.URLClassLoader;

import com.example.lib.api.LibApi;

public class App {

    public static void main(String... args) throws Exception {
        try (URLClassLoader loader = new URLClassLoader(new URL[] { new URL("file:/path/to/lib1.jar") })) {
            ((LibApi) Class.forName("com.example.lib.impl.LibApiImpl", true, loader).newInstance()).printVersionInfo();
        }
        try (URLClassLoader loader = new URLClassLoader(new URL[] { new URL("file:/path/to/lib2.jar") })) {
            ((LibApi) Class.forName("com.example.lib.impl.LibApiImpl", true, loader).newInstance()).printVersionInfo();
        }
    }

}

package com.example.lib.api;

public interface LibApi {

    void printVersionInfo();

}

package com.example.lib.impl;

import com.example.lib.api.LibApi;

public class LibApiImpl implements LibApi {

    @Override
    public void printVersionInfo() {
        System.out.println("\n** lib " + getClass() + " / loaded by " + getClass().getClassLoader() + " **\n");
    }

}

Packaging
Correct the paths in com.example.app.App; then produce the following 4 JARs:

An app.jar containing the com.example.app package.
A lib-api.jar containing the com.example.lib.api package.
Two "versions" (just export twice), lib1.jar and lib2.jar, each containing the com.example.lib.impl package.

Testing
Run as follows:
java -cp '/path/to/app.jar:/path/to/lib-api.jar' com.example.app.App

Sample output:
** lib class com.example.lib.impl.LibApiImpl / loaded by java.net.URLClassLoader@55f96302 **

** lib class com.example.lib.impl.LibApiImpl / loaded by java.net.URLClassLoader@135fbaa4 **

Approach #2 - Creating a "Master-Slave" loader
Sometimes the "parent-first" model is insufficient. As a contrived example, suppose that we wanted to obtain the "copy" of LibApiImpl that was last loaded by some child of the application class loader, without having to care about which child it actually was that defined the copy. In other words, we want the call Class.forName("com.example.lib.impl.LibApiImpl") to return the "most fresh" LibApiImpl version. But, unless we override the application class loader, or, more generally, the class loader of the App class, with a custom implementation, that call will always fail, because, under the default delegation model, delegation flows unidirectionally from lower-level loaders to their ancestors and not vice versa.
The application class loader implementation, given below, behaves as follows (refer to the Javadoc overview of the Loaders class for a concrete explanation): There is a "master" loader, serving as the application class loader, that may have a child, referred to as its "slave". The master is responsible for loading non-reloadable application classes from the classpath (app.jar and lib-api.jar, in this case), while the slave gets to load reloadable, non-classpath-residing ones (lib1.jar and lib2.jar). The communication between the two is bidirectional, and the loader that will ultimately define any given class, "fixed" or "reloadable", is always respectively the master and the slave, regardless the "initiating" loader, i.e., the loader on which the application called loadClass, or passed to Class::forName. Of course this is nothing but a toy implementation meant to (hopefully) illustrate how a different delegation scheme might look like, and is probably flawed in ways I have not even begun to imagine. A real-world implementation would, e.g., have to provide proper concurrency; provide compliant implementations of getResource et al.; address concerns of code accessibility, verification, and possibly code base privilege assignment; and allow extensibility by, and configuration of, multiple slaves, or even attachment of other children, potentially of arbitrary implementation, to the master, while preserving well-defined delegation semantics. The point of course being that it is generally too much effort to write a proper implementation, when there is OSGi and the like doing just that (among many others).
Demo code
package com.example.app;

import java.net.URL;

import com.example.app.Loaders.MasterLoader;
import com.example.lib.api.LibApi;

public class App2 {

    public static void main(String... args) throws Exception {

        MasterLoader loader = (MasterLoader) ClassLoader.getSystemClassLoader();
        loader.setDebug(true);
        loader.refresh(new URL[] { new URL("file:/path/to/lib1.jar") });

        newLibApi().printVersionInfo();

        loader.refresh(new URL[] { new URL("file:/path/to/lib2.jar") });

        newLibApi().printVersionInfo();

    }

    static LibApi newLibApi() throws Exception {
        return (LibApi) Class.forName("com.example.lib.impl.LibApiImpl").newInstance();
    }

}

package com.example.app;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;
import java.nio.file.Paths;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.regex.Pattern;

/**
 * Contains a "Master (parent)/Slave (child)" ClassLoader "duo".

 *

 * The class loading "protocol" adhered by the respective {@code loadClass(String, boolean)}
 * implementations of the two is as follows:
 *

 *
If the name argument matches the name of the loader's class itself, return that class.
 * Otherwise proceed.

 *
If a call to {@code findLoadedClass(name)} yields a non-null class, return that class.
 * Otherwise proceed.

 *
Let C be either this loader's parent, if this is a "slave", or its child, if this is
 * a "master". If C is non-null, have it execute steps (1), (2) itself. If a class gets
 * produced, return that class. Otherwise (i.e., if there either is no result, or C is
 * null) proceed.

 *
If the name argument refers to a potential bootstrap classpath class name, call
 * {@code loadClass(name)} on the default system classloader (the "master's" parent). If the call
 * succeeds, return that class. Otherwise proceed.

 *
If the name argument refers to a .class file under this loader's search path, read it, define
 * and link a new class off of its contents, and return that "freshly-fefined" class. Otherwise
 * proceed.

 *
Once again, let C be the loader specified in step (3). If non-null, have it execute
 * step (5) on itself. If a class gets produced, return that class. Otherwise fail.

 *

 */
public class Loaders {

    private static class SlaveLoader extends URLClassLoader {

        static final Pattern BOOT_CLASS_PATH_RES_NAMES = Pattern.compile("((com\\.)?sun|java(x)?)\\..*");
        static final URL[] EMPTY_SEARCH_PATH = new URL[0];

        static final URL[] createSearchPath(String pathNames) {
            if (pathNames != null) {
                List<URL> searchPath = new ArrayList<>();
                for (String pathName : pathNames.split(File.pathSeparator)) {
                    try {
                        searchPath.add(Paths.get(pathName).toUri().toURL());
                    }
                    catch (MalformedURLException e) {
                        e.printStackTrace();
                    }
                }
                return searchPath.toArray(new URL[0]);
            }
            return EMPTY_SEARCH_PATH;
        }

        static final byte[] readClassData(URL classResource) throws IOException {
            try (InputStream in = classResource.openStream(); ByteArrayOutputStream out = new ByteArrayOutputStream()) {
                while (in.available() > 0) {
                    out.write(in.read());
                }
                return out.toByteArray();
            }
        }

        final String loadClassOutcomeMsgFmt = "loadClass return '{'\n\tloader = {0}\n\ttarget = {1}\n\tresult : {2}\n'}'";
        volatile boolean debug;

        SlaveLoader(URL[] searchPath, ClassLoader parent) {
            super(searchPath, parent);
        }

        @Override
        protected synchronized Class<?> loadClass(String name, boolean resolve) throws ClassNotFoundException {
            validateName(name);
            Class<?> ret = loadFromCache(name);
            if (ret != null) {
                return ret;
            }
            MasterLoader parent = (MasterLoader) getParent();
            if ((ret = parent.loadFromCache(name)) != null) {
                log(loadClassOutcomeMsgFmt, this, name, "3 - early return - pre-loaded/cached - via " + parent);
                return ret;
            }
            if ((ret = loadFromBootClasspath(name)) != null) {
                return ret;
            }
            if ((ret = loadFromSearchPath(name, resolve)) != null) {
                return ret;
            }
            if ((ret = parent.loadFromSearchPath(name, resolve)) != null) {
                log(loadClassOutcomeMsgFmt, this, name,
                        "6 - common/non-reloadable classpath delegation - via " + parent);
                return ret;
            }
            if ((ret = parent.loadFromSearchPath(name, resolve)) != null) {
                return ret;
            }
            throw createCnfe(name, null);
        }

        void validateName(String name) throws ClassNotFoundException {
            log("loadClass entry '{'\n\tloader = {0}\n\ttarget = {1}\n'}'", this, name);
            if ((name == null) || name.trim().isEmpty()) {
                throw createCnfe(name, null);
            }
        }

        Class<?> loadFromCache(String name) {
            Class<?> ret = getClass();
            if (ret.getName().equals(name)) {
                log(loadClassOutcomeMsgFmt, this, name, "1 - early return - own class");
                return ret;
            }
            if ((ret = findLoadedClass(name)) != null) {
                log(loadClassOutcomeMsgFmt, this, name, "2 - early return - pre-loaded/cached");
                return ret;
            }
            return null;
        }

        Class<?> loadFromBootClasspath(String name) {
            if (BOOT_CLASS_PATH_RES_NAMES.matcher(name).matches()) {
                ClassLoader defSysCl = ClassLoader.getSystemClassLoader().getParent();
                try {
                    Class<?> ret = ClassLoader.getSystemClassLoader().getParent().loadClass(name);
                    log(loadClassOutcomeMsgFmt, this, name, "4 - bootstrap classpath delegation - via " + defSysCl);
                    return ret;
                }
                catch (ClassNotFoundException cnfe) {
                }
            }
            return null;
        }

        Class<?> loadFromSearchPath(String name, boolean resolve) throws ClassNotFoundException {
            Class<?> ret = null;
            URL res = findResource(name.replace(".", "/") + ".class");
            if (res != null) {
                byte[] b;
                try {
                    b = readClassData(res);
                }
                catch (IOException ioe) {
                    throw createCnfe(name, ioe);
                }
                ret = defineClass(name, b, 0, b.length);
                if (resolve) {
                    resolveClass(ret);
                }
                log(loadClassOutcomeMsgFmt, this, name, "5 - freshly-defined from local search path");
                return ret;
            }
            return null;
        }

        ClassNotFoundException createCnfe(String name, Throwable cause) throws ClassNotFoundException {
            return new ClassNotFoundException(MessageFormat.format("Class loading : {0} : {1} : FAILED", this,
                    (name == null) ? "null" : name, cause));
        }

        void log(String msg, Object... args) {
            if (debug) {
                System.out.println(MessageFormat.format("\n" + msg + "\n", args));
            }
        }

        public void setDebug(boolean debug) {
            this.debug = debug;
        }

        @Override
        protected void finalize() throws Throwable {
            try {
                close();
            }
            finally {
                super.finalize();
            }
            log("ClassLoader finalization : {0}", this);
        }

    }

    public static class MasterLoader extends SlaveLoader {

        static final URL[] DEFAULT_CLASS_PATH = createSearchPath(System.getProperty("java.class.path"));

        private URL[] reloadableSearchPath = EMPTY_SEARCH_PATH;
        private volatile SlaveLoader slave;

        public MasterLoader(ClassLoader parent) {
            super(DEFAULT_CLASS_PATH, parent);
        }

        public synchronized void refresh(URL[] reloadableSearchPath) {
            int len;
            if ((reloadableSearchPath != null) && ((len = reloadableSearchPath.length) > 0)) {
                List<URL> path = new ArrayList<>(len + 1);
                for (int i = 0; i < len; i++) {
                    URL entry = reloadableSearchPath[i];
                    if (entry != null) {
                        path.add(entry);
                    }
                }
                this.reloadableSearchPath = (!path.isEmpty()) ? path.toArray(EMPTY_SEARCH_PATH) : EMPTY_SEARCH_PATH;
            }
            else {
                this.reloadableSearchPath = EMPTY_SEARCH_PATH;
            }
            if (slave != null) {
                try {
                    slave.close();
                }
                catch (IOException ioe) {
                }
                slave = null;
                /*
                 * At least two calls to System::gc appear to be required in order for Class::forName to cease
                 * returning cached classes previously defined by slave and for which the master served as an
                 * intermediary, i.e., an "initiating loader".
                 *
                 * See also http://blog.hargrave.io/2007/09/classforname-caches-defined-class-in.html
                 */
                for (int i = 0; i < 2; i++) {
                    System.gc();
                    try {
                        Thread.sleep(100);
                    }
                    catch (InterruptedException ie) {
                    }
                }
            }
            if (this.reloadableSearchPath != EMPTY_SEARCH_PATH) {
                log("Class loader search path refresh : {0}\n\tSearch path = {1}", this,
                        Arrays.toString(this.reloadableSearchPath));
                slave = new SlaveLoader(this.reloadableSearchPath, this);
                slave.setDebug(debug);
            }
        }

        @Override
        protected synchronized Class<?> loadClass(String name, boolean resolve) throws ClassNotFoundException {
            validateName(name);
            Class<?> ret = loadFromCache(name);
            if (ret != null) {
                return ret;
            }
            if ((slave != null) && ((ret = slave.loadFromCache(name)) != null)) {
                log(loadClassOutcomeMsgFmt, this, name, "3 - early return - pre-loaded/cached - via " + slave);
                return ret;
            }
            if ((ret = loadFromBootClasspath(name)) != null) {
                return ret;
            }
            if ((ret = loadFromSearchPath(name, resolve)) != null) {
                return ret;
            }
            if ((slave != null) && ((ret = slave.loadFromSearchPath(name, resolve)) != null)) {
                log(loadClassOutcomeMsgFmt, this, name,
                        "6 - reloadable classpath delegation - via " + ret.getClassLoader());
                return ret;
            }
            throw createCnfe(name, null);
        }

    }

}

Packaging
Once again correct the paths in com.example.app.App2; add App2 and com.example.app.Loaders to app.jar; and re-export. The other JARs should remain as in the former example.
Testing
Run as follows:
java -cp '/path/to/app.jar:/path/to/lib-api.jar' \
'-Djava.system.class.loader=com.example.app.Loaders$MasterLoader' \
com.example.app.App2

Sample output (loadClass debug omitted):
** lib class com.example.lib.impl.LibApiImpl / loaded by com.example.app.Loaders$SlaveLoader@7f31245a **

...

ClassLoader finalization : com.example.app.Loaders$SlaveLoader@7f31245a

...

** lib class com.example.lib.impl.LibApiImpl / loaded by com.example.app.Loaders$SlaveLoader@12a3a380 **


Question in undetermined coefficient method for ODE

Question: How should I formulate particular solution of this ODE? I want to use method of undetermined coefficients.
$$
y'' - y = e^x \\
y_H = C_1 e^x +C_2 x e^x
$$
$y_H,  y_P$ are homogeneous and particular solutions respectively.
From method of undetermined coefficients, I assume  $y_P = Ax^2 e^x + Bxe^x$
Is it valid to include first power of x? It is part of homogeneous solution.
$$
y^{'}_P=Be^x + ax^2 e^x + (2A+B)xe^x \\
y^{''}_P = e^x(2A+2B) + xe^x(4A+B) + Ax^2 e^x
$$
Substituting above values in given ODE,
$$
y^{''}_P - y_P = e^x (2A+2B) + xe^x (4A) = e^x
$$
Comparing coefficients,
$$
A=0 \\ B=\frac{1}{2} \\
\therefore y_P =\frac{1}{2} xe^x
$$
This result is wrong as it is homogeneous solution. Now, I take another particular solution.
$$
y_P = Ax^3 e^x + Bx^2 e^x \\
y^{'}_P= x^2 e^x (3A + B) + 2Bxe^x + Ax^3 e^x \\
y^{''}_P= 2B e^x + x e^x (6A + 4B) + x^2 e^x (6A + B) + A e^x x^3 \\
\therefore y^{''}_P - y_P = 2B e^x +  x e^x (6A + 4B) + 6A e^x x^2 = e^x \\
$$
Comparing coefficients,
$$
A=0 \\
6A + 4B = 0 \\
B=\frac{1}{2}\\
$$
Now, these conditions seem inconsistent.
Can someone please explain?
Comment: I got the mistake, thanks for replies. I went wrong in finding homogeneous solution.
Answer: Here, there is already a problem with the characteristic equation:
$$
r^2 - 1 = 0 \iff r = \pm 1
$$

I recommend you to take a look at the variation of constants:
$$
y_P = Ae^x + Be^{-x}
$$with $A,B$ such as
$$
A'e^x + B'e^{-x} = 0
$$
When you write the derivatives you get:
$$
y_P' = Ae^x - Be^{-x}
\\
y_P'' = Ae^x + A'e^x + Be^{-x} - B'e^{-x}
$$
so
$$
A'e^x + B'e^{-x} = 0\\
A'e^x - B'e^{-x} = e^x
\\\implies A' = \frac 12, B' = -\frac 12 e^{2x};
\\ A = \frac 12x + a, B = -\frac 14 e^{2x} + b
$$
and finally
$$
y_P = Ae^x + Be^{-x} = \frac 12xe^x -\frac 14 e^{x} + ae^x + be^{-x}, (a,b)\in\Bbb R^2
$$
or after simplification:
$$
y_P = Ae^x + Be^{-x} = \frac 12xe^x  + a'e^x + be^{-x}, (a',b)\in\Bbb R^2
$$
Answer: $y_p=C_1e^{x}+C_2e^{-x}$ and for the special solution of the inhomogeneous equation make the ansatz $(Ax+B)e^{x}$
Comment: the part $Be^x$ is useless.


Can legato notes be played staccato?

Question: I've been working on this piece by Sousa, and I came across this oddity:

Does this mean to play these notes somehow legato and staccato at the same time? If so, how would I play it? If not, what does it mean?
P.S., this is written for a Bb Cornet.
Comment: In terms of violin, what I would do is play those notes with the same bow (without changing the direction of the bow for the next note) while reducing the value of the 16th notes by half along with a half rest. I think these are called semi-staccatos. If you play windwood, then perhaps you blow once for both notes?
Comment: On the violin it is simply called staccato, well up bow staccato since you would typically play it with an up bow when it is an up beat. You would often play it that way whether the slurs are printed on the sheet or not. BUT since this is not a violin part it must mean something else, and you can see from the different answers below that it is a very opinion-based matter.
Answer: This could be an instance of portato. Via wikipedia:

Portato (Italian, past participle of portare, "to carry") in music
  denotes a smooth, pulsing articulation and is often notated by adding
  dots under slur markings.
Portato, also known as articulated legato or slurred staccato or
  semi-staccato or mezzo-staccato, that means "moderately detached". It
  is a style of playing between staccato and legato, and is also
  referred to as non-legato. Mezzo-staccato notes are held for a longer
  time than with standard staccato notes, but none of the notes is
  attached to the next.

This blog post describes the technique further, and mentions that this particular form of notation could also be interpreted as slim described:

Portato is sometimes called mezzo-staccato, and it can also be
  indicated with slurs over staccato marks.  However, slurs over
  staccatos does not always imply portato articulation:  sometimes a
  slur mark is not an articulation mark at all, but simply a structural
  indication of note groupings which might effect dynamic shaping and
  rubato instead of articulation.  In other words, composers are allowed
  to group even very staccato notes (marked with pointy "staccatissimo"
  signs) under a slur to indicate where phrases begin and end.
Answer: I concur with @slim regarding this being a phrase marking, and not a slur or legato mark.
I think the reason for it being there at all is to indicate that the two groups of three notes (F, A, D) are not to be phrased as such - rather, the semiquavers are to be phrased together in such a way as to stand apart from the D that follows.
Without the phrase marking, the 'default' assumption would be that the semiquavers are merely passing/grace notes leading to the D, which would render them less significant than if they were played as marked, in a (short) phrase of their own.
That said, I find it curious that this is only marked on the first line and not in the otherwise identical pattern that follows on the second - I'd have expected to see a simile instruction or similar*.
*No pun intended
Comment: Yes, I also found it odd that the second time does not have similar construction. It might have been a typo.
Answer: You should play this passage portato, as if each of the note were marked with a tenuto. I.e., you should detach each note, but play them to their full length.
Answer: It seems to me that a pair of notes cannot be both legato and staccato at the same time.
The only explanation that makes sense to me is that these are not slurs but phrase marks.
Per Wikipedia:

The slur is not to be confused with two other similar musical symbols.
  The tie is a curved line that links two notes of the same pitch to
  show that their durations are to be added together. The phrase mark is
  a curved line that extends over a passage which is visually
  indistinguishable from the slur, and indicates that the passage is to
  be interpreted as a single phrase.

So you should phrase such that the two staccato notes feel like a phrase on their own, rather than being part of a phrase including the preceding or following notes.
Answer: This is an articulation symbol called semi-staccato.  It is meant to be performed exactly as its name implies; halfway between smoothly connected and detached, with only a slight disconnect between the notes.  For any wind instrument, the semi-staccato notes in bars 2-3 would be performed with a very gentled tonguing on the notes indicated, such as using a "d" sound with the tongue on the back side of your front teeth, instead of a more pronounced "t" sound for regular staccato marks, as in bar 4.
You can find more information at this website:
http://www.abrahamdevar.com/theory-grade-2.html
Answer: You've gotten some great answers about the specific piece of music - I'll answer the more general question.
Legato literally means "bound together" - the sounds are connected.  Staccato literally means "detached" - there's a space between the sounds.  So you can't have a phrase that is both staccato and legato.
But the symbol we use for legato, the curved line over a set of notes, is also called a "phrase mark".  And phrases are not necessarily all legato.  So you CAN find examples of staccato notes under a phrase mark.  The notes under the mark are to be treated as a musical "sentence", and part of that sentence has a bit of a stutter in it.
Some composers will use a dashed phrase mark when it's a phrase, but not entirely a legato phrase.  I've heard this began with Bartók, but I haven't done any research to see if that's true.  But in my opinion that makes things really clear - and a composer can build a phrase that contains both legato bits and staccato notes while still giving the musician important clues about how to perform it.
Comment: Are you sure that it began with Bartok(the dashed phrase mark I mean)? Because I have heard of dashed slurs being used back in Mozart's era. That is more than a century between Mozart and Bartok.
Answer: It is possible to play both legato and staccato at the same time.  Legato means "tied together", and as Widor says you want these notes to be "phrased together"; those concepts are obviously closely related and, depending on the interpretation, may be considered one and the same.  I'd disagree with Wikipedia — legato doesn't strictly mean that the notes need to be played with no intervening silence, though that is the natural interpretation in its most common usage.  Try playing staccato notes smoothly; it's quite a fun exercise.
Answer: I play the French horn and we see this sort of thing all the time in our music. Many of the answers mention phrase markings, and I think that's a fitting term. I've always been told that it meant to play them legato, but tongue them. If you're playing in an ensemble, you might want to check with the other members to see how they are handling it.
Answer: This is NOT a phrase mark.  You don't use a phrase mark to connect two sixteenths.  This is an indication that the notes should be played connected, but still re-articulated.
Answer: Yes.  Legato is a matter of performance, and staccato is a matter of note articulation.  To me, in terms of a guitar, this means I would play short notes, but I would hammer-on to the second note to obey the legato marking.
I'm not sure exactly how this translates to brass, but I imagine a single tonguing, or maybe two distinct tonguings with no gap between the notes.
Comment: This doesn't solve the mystery for me. From your WP links: Legato - "in transitioning from note to note, there should be **no intervening silence**. "; Staccato - "a note of shortened duration, **separated from the note that may follow by silence**". They seem to be mutually exclusive.
Comment: I got to thinking later that they were something other than legato markings, but it was bedtime.
Answer: These notes are to be played legato but slightly detached.
Another name for this is portato.
Answer: I would guess that it's a string player artifact: with string players, the combination of slur and staccato is indicating detached notes played without changing bowing direction.
Now either this part is doubled by strings (in which case the slur is not interesting for the cornet), or it indicates similar articulation.  What would that be?  Staccato by just stopping the breath without tongue/lip action?
Comment: No, this is written for a band with brass, wind, and percussion sections. No strings.

Can legato notes be played staccato?


PHP difference between two times

Question: I want to find the difference between two times. I have only time stored in database. I don't have date stored.
Note : Time is in string format.
Case 1:
 Starting time : 06:18:09
 Ending time :  06:18:45

Case 2:
Starting time : 06:03:35
Ending time 06:18:04

Case 3: [This case isn't working ]
Starting time : 23:44:56
Ending time : 00:45:43

I'm using this code to find in seconds.But not working for me.
$datetime1 = date_create($a);
  $datetime2 = date_create($b);
  $interval = date_diff($datetime1, $datetime2);
 $min=$interval->format('%s');

Any helps ?
Thanks!
Comment: The solution is here: http://stackoverflow.com/questions/13928021/getting-time-difference-between-two-times-in-php
Comment: Yes! I tried your method. But for this Starting time : 23:48:02 Ending time : 00:15:12 doesn't work. Thank you!
Answer: Substring at the first colon to remove the label, then use the remaining time stamp for parsing and subtracting.
Use PHP's strtotime method to convert the times as strings into longs, then subtract the two to find the difference in seconds. You'll have a number at this point, which you can then do whatever with.
$datetime1 = substr($datetime1, strpos($datetime1, ":"));
$time1 = strtotime($datetime1);

You can then use the date method to convert the time difference into a new string for outputting.
See:

http://php.net/manual/en/function.substr.php
http://php.net/manual/en/function.strtotime.php
http://php.net/manual/en/function.strpos.php
http://php.net/manual/en/function.date.php
Comment: Yes! I tried your method. But for this Starting time : 23:48:02  Ending time : 00:15:12  doesn't work. Thank you!
Comment: It won't work because there is an overflow. Check if the second time is less than the first time, and if it is, add 24 hours worth of time to the second.
Comment: Yes. I also thought that to add 24 hours since second time is less than first. Again thank you so much sir!
Comment: subtracting 23:00 from 00:23 error

PHP difference between two times


Outlook Anywhere and Authentication

Question: Environment:
Windows 2008R2 and 2003 DCs
Exchange 2007 two servers, one client access/hub server, one mailbox server. Outlook Anywhere is configured.
Windows Vista, Windows 7 Clients, Mix of Outlook 2007/2010.
Here's what's happening:
On the LAN: Clients occasionally get prompted for password, never fails to authenticate.
From the Outside: Clients almost always get prompted for password, it will either work, or prompt for password over and over and over.
I see three places for me to make adjustments here:

The client and choose NTLM or Basic authentication, since this is over HTTPS, I have no preference.
The directories in IIS on the OWA server have authentication properties you can set, I've ticked a few of these on and off to no avail (basic, windows integrated, etc).
From Exchange Management Console, you can choose basic or NTLM.

I imagine these all need to align, but what's the RIGHT way to set this up? I've tried to find some authoritative Microsoft articles, but I'm banging my head on the table here.
Answer: I'm hoping this is the solution. For some reason my google-fu never found this. I had to read through every document on technet to get here:
When Exchange 2007 is run under Windows Server 2008, clients who use Exchange 2007 may be repeatedly prompted for their credentials during Outlook Anywhere sessions. This issue occurs when NTLM Authentication is selected as the authentication method in the Exchange Proxy Settings dialog box for the Outlook profile on the client computer. This issue does not occur if Basic Authentication is selected as the authentication method in the Exchange Proxy Settings dialog box. By default, Kernel Mode Authentication is enabled in Internet Information Services (IIS) 7.0 on Client Access servers that are running Windows Server 2008 with versions of Exchange 2007 that are earlier than Exchange Server 2007 Update Rollup 8. This issue does not occur with the following versions of Exchange 2007:
Exchange Server 2007 Service Pack 1 (SP1) with Update Rollup 8
Exchange Server 2007 Service Pack 2 (SP2)
To resolve this issue, disable Kernel Mode Authentication for Client Access servers that are running Windows Server 2008.
To disable Kernel Mode Authentication for Client Access servers that are running Windows Server 2008
At a command prompt, type the following command, and then press ENTER:
%systemroot%\system32\inetsrv\AppCmd.exe set config /section:system.webServer/security/authentication/windowsAuthentication /useKernelMode:false
Comment: wow, many thakns for returning back to us here, however "This issue does not occur if Basic Authentication is selected as the authentication method in the Exchange Proxy Settings dialog box' --> is that OK since we are using TMG 2010 ?
Comment: No idea... still on 2007 here. I have observed also that the issue seems persistent when both when both exchange and the user are behind NAT's to the similarly addressed private networks. Example: I'm at home using 192.168.1.0/24 behind my router, and so is my office behind theirs. I haven't had time to figure this one out :)
Comment: ahh. ok, I'll post something else then. thanks forgetting back to me.

Outlook Anywhere and Authentication


How to find number of contributors for a repository?

Question: Is there any way to find the number of contributors of a project via the GitHub API? Such information is available on the main page of each project, but it doesn't seem to be present in the API.
For example, we could find the number of contributors on https://github.com/nodejs/node:

but this key isn't present in https://api.github.com/repos/nodejs/node.
Comment: Yes, that's what you'll have to do. Read the docs: if they don't list it, you can't get it. In your case you could make two requests: get the first page, get the last page (from the `Link` header), calculate `(first_page_length * (page_count - 1)) + last_page_length`
Comment: Did you read the docs? You can get the [contributor list](https://developer.github.com/v3/repos/#list-contributors) and then use its length. You will have to deal with paging, though, by the looks of it. In general: if it's not in the API docs, then you can't do it.
Comment: Ah it did, sorry; I think that was in my clipboard from your other question! But yes, `/issues` and `/contributors` (like all paginated resources in the GitHub API) both have a `Link` response header.
Comment: In the case of big projects, as https://github.com/nodejs/node/, we should itterate over all pages, which will provoke many request. Not cleanest way and the risk to be blocked if too much requests. I don't need all data of all contributors, just one simple number.
Comment: @jonrsharpe Sorry, didn't understood Your hint about the last page and Link header.
Comment: Per [the API docs](https://developer.github.com/v3/issues/#list-issues-for-a-repository), the response includes a `Link` header which contains links to the next *and last* pages of the results. This means that, assuming every other page *except* possibly the last one has as many results as the first page, you can figure out the total count with only two requests.
Comment: I see. Meanwhile Your link point to issues, not contributors. I've found similar Link header in collaborator query : `curl -i https://api.github.com/repos/nodejs/node/contributors`. Thanks for the hint.
Answer: Sorry to say, but it easier to read from page then from API.
Sample with page parsing from https://github.com/pimcore/pimcore using Google Spreadsheet:
<code>=INDEX(IMPORTXML($F2, "//a[contains(text(), 'Contributors')]"),2)
</code>
You can do the same with any XPath loader.
To do the same from API we need to iterate pages until receive error 404:
https://api.github.com/repos/pimcore/pimcore/contributors?per_page=100&page=1
Documentation is here:
https://docs.github.com/en/free-pro-team@latest/rest/repos/repos?apiVersion=2022-11-28#list-repository-contributors
Comment: Google Spreadsheet sample to compare GitHub repositories https://docs.google.com/spreadsheets/d/1eDbZezk2TcO-AZ4sz1miVEDnZI1Wx_YGRmHscs1Gg_8/edit#gid=0


Is the permutation in $S_1$ even or odd?

Question: A permutation is even or odd depending on whether it can be written as an even or odd number of transpositions. However, the permutation in $S_1$ cannot be written as a product of transpositions, so is it just undefined?
Comment: It can be written as the product of $0$ transpositions.
Comment: This follows from the same idea that an empty sum is equal to zero, and an empty product is equal to $1$.
Comment: Its subgroup $A_1$ is the group of even permutations. Since $\{ e \}<A_1<S_1=\{e\}$ (where $e$ is the identity of $S_1$), we have $S_1=A_1$ so $e$ is even.
Comment: The sign of a permutation can be thought of as the determinant of the corresponding permutation matrix. And the determinant of $[1]$ is $1$.
Comment: After you ask a question here, if you get an acceptable answer, you should "accept" the answer by clicking the check mark $\checkmark$ next to it. This scores points for you and for the person who answered your question. You can find out more about accepting answers here: [How do I accept an answer?](http://meta.math.stackexchange.com/questions/3286/), [Why should we accept answers?](http://meta.math.stackexchange.com/questions/3399/), [What should I do if someone answers my question?](https://math.stackexchange.com/help/someone-answers).
Answer: It can be written as the product of $0$ transpositions, and $0$ is an even number, making it an even permutation. This is not just true of the permutation in $S_1$, it's true of the identity element in every symmetric group $S_n$.
Answer: Hint: Since zero is even, what can we conclude?


How to prepared statements with Laravel

Question: I am trying to run a statement to create a database and a user, but it seems laravel continues to run weird queries. My code is as follows:
<code>$res = DB::statement("CREATE DATABASE IF NOT EXISTS `?`", array($databaseName));
$res2 = DB::statement("CREATE USER '?'@'%' IDENTIFIED BY '?'", array($databaseName, $password));
return $res . " - " . $res2;
</code>
I would expect the database to be created and a "true" result, but the query still gives me a false response and no database is created. Trying to run a statement with the $databaseName variable inside the query in a "dirty way" works, so I think there's something wrong with prepared statements. Which would be the right way to do it?
Thank you! :)
Update:
I've managed to do it, but it seems there are still SQL-injection issues because I'm still not able to use prepared statements. The first solution I've found is the following one:
<code>$res = DB::statement("CREATE DATABASE IF NOT EXISTS `{$databaseName}`");
$res2 = DB::statement("CREATE USER '{$databaseName}'@'%' IDENTIFIED BY '{$password}'");
return $res . " - " . $res2;
</code>
Comment: I believe your bindings are automatically quoted so there might be a possibility that you just created the database `'db_name'` with the quotes around it.  Did that one get created?
Comment: Not in this case, but using variables (like \`?\`) you're right: they are quoted and the query generated causes the database name to be malformed.
Eg.:

    `DB::statement("CREATE USER '?'@'%' IDENTIFIED BY '?'", array($databaseName, $databasePassword));`

Isn't there a way to fix it?
Answer: Here's the code I've found that works:
<code>DB::connection('database')->statement("CREATE USER '{$mysqlDatabaseName}'@'%' IDENTIFIED BY '{$mysqlUserPassword}'");
DB::connection('database')->statement("CREATE DATABASE IF NOT EXISTS `{$mysqlDatabaseName}`");
DB::connection('database')->statement("GRANT ALL PRIVILEGES ON `{$mysqlDatabaseName}`.* TO '{$mysqlDatabaseName}'@'%'");
</code>
However, before you run these queries, you must make sure you have no SQL-injection in your code.
Hope this will help somebody else! :)
Comment: It helped, i was like you, no way to make this work, tried without quotes, tried with named parameters (:id) ...etc Only your solution worked. Is it a bug ?
Comment: I'm not sure if this is the way you are supposed to deal with it, but to be honest since it works i don't care about it anymore. Yeah, it's not a clean solution, but right now it's not a huge deal :)

How to prepared statements with Laravel


Css focus beginner

Question: I'm a beginner in CSS and already hate it :(. When the user will click outside of the calendar, I want the calendar to disappear.
Here is the html code for the calendar:

I tried:
.RadCalendar_Default .rsHeader a.rsDatePickerCalendar:hover
{
    visibility:hidden !important;
}
But it's not working.
Comment: Your title has nothing to do with your question.
Comment: I don't think what you want is possible with just css.
Answer: First, instead of visibility: hidden;, I recommend to use display: none; to hide elements. Otherwise you may have undesired side-effects.
Then, the :hover pseudo-class doesn't handle click events, it's just active, if the user (as the name suggests) is hovering the element with the cursor. To change the appearance of an element on a click, use jQuery like this:
$('body').bind('click', function() {
    $(".RadScheduler", this).addClass("hide");
});

and have a css rule like this:
.hide { display: none; }

Comment: @Nikosinathi But the class isn't called RadScheduler
Comment: You need to replace "RadScheduler" with whatever identifier you're using to target the element you want to hide.

Css focus beginner


Statistical significance test: One way Anova and Kruskal-Wallis test

Question: I was comparing data between two groups and for each group there was six samples.
My data are as follows:
group 1: 103.56, 103.32, 103.32, 104.27, 103.56, 103.8
group 2: 97.16, 97.16, 96.69, 98.58, 90.76, 97.64
I ran one way Anova and also kruskal-Wallis test for both the groups. The p-value from Anova was much smaller than 0.05 indicating that at 0.05 significance level there was a significant difference between the data sets of the two groups. The p value from kruskal-Wallis test was  0.3553 (> 0.05) indicating that at 0.05 significance level, there was no significant difference between the two data sets of the groups.
I will really appreciate if someone could give me some insight on why I am getting different p values for the same data set by running these two tests.
Comment: They make different assumptions about your data, & those assumptions have value. If you have only 2 groups, why didn't you try a t-test & a Mann-Whitney U-test? What software did you use? I don't get a p-value of .35 for KW. Can you paste your code or output?
Answer: In general, you wouldn't necessarily expect one way ANOVA and the Kruskal-Wallis to be similar, sometimes they can give quite different p-values. See here for a little partial motivation for why you might expect a difference. [When samples are reasonably normal-looking and with means not too many standard errors apart, they often tend to give similar p-values. Outside that, they frequently don't.]
However, in this case the reason is more prosaic: Your Kruskal-Wallis p-value is wrong.
Here's a summary of results in R (details below).
                     p-value
Welch t-test:        0.001287
Equal-var. t-test:   8.552e-05
One way anova:       8.55e-05
Wilcoxon test:       0.004847
Kruskal-Wallis:      0.003761

(Neither of the last two p-values are exact; if they were, you'd get the same p-value for the two-group comparison.)
Your problem is you're treating the second group's data as a factor (see the end of this answer).

Here's what I get in R with your data:
frh <- data.frame(group1 = c(103.56, 103.32, 103.32, 104.27, 103.56, 103.8),
                  group2 = c( 97.16,  97.16,  96.69,  98.58,  90.76,  97.64))

# strip chart:

# Welch t-test:
> with(frh,t.test(group1,group2))

    Welch Two Sample t-test

data:  group1 and group2
t = 6.3316, df = 5.163, p-value = 0.001287
alternative hypothesis: true difference in means is not equal to 0
95 percent confidence interval:
  4.368147 10.245186
sample estimates:
mean of x mean of y
103.63833  96.33167

$\,$
# equal-variance t-test:
> with(frh,t.test(group1,group2,var.equal=TRUE))

    Two Sample t-test

data:  group1 and group2
t = 6.3316, df = 10, p-value = 8.552e-05
alternative hypothesis: true difference in means is not equal to 0
95 percent confidence interval:
 4.735411 9.877922
sample estimates:
mean of x mean of y
103.63833  96.33167

$\,$
#one way anova:
summary(aov(values~ind,stack(frh)))
            Df Sum Sq Mean Sq F value   Pr(>F)
ind          1 160.16   160.2   40.09 8.55e-05 ***
Residuals   10  39.95     4.0

$\,$
# Wilcoxon-Mann-Whitney:
> with(frh,wilcox.test(group1,group2))

    Wilcoxon rank sum test with continuity correction

data:  group1 and group2
W = 36, p-value = 0.004847
alternative hypothesis: true location shift is not equal to 0

Warning message:
In wilcox.test.default(group1, group2) :
  cannot compute exact p-value with ties

$\,$
# Kruskal-Wallis test:
> kruskal.test(frh)

    Kruskal-Wallis rank sum test

data:  frh
Kruskal-Wallis chi-squared = 8.3958, df = 1, p-value = 0.003761

Those are all about as consistent with each other as I would expect on that data.

Now, here's how to get what you got for the Kruskal-Wallis:
with(frh,kruskal.test(group1,group2))

    Kruskal-Wallis rank sum test

data:  group1 and group2
Kruskal-Wallis chi-squared = 4.3939, df = 4, p-value = 0.3553

The problem is, if you're getting this, you're using it wrong. That's not how the function works - group2 is being treated as a factor defining different groups for data in group1.
So the main reason the Kruskal Wallis isn't giving you a roughly similar p-value to ANOVA is you didn't call it correctly.
Comment: @gung Several things going on. Neither are exact for ties (the wilcox.test output even warns you!) and K-W merely uses the chi-square approximation for the test statistic (its help explains how to get exact p-values by using a function in another package - `coin`). So they're both inexact, and not in the same way; if you do them both exactly, then they should be the same. If I wanted an effectively exact answer, I could run a permutation/randomization test on the ranks far quicker than I could load `coin` and get the syntax right.
Comment: Any thoughts on why the p-values differ for MW & KW? I would have thought they'd be identical (as, eg, the t-test & ANOVA are)?
Comment: @gung In fact the exact two-tailed p-value is 2/924 $\approx$ 0.00216 ... (using `combn` and the sum of the ranks in the first sample)
Comment: @gung in fact because the samples don't overlap at all, one can do it with simple mental arithmetic; one need only count how many arrangements into two groups of six there are (keeping in mind the pattern of ties); that will be the denominator, and since only the most extreme arrangement counts in the p-value, for a two-tailed test the numerator must be 2.


How to calculate Schoenfeld Residuals in R

Question: I am trying to manually calculate the schoenfeld residuals in Cox model. Please see the code below.  Sresid gives the calculation in cox.zph function using schoenfeld residuals. Schoenfeld gives the result in r when based on own code. These two output are different. How can I make sresid=Schoenfeld?
> rm(list=ls()); set.seed(1234)
> library("survival")
> hmohiv<-read.table("https://stats.idre.ucla.edu/stat/r/examples/asa/hmohiv.csv", sep=",", header = TRUE)
> attach(hmohiv)
> #______Schoenfeld Residuals from coxph()__________
> res.cox<-coxph( Surv(time, censor)~drug+age)
> sresid <- residuals(res.cox, "schoenfeld")
> #______________Own code__________
> beta<-as.matrix( c (res.cox$coefficients[1], res.cox$coefficients[2]) )
> newdata <- hmohiv[ which(censor==1), ]
> OrderedData <- newdata[order(newdata$time), ]; #order the data according to the event times
> x_ordered<-as.matrix(OrderedData[,3:4]) #Consider x1 and x2.
> n<-80 #length of newdata;
> Numerator1<-numeric(n);Numerator2<-  numeric(n);Denominator<-numeric(n)
> Num1<-  numeric(n);Num2<-  numeric(n);Den<-numeric(n)
> for(j in 1:n) {
  Numerator1[j] <- x_ordered[j,1]*exp( x_ordered[j,]%*%beta)
  Numerator2[j] <- x_ordered[j,2]*exp( x_ordered[j,]%*%beta)
  Denominator[j]<-exp( x_ordered[j,] %*%beta) }
> for(j in 1:n) {
  Num1[j] <- sum(Numerator1[j:n])
   Num2[j]<- sum(Numerator2[j:n])
   Den[j] <- sum(Denominator[j:n]) }
> Schoenfeld<-as.matrix(cbind( (x_ordered[,1]-Num1/Den), (x_ordered[,2]-Num2/Den))  )
> head(Schoenfeld) #Residuals based on own code
         [,1]        [,2]
13  -9.755948  0.98106142
16 -17.756333 -0.01889986
28  -6.756333  0.98110014
32 -12.761970 -0.01808142
52 -22.761991 -0.01808145
54  -3.761991  0.98191855
> head(sresid) #Residuals based on res.cox
       drug       age
1  0.300015  4.090062
1 -0.699985 -3.909938
1  0.300015  7.090062
1 -0.699985  1.090062
1 -0.699985 -8.909938
1  0.300015 10.090062

Answer: Ok, to start with you can tell who is wrong by looking at sums. The Schoenfeld residuals add up to the partial likelihood score, which is zero by construction at $\beta=\hat\beta$.
> colSums(Schoenfeld)
[1] -936.12129   36.28693
> colSums(sresid)
         drug           age
 2.373102e-15 -2.877698e-13

I'm going to try to make minimal changes to your code; this is not how I would have done the coding.
Ok. One problem is this
newdata <- hmohiv[ which(censor==1), ]
OrderedData <- newdata[order(newdata$time), ]; #order the data according to the event times
x_ordered<-as.matrix(OrderedData[,3:4]) #Consider x1 and x2.

There is only a Schoenfeld residual at event times, but Numerator1 and Numerator2 and Denominator need to use all individuals in the risk set, including people who will be censored in the future, who you are leaving out.
A second problem is this
> head(x_ordered)
   age drug
13  44    1
16  36    0
28  47    1
32  41    0
52  31    0
54  50    1
> beta
           [,1]
drug 1.01669835
age  0.09714082

You've got the variables around the wrong way.
Fixing these, we get
>  head(Schoenfeldr) #Residuals based on own code
         [,1]      [,2]
13  0.2818468  3.740749
16 -0.7106238 -4.159318
28  0.2862046  6.822119
32 -0.7031342  1.076245
52 -0.7084648 -8.915596
54  0.2894962 10.058744

which is still wrong but a lot closer.
Next, ties:
> length(unique(hmohiv$time))
[1] 31
> sum(hmohiv$censor)
[1] 80

Your Numerator and Denominator should be constant for observations at the same time, but they aren't. This means that if you change the starting order for hmohiv, your Schoenfeld residuals change but the built-in ones don't.
Fixing this gives us
> head(Schoenfeldr)
         [,1]       [,2]
13  0.2818468  3.7407492
16 -0.7181532 -4.2592508
28  0.2818468  6.7407492
32 -0.7181532  0.7407492
52 -0.7181532 -9.2592508
54  0.2818468  9.7407492
> head(sresid)
       drug       age
1  0.300015  4.090062
1 -0.699985 -3.909938
1  0.300015  7.090062
1 -0.699985  1.090062
1 -0.699985 -8.909938
1  0.300015 10.090062

That doesn't quite work.  The next issue is more subtle, but again is ties.
The formula for the Schoenfeld residuals is more complicated with the default Efron approximation to ties, because the approximation changes how the numerator and denominator are calculated. If we switch to the Breslow approximation, we do get exact agreement:
rm(list=ls()); set.seed(1234)
 library("survival")
 hmohiv<-read.table("https://stats.idre.ucla.edu/stat/r/examples/asa/hmohiv.csv", sep=",", header = TRUE)
 #______Schoenfeld Residuals from coxph()__________
 res.cox<-coxph( Surv(time, censor)~drug+age, data=hmohiv,ties="breslow")
 sresid <- residuals(res.cox, "schoenfeld")
 #______________Own code__________
 beta<-as.matrix( c (res.cox$coefficients[1], res.cox$coefficients[2]) )
 OrderedData <- hmohiv[order(hmohiv$time), ] #order the data according to the event times
 x_ordered<-as.matrix(OrderedData[ ,4:3]) #Consider x1 and x2.
 n<-nrow(OrderedData)
 Numerator1<-numeric(n);Numerator2<-  numeric(n);Denominator<-numeric(n)
 Num1<-  numeric(n);Num2<-  numeric(n);Den<-numeric(n)
 for(j in 1:n) {
  Numerator1[j] <- x_ordered[j,1]*exp( x_ordered[j,]%*%beta)
  Numerator2[j] <- x_ordered[j,2]*exp( x_ordered[j,]%*%beta)
  Denominator[j]<-exp( x_ordered[j,] %*%beta)
 }

 for(j in 1:n) {
   thistime<-OrderedData$time[j]
   riskset <- which(thistime<=OrderedData$time)
   Num1[j] <- sum(Numerator1[riskset])
   Num2[j]<- sum(Numerator2[riskset])
   Den[j] <- sum(Denominator[riskset])
 }

Schoenfeld<-as.matrix(cbind( (x_ordered[,1]-Num1/Den), (x_ordered[,2]-Num2/Den))  )
Schoenfeldr<- Schoenfeld[OrderedData$censor==1, ]

Now we get
>  head(Schoenfeldr) #Residuals based on own code
         [,1]       [,2]
13  0.2957278  3.9555414
16 -0.7042722 -4.0444586
28  0.2957278  6.9555414
32 -0.7042722  0.9555414
52 -0.7042722 -9.0444586
54  0.2957278  9.9555414
>  head(sresid) #Residuals based on res.cox
        drug        age
1  0.2957278  3.9555414
1 -0.7042722 -4.0444586
1  0.2957278  6.9555414
1 -0.7042722  0.9555414
1 -0.7042722 -9.0444586
1  0.2957278  9.9555414

PS: attach() is increasingly unpopular these days, for good reason.
Comment: Thank you for the well detailed answer. However, I still get different Chi-square values for own code as compared to the cox.zph() function.
https://stats.stackexchange.com/questions/531481/computing-chi-square-values-from-schoenfeld-residuals


XMl parse in SQL Server

Question: I have this xml structure.I use the following  sql to read the values but it doesnt work
DECLARE @x XML =
'<Events>
  <Event DateTimeGMT="25/10/2013 18:45:00" Branch="Soccer" Sport="Soccer" BranchID="1" League="England - Championship" LeagueID="10099" ID="5693075" IsOption="0" EventType="0" MEID="2673883">
    <Participants>
      <Participant1 Name="Middlesbrough" Home_Visiting="Home" />
      <Participant2 Name="Doncaster" Home_Visiting="Visiting" />
    </Participants>
    <MoneyLine Home="1.69" Draw="3.7" Away="5" />
    <Spread Home_Odds="1.885" Home_Points="-0.75" Away_Points="0.75" Away_Odds="1.962" />
    <Total Points="2.75" Over="2.06" Under="1.763" />
  </Event>
  <Event DateTimeGMT="25/10/2013 18:45:00" Branch="Soccer" Sport="Soccer" BranchID="1" League="England - Championship" LeagueID="10099" ID="5693993" IsOption="1" EventType="200" MEID="2673883">
    <Participants>
      <Participant1 Name="Middlesbrough" Home_Visiting="Home" />
      <Participant2 Name="Doncaster" Home_Visiting="Visiting" />
    </Participants>
    <Total Points="4.5" Over="5.75" Under="1.125" />
  </Event>
</Events>
'
DECLARE @iDoc INT
EXECUTE sp_xml_preparedocument @iDoc OUTPUT, @x

SELECT  *
FROM    OPENXML(@iDoc,'/Events/Event')
WITH    (
ID int '@ID',
DateTimeGMT [varchar](100) '@DateTimeGMT',
Branch [varchar](100) '@Branch',
Sport [varchar](100) '@Sport',
BranchID int '@BranchID',
League [varchar](100) '@League',
LeagueID int '@LeagueID',
IsOption int '@IsOption',
EventType int '@EventType',
MEID int '@MEID',
QAID int '@QAID',
EventName [varchar](500) '@EventName',
Home [varchar](100) '../Event/Participants/Participant1/@Name',
Away [varchar](100) '../Event/Participants/Participant2/@Name',
[1] [varchar](5) '../Event/MoneyLine/@Home',
[X] [varchar](5) '../Event/MoneyLine/@Draw',
[2] [varchar](5) '../Event/MoneyLine/@Away',
Spread_Home_Points float '../Event/Spread/@Home_Points',
Spread_Home_Odds float '../Event/Spread/@Home_Odds',
Spread_Away_Points float '../Event/Spread/@Away_Points',
Spread_Away_Odds float '../Event/Spread/@Away_Odds',
Total_Points float '../Event/Total/@Points',
Lart float '../Event/Total/@Over',
Posht float '../Event/Total/@Under'
        )

EXECUTE sp_xml_removedocument @iDoc

But this doent give a correct answer. On the second row that doesnt fine MoneyLine it repeats the first row values.

The values marked with circle showld be empty.Any help please?
Comment: can you make the output readable/view-able/larger?
Comment: I croped a bit the picture
Answer: The XPath expressions you are using are not matching the Event element you are after. Considering only the 1, X and 2 columns, their XPath expressions should be:
[1] [varchar](5) 'MoneyLine/@Home',
[X] [varchar](5) 'MoneyLine/@Draw',
[2] [varchar](5) 'MoneyLine/@Away',

This way, they will be relative to the Event element you are considering. With your original expressions, they pointed to the first Event element of the parent of the row being processed and this is why they behaved wrongly. The same considerations apply for every other expression in your block of code starting with ../Event.
Comment: Can you help with my new xml?
Answer: I suggest to use nodes() method for reading xml in SQL server, it's much easier to use. For your XML it could be something like this:
select
    T.C.value('@DateTimeGMT', 'varchar(100)') as DateTimeGMT,
    T.C.value('@Branch', 'varchar(100)') as Branch,
    T.C.value('@BranchID', 'int') as BranchID,
    T.C.value('@League', 'varchar(100)') as League,
    T.C.value('@LeagueID', 'int') as LeagueID,
    T.C.value('@IsOption', 'int') as IsOption,
    T.C.value('@EventType', 'int') as EventType,
    T.C.value('@MEID', 'int') as MEID,
    T.C.value('@QAID', 'int') as QAID,
    T.C.value('@EventName', 'varchar(500)') as EventName,
    T.C.value('(Participants/Participant1)[1]/@Name', 'varchar(100)') as Home,
    T.C.value('(Participants/Participant2)[1]/@Name', 'varchar(100)') as Away,
    T.C.value('(MoneyLine)[1]/@Home', 'varchar(5)') as [1],
    T.C.value('(MoneyLine)[1]/@Draw', 'varchar(5)') as [X],
    T.C.value('(MoneyLine)[1]/@Away', 'varchar(5)') as [2],
    T.C.value('(Spread)[1]/@Home_Points', 'float') as Spread_Home_Points,
    T.C.value('(Spread)[1]/@Home_Odds', 'float') as Spread_Home_Odds,
    T.C.value('(Spread)[1]/@Away_Points', 'float') as Spread_Away_Points,
    T.C.value('(Spread)[1]/@Away_Odds', 'float') as Spread_Away_Odds,
    T.C.value('(Spread)[1]/@Away_Odds', 'float') as Spread_Away_Odds,
    T.C.value('(Total)[1]/@Points', 'float') as Total_Points,
    T.C.value('(Total)[1]/@Over', 'float') as Lart,
    T.C.value('(Total)[1]/@Under', 'float') as Posht
from @x.nodes('Events/Event') as T(C)

sql fiddle demo
To get data from element filtered by attribute, you can use xpath:
select
    T.C.value('(Participants/Participant[@Name="Odd"]/Odds)[1]/@OddsValue', 'float') as Odd,
    T.C.value('(Participants/Participant[@Name="Even"]/Odds)[1]/@OddsValue', 'float') as Even
from @x.nodes('Events/Event') as T(C)

sql fiddle demo
Comment: Yes this works ok but if you see my second answer when i add a different node i cannot get all the parameters there. Please check my second answer
Comment: @user1361208 dont' know what exactly you want. Updated answer to show how can you filter xml by attribute value. Answered your other question with another way of parsing - all participants to the rows
Answer: Apart of Efran's answer (+1) I would use nodes and value methods (ref)  to query XML:
SELECT  x.XmlCol.value('(@ID)[1]', 'INT') AS [ID],
        x.XmlCol.value('(@DateTimeGMT)[1]', '[varchar](100)') AS [DateTimeGMT],
        x.XmlCol.value('(Sport)[1]', '[varchar](100)') AS [Sport],
        -- ...
        x.XmlCol.value('(Participants/Participant1/@Name)[1]', '[varchar](100)') AS [Home],
        x.XmlCol.value('(Participants/Participant2/@Name)[1]', '[varchar](100)') AS [Away],
        -- ...
        x.XmlCol.value('(MoneyLine/@Home)[1]', '[varchar](5)') AS [1],
        x.XmlCol.value('(MoneyLine/@Draw)[1]', '[varchar](5)') AS [X],
        x.XmlCol.value('(MoneyLine/@Away)[1]', '[varchar](5)') AS [2]
FROM    @x.nodes('/Events/Event') x(XmlCol);

XMl parse in SQL Server


How do I get the video media path in a theme?

Question: I want to embed a video on a page.
How do I display the field_media_video_embed_field in my twig?
The complicated thing about this is that I am using a view inside tabs.
<code>{{ kint(programme.video) }}</code> gives me the following output.

In my theme I have used the following code.
<code>$programmes = [];
$view = Views::getView('participating_programmes');
$view->execute();
foreach ($view->result as $row) {
  $video = $row->_entity->get('field_pvideo')->referencedEntities();
  $programmes[$nid]['video'] = $video;
}
</code>
Ideally I want to embed the video, but I would be happy if I could just get the field_media_video_embed_field and work from there.
Comment: Try `{{ kint(programme.video.field_media_video_embed_field.value) }}`
Comment: Sorry, that returns NULL
Comment: The comment is correct about the field value. The problem is that referencedEntities() returns an array when you probably only want a single entity. See my answer.
Answer: It's unclear whether you want to get one or multiple videos:
<code>// get one video media entity
$video = $row->_entity->get('field_pvideo')->entity;
// get multiple video media entities
$videos = $row->_entity->get('field_pvideo')->referencedEntities();
</code>
Then in Twig for one video:
<code>{{ programme.video.field_media_video_embed_field.value }}
</code>
or multiple videos:
<code>{% for video in programme.videos %}
  {{ video.field_media_video_embed_field.value }}
{% endfor %}
</code>


Does the multiplication of countably infinite many numbers between $0$ and $1$ equal $0$?

Question: Suppose every term of a countably infinite sequence $x_1,x_2,\dots$ is between $0$ and $1$, i.e. $0<x_i<1$ for every $i$. Does $\mathop {\lim }\limits_{n \to \infty } \prod\limits_{i = 1}^n {{x_i}} $ equal $0$ or there is counterexample that it might not be $0$? Thank you!
Comment: Look up [infinite product](https://en.wikipedia.org/wiki/Infinite_product)
Answer: Let $(a_i)$ be a strictly increasing sequence of positive numbers which is bounded above. Such a sequence necessarily converges, call the limit $a$. Now set $x_i = \frac{a_i}{a_{i+1}}$. Then $0 < x_i < 1$ and
$$\prod_{i=1}^nx_i = x_1\dots x_n = \frac{a_1}{a_2}\dots\frac{a_n}{a_{n+1}} = \frac{a_1}{a_{n+1}}.$$
Therefore,
$$\prod_{i = 1}^{\infty}x_i = \lim_{n\to\infty}\prod_{i=1}^n x_i = \lim_{n\to\infty}\frac{a_1}{a_{n+1}} = \frac{a_1}{a}$$
which is non-zero as $a_1 \neq 0$. It follows from this construction that any $p \in (0, 1)$ arises as such an infinite product.
Answer: $$\frac{1}{2}=\frac{1}{2^{1/2}}\cdot \frac{1}{2^{1/4}}\cdot \frac{1}{2^{1/8}}\cdot \frac{1}{2^{1/16}}\cdot \frac{1}{2^{1/32}}\cdot \frac{1}{2^{1/64}} \cdots$$
Answer: Start with the decreasing sequence
$$p_1 = 1 - \frac{1}{4}, \quad p_2 = 1 - \frac{3}{8}, \quad p_3 = 1 - \frac{7}{16}\quad, \quad ...\quad , \quad p_n = 1 - \frac{2^n-1}{2^{n+1}}
$$
whose limit equals $\frac{1}{2}$. Then set
$$x_1 = p_1, \quad x_2 = p_2/p_1, \quad x_3 = p_3/p_2,\quad \ldots
$$
The partial product $\prod_{i=1}^n x_i$ equals $p_n$, and so the limit is $\frac{1}{2}$.
Answer: Take $x_i = 1-\frac{1}{(i+1)^2}$. Then, we have
$$
\ln \prod_{i=1}^n x_i = \sum_{i=1}^n \ln\left(1-\frac{1}{(i+1)^2}\right)
$$
and as $\ln\left(1-\frac{1}{(i+1)^2}\right) \sim_{i\to\infty} -\frac{1}{i^2}$, the series $\sum_{i=1}^n \ln\left(1-\frac{1}{(i+1)^2}\right)$ converges (by comparison) to some real number $\ell < 0$. But this means that
$$
\prod_{i=1}^n x_i\xrightarrow[n\to\infty]{} e^\ell > 0.
$$
Comment: ...and then I think the product goes to $1/2$.
Comment: Possible... TBH, since convergence was sufficient, I did not care too much about the exact value. (Also, adding computations and details could actually drown the point...)
Answer: Good result to know: Suppose $a_n\in (0,1)$ for all $n.$ Then $\prod_{n=1}^\infty (1-a_n) > 0$ iff $\sum a_n < \infty.$ The proof is a nice exercise in taking logs and using $\log (1+u) = u + o(u).$


Uma imagem grande atrapalha no desempenho da aplicação?

Question: Meu banner tem uma imagem de 11mb, enquanto local está tudo ok, mas gostaria de saber se quando subir esta aplicação irá deixar a mesma pesada.
Agradeço desde já.
Comment: Tudo que o navegador vai precisar baixar "atrapalha" a aplicação, quanto mais arquivos e mais pesados esse arquivos forem, mais lento pra carregar
Comment: Complementando o que @DanielCosta comentou... Lembre-se que atualmente acessamos páginas web pelo Mobile e que geralmente possuem uma conexão 3g. Imagina o quão custoso seria para esse usuário abrir sua página já que só seu Banner é do tamanho de um App.
Comment: Obrigado galera, pensarei nisso e escolhei a melhor maneira para tal.
Answer: No Brasil, a velocidade média da internet móvel gira em torno de 2 Mbps, isso resulta em uma taxa de download de aproximadamente 256 KB/s. Sua imagem pesa 11 MB, isso levaria aproximadamente 44 segundos para baixar apenas sua imagem.
Mesmo para uma internet de 15 Mbps, o download da imagem demoraria aproximadamente 6 segundos, o que ainda assim pode ser considerado demorado.
Você pode verificar o desempenho da sua aplicação por alguns websites. Segue uma lista:

Think with Google
Varvy
Page Speed Insights

Alguns artigos sobre otimização de imagens:

Otimização de imagens - Google Developers
10 Must Know Image Optimization Tips - Shopify Blog (Inglês)
Answer: Lembre-se que não desenvolvemos mais apenas para plataforma PC, dar suporte para celulares e tablets é extremamente importante.
A questão das imagens é um tópico importante do design responsivo. Imagina que tem gente por aí que acessa a sua página através do plano de dados. No brasil vamos achar planos de 600mb, 400mb até de 200mb.
Se o seu site com uma imagem é capaz de consumir 5% de uma franquia, isso certamente é um problema.
Otimize a sua imagem para web.


What constitutes "idle" CPU during T2 CPU credit calculation?

Question: The documentation for EC2 T2 "burstable" types say:

The baseline performance and ability to burst are governed by CPU
  credits. Each T2 instance continuously receives CPU credits at a set
  rate, depending on the instance size. T2 instances accrue CPU credits
  when they are idle, and use CPU credits when they are active. A CPU
  credit provides the performance of a full CPU core for one minute.

What I don't understand is what does idle mean? All instances use some CPU > 0%, so is there are CPU usage figure under which the instance is considered to be "idle"?
Surprisingly, given the liberal usage of this term, I cannot find a definition of "idle" anywhere.
Answer: Good question, the Amazon EC2 documentation for CPU Credits in T2 Instances could be more precise here indeed - the introductory blog post New Low Cost EC2 Instances with Burstable Performance provides a better explanation, see the table in the middle:

The column labeled "Baseline Performance" indicates the percentage of
  single core performance of the underlying physical CPU allocated to
  the instance. For example, a t2.small instance has access to 20% of a
  single core of an Intel Xeon processor running at 2.5 GHz (up to 3.3
  GHz in Turbo mode). A t2.medium has access to 40% of the performance
  of a single core, which you (or your operating system, to be a bit
  more precise) can use on one or both cores as dictated by demand.
The column labeled "CPU Credits / Hour" indicates the rate of CPU
  Credits that the T2 instance receives each hour. CPU Credits
  accumulate when the instance doesn't use its baseline allocation of
  CPU, and are spent when the instance is active. Unused CPU Credits are
  stored for up to 24 hours. [emphasis mine]
Comment: Great, so in the case of T2.small, for example, which has a baseline of 20% CPU, when it's under 20% we are earning at a fixed rate, when it's above we are spending at a variable rate as per http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/t2-instances.html#t2-instances-cpu-credits
Comment: Exactly - this transparent approach (including appropriate [CloudWatch metrics](http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/t2-instances.html#t2-instances-monitoring-cpu-credits)) is a rather significant and competitive improvement over the previous throttling model for the respectively infamous `t1.micro` instances.
Comment: @DanGravell, you earn at a variable rate "For example, if a t2.small instance had a CPU utilization of 5% for the hour, it would have used 3 CPU credits (5% of 60 minutes), but it would have earned 12 CPU credits during the hour, so the difference of 9 CPU credits would be added to the CPU credit balance"
Answer: "idle" is notoriously hard to define in general for Linux servers. On general level, idle should be any time not spent on user-mode, system-mode, low priority mode, i/o waiting or interrupts -- with the special provision that given the right kind of workload, i/o wait time could be converted to user-mode time (for another process).
However, on the question of idle of AWS t2, this doesn't hold. It didn't hold for t1 either (due to "stolen" time), but even that doesn't explain t2 behavior. I've run into scenarios where idle time (as reported both by Linux top and by AWS CloudWatch) is way above the documented threshold levels, yet the instance is losing CPU credits instead of gaining them. I believe this to be an accounting error on Amazon's side, and until it is fixed, trying too hard to understand how CPU utilization and idle are defined will be a waste of time..
I've posted some illustrative charts on AWS's support forums, where hopefully they will respond. https://forums.aws.amazon.com/thread.jspa?messageID=568026#568026
Comment: We may be having the same issue with a medium instance for mail processing. Credits accumulated linearly with no usage at all, and now deployed, there's a gradual drop even with maximum utilisation in 5 minute buckets of less than 1%. It may be that the idle threshold is a small fraction of 1%, but that would not make the instances useful. Responses from Amazon to your ticket and others do suggest that the credits calculation is not working as intended though.
Comment: Amazon staff posted an explanation of the system, which appears to be more complex than the documentation leads to think: not only is there a maximum balance of credits for each T2 instance type, but credits earned 24h ago will expire from the balance.

That is, a t2.small will earn 12 credits per hour, maintain a maximum balance of 288 credits, but ALSO any credits it earned 24 hours ago will be subtracted from the balance. This means instances over 24 hours old will lose credits faster than you would expect, and long-term balance will likely be closer to the initial than maximum value.
Comment: @osama thanks for adding that. From the charts I suspect there's even *more* to it, but it's working out for us at the moment which is what matters :) We've increased average load on a medium since Friday and are watching to see what happens now.
Answer: This is something like below
If you are using micro instance that runs on max 10% single core throughout. suppose times come when your server is consuming 5% of single core, so it consider remaining 5% of computing power as idle. This 5% keeps on accumulate off-course for 24hrs only. Now if you have this accumulation and mean while your server is starving for computing power than it can borrow from this accumulated computing power. For this computing power they  have used a fancy word called CPU Credits.
I Googled out and found good explanation on some blog http://themindtracks.com/amazon-launches-new-low-cost-ec2-instances-burstable-performance/


How to check for a pre requisite and then install it in WiX?

Question: I am creating an installer. I have a setup project for the same along with a bootstrapper project which consists of all my pre requisites. I would like to check if the .NETFramework 4.8 is installed in the machine, and only if the version 4.8 is not installed, I would like the installer to install the same. In order to achieve this I am making use of the NetFxExtension in my bootstrapper project.
After following some sources online, this is what I tried doing but it does not work.
<Fragment>
<PropertyRef Id="NetFx48Redist"/>
<Condition Message="Please install the .NET Framework 4.8 and run this installer again.">
<![CDATA[Installed OR NETFRAMEWORK48]]>
</Condition>
</Fragment>

Answer: WixNetFxExtension includes package groups you can reference in your bundle's Chain element. .NET Framework v4.8 is supported on WiX v3.14 and v4. Here's a sample: https://wixtoolset.org/docs/v3/howtos/redistributables_and_install_checks/install_dotnet/