Why does my Data Export View use the default value for an exposed Grouped Filter?

Question: I am using Views 7.x-3.8, Drupal 7.28 and Views Data Export 7.x-3.0-beta7.
From a view (page) with multiple fields and exposed filters, I created a homemade search engine with search results within a table. I have created an export view, attached to that view, with exactly the same fields and exposed filters. So users can export filtered search results.
From the search engine, after choosing a value for a field with exposed grouped filter (Any, Yes, No), the export does not consider that choice and keeps the default value for this filter. Same result if I activate the option "Remember last selection" on the export view.
Any idea why?
Thanks in advance.
Answer: It could be that the export display is not attached to the page display. Try to edit the export display (typically you can not adjust the exposed filters on this page, as visiting the page will simply download all the results for the master view without considering any exposed filters).
Instead of getting your file by visiting the path of the data export, instead attach the data export to the page display where you placed your exposed filters.
You can do this by editing your data export display and adjusting the settings in your "Attach to" settings in the data export settings column (see screenshot below).

Once you click the Attach to link you'll be able to add your data export to any display in that view. Add it to your page.

Then, load the page in your browser, adjust your exposed filters until you see the results you want, and then scroll to the bottom of your page. You should see an icon that will enable you to execute the download of whatever file type you specified for your data export. For example, below I've filtered results for a page and set it to download as CSV.

By clicking the orange button, I'll download the filtered results on the page.
Comment: My Export view is already attached to the page where the exposed filters are, actually. My mistake, I said Master view but indeed it is attached to "Page". My problem is the default value always considered by the export instead of the choice made on the dropdown menu for a specific field, within the exposed filters.


"Failed to instantiate java.util.List using constructor NO_CONSTRUCTOR with arguments ",

Question: "Failed to instantiate java.util.List using constructor NO_CONSTRUCTOR with arguments ",
while fetching data from mongo .. what could be possible reason for this
Comment: Do you use lombok?
Comment: Yes i use lombok
Answer: I was having the same issue, It was the aggregation when unwind happened,Dont create the List of Object in Data object,
My previous class
Account{
        String _id;
          List<Transaction> trasactionList
       }

Corrected class
Account{
          String _id;
          Transaction trasactionList
    }

Comment: This might not be the solution. Your situation happened in the output class. It depends on the query where you create the output class
Comment: the query doesn't use aggregation..it simply fetch data with id


Does the webbing seen in some trumpets change the sound?

Question: Back in high school I played the trumpet for 6 months, and then clarinet for the next 4.5 years (high school is odd in Quebec, and it's not important to the question anyway), and I was a science student, so I have a decent idea of how a wind instrument makes different tones.
Recently I got a chance to see one of my favourite bands (SOIL & "PIMP" SESSIONS) live for the first time and noticed something about one member's trumpet: it had a sort of webbing in the 2 big bends, like on a duck's foot.
My question is how would it affect the sound? Would the additional stability prevent the pipes from vibrating and altering the vibration of the air flowing inside? Or would they maybe send the vibration to the rest of the tube? (though that would likely also have the same effect)
This is the trumpet of that player:
Comment: I've no idea about the sound, but at least this link says who makes them: http://www.taylortrumpets.com/utleycollection-visitingtrumpetmaker.html Given Taylor's sense of humour mentioned in that link, it could just be a joke - Norwich (in the east of England) is in a very low-lying part of the country (any land that is 10 feet above sea level counts as a hill!) which is criss-crossed by a complex water drainage system that was constructed a few hundred years ago, and because of that the indigenous inhabitants are reputed to have evolved webbed feet...
Answer: It does affect the sound, but by how much is debatable and I doubt anyone could reliably discern between a trumpet with or without this kind of bracing in a blind listening test.
The main thing it does is affect the way the instrument resonates.  When you play a brass instrument, you set up a vibration in the air stream inside the tubing.  Some of this vibration will transfer into the instrument itself, which is just a loss of energy.  This extra bracing is supposed to reduce this parasitic resistance.  I have a trumpet that looks a lot like the one in your second picture, and the feeling is very noticeable.  It's much easier to play and doesn't push back as hard as a normal trumpet.
Comment: Have you done a blindfold test with two instruments, identical except for this webbing?  I find it hard to believe that there would be any noticeable acoustic affect here, since the webbing is confined to a part of the tubing which is bent and thus very stiff anyway.  Webbing on the bell, sure, that would make a difference, but webbing on a curve?
Comment: I have not, and I totally admit that my knowledge is mostly anecdotal, but I have a very large collection of trumpets and the more heavily braced, the more free-blowing they are.
Comment: Of course you may be right.  I'm just speculating based on what I imagine the acoustical forces to be here.  I guess the only true test would require building otherwise identical instruments, and probably no one will do it.
Answer: When it comes down to it, every decision regarding the construction of an instrument will have some effect on the instrument's own distinctive timbre. With that said, there will probably always be some point of diminishing returns where these changes in the design don't make any noticeable difference.
Notice that above I said "distinctive timbre," and not anything about a good or bad quality sound. This is because different playing environments require different timbres; between an instrument with this webbing and an instrument without, Chris Martin might choose one, and Wynton Marsalis might choose another. (Indeed, a quick Internet search of the latter shows him playing on both types of instruments!)
For me personally, these extra braces improve instrument response quite a bit; I don't get that "push back" that I get with some other instruments. This suggests that yes, the increased stability of the pipes does improve the vibration flowing through the horn. But it's also tough to isolate this one factor from the various other construction decisions that go into manufacturing an instrument.
I've learned that Kanstul apparently creates trumpets with movable braces; this would be an interesting thing to experiment with!
And if you're really in the mood for some research, you can check out some scholarly literature on (and related to) the matter; here is an interesting start!
Comment: I agree that link is an interesting start, though (speaking as an engineer who works on vibration problems) it seems to dance all round the subject without really hitting the target. If they had actually *measured* the vibration response of the instrument (not the air inside it), rather than theorizing about what it ought  to be, that would have been a much more solid foundation to build on. That vibration response will be very much affected by the fact that the tubing is *curved*, and the bracing will reduce its flexibility when it bends, but the question is how much this really matters.
Comment: I agree wholeheartedly with your point about diminishing returns! I  think there's a huge amount of quasi-scientific-sounding voodoo about trumpet materials and construction.
Comment: Yeah, to me it's the old Arnold Jacobs thing: quit worrying about all the little details, and just focus on the sound that you want! And @alephzero, I agree that the article isn't exactly what the OP was looking for, but I found it and thought it would be interesting to share.
Answer: There are fads in trumpet construction, some concerned in 'coupling' the mouthpiece to the mouthpipe, others with controlling mechanical vibration of the tubing.
Play a note on your trumpet.  Feel the vibration of the tubing, even of the bell.  Not much, is there?   I wouldn't worry TOO much about these fads.


Problem in Multinomial Theorem

Question:
If $n$ & $k$ are positive integers such that $$n \ge \frac{(k)(k+1)}{2}$$
  then the number of solutions $(x_1,x_2,...,x_k)$ such that $x_1 \ge 1 , x_2 \ge 2,..., x_k \ge k$ are all integers satisfying $$x_1 + x_2 + ... + x_k = n$$ is?

My attempt at a solution:
The answer equals the coefficient of $x^n$ in the following
$$(x+x^2+x^3+....)(x^2+x^3+x^4+...)...(x^k+x^{k+1}...)$$
This equals
$$x^{\frac {k(k+1)}{2}}(1+x+x^2+x^3+...)^k$$
This is where I'm stuck. How do I find the coefficient of $x^n$ if I don't know what it equals?
Comment: It's equivalent to say $(x_1-1)+(x_2-2)+\dotsb+(x_k-k)=n-\frac{k(k+1)}{2}$, where each $x_i-i \geq 0$. Do you know the number of ways to write a nonnegative integer, $n - \frac{k(k+1)}{2}$, as a sum of $k$ nonnegative integers?
Comment: Right, that's it. $n-\frac {{k}{(k+1)}}{2}+k-1 \choose k-1$. Thanks so much.
Answer: In your question, you got a very nice approach so far. So here is an answer which follows your approach  further.
The number of solutions is to be given as a function of k and n.  Now with your approach, that number is  the number of terms with power $p = n - \frac {k(k+1)}{2}$ in $(1+x+x^2+x^3+...)^k$.
Let $|x| <1$ then the sum in parantheses is (geometric series)
$$
\frac{1}{1-x}
$$
So the power you are looking for  is given by expansion of
$$
f(x) = \frac{1}{(1-x)^k}
$$
into a series about $x=0$, where (Taylor) the coefficient with power $p$ has the factor
$$
\frac{1}{p!} \frac{d^{(p)}f(x)}{dx^{(p)}} |_{x=0}
$$
Now taking the derivatives is easy to see:
$$
\frac{d^{(p)}f(x)}{dx^{(p)}}  = \frac{k(k+1) \cdots (k+p-1)}{(1-x)^{k+p}}
$$
so the factor in  the Taylor expansion is
$$
\frac{k(k+1) \cdots (k+p-1)}{p!} = \frac{(k+p-1)!}{p! (k-1)!} = \binom{k+p-1}{k-1}
$$
Finally, plugging in
$p = n - \frac {k(k+1)}{2}$ from above, we get
$$
\binom{k-1+n - \frac {k(k+1)}{2} }{k-1}
$$

Problem in Multinomial Theorem


Compare two lists with linq and lambda where one is string and other long

Question: I have read alot here but haven't found the answer to correctly compare two lists in the final part of my query since one list is string list and other is a long list. should be easy for someone familiar with linq.
List 1 :
var fileContactIds = new List<string> {
    "5678765", "2135123", "12341234", "341234123", "12341234123",
    "2341234123", "341234123", "123412341", "13342354","12342341",
    "123412322", "163341234", "2345234115", "8967896", "75626234"
};

List 2:
returned from JsonConvert.DeserializeObject<RelatedContacts>(json)?.list
sample:
{
   "type":"com.kurtosys.api.userprofile.domain.RelatedContactList",
   "list":[
      {
         "objectlistid":5678765,
         "objectlisttypeid":4567876,
         "objectlistname":"ALL.National",
         "clienttaxonomyid":765677,
         "clienttaxonomy":"National Wholesaler",
         "order":1,
         "contacts":[
            {
               "personid":7654345678,
               "fullname":"Person Jallo",
               "userid":876567,
               "userclientcode":"5678765",
               "contactdetails":[
                  {
                     "contactid":8765567,
                     "contacttypeid":4565,
                     "contactdata":"firstname.lastname@example.com"
                  },
                  {
                     "contactid":876545678,
                     "contacttypeid":4565,
                     "contactdata":"Baltimore,MD,21209,United States"
                  },
                  {
                     "contactid":87654567,
                     "contacttypeid":4584,
                     "contactdata":"410-413-2640"
                  }
               ]
            }
         ]
      },
      {
         "objectlistid":765678,
         "objectlisttypeid":40400461,
         "objectlistname":"RM.Internal",
         "clienttaxonomyid":7567898,
         "clienttaxonomy":"Internal Regional Wholesaler",
         "order":2,
         "contacts":[
            {
               "personid":56789876,
               "fullname":"Jackson Man",
               "userid":876567,
               "userclientcode":"12341234",
               "contactdetails":[
                  {
                     "contactid":309598309,
                     "contacttypeid":76546,
                     "contactdata":"mister.jackson@@site.com.com"
                  },
                  {
                     "contactid":876567,
                     "contacttypeid":4581,
                     "contactdata":"Baltimore,MD,21209,United States"
                  },
                  {
                     "contactid":876567,
                     "contacttypeid":2342,
                     "contactdata":"123-413-2604"
                  }
               ]
            }
         ]
      },
      {
         "objectlistid":309571364,
         "objectlisttypeid":40400461,
         "objectlistname":"RM.External",
         "clienttaxonomyid":309580710,
         "clienttaxonomy":"External Regional Wholesaler",
         "order":3,
         "contacts":[
            {
               "personid":302736188,
               "fullname":"Phal Sumi",
               "userid":303826019,
               "userclientcode":"1016023",
               "contactdetails":[
                  {
                     "contactid":309598253,
                     "contacttypeid":2342,
                     "contactdata":"firstname.lastname@example.com"
                  },
                  {
                     "contactid":309611930,
                     "contacttypeid":2342,
                     "contactdata":"Baltimore,MD,21209,United States"
                  },
                  {
                     "contactid":34234132,
                     "contacttypeid":3422,
                     "contactdata":"342-803-1793"
                  }
               ]
            }
         ]
      }
   ]
}

and mapped to :
namespace Company.AppServices.RestClient.Users
{

    public class RelatedContacts
    {
        public string type { get; set; }
        public List<RelatedContactList> list { get; set; }
    }

    public class RelatedContactList
    {
        public long objectlistid { get; set; }
        public long objectlisttypeid { get; set; }
        public string objectlistname { get; set; }
        public long clienttaxonomyid { get; set; }
        public string clienttaxonomy { get; set; }
        public int order { get; set; }
        public List<PersonContact> contacts { get; set; }
    }

    public class PersonContact
    {
        public long personid { get; set; }
        public string fullname { get; set; }
        public long userid { get; set; }
        public string userclientcode { get; set; }
        public List<ContactType> contactdetails { get; set; }
    }

    public class ContactType
    {
        public long contacttypeid { get; set; }
        public string contacttype { get; set; }
        public long contactid { get; set; }
        public long personid { get; set; }
        public string contactdata { get; set; }
        public int countrycode { get; set; }
        public int areacode { get; set; }
        public long phonenumber { get; set; }

    }
}}

My query:
var res =
    relatedContact.SelectMany(
     rc =>
     {
         return rc.contacts
            .Select(pc =>
            {
                return new
                {
                    ClientId = pc.userclientcode,
                    Description = rc.clienttaxonomy,
                    Fullname = pc.fullname,
                    Email = pc.contactdetails != null && pc.contactdetails.Count >= 1 ? pc.contactdetails[0].contactdata : "",
                    Address = pc.contactdetails != null && pc.contactdetails.Count >= 2 ? pc.contactdetails[1].contactdata : "",
                    PhoneNumber = pc.contactdetails != null && pc.contactdetails.Count >= 3 ? pc.contactdetails[2].contactdata : "",
                };
            });
     })
    .Where(
     el =>
     {
       //Stuck here -> need only items where userclientcode in second list matches an item in first list.
     }
    );

Comment: Possible duplicate of [Use Linq or C# to parse Json](http://stackoverflow.com/questions/40375294/use-linq-or-c-sharp-to-parse-json)
Comment: Please don't ask the same question again.  If your previous question didn't get an answer, edit it.  Don't repeat.
Comment: https://stackoverflow.com/questions/40383610/easiest-method-to-extract-info-and-add-to-a-list-in-c-sharp
Answer: Use .Contains for the ids list:
.Where(item => fileContactIds.Contains(item.ClientId))

All together (with a bit of refactoring):
var res = relatedContact.SelectMany(rc => rc.contacts.Select(pc => new
            {
                ClientId = pc.userclientcode,
                Description = rc.clienttaxonomy,
                Fullname = pc.fullname,
                Email = pc.contactdetails != null && pc.contactdetails.Count >= 1 ? pc.contactdetails[0].contactdata : "",
                Address = pc.contactdetails != null && pc.contactdetails.Count >= 2 ? pc.contactdetails[1].contactdata : "",
                PhoneNumber = pc.contactdetails != null && pc.contactdetails.Count >= 3 ? pc.contactdetails[2].contactdata : "",
            }))
           .Where(el => fileContactIds.Contains(el.ClientId));

Comment: @AfshinGhazi - yes. From what I understand you want only the items of `relatedContact` that the `ClientId` is present in the `fileContactIds`
Comment: sorry answer came late as page was refereshing. Thanks!


Immutable value of type 'Any[]' only has mutating members named 'append' in Swift, despite the array is defined as 'var'

Question: I want to append a new object to my Array, which is defined as var in my Swift app, but despite me defining it as var, the following error occurred when I tried to append it.
`Immutable value of type 'Any[]' only has mutating members named 'append'`

Here's my code:
var contactsArray: Any[]!
func popoverWillClose(notification: NSNotification) {
    if popoverTxtName.stringValue != "" && popoverTxtContactInfo.stringValue != "" {
        contactsArray.append(makeDictionaryRecord(popoverTxtName.stringValue, withInfo: popoverTxtContactInfo.stringValue))
    }
}

(makeDictionaryRecord(withInfo:) method takes two String and returns Dictionary<String, Any>)
My original code defines contactsArray as let, and later I found it was my mistake, so I changed it to var. However, things still didn't make it so far.
I also changed the type of components of contactsArray to AnyObject[], Any[], and AnyObject[]!, but nothing didn't change at all.
( That being said, since the contactsArray has to take Dictionary within it, it has to be defined as either Any[] or Any[]!, since Dictionary is defined as struct, if I understand it correctly. )
What's wrong with my code? How can I properly append the component to contactsArray?
Comment: possible duplicate of [Implicitly unwrapped optional made immutable](http://stackoverflow.com/questions/24091729/implicitly-unwrapped-optional-made-immutable)
Answer: Problem 1: You've defined contactsArray as an implicitly unwrapped Optional, but the values of Optional variables are always immutable. You can define it this way instead to allow appending values:
var contactsArray: [Any]

Update: This hasn't been a problem since Swift introduced assignment through optional chaining. With implicitly unwrapped optionals, this happens automatically.
Problem 2: You haven't given the array an initial value -- the compiler starts complaining about that when you fix problem 1 for an implicitly unwrapped optional, that means the value is nil, so you'll get a runtime exception. The solution is to initialize the variable with an empty array:
var contactsArray: [Any]! = []

You almost never need an optional Array—an empty array is just as good a signifier of "no values" as nil, and safer, to boot. If you decide to use an optional array anyway, use a regular optional (i.e., declared with ?), not an implicitly unwrapped one:
var contactsArray: [Any]? = []

Comment: Awesome! I didn't know that the optional is always immutable. However, is it still possible to define an array as both optional and mutable? I might want to assign `nil` during the lifetime of the application...
Comment: Nope! I'd stick with empty arrays instead of `nil`. If you absolutely need optionality (?) you'll have to make variable, non-optional copy of the array, add to it, then reassign to `self.contactsArray`.
Answer: The syntax for array declaration has been changed, it's now
var contractsArray: [Any] = []
Also if you're modifying an array as part of a struct or an enum you might see this error. A struct or an enum is a value type and the method needs the mutating keyword:
struct contacts {
    var contactsArray:[Any] = []
    mutating func popoverWillClose(notification: NSNotification) {
        if popoverTxtName.stringValue != "" && popoverTxtContactInfo.stringValue != "" {

            contactsArray.append(makeDictionaryRecord(popoverTxtName.stringValue, withInfo: popoverTxtContactInfo.stringValue))
        }
    }
}

In addition you cannot save instances of a struct with mutating methods as a constant using the let keyword, it needs to be declared as var because the value for the variable will change when you call a mutating function.


How can a program know its own git SHA?

Question: I understand there may be no solution for this but we are building a system which does some data processing and in the logs we want to store the version of the program which is used to generate the data. We are using Java in case it matters. The program version is nothing but the git SHA. Using the SHA we can track which build / commit was used to generate the data. How can our program determine its git SHA? Is it even possible? Appreciate your thoughts.
One possible thought is to have a script which upon committing the code, extracts the git SHA from the commit message and then writes it to a resources file. This file obviously would not be tracked by git (i.e., file needs to be added to .gitignore). At runtime the program would read the SHA from this file. Any  better alternatives?
One thing we really want to avoid is a developer accidentally committing code by running git commit directly instead of running the script. If that happens the SHA in the resources file will not get updated and this would introduce a serious bug. How to handle this?
Another issue is that when we do git commit -m "commit message", git does not spit out the complete SHA but instead truncates it. How can we get git to print out the full SHA?
Comment: Why not store the SHA at compile time, as a post-build step?  You don't actually need it when you're checking in changes, just when you're running, correct?
Answer: You can store the Git SHA as part of your packaging process. Obviously the implementation depends on your build system but in general, you can write the SHA to a property file and load it at runtime.

http://www.mojohaus.org/buildnumber-maven-plugin/
Comment: Great. Thanks http://www.mojohaus.org/buildnumber-maven-plugin/usage.html
Answer: Bash variable for your SHA in the repo:
$(git rev-parse HEAD)

You can use that in your build.  If you are using something like Jenkins for your builds, then there are other questions with answers for that.
Answer: Git SHA isnt truncated. Truncate means cutting it off.
SHA is just 64bit hascode key in non-human readable format.
What is sha?

sha is a simple program that hashes files. It uses the National
  Institute of Standards and Technology's Secure Hash Algorithm. It can
  use SHA-1, SHA-256, SHA-384, or SHA-512, which generate respectively,
  hashes of 160, 256, 384, or 512 bits. sha can be used in scripts to
  do, for example, file integrity checking. The C implementations of the
  algorithms might be useful in other projects as well.

There are several techniques to extract the version of software, usually how we use it is using git tag and suffix Major, Minor and Patch at git pre commit hooks, it will autogenrate the release notes and easy to know what feature is running in the different versions.

How can a program know its own git SHA?


single quotes or not in square bracket data?

Question: I have a (probably) very simple and easy to answer question, which I cannot find the answer to anywhere, perhaps it is too simple, and I am not well-versed in php.
I am using a script written by someone else, and they sometimes use single quotes within the square brackets, [ ], and sometimes not. What is the correct way?
For example, is it best written [data] or ['data']? I am a perfectionist and this is driving me crazy to know the proper method.
Echo "Name: " .$ratings['name']."";
$current = $ratings[total] / $ratings[votes];
 Echo "Current Rating: " . round($current, 1) . "";
Comment: @MatW The question isn't asking about single vs. double quotes - it is asking about single vs. no quotes.
Comment: This has been covered before, many times. There is no right way, just use whatever coding standard makes sense to you. Personally, I use `'` everywhere, unless I'm dealing with an actual string of text, then it's `"`
Comment: See here: http://stackoverflow.com/questions/13622486/php-array-access-without-quotes - you may get a warning if you have errors turned on. non quoted attempts a constant first. If not found, it reads as a string. proper way would be to avoid errors. I quote them always.
Comment: And as an extra note you should always be developing with error reporting turned all the way up so you see every tiny thing PHP thinks may be a problem.
Answer: You must always use single or double quotes when accessing an array element.
I asked in ##php on freenode, and they believe this quirk existed since PHP4.3 (god knows why), but right now when PHP comes across $array[value], it firstly tries to look for a constant named value, and if it is not define()'d, it treats the expression as $array["value"] and spit a Notice in PHP4. In PHP5, this has been upgraded to a warning.
In short: Don't use it. It confuses yourself.
Comment: Always with one exception. If the value inside the square brackets is a constant. ie. `$array[SOME_CONSTANT]` must not be put inside quotes.
Comment: so the answer i'm getting here is always use single quotes in square brackets i.e. ['data']...?
Comment: @user3175564 Correct.
Answer: Definitely use the quotes. Additionally, there is a subtle but important difference in PHP between single and double quotes strings. A single quoted string is actually faster, because it is treated as a literal, whereas a double quoted string gets interpreted, which takes O(n) time.  Example:

$test = 'world';
echo 'hello\n$test';

yields hello\n$test

$test = 'world';
echo "hello\n$test";

yields

hello
world
Answer: Either double or single would work. Personally I prefer single.
PHP is very forgiving and only spits out a notice if no quotes are given to an index of the array.
Comment: It's no longer so forgiving with php 7.2, now showing warnings and code will fail with future php versions.


O History não funciona

Question: galera o meu grande problema ai é o seguinte, eu outra aplicação eu usei a propriedade "history" para redirecionar para outra pagina, eu aprendi que não precisava importa nada de nenhuma lib para usar o history só era desestruturar ele na função e usar. Porém quando a atentificação passa chega na linha do "history" e da esse erro :
"Unhandled Rejection (TypeError): Cannot read property 'push' of undefined".
como se o history não tivesse essa função , realmente não sei como proceder, porque é a unica forma que sei chamar outra pagina passando o id e outros dados.

O History não funciona


Is it always true that $-\int_{\mathbb{R}} \log p(Y|\theta)v(\theta)d\theta \geq 0$?

Question: Is it always true that -$\int_{\mathbb{R}} \log[p(Y|\theta)]v(\theta)d\theta \geq 0$ where $p(Y|\theta)$ is the likelihood for data $Y$ and $v(\theta)$ is any prior distribution? Thanks.
Answer: For the case when $Y$ is not discrete, this expectation can be negative. Let for simplicity $Y$ is a single r.v. with PDF $p(y|\theta)=\theta e^{-\theta y}$ for $y>0$, $P(\theta=1)=P(\theta=4)=1/2$.
Let also observed $Y=1/4$.
Then $-\log p(y|\theta)=-\log(\theta)+\theta y=-\log \theta+\dfrac{\theta}4$,
$$
E\left(-\log\theta+\dfrac{\theta}4\right)=\dfrac12\left(-\log 1+\dfrac14\right)+\dfrac12\left(-\log 4+1\right)=\dfrac58-\log 2\approx -0.068 < 0.
$$
Answer: If $Y$ is discrete, you can use Jensen's inequality and the fact that $P(Y) \le 1$:
\begin{align*}
\int_{\mathbb{R}} -\log[p(Y|\theta)]v(\theta)d\theta  &\ge - \log \int_{\mathbb{R}}p(Y|\theta)\nu(\theta)d\theta \\
&= -\log p(Y) \\
&\ge 0.
\end{align*}
Otherwise I'm not sure.


Android: more scrolling woes

Question: Alright, so because of this question which I asked previously, I found out that you cannot know the scroll position of a WebView. I followed advice to put my content in a ListView instead. There's now a new problem.
All I am trying to do is tell when a certain part of the view scrolls past the bottom edge and the top edge of the screen. When the image appears at the bottom of the screen or disappears above the top of the screen, i want to play a sound effect.
Here's my code using a ListView. The problem is that onScroll is not consistently called. It seems like it's called only if I lift my finger and wait, then start scrolling again.
At the same time, onScrollStateChanged isn't always called either---it seems to only be called on the first frame of the scroll.
Isn't there some way to just continuously get scrolling information on every single frame of the scroll, regardless of whether I'm touching the screen? I just want to know whether the scroll animation has been activated, even if it's one pixel, so that I can look at the position of the image element and see whether it's on screen or not.
<code>public class Scroll extends ListActivity implements ListView.OnScrollListener {

    public  ListView        listview;

    public int firstItemOnScreen;
    public int lastItemOnScreen;
    public int previousFirstItemOnScreen;
    public int previousLastItemOnScreen;

    private TextView mStatus;

    private boolean mBusy = false;

     //
     // Will not bind views while the list is scrolling
     //
     //
    private class SlowAdapter extends BaseAdapter {
        private LayoutInflater mInflater;

        public SlowAdapter(Context context) {
            mContext = context;
            mInflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        }

         //
         // The number of items in the list is determined by the number of speeches
         // in our array.
         //
         // @see android.widget.ListAdapter#getCount()
         //
        public int getCount() {
            return 0;//mStrings.length;
        }

         //
         // Since the data comes from an array, just returning the index is
         // sufficent to get at the data. If we were using a more complex data
         // structure, we would return whatever object represents one row in the
         // list.
         //
         // @see android.widget.ListAdapter#getItem(int)
         //
        public Object getItem(int position) {
            return position;
        }

         //
         // Use the array index as a unique id.
         //
         // @see android.widget.ListAdapter#getItemId(int)
         //
        public long getItemId(int position) {
            return position;
        }

         //
         // Make a view to hold each row.
         //
         // @see android.widget.ListAdapter#getView(int, android.view.View,
         //      android.view.ViewGroup)
         //
        public View getView(int position, View convertView, ViewGroup parent) {
            TextView text;

            if (convertView == null) {
                text = (TextView)mInflater.inflate(android.R.layout.simple_list_item_1, parent, false);
            } else {
                text = (TextView)convertView;
            }

            if (!mBusy) {
                //text.setText(mStrings[position]);
                // Null tag means the view has the correct data
                text.setTag(null);
            } else {
                text.setText("Loading...");
                // Non-null tag means the view still needs to load its data
                text.setTag(this);
            }

            return text;
        }

         //
         //Remember our context so we can use it when constructing views.
         //
        private Context mContext;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        ImageListAdapter ila = new ImageListAdapter(this);

        // Add four items
        ila.addItem(new ImageList(
               "", getResources().getDrawable(R.drawable.header)));

        ila.addItem(new ImageList(
               "Test text", null));

        ila.addItem(new ImageList(
                "", getResources().getDrawable(R.drawable.interstitial1)));

        ila.addItem(new ImageList(
               "Test text", null));
        // Display it
        setListAdapter(ila);

        getListView().setOnScrollListener(this);
    }

    public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount,
            int totalItemCount){

        firstItemOnScreen = getListView().getFirstVisiblePosition();
        lastItemOnScreen = getListView().getLastVisiblePosition();

        Log.v("List", "first:" + firstItemOnScreen);
        Log.v("List", "last:" + lastItemOnScreen);

        // Bottom edge appears at top of screen
        if (firstItemOnScreen == 2 && previousFirstItemOnScreen != 2) {
            tvt.playEffect(2, 0);
        }

        // Top edge appears at top of screen
        // AND
        // Bottom edge appears at bottom of screen
        if (firstItemOnScreen == 1 && lastItemOnScreen == 3) {
            if (lastItemOnScreen != previousLastItemOnScreen || firstItemOnScreen != previousFirstItemOnScreen)
                tvt.playEffect(2, 0);

        }

        // Top edge appears at bottom of screen
        if (lastItemOnScreen == 2 && previousLastItemOnScreen != 2) {
            tvt.playEffect(2, 0);
        }

        if (firstItemOnScreen == 3 && previousFirstItemOnScreen == 2)
            tvt.playEffect(2, 0);

        if (previousLastItemOnScreen == 3 && lastItemOnScreen == 2)
            tvt.playEffect(2, 0);

        if (previousFirstItemOnScreen == 1 && firstItemOnScreen == 2 && previousLastItemOnScreen == 3 && lastItemOnScreen == 3)
            tvt.playEffect(2, 0);

        if (firstItemOnScreen == 1 && previousFirstItemOnScreen == 1) {
            if (lastItemOnScreen ==1 && previousLastItemOnScreen == 2)
                tvt.playEffect(2, 0);
        }
        previousFirstItemOnScreen = firstItemOnScreen;
        previousLastItemOnScreen = lastItemOnScreen;

    }

    public void onScrollStateChanged(AbsListView view, int scrollState) {

        switch (scrollState) {
        case OnScrollListener.SCROLL_STATE_IDLE:
            mBusy = false;

            int count = view.getChildCount();
            for (int i=0; i<count; i++) {
                ImageListView t = (ImageListView)view.getChildAt(i);
                if (t.getTag() != null) {
                    t.setTag(null);
                }
            }
            break;

        case OnScrollListener.SCROLL_STATE_TOUCH_SCROLL:
            mBusy = true;
            break;

        case OnScrollListener.SCROLL_STATE_FLING:
            mBusy = true;
            break;
        }
    }
</code>
Answer: This answer comes late, but the way scrolling is implemented in Android I think you may need to subclass ListView to do what you want.  You can override scrollTo and scrollBy and check your conditions there (make sure to call super.scrollTo and super.scrollBy at the appropriate time).

Android: more scrolling woes


Uso do preg_match

Question: Com este código consigo bloquear caracteres especiais no meu input, porém quero que ele ainda aceite ., - e _ como proceder?
elseif (!preg_match('/^[a-z A-Z0-9]+$/', $username)) {
    echo json_encode(array(
        'login'     => false,
        'message' => 'Existem caracteres especiais no seu nome de usuário, se estiver utilizando @, remova-o.'
    ));
}

Comment: Sem espaço: `[a-zA-Z0-9_.-]`
Comment: Só vai permitir os caracteres que estão na lista, se colocar uma `@` vai 'bloquear' e executar o `echo` e `json_encode()`
Comment: Adicione eles na lista (o que conteúdo que está entre os colchetes).
Comment: @rray [a-z A-Z0-9 . - _]  assim ?
Comment: Só uma dúvida, isso também fará bloquear caso usuário tente logar com email ?
Answer: Você pode usar esta expressão:
/^[\w-.@]+$/

Só irá retornar true se o $username tiver:
\w Caractere alfa-numérico. Letras (maiúsculas e minúsculas), números e _ (underline)
- Hífen
. Ponto
@ Arroba
Qualquer caractere diferente dos listados acima, o preg_match será false.
Veja no Ideone.
Comment: E funcionou mesmo, obrigado @DvD

Uso do preg_match


How to conditionally format a range of cells, based on a cells value, where that value is a specific formula in Excel

Question: I have an excel spreadsheet with columns A through S, and roughly 200 rows. In column A I have several cells that contain different formulas. I want to conditionally format the entire row (A-S) based on a specific formula, such as =first_inspection_name&" Inspection", found in column A.
I have tried formatting based on cell value, but that will only format the cell in column A.
I have also tried formatting based on a formula, like this: =$A3="=first_inspection_name&" Inspection"" but I get an error.
I don't think I can name the cell because I sort the columns, and I'm not even sure how to format based on a named cell, it was just a thought.
Is there a way to do this?
Comment: `=$A3=first_inspection_name&" Inspection"` Use the formula not a string of the fomula.
Comment: Well that's embarrassing. Thank you. Please add that as an answer so I can mark it as solved.
Answer: Just equate the formula to the cell:
=$A3=first_inspection_name&" Inspection"

and not the literal string of the formula.


How substr_replace array values shorter?

Question: After unsuccessfully  searching through the web. Here is my problem.
I want to change some values on different array values and not change the name of the array like.
$arr = array('Example1','Example2','Example3');
$arr2 = array('Value1','Value2','Value3');

$arr[0]  = substr_replace($arr[0], 'X', -1, 1);
$arr[2]  = substr_replace($arr[2], 'X', -1, 1);
$arr2[1] = substr_replace($arr2[1], 'X', -1, 1);
$arr2[2] = substr_replace($arr2[2], 'X', -1, 1);

How to short all the substr_replace lines? I think I need a loop.
Comment: The loop wouldn't make sense in this case because you're avoiding certain keys from the array, and then you would just end up with a bunch of if statements resulting in several more lines of code.
Answer: EDIT:
If you will change every values, use foreach for loop
If you will change only some known strings, use function:
function rpl($arr,$a){
    return substr_replace($arr[$a],'X',-1,1);
}

then usage:
$arr[0]=rpl($arr,0);
$arr[2]=rpl($arr,2);
$arr2[1]=rpl($arr2,1);
$arr2[2]=rpl($arr2,2);

Comment: Thank you! Although I was hoping for a really short solution
Comment: Can you please show me also the a foreach example, if I want change every value of an array? I have now a solution in which the start postion is also a variable of the function. I'm also searching for a multibyte version of `substr_replace` like `mb_substr` for `substr`
Answer: If you want change everything in array, you can pass array instead of string to substr_replace

http://php.net/manual/en/function.substr-replace.php

example:
$arr=substr_replace($arr,'X',-1,1);

If you want to do with loop:
For changing values in array using foreach is actually complicated (which I realized later)
using normal loop is better here
for($i=0;$i<count($arr);$i++)
    $arr[$i]=substr_replace($arr[$i],'X',-1,1);


Conditional expectation based on events

Question: Consider two continuous random variables $X,Y$ and scalars $b>a,$ and $t_1$, $t_2$. I want to compute expected value of $X,$ that is $E[X]$.
Let a realization of $X$ be $x$ and $Y$ be $y$. I know that $X=x t_1$ if $a+x<y<b+x$, $X=x t_2$ if $b+x<y$ and $X=0,$ otherwise. Hence, we can write
\begin{equation}
E[X]=E[X|a+X<Y<b+X] P(a+X<Y<b+X) + E[X|b+X<Y] P(b+X<Y).
\end{equation}
Now, my question is how can we express these conditional expectations with integrals. That is, can we say
\begin{equation}
E[X|a+X<Y<b+X] P(a+X<Y<b+X)= \int_{x=-\infty}^{\infty}ta_1 \left[ \int_ {y=a+x} ^{b+x}f_{Y|X}(y|x)dy \right]f_X(x)dx?
\end{equation}
If this is true, then,
\begin{equation}
E[X|a+X<Y<b+X] = \frac{ \int_{x=-\infty}^{\infty}ta_1 \left[ \int_ {y=a+x} ^{b+x}f_{Y|X}(y|x)dy \right]f_X(x)dx}{\int_{x=-\infty}^{\infty} \left[ \int_ {y=a+x} ^{b+x}f_{Y|X}(y|x)dy \right]f_X(x)dx}?
\end{equation}
This second expression looks very weird to me that makes me think that there is a problem with the first one as well.
Answer:
Let a realization of $X$ be $x$ and $Y$ be $y$. I know that $X=xt_1$
   if $a+x<y<b+x$ ...

No.   When $X$ realises a value of $x$ then $X=x$.   That's what it means.

However, perhaps you mean to find the expectation of a function $g(X,Y)$, where $g(x,y)=xt_1$ when ... and so on.
Then indeed:
$$\mathsf E(g(X,Y)\mid a+X<Y<b+X) = \dfrac{\int\limits_{-\infty}^{\infty} x t_1 f_X(x)\left(\int\limits_{a+x}^{b+x} f_{Y\mid X}(y\mid x)\operatorname d y\right)\operatorname d x}{\int\limits_{-\infty}^{\infty} f_X(x) \left(\int\limits_{a+x}^{b+x} f_{Y\mid X}(y\mid x)\operatorname d y\right)\operatorname d x}$$

Conditional expectation based on events


Change from address of user registration email

Question: How can I update the from address of the email sent when a user successfully registers to the website. Currently the from address is same as the site administrator email id. Instead I would like to set it some custom email id like firstname.lastname@example.com.
I looked at the Mail editor module and from the documentation I understand that it can be used only for updating the subject and body of the email and not the from address.
Any thoughts??
Answer: There is one e-mail address that is used as From-address for all mails sent automatically by the system.  By default, this is set to the same as the site administrator email.  To change it, do the following:

Navigate to Administration » Configuration » System » Site Information.
Locate the field "E-mail address". Change it to whatever you want it to be.
Press Save configuration.

Note that will also be used as the From-adress for password resets and other generated mail.
If you require fine-tuning beyond this (to distinguish between different types of auto-generated email messages), you need to write a custom module. In that case, you may use hook_mail_alter to alter the From:-address, based upon some criteria (e.g. the subject field.
For avoidance of misunderstanding: The three steps listed above will not change the site administrator email id.  To inspect and change the site administrator email id, click on the  "My account" link while logged in as site admin, and then press the Edit tab to see it. The  site administrator email id is by default the same email id as the From-address used for email sent by the site itself - but they do not need to be the same.
Comment: @Bhuvana, I do *not* propose that you change  the site administrator email id.  The site administrator email id will remain the same if you go through the three steps listed in my answer to change the From-address of auto-generated email (such as the user registration email).
Comment: My question is definitely not on how to edit the site administrator email id. I will no way want to update it to do-not-reply.XXX. I only want to update the from address in the email. Custom module sounds fine but is there a hook available for it or if you can give more details on how it can be done then it would be helpful.
Comment: @Bhuvana, as per Free Radical, The administrator email is the one set on your _user account_, the Site Information email is the _site_ email, and designed specifically for this.


Panoramio pictures on iOS without Google Maps

Question: I'm developing a little iOS App which shows POIs on a standard MKMapKit map (from Apple). When the user select a POI, the app send a request to Panoramio to get a photo from the latitude and the longitude, like that :
http://www.panoramio.com/map/get_panoramas.php?order=popularity&set=public&from=0&to=2&minx=XXXXXXXX&miny=XXXXXXXX... etc...

The problem is that I saw today on the Panoramio ToS :
http://www.panoramio.com/api/terms.html

Section 2: API Client restrictions
      You may not use the API in API Clients using map technology other than Google Maps or any photo-sharing sites.

I'm not using Google Maps API for iOS so the question is : can I use the standard MKMapKit from Apple AND show photos from Panoramio in the same app ?
If not, is there an alternative solution to get photos from GPS coordinates ?
Thanks
Answer: First off, I AM NOT A LAWYER AND THIS IS NOT LEGAL ADVICE.
Disclaimer aside, use apple's CoreLocation classes to generate latitude/longitude information, and you never touch mapping software.
Geolocation and mapping are two complimentary functions that don't necessarily interact.
From what I read there, I don't see a problem with retrieving your location via the CoreLocation framework, and subsequently using that info to request map information from Panoramio.
Good luck!


Git hub how to add repository to Netbeans?

Question: I'm new to GitHub.
I just registered, because my client use it. He added me to repository, so  I can see it now on gitHub website.
I worked with SVN, but not with Git.
I use Netbeans IDE and there is a plugin for git. I just want to know, how can I create local copy of repository and how do I need to do commit.
I'm just afraid to do it myself, because I can corrupt data.
Answer: Add the NBGit plugin to your NetBeans: you will then been able to clone your repo.
Don't fear any data corruption - worst case, you could end up corrupting your local copy, but there won't be any consequence on the GitHub side.
Note: The clone or pull itself would still be made by hand (in a command-line interface): what was reported in "How do you use Netbeans to work with a Github project?" is still accurate.
NetBeans 7.0 has a native Git support, but it is still a bit immature.
Comment: Thanks. Just one question. This is what I do Group->Git->Clone other

then I insert repository url (ssh) and there is need to insert username and password.

This is not my repository, my client added me to it. So do I need to insert my github account username and password? or any other login details?
Comment: @Ahmed: So I suppose you are using NB7.0.1 (http://netbeans.org/projects/versioncontrol/pages/Git_plan#M5_%2814._May_2011,_planned_for_7.0.1%29) which has clone support. I would rather use the https address, rather than the ssh one. That means setting my GitHub token once cloned: http://help.github.com/set-your-user-name-email-and-github-token/. And that means having a `.netrc` (or `_netrc` on Windows) file, with github.com, login an password in it.


betting - do favorites get undervalued quotes?

Question: I came across an example of a job interview question related to betting and want to ask the opinion of experts as my betting knowledge is very basic.
Here is the question:

"Do you think favorites in the English Premier League are undervalued in the betting market?"

Is this true? if yes, why?

My guess:
 Assuming it is true statement, it would be because the bookies are trying to discourage betting on favorites where the probability of them winning is bigger (giving bettors odds less than the probability of a win) and tempting people to bet on underdogs where the probabilities are lower (giving bettors better odds than the probability of a loss), therefore maximizing their profits.
That would be the gist of it.
Would my guess be close to the answer to this question?
Plus, how this would be relevant in the world of constantly changing odds?
Comment: Hi Chris, and welcome to Sports SE. From what I can tell, questions about sports betting and gambling certainly are on topic, as per ['What questions can I ask here?'](https://sports.stackexchange.com/help/on-topic) in our help centre, and [this](http://meta.sports.stackexchange.com/questions/123/are-questions-about-sports-betting-spreads-and-odds-on-topic) and [this](http://meta.sports.stackexchange.com/questions/85/asking-a-question-regarding-gambling) question in meta.
Comment: To the downvoters: whilst downvoting questions that are effectively unsalvageable without leaving a comment is fine, I think it's very poor form to do so here (particularly when it's a new user), when a quick comment can result in the question being improved and contribute further to the quality of this site.
Comment: Hi Chris, see if my edit makes sense to what you are asking please?  You're suggesting they give bad odds for favorited teams so that less people bet on them, so when they win, the bookies give up less money?
Comment: what is wrong with the question?? why downvote?
Comment: @  JeopardyTempest, that's exactly what I meant. However as Coach-D below explained and how I understood it  that might be only one of  many possible scenarios. How often the bookies really follow this scenario  is another story.
Answer: It is really simple.  A books goal is to get half the action on each side, for all pure win/loss bets.  They make their money on juice not guessing which side will win.
It does not matter if favorites make the most money for bettors on average.  It is all about getting an even amount of action on each side.
So the answer is possibly yes if it met certain conditions - covered more than juice - but it wouldn't matter long as the market (books) would adjust quickly.
(Just a tidbit but there were years straight that you could have won a lot more games than lost by just picking underdog every game in American football.  The books didn't care because people kept betting the favorites.  Maybe they were trying to make a 50/50 win-loss line or maybe the books were systematically adding a point or so to each game.  Each big book in Vegas hires a person to set the lines and then the lines move if the book is experiencing too much risk based on one side getting most of the action - but when the lines move the book can lose both ends)


Some kind of a Manova with repeated measures

Question: I have a question that is somewhere between R and stats I guess...
Let's set up the situation: I have a test that gives 4 scores, corresponding to 4 different dimensions of a problem. We can assume the data are relatively well distributed, and accept the normality assumptions and all that stuff.
The patients carried a surgery, and I have multiple measures before (1 to 3 measures, one per year), and after (2 to 5, one per year).
I want to know if there is an effect of the surgery.
Simple solution
If I want to analyze the scores separately, it's relatively easy, and I will use a linear mixed model, where I want to explain the score by the time and by what we can call the period (before or after the surgery). The patient is included as random effects. In this model, I can test if there is a surgery effect, adjusting to natural evolution.
The main pitfall of this strategy is that, as I am analyzing 4 different scores, I should adjust the p-values with a multiplicity correction method, say Holm's method. This will impact the power of my analysis...
Manova
The problem is finally a problem of multivariate ANOVA with repeated measures. Thus, what I am looking for, is an extension of the previous strategy, so that I can put all my scores together. I should include then a new variable dimension, saying what is the corresponding dimension of the measure.
I feel that the problem is nearly solved, however, I'm pretty sure there is a big issue with the options to specify: what kind of correlation matrix?
So, does this problem inspire someone?
And, bonus points: I will have to implement it in R...
So far, I have no data to share, I have not reached the simulation phase, and the real data are not yet available... I'm writing the analysis plan...
Thank you for any ideas!
Answer: It sounds like you need a multivariate mixed effects model. In R, there is the sabreR package and an accompanying book:
The only other package in R that fits such a model natively, as far as I know, is MCMCglmm. I can also think of some non-native alternatives; one is to use BUGS or JAGS which both have an R interface and are free but you would have to code the model from scratch. Another is MPlus which is not free but has an R interface and finally in Stata (again, not free but does have an R interface) you could try GLLAMM.
Comment: Does this answer your question ? If so, please consider marking it as accepted. If not, please let us know why. Thanks !


Advice reviewing academic paper

Question: For a piece of university coursework, I have been asked to review a paper of my choice. It is a computer science course, but since it is very mathematical, I thought it was worth asking here.
I was wondering if you had any advice for how I should go about doing this. I am asked to write a two page review covering basic ideas an assumptions they have made. I am also asked, which is the part I am slightly more confused about, to review the quality of the arguments used.
Do you have any general advice, I am not used to reading academic papers.
Answer: Reading contemporary, non-expository math papers is so hard! It takes like, a day per page. Pick something easy, give yourself plenty of times to digest the ideas before writing, and go slow! (Do not take this advice as insulting! It comes from years of failing to read papers well.)
Answer: A general principle is to write down your report with one audience in mind: yourself, but before you started studying the paper.
Answer: As a former journal editor, the most important advice I can give a reviewer is to find out where the author states his/her goals of the paper (i.e., what problems is being solved?  What mistake has been mode in the past? etc.).  Then ensure that the author accomplished that goal.  All too often, a goal is stated, and then the paper drifts into a half-measure, or just a lot of snow, and the goal is never addressed.

Advice reviewing academic paper


How do I pass a theme variable from a template to another?

Question: Several fields in a node need to be displayed in a particular way depending upon which newsletter body they are a part of. How do I pass a variable from the enclosing newsletter body to enclosed fields so that I can inform the field of its context and control the way the field is displayed?
I have a theme that has preprocess functions both for the newsletter body and for fields contained within the body.
I want to set a variable in the body preprocess function, and its related twig template, that can be inspected by the field preprocess function, and/or its own template.
In other words, I want each field to be aware of the body context in which it is being rendered.
Specifically, I have mytheme_preprocess_simplenews_newsletter_body() that sets a variable ($variables['summons'] = 'placeholder';) which can be inspected (and also set) by the theme's simplenews-newsletter-body.html.twig template, but (because it's in a different render array) is subsequently neither visible to mytheme_preprocess_field() nor field--node--title.html.twig.
How do I communicate between the two render arrays?
Note that

There are apparently global variables like $db_is_active and
$is_admin.
Sometimes, it is possible to achieve this kind of thing by cascading CSS
class attributes from a containing element to a contained element. This is not generally satisfactory and in this particular case, it won't wash on different target mail clients unpredictable treatment of CSS.
Comment: I've tried $variables['context']  but it doesn't work. Using drupal_static() seems the only way - ridiculous
Answer: The solution I am working with is to use drupal_static(); simplified essentials in code below - take care with the &ampersands. It is giving me control where I need it.
So, using this approach, I can - taking their global context into account -  per field, set variables in the usual way e.g. in mytheme_preprocess_field() subsequently to be used in a related template like field--node--title--agenda.html.twig
function mytheme_preprocess_simplenews_newsletter_body(&$variables) {
  // prepare to alter static var ...
  // get a reference binding to static var
  $var = &myvariable_function();
  // alter static var
  $var = 'simplenews_newsletter';
}

function mytheme_preprocess_field(&$variables, $hook) {
  // prepare to read static var
  // assign static var
  $var = myvariable_function();
  // $element is the render array for the field
  $element = $variables['element'];
  // filter those cases where it matters that we're theming a newsletter
  if ($element['#view_mode'] == 'email_html' and $var == 'simplenews_newsletter') {
    // Do stuff here like setting a variable for twig ...
    $variables['summons'] = 'some text';
  }
}
function &myvariable_function() {
  $var = &drupal_static(__FUNCTION__);
  if (!isset($var)) {
    // generate contents of static variable
    $var =  'initial_value';
  }
  return $var;
}

I am sure that there are other ways of communicating common context between different levels of a page's render hierarchy. Let me know how you'd do it.
Comment: There's a related core issue:  https://www.drupal.org/project/drupal/issues/2511548
Answer: I use this code:
/**
 * Helper function to pass slider variables from preprocess_page to preprocess_page_title_custom
 * @param  string $new_image Image URL
 * @return array             Images URL Array
 */
function _core_slider_images($new_image = NULL) {
  $vars = &drupal_static(__FUNCTION__, array());
  // If a new value has been passed add to the array.
  if ($new_image) {
    $vars[] = $new_image;
  }
  return $vars;
}

From this template:
In page.html.twig we have access to the $node var, and we need to pass the values to another template that don't have  access to this var. We will search the values that we need to pass and call the _core_slider_images(), this function will be the bridge between the two templates (preprocess functions)
/**
 * Implements hook_preprocess_page().
 */
function MODULE_preprocess_page(&$variables) {
  // ...
  // Sending Images URL and titles from page to page_title.
    for ($i = 0; $i < $cant; $i++) {
      // Adding the images to the static function.
      _core_slider_images($variables['node']->field_image[$i]->entity->url());
    }
  }

To this template:
page-title-custom.html.twig is a custom template and don't have access to $node. As hook_preprocess_page() is called first we have stored the $node values in a static var, and we only need to call the _core_slider_images() function.
/**
 * Implements hook_preprocess_HOOK().
 */
function MODULE_preprocess_page_title_custom(&$variables) {
  // Searching the variables for sending to the page-title-custom template.
   $images = _core_slider_images();
}

Answer: I'm still new to D8, so I could easily be missing a trick. Generally in this situation you want to look for the most specific hook that gives you access to everything you want to alter. So altering at the field level is too specific and at the page level (for example) is too general.
Unfortunately MailEntity isn't a real (Drupal) entity, so you can't use standard hooks to alter its render array. It doesn't invoke any custom hooks I can see to allow you to alter the content either. In D7 in this situation I'd be tempted to use hook_page_alter() which is dirty but would work I think, but that's been removed from D8.
You could always override the MailEntity class and provide your own customisations directly there, but needing to do that for theme changes does seem a bit wrong to me.
Comment: My OP poses my question as clearly as I can: you've quoted the nub of it in your post. In this case the  "body" is not the `body` field of a node; it's the body of the newsletter that contains the displayed view_mode of the node. If you were to look at the twig debug info you'd see clearly how `simplenews-newsletter-body.html.twig`  contains an hierarchy of entities; entity relationships; taxonomy terms; and fields that make up the email "body".  Even if I were to employ ` hook_entity_view_alter()` I'd still need to know the context of the body in which the entities were being displayed.
Comment: @iainH You've described the mechanism you want, just not what exactly you're using it for: maybe there's another way to reach your ultimate goal. I'm still not clear what you really mean by _the context of the body in which the entities [are] being displayed_. I'll try to update the answer with what seems like the way forwards to me. (Btw I don't see any twig debug info??)
Comment: I added an initial paragraph in the question. Hope that makes the case clearer.
Comment: I appreciate your time. re twig debug info ... a bit lengthy to include a meaningful snippet in this forum but if I show you the enclosing template, I think this illustrates the hierarchical nature of the newsletter body. This is `simplenews-newsletter-body.html.twig`:      `{{ title }} {{ build }}
` - that's it.
Comment: @iainH it's very clear now I've looked at the module itself, thanks! It feels to me like the code in MailEntity.php is missing at least one alter hook, but with D8 I'm still not confident what the Drupal Way is yet. I'd rather not be overriding plugins for theme level changes tho :/


Rewrite and redirect in asp.net rewrite rules

Question: I am really struggling to understand rewrite rules and why mine do not do as id expect.
I have 2 rules, and basically what I need to achieve is that it picks up my pretty URL, regardless of sub directory and then redirect to a specific folder. This will then use an id, which is specified in the pretty URL to then hit the appropriate page in my solution.
So, this rule should be able to grab anything that comes before the pretty URL and then redirect to the folder /gen1/ from the root directory.
<rule name="PokemonGen1Rule 1">
    <match url="^gen1-[\w-]*[^?]*-pkmid([\d]+)\.html" ignoreCase="true" />
    <action type="Redirect" url="^/gen1/{R:0}" />
</rule>

This rule should then catch the url as it hits the gen1 folder and use the id contained within the pretty url, to pass it is as a parameter to the pokemon.aspx page.
<rule name="PokemonGen1Rule 2">
    <match url="^gen1/gen1-[\w-]*[^?]*-pkmid([\d]+)\.html" ignoreCase="true" />
    <action type="Rewrite" url="/gen1/pokemon.aspx?pkmid={R:1}"
    appendQueryString="false" logRewrittenUrl="true" />
</rule>

It doesnt work, yet in my brain i cant work out whats broken. I've tried various different combinations of putting chevrons, and whatnot and it doesnt work.
Any suggestions would be greatly appreciated.
Answer: <rule name="PokemonGen1Rule 1" stopProcessing="true">
    <match url="[\w-]*[^?]*/(gen1-[\w-]*[^?]*-pkmid([\d]+)\.html)"
    ignoreCase="true" />
       <conditions>
         <add input="{REQUEST_URI}" negate="true"
           pattern="/gen1/gen1-[\w-]*[^?]*-pkmid([\d]+)\.html"
           ignoreCase="true" />
       </conditions>
   <action type="Redirect" url="/gen1/{R:1}" />
</rule>
<rule name="PokemonGen1Rule 2" stopProcessing="true">
    <match url="[\w-]*[^?]*/gen1-[\w-]*[^?]*-pkmid([\d]+)\.html"
    ignoreCase="true" />
     <action type="Rewrite" url="/gen1/pokemon.aspx?pkmid={R:1}"
     appendQueryString="false" logRewrittenUrl="true" />
</rule>

Solved it!


Implicit typecasting not working

Question: I have an abstract class called Product and another class called DifferentProduct and an interface called IProduct.
Both class Product and class DifferentProduct are derived from an interface called IProduct.
public class Product : IProduct
{
    public int ID { get; set; }
    public string ProductName { get; set; }
}

public class DifferentProduct : IProduct
{
    public int ID { get; set; }
}

public interface IProduct
{
    int ID { get; set; }
}

I have function in which I am passing
    ProductListing( List<IProduct>, List<IProduct> )
    {

    }

Now trying to call function from some file
    List<Product> productList1;
    List<DifferentProduct> differentProductList;

    XYZ.ProductListing( productList1, differentProductList );

I am getting following errors on above line

error CS1503 : Argument 1 cannot convert from
  'System.Collections.Generic.List' to
  'System.Collections.Generic.List '
error CS1503 : Argument 2 cannot convert from System.Collections.Generic.List to
  System.Collections.Generic.List

Is there any way to work out this solution without explicit typecasting ?
I need to work without explicit typecasting.
Comment: Read about Covariance and Contravariance. https://msdn.microsoft.com/en-us/library/dd799517(v=vs.110).aspx
Comment: This question is definitely a duplicate of some co/contra variance question
Comment: A list of apples is not a list of fruits. You can add an orange to a list of fruits, but your apple list can't accept that. Your list of DifferentProduct is the same thing. Someone working with a list of Product might expect to be able to add a Widget to your list, but you only gave (or, rather, tried to give) it a list that could accept DifferentProduct.
Comment: Since your method is called `ProductListing`, do you *really* need `IList` as your arguments? Won't `IEnumerable` be enough?
Answer: Try this:
var productList1 = new List<IProduct>();
productList1.Add(new Product());

var differentProductList = new List<IProduct>();
differentProductList.Add(new DifferentProduct)();

XYZ.ProductListing(productList1, differentProductList);

You could also do something like this:
ProductListing<T, U>(List<T> list1, List list2) where T : IProduct, U : IProduct

Answer: That is because an List<Product> is not a List<IProduct>, the same with List<DifferentProduct>.
If parameter types in ProductListing(...) can be changed to a covariant interface like IEnumerable<IProduct> or IReadOnlyList<IProduct> then you can pass lists of Product or DifferentProduct without problems.
Something like this:
void ProductListing(IReadOnlyList<IProduct> list1, IReadOnlyList<IProduct> list2)
{
    ...
}

Then this is possible:
List<Product> productList1;
List<DifferentProduct> differentProductList;

XYZ.ProductListing(productList1, differentProductList);

Answer: Try Using generics :
class Program
{
    static void Main(string[] args)
    {
        test t = new test();
        List<Product> productList1 = new List<Product>();
        List<DifferentProduct> differentProductList = new List<DifferentProduct>();

        t.ProductListing(productList1, differentProductList);
    }
}

public class test
{
    public void ProductListing<T, U>(List<T> list1, List list2)
        where T : IProduct
        where U : IProduct
    {

    }
}

public abstract class Product : IProduct
{
  public int ID { get; set; }
  public string ProductName{ get; set; }
}

public class DifferentProduct : IProduct
{
  public int ID{get; set;}
}

public interface IProduct
{
    int ID { get; set; }
}

Comment: my bad, generic constraints trip me up sometimes. I'd personally make the method parameters be of some covariant interface type instead though, I don't think there's any need for generics here. I find there are very few cases where I actually want a concrete `List` in a method signature.
Comment: I did it this way, because what he wants is to call the ProductListing method with the constraint that the type in the List is an implementation of IProduct interface.

Implicit typecasting not working


Rsync pull - host key verification failed

Question: I have set up an Rsync job to backup my Nextcloud data folder (NC on a Raspberry Pi, Raspbian Stretch, on my local network) to my OMV server (Debian Stretch, OMV 4.1.19). So far I did the following:

As the Nextcloud data folder is owned by www-data, I created a user "NCrsync" on the Pi and added it to the www-data group
In the OMV GUI, I created a new SSH key and tried to copy the public key to the Pi which failed as the GUI can't handle the "Trust this RSA key" prompt. So I created the file /home/NCrsync/.ssh/authorized_keys on the Pi, copied the public key from the OMV GUI and pasted it into this file
Set up an Rsync job in the OMV gui with the following settings:

Type: Remote
Mode: Pull
Source server: NCrsync@<pi-ip>:/media/hdd1/data
Destination folder: shared folder on my OMV server
Authentication: Public key
SSH port: 22
SSH certificate: nc-rsync

However, if I start the Rsync job, it fails:
Please wait, syncing <NCrsync@<pi-ip>:/media/hdd1/data> to <path-on-server> ...

Host key verification failed.
rsync: connection unexpectedly closed (0 bytes received so far) [Receiver]
rsync error: unexplained error (code 255) at io.c(235) [Receiver=3.1.2]

The synchronisation has completed successfully.
Done ...

What could be the reason for this to fail?
Thank you very much in advance!
Answer: AFAIK, OMV rsync jobs are running on root account with cron.
I thought that you have to add a hostkey to /root/.ssh/known_hosts on OMV.
I don't know how to do it via GUI.
So I once logged-in OMV with ssh, then invoked 'sudo -i' and 'ssh remote-server'.
I hope this will help you :-)
Comment: Thanks, I'll try that!


Fontawesome doesn't work, the icons aren't shown

Question: The problem is that my website aren't shown the Icons. I am a starter and I don't see some error there.
Here is the Code:
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" integrity="sha384-wvfXpqpZZVQGK6TAh5PVlGOfQNHSoD2xbE+QkPxCAFlNEevoEH3Sl0sibVcOQVnN" crossorigin="anonymous">

and here I tried to use icons:

                Home

That is not the full code but I think it should display an icon.
Comment: That's unrelated to this issue.
Answer: The fas variant doesn't exist in that library. Use fa.

<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" ntegrity="sha384-wvfXpqpZZVQGK6TAh5PVlGOfQNHSoD2xbE+QkPxCAFlNEevoEH3Sl0sibVcOQVnN" crossorigin="anonymous">

                Home


how to install phpshield loaders on centos 5 64 bit, (i have php 5.3.8)

Question: I have followed this tutorial and this one, I have downloaded the proper version and still cannot get phpmotion to detect it. Before i contact the support team for help, I just want to know if there's a third way to install phpshield loaders
Answer: Download loaders for Linux 64b and copy ixed.5.3.lin inside /usr/lib64/php/modules dir.
Then open /etc/php.ini and add the next line at the end of the file

extension=ixed.5.3.lin

Save the changes and restart apache (service httpd restart)


Recorder left-hand thumb position with certain note combinations

Question: Looks like thumbs in general are a real issue for me.
I'm teaching myself the recorder, and would not want to acquire a bad habit. I'm approaching notes in the higher octave (soprano recorder) and closing the thumb hole partially in a solid way becomes of paramount importance.
My question is what to do with the thumb when playing notes that don't require the thumb (e.g. high D). I find myself starting a piece with my thumb well in position (upper left part of my thumb closes the thumb hole), which allows me to play high notes that require the thumb hole to be half closed (e.g. high E, G, A) very swiftly (I just gently slide my thumb back), but if after a while I encounter the aforementioned high D then it becomes very hard to find that good thumb position again while playing.
So what does one do when one plays a high D? Does one simply slide it more and more (like one would do for partially closed notes) but keeping it on the recorder or does one lift it completely from the instrument? I have tried the former solution and the issue seems to be that one has to REALLY slide the thumb out of the holes way to make the D sound well.
Any tips?
Comment: Not having played for years, but while the thumb is in contact with the body of the recorder, you know where it is. Once it waves about freely, it's more difficult to re-instate it in exactly the spot you need it.
Answer: I lift my thumb completely off for the D.
It may seem a bit counter-intuitive, but it's actually a smaller and easier movement than the slide you're talking about. When you "half" hole for the higher notes you're moving your thumbnail less than a quarter of the width of the hole, and there's enough give in your flesh that the contact area between your thumb and the recorder probably isn't moving at all. As you've discovered, to completely open the hole for the D you have to extend that movement a LONG way, much further than seems reasonable, actually sliding your skin against the wood as you do so. It's an awkward movement, there's a tendency for the thumb to roll, and you lose your nice comfortable position on the thumb hole.
If you lift your thumb to achieve the same result, the minimum movement necessary is actually much smaller, and it's much easier to immediately put your thumb back down in the same position. Try trilling between C and D by lifting and then by sliding - which is easier?
If you don't think there's much in it either way, try the same exercise on a tenor.
Answer: Lift the thumb. You don't have to lift it very far.
Rolling the thumb all the way off the tone hole fundamentally changes your grip on the instrument, which is already kind of tenuous, especially when playing notes with few fingers on the instrument like the second octave D.
Answer: Look at your left hand as a whole - it should be in a relaxed C shape. Your right thumb and lips provide the stability needed to keep all fingers of your left hand off the instrument. With a good hand shape you can keep the thumb always over the thumbhole and you'll develop the muscle memory to keep it from flying around as you need to replace it either full or half-hole depending on where you're going from the D or C#.
I bend the thumb knuckle with very little motion on and off the thumbhole, that gives me the top-left side of the thumb to act as my half-hole edge.  -- your mileage may vary --


AccessDenied for requests to redirecting S3 bucket deployed using CDK

Question: I'm migrating a static website hosted on Amazon S3 to use CDK for deployment, following the example. I want to redirect from www.mydomain.com to mydomain.com so I have S3 buckets for both, and the www one redirects to the apex domain. They're both fronted by CloudFront. I had all this working before using CDK, but after migrating I'm getting an AccessDenied error when accessing the www URL. The code to deploy the buckets looks like this:
const siteBucket = new s3.Bucket(this, 'SiteBucket', {
    bucketName: siteDomain,
    websiteIndexDocument: 'index.html',
    websiteErrorDocument: 'error.html',
    publicReadAccess: true,
    removalPolicy: cdk.RemovalPolicy.DESTROY,
});
new cdk.CfnOutput(this, 'Bucket', {value: siteBucket.bucketName});
const wwwRedirectBucket = new s3.Bucket(this, 'WwwBucket', {
    bucketName: wwwDomain,
    websiteRedirect: {hostName: siteDomain, protocol: RedirectProtocol.HTTPS},
    publicReadAccess: true,
    removalPolicy: cdk.RemovalPolicy.DESTROY,
});
const certificateArn = "arn:aws:acm:etcetc"

const distribution = new cloudfront.CloudFrontWebDistribution(this, 'SiteDistribution', {
    aliasConfiguration: {
        acmCertRef: certificateArn,
        names: [siteDomain],
        sslMethod: cloudfront.SSLMethod.SNI,
        securityPolicy: cloudfront.SecurityPolicyProtocol.TLS_V1_1_2016,
    },
    originConfigs: [
        {
            s3OriginSource: {
                s3BucketSource: siteBucket
            },
            behaviors: [{isDefaultBehavior: true}],
        }
    ]
});

const wwwDistribution = new cloudfront.CloudFrontWebDistribution(this, 'WwwDistribution', {
    aliasConfiguration: {
        acmCertRef: certificateArn,
        names: [wwwDomain],
        sslMethod: cloudfront.SSLMethod.SNI,
        securityPolicy: cloudfront.SecurityPolicyProtocol.TLS_V1_1_2016,
    },
    originConfigs: [
        {
            s3OriginSource: {
                s3BucketSource: wwwRedirectBucket
            },
            behaviors: [{isDefaultBehavior: true}],
        }
    ]
});

I've looked at the bucket in the console and as far as I can tell it all looks good. Am I missing something obvious?
Answer: I figured this out using this answer. Instead of:
s3OriginSource: {
    s3BucketSource: siteBucket
},

I need the following:
customOriginSource: {
    domainName: bucket.bucketWebsiteDomainName,
    originProtocolPolicy: OriginProtocolPolicy.HTTP_ONLY,
},

Redirects and other website-like features will not work when using the REST-style interface, which it looks like CDK configures by default.


How can I use thre Migrate module?

Question: I installed the Migrate module, but I can't use it, nor can I find any useful documentation that explains how to use it. The page on /admin/content/migrate is empty.
How can I use this module?
Answer: The Migrate module only provides a flexible framework for data migration into Drupal. The logic and data mappings to perform an actual migration are pretty complex. Migrate does not provides an UI to build or configure your migration. IMHO, this is good because a complete UI to build such script would be at least as complex as writing it directly in PHP.
Its documentation is pretty complete and provides all the information needed to start using it. I recently started to use it and, coming from an OOP background, find it intuitive and easy to learn.
Answer: Speaking as one of the maintainers, Migrate is kind of a pain at first with but once you get up to speed on it's really powerful. The biggest change between version 1.x and 2.x is as MPD noted the lack of of the Table Wizard. It's now all class based which makes it trickier to setup a migration but much more flexible. Instead of having to get all your data into MySQL now you can use a variety of different sources.
I've got some slides that might be helpful:
http://denver2012.drupal.org/sites/default/files/Migrate.pdf
Comment: The link no longer works.
Comment: Fixed the link. It seems like they'd archived the site.
Answer: Cyrve developed the module and they have a post on the blog entitled Performing a data migration with migrate module that might be helpful.
Also, the video from the Migration: not just for the birds presentation at Drupalcon DC 2009 is probably somewhat out-of-date, but it should provide a good overview.
Comment: Yes, Acquia bought Cyrve a while back: http://techcrunch.com/2011/08/16/acquia-expands-drupal-product-suite-with-purchases-of-cyrve-growing-venture-solutions/
Comment: Cyrve appears to have migrated south, **deep** south (3 out of 4 links here are dead).
Answer: Migrate 2 is powerful. Just spent some time to learn it you won't regret.
Here's a full example of migrating contents to Drupal 7.
http://miss-hana.com/migrate-contents-from-drupal-6-to-drupal-7-using-migrate-2/
Answer: Very nice documentation in the answers.
Personally I found this post very helpfull
Using migrate module to handle big data imports
Answer: Are you accessing it as the admin user (uid 1)?  If not, I suspect you need to explicitly assign permissions.  Goto /admin/user/permissions, find the "migrate module" heading, and assign permissions as needed.
The last time we used this module, we did it in conjunction with Table Wizard.
To be honest, I just find it easier to write manual import scripts, rather than work within the confines of these modules.
Answer: This link might might help explain more about migration. It contains screen shots as well as examples. it gives a step by step approach to migration. http://www.lullabot.com/articles/drupal-data-imports-migrate-and-table-wizard. This link give a brief explanation on how to migrate content http://btmash.com/article/2011-02-25/migrating-content-using-migrate-module.
I found think link about  migrating the cck construction it. It might be worth a look as well. http://drupal.org/node/1144136
Answer: It's possible to move your website content directly from your Drupal to Joomla without using the importer module. You may try cms2cms tool that migrates site content via the connection bridge that is created between your sites. Such process requires both of your sites Drupal and Joomla being available online. Here you may watch how this converter works http://www.youtube.com/watch?v=cCkW-vwzlEg
But, if you want to move custom type posts, I'm not sure this tool will work as well with the migration of your theme.

How can I use thre Migrate module?


How do we override the default indexing limit in mongoDB?

Question: I have an AWS Cognito JWT of more than 125 characters for which I need to create indexing in MongoDB. But the problem is MongoDB indexing accepts the character of max limit, 125. How can we set the max limit or is there any way to increase the default character limit.
I tried indexing the JWT(around 150 characters) where I have the following error.
<code>  MongoError: WiredTigerIndex::insert: key too large to index, failing  1025 { : "email@example.com", "asdfghjkertyjk......"}
</code>
This how I created schema index.
<code>schemaName.index({ email: 1, token: 1 });
</code>
Comment: You haven't mentioned what version of MongoDB server you are using, but the current [Index Key Limit](https://docs.mongodb.com/manual/reference/limits/#Index-Key-Limit) is 1024 bytes. The error message suggests you are trying to index a value of 1025 bytes, so your JWT value appears to be much larger than expected. Indexing large values generally isn't helpful for performance, so I would definitely consider a different approach.
Answer: I would go with a different approach, as indexing a large text/string field is not always the best option.
Use SHA1 or MD5 to generate a unique checksum of the JWT string (which will give you a constant string length) and save that field. Index and search by that field
Another option is to decode the JWT token to JSON and store it as an embedded document - and then you can index the document (but it's risky option IMHO)
Comment: you can still use it - add another field which holds the SHA1/MD5 result - and when you do a lookup - calculate the SHA1/MD5 and lookup by that value.
You'll probably will get a faster index lookup...

Another option is to decode the JWT token to JSON and store it as an embedded document - and then you can index the document (but it's risky option IMHO)
Comment: Thank you, Shahar. As per my requirements, I need to use the Cognito JWT token.


QR code ios 7 AVMetadataObject

Question: I Have problem with detect where is qr code.
I need draw border around it.
I use AVMetadataObject bezierpath, but it dont work.
Please help me.
- (void)captureOutput:(AVCaptureOutput *)captureOutput
didOutputMetadataObjects:(NSArray *)metadataObjects
       fromConnection:(AVCaptureConnection *)connection
{
    for (AVMetadataObject *metadata in metadataObjects)
    {
            AnimationView *cv = [[AnimationView alloc]initWithFrame:self.livevideo.bounds]; //creat an instance of your custom view
        [cv setBackgroundColor:[UIColor clearColor]];

        NSLog(@"%f",metadata.accessibilityPath.accessibilityActivationPoint.x);

        [location addSubview:cv];

        if ([metadata.type isEqualToString:AVMetadataObjectTypeEAN13Code])
        {

        }
        else if ([metadata.type isEqualToString:AVMetadataObjectTypeUPCECode])
        {

        }
        else if ([metadata.type isEqualToString:AVMetadataObjectTypeEAN8Code])
        {

        }
        else if ([metadata.type isEqualToString:AVMetadataObjectTypeQRCode])
        {

        }
    }
}

Answer: You will need to use the corners property from AVMetadataMachineReadableCodeObject to draw a perspective box around the detected code.
See my example at https://github.com/werner77/WECodeScanner
Comment: You save me :)
Thank you!
Comment: Have you any ide why I have this error with XCtest? clang: error: linker command failed with exit code 1 (use -v to see invocation)
Comment: Werner Altewischer, thank you for the very instructive code you shared with all of us.
Answer: Use the transformedMetadataObject(for:) method on AVCaptureVideoPreviewLayer.
In the AVCaptureMetadataOutputObjectsDelegate method below, the previewLayer is an instance of AVCaptureVideoPreviewLayer.
func metadataOutput(_ output: AVCaptureMetadataOutput, didOutput metadataObjects: [AVMetadataObject], from connection: AVCaptureConnection) {
    if let metadataObject = metadataObjects.first, let transformedMetadataObject = previewLayer.transformedMetadataObject(for: metadataObject) {
        print(transformedMetadataObject.bounds)
    }
}

QR code ios 7 AVMetadataObject


Variable transformation Birnbaum-Saunders distribution

Question: I am having some trouble with a textbook problem.
I have to show that if T ∼ BS(α, β) then 1/T∼ BS(α, 1/β) How should I do it?
I already find the way to show that T is Birnbaum-Saunders distributed by doing a transformation
of the R.V.

then I find out that Z is a standard normal random variable so it was easy to find the mean and the Variance.
Now I don't know how to show that 1/T is also Birnbaum-Saunders distributed, I tried to replace 1/T and 1/B in the pdf, but I'm not sure how to proceed.
Any help will be appreciated.
Here the PDF and the CDF of the Birnbaum-Saunders
Comment: Please type your question as text, do not just post a photograph or screenshot (see
[here](https://stats.meta.stackexchange.com/a/3176/)). When you retype the question,
add the [tag:self-study] tag & read
[its wiki](https://stats.stackexchange.com/tags/self-study/info).
Then tell us what you understand thus far, what you've tried & where you're stuck.
We'll provide hints to help you get unstuck. Please make these changes as just
posting your homework & hoping someone will do it for you is grounds for closing.
Answer: Here are some hints: Use the fact that for a probability distribution $X$ with strictly positive support (which the Birnbaum-Saunders distribution is), it is relatively easy to find the distribution of $Y=1/X$. Let $F_{X}(x)$ be the cumulative distribution function (cdf) of $X$. Then, the cdf of $Y$, $F_{Y}(y)$ is:
$$
F_{Y}(y) = \mathbb{P}(1/X\leq y) = \mathbb{P}(X\geq 1/y) = 1 - F_{X}(1/y)
$$
Another useful fact is $1-\Phi(x)= \Phi(-x)$. So you're left to show that $1-F_{X}(1/y;\ \alpha, \beta) = F_{X}(y;\ \alpha, 1/\beta)$.


$GL_n(F)$ acts on the flag variety

Question: I have the following 2-part question as a homework assignment...

Let $F$ be a field and $n\in \mathbb{Z}_{\geq 1}$. A full flag in the vector space $F^n$ is a chain of subspaces
  \begin{align} \{0\}\subset V_1\subset \cdots\subset V_{n-1}\subset V_n=F^n\end{align}
  such that $\dim V_i=i$ for all $i\in \{1,2,...,n\}$. The flag variety of $GL_n(F)$ is the set $\mathcal{B}$ of all full flags in $F^n$.
(a) Show that $GL_n(F)$ acts on the flag variety $\mathcal{B}$.
(b) Let $e_i$ be the coordinate basis vectors of $F^n$. Let $e_{*}$ be the full flag given by $V_i=\mathrm{span}\{e_1,...,e_i\}$. Show that $\mathrm{Stab}_{GL_n(F)}(e_*)=B$, where $B$ is the subgroup of upper-triangular matrices.

I feel like once i understand how to tackle part (a), I will understand part (b), but at the moment I really don't understand what this flag variety really is.
$\quad$-What does an element of the flag variety look like?
$\quad$-How would $GL_n(F)$ act on such an element?
These are the things I need some hints on. Thank you!
Comment: OK this part is beyond the level of hint you asked for.  But it's also helpful when showing an action exists, to describe also: (3) What properties are preserved under this action?  (4) Why did they pick $GL_n(F)$ instead of $M_n(F)$, i.e. why invertible matrices instead of all $n\times n$ matrices? (5) Is the action transitive? What about free? etc.
Comment: I think there might be a typo, as I'm pretty sure $\mathcal{B}$ should be "the set of all full flags", not "the set of all full flag varieties".  So an element is a full flag as they described.
Comment: For the question of how $GL_n(F)$ acts on $\mathcal{B}$, we need to know at minimum: (1) is there a sensible way to make any invertible $n\times n$ matrix $M$ transform a full flag? I would say yes: multiply $M$ by every vector in the subspaces. (2) Is the result always a full flag?  (It needs to be, to have a group action.)
Comment: @ElizabethS.Q.Goodman you're right, I fixed it.
Comment: Does that help though or are you still stuck?
Comment: @ElizabethS.Q.Goodman between your hints and N.H. I understand this problem now, thank you both so much!
Answer: 1) If $V_1 \subset V_2 \subset \dots \subset V_n$ is a flag, and $g \in GL_n(F)$ then $gV_1 \subset gV_2 \subset \dots \subset gV_n$ is a flag. This is the action of $GL_n(F)$ on $\mathcal B$.
2) Let $g \in Stab(e_*)$. This mean that $g V_i \subset V_i$ for all $i$. For $i = 1$, we want $g e_1 \in \text{span} \{e_1\}$ by definition so the first column of $g$ is $\begin{pmatrix} \lambda \\ 0 \\ \dots \\ 0\end{pmatrix}$
Next step is $gV_2 \subset V_2$, i.e $g e_2 \in \text{span}\{e_1, e_2\}$ i.e the second column of $g$ will be $\begin{pmatrix} \mu \\ \gamma \\ 0 \\ \dots \\ 0\end{pmatrix}$. I think you can continue easily this describtion.
3) If you want to be sure you understood correctly, you can try to find the stabilizer of the incomplete flag $\{e_1\} \subset \{e_1, e_2, e_3\}$ in $F^4$.

$GL_n(F)$ acts on the flag variety


MDT 2013 WinPE File Name

Question: In MDT 2013, is there a way to change the file name of the WinPE WIM that's generated from updating the share?
I'm going to be using multiple deployment shares with WDS, and I was trying to automate importing the WinPE WIMs into WDS. I know you can change the image name, but it would be easier for the WIM file name to be different from LiteTouchPE_x64 (or x86). I was thinking about just adding an rni line to the PS script for auto importing to WDS, but I wasn't sure if it would cause any issues if I manually renamed the WIM file.
Comment: Are you referring to automatically generating a file with a certain name or just about manually renaming WIM files?
Answer: Manually renaming the file is not a problem.
Changing the name in the deployment properties only changes the description, but not the filename I presume?
Since you are importing the Images in WDS, what does the original WIM-containers file matter? I would assume the image name matters but the filename seems irrelevant to me.
Comment: I was modifying a PowerShell script to copy the boot image to the WDS folder, and I didn't want the boot image from Company A to overwrite the boot image from Company B. I ended up adding a line;    cpi X:\CompanyA\Boot\LiteTouchPE_x64.wim X:\RemoteInstall\Boot\x64\Images\CompanyA.wim  to the script that gets the job done.
Answer: Unfortunately you cannot change the name of the image that is automatically generated in MDT.
You can safely change the name of the outputted WIM file without affecting anything.
When WDS imports a boot image it renames it to boot.wim on the inside of the WDS file storage system, so the filename that MDT outputs is really only for the sysadmin.
It is the image name and description that really counts. I would change those as WDS automatically gathers that info upon image import (using the GUI) and that is what you see when manipulating the images.

MDT 2013 WinPE File Name


Get specific cell values of Excel file in Laravel/Cyber-duck excel

Question: Currently, I can get the data coming from excel file with this format.

This is my working code.
        $validator = Validator::make(
        [
            'file'      => $request->file,
            'extension' => strtolower($request->file->getClientOriginalExtension()),
        ],
        [
            'file'          => 'required|max:5000',
            'extension'      => 'required|in:,csv,xlsx,xls',
        ]
    );

    $modal = "active";
    if($validator->fails()){
        return redirect()
        ->back()
        ->with(['errors'=>$validator->errors()->all()])
        ->with('modal',$modal);
    }

    $dateTime = date('Ymd_His');
    $file = $request->file('file');
    $fileName = $dateTime . '-' . $file->getClientOriginalName();
    $savePath = public_path('/upload/projectlist/');
    $file->move($savePath, $fileName);

    $excel = Importer::make('Excel');
    $excel->hasHeader(true);
    $excel->load($savePath.$fileName);
    $collection = $excel->getCollection();

    if(sizeof($collection[1]) == 5)
    {
       $arr = json_decode($collection,true);
            foreach ($arr as $row) {
                $insert_data[] = array(
                    'first_name'  => $row['first_name'],
                    'last_name'  => $row['last_name'],
                    'email'  => $row['email'],
                    'birthdate'  => $row['birthdate']['date'],
                    'created_at'  => now(),
                    'updated_at'  => now(),
                );

            }

        DB::table('tbl_sampleimport')->insert($insert_data);
    }
    else
    {
        return redirect()
        ->back()
        ->with(['errors'=> [0=> 'Please provide date in file according to your format.']])
        ->with('modal',$modal);
    }

    return redirect()->back()
    ->with(['success'=>'File uploaded successfully!'])
    ->with('modal',$modal);

Now that the format was changed. Added some fields with single value. Like Project Name and Project Date
I'm trying to get its value. Just want to get the value but not necessary to save it too to the database.

How can I get the value of Project Name and Project Date to declare as a variable. and still be able to save the data of j.doe17 and j.doe18 ?
I'm using cyber-duck as my laravel/excel for import and so on.
Comment: I am suggesting you to go for other sheet for metadata in a same excel because if not the you are unable to get your collections as library unable to parse the header and unable to give you the key value pair of data.
Comment: Any library will have the same limitation. If you need collection then data should be like header row and data rows. I haven't found any solution till now that we can skip five rows and then get the collections.
Comment: gonna go for first option to separate sheets.
Comment: What is your importer class does ?
Is it a custom class that you have made it or it is a library.?
Comment: Have you used `phpspreadsheet` before?
Comment: I'm using cyberduck it's a library for laravel/excel. The current file is named as `sample.xlsx`
Comment: so what the basic things you can do is have two sheets one is for metadata like Project name and date and another is for data.
Comment: So you can get the data same as you are parsing before in collection.
Comment: Otherwise you need to manually go to every rows and columns and do the checks
Comment: not possible if the excel format is like in the picture? Since I have lot of fields in different cell range to be added soon.. That format is just a sample and will add more when I know how to get the values of specific cells
Comment: what not possible having two sheets in one excel or manual thing?
Comment: one sheet only but all of the fields are there no need to migrate some fields on the other sheets
Comment: Do I need to change my library just to get what I want? What library can you suggest
Comment: Cool @RaeIan if any one has the solution for what i mentioned above then they will give the answer otherwise separating sheets would be the best option.
Comment: my problem now, how to get the collection of specific sheet since cyberduck documentation doesn't include per sheet..
Comment: You should have `setSheet` method as shown here https://packagist.org/packages/cyber-duck/laravel-excel
Answer: Solution suggested by @Dhaval Purohit
create sheets and define setSheet($sheetNumber).

So I tried to create new sheet in the same excel file with this format only

and this will give me like this
[{
      "project_name":"Creator Doe",
      "project_date":"7/9/2019"
}]