Relationship between Primes and Fibonacci Sequence

Question: I recently stumbled across an unexpected relationship between the prime numbers and the Fibonacci sequence. We know a lot about Fibonacci numbers but relatively little about primes, so this connection seems worth exploring. I'm interested whether anyone knows of a theorem or proof of whether this relationship holds true in general for primes > 5 -- I've empirically tested it for the first 100k primes using Mathematica, but that's hardly a proof.
$$
S_n = GCD(n, Fib(n+1))
$$
If we evaluate this for $n ~ in ~{1..100}$ we get:
{1, 2, 3, 1, 1, 1, 7, 2, 1, 1, 1, 1, 13, 2, 3, 1, 17, 1, 1, 2, 1, 1,
     23, 1, 1, 2, 3, 1, 1, 1, 1, 2, 1, 1, 1, 1, 37, 2, 3, 1, 1, 1, 43, 2,
     1, 1, 47, 1, 1, 2, 3, 1, 53, 1, 1, 2, 1, 1, 1, 1, 1, 2, 21, 1, 1, 1,
     67, 2, 1, 1, 1, 1, 73, 2, 3, 1, 1, 1, 1, 2, 1, 1, 83, 1, 1, 2, 3, 1,
     1, 1, 1, 2, 1, 1, 1, 1, 97, 2, 33, 1}
What's interesting about this result is that primes appears at their natural indexes: 2 appears at $n_2$, 13 appears at $n_{13}$, 83 appears at $n_{83}$, and so on. But some of the primes are missing, including:
{5, 11, 19, 29, 31, 41, 59, 61, 71, 79, 89}
But let's also examine the sequence:
$$
P_n = GCD(n, Fib(n-1))
$$
Here we find that in the first 100 terms we get:
{1, 1, 1, 2, 1, 1, 1, 1, 3, 2, 11, 1, 1, 1, 1, 2, 1, 1, 19, 1, 3, 2,
1, 1, 1, 1, 1, 2, 29, 1, 31, 1, 3, 2, 1, 1, 1, 1, 1, 2, 41, 1, 1, 1,
3, 2, 1, 1, 7, 1, 1, 2, 1, 1, 1, 1, 3, 2, 59, 1, 61, 1, 1, 2, 1, 1,
1, 1, 3, 2, 71, 1, 1, 1, 1, 2, 1, 13, 79, 1, 3, 2, 1, 1, 1, 1, 1, 2,
89, 1, 1, 1, 3, 2, 1, 1, 1, 1, 1, 2}
If we combine the sequences $S_n$ and $P_n$ we seem to get all of the primes, except 5:
{2, 3, (missing: 5), 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67,
71, 73, 79, 83, 89, 97}
Below is a simple Mathematica program that tests this for the first few thousand values:
<code>fibSuc[x_] := GCD[n, Fibonacci[n + 1]];
fibPre[x_] := GCD[n, Fibonacci[n - 1]];
fibPRZ[w_, fp_] :=
  (Cases[Select[Transpose[{Table[fp[n], {n, 1, w}],
     Table[x, {x, 1, w}]}], PrimeQ[#1[[2]]] & ], {a_, a_}]) /. {a_, a_} -> a;
genPrimes[z_] := Union[fibPRZ[z, fibSuc], fibPRZ[z, fibPre]];

With[{pz = genPrimes[50000]},
   Complement[Table[Prime[n], {n, 1, Length[pz] + 1}], pz]]
</code>
Comment: It's probably of note that the primes in the first list are $\pm 3 \pmod{10}$ and in the second are $\pm1 \pmod{10}$. $2,5$ are the only primes not in these categories
Comment: I'd also note that if $p$ is prime, then $P_p$ is either $1$ or $p$, so this result is not that surprising - what it says, for example, is that if $p \equiv \pm 1 \pmod {10}$ then $p \not \mid Fib(p-1)$
Comment: @LBushkin can you please write in your question what $Fib(1)$ is, so not every reader has to figure out on their own=)
Comment: This seems to be a known result, as it is listed on the Wikipedia page for the Fibonacci numbers (in the section "Prime divisors of Fibonacci numbers"). Unfortunately, no proof is given, although it references two books.
Comment: I was playing around with Fibonacci, and surprise!,  i found this prime number relationship:  https://repl.it/JJPL/55
Answer: For primes $p > 5$, the Binet formula applies mod $p$, in the following sense.
If $p \equiv \pm 1 \mod 5$, $5$ is a quadratic residue mod $p$, and  $z^2 - z - 1$ has two roots $\phi_\pm = (1 \pm \sqrt{5})/2$ in ${\mathbb Z}_p$.
Then $F_n \equiv ((\phi_+^n - \phi_-^n)/\sqrt{5} \mod p$.   In particular,
$F_{p-1}$ is divisible by $p$, so $\gcd(p, F_{p-1}) = p$.
If $p \equiv \pm 2 \mod 5$, $z^2 - z - 1$ doesn't have roots in ${\mathbb Z}_p$,
but it has roots in an extension field $GF(p^2)$.  In this case it turns out that  $F_{p+1}$ is divisible by $p$, so $\gcd(p, F_{p+1}) = p$.
EDIT: Note that we have $\phi_+ + \phi_- = 1$ and $\phi_+ \phi_- = -1$.
Since we're in characteristic $p$,
$\phi_+^p + \phi_-^p = 1^p = 1$, and $\phi_+^p\phi_-^p = (-1)^p = -1$ as well.
So $\phi_+^p$ and $\phi_-^p$ are also roots of $z^2 - z - 1$.  But there are only two such roots.  In the second case, we can't have $\phi_+^p = \phi_+$, because only elements of ${\mathbb Z}_p$ have the property $z^p = z$, so we must have $\phi_+^p = \phi_-$, and similarly $\phi_-^p = \phi_+$.
Then $$F_{p+1} = \dfrac{\phi_+^{p+1} - \phi_-^{p+1}}{\sqrt{5}} = \dfrac{\phi_- \phi_+ - \phi_+ \phi_-}{\sqrt{5}} = 0 \ \text{(as a member of $GF(p^2)$)}$$
i.e. $F_{p+1} \equiv 0 \mod p$.
Comment: Is there a simple proof that $F_{p+1}$ is divisible by $p$?  I know how to do this with the binomial theorem, but I don't see how to get here directly from $GP(p^2)$ (naively, we can show that $F_{p^2-1}$ is divisible by $p$, of course, which is a strong hint).
Comment: @you-sir-33433 : see latest edit.
Comment: @you-sir-33433 also see here: http://math.stackexchange.com/questions/695979/does-every-prime-divide-some-fibonacci-number/696599#696599
Answer: I would like to point out that $p$ cannot divide $F_{p}$ save perhaps in the case of $p=5$. Your indexing might be off by one; for example, $83 | F_{84}$ not $F_{83}$ as you suggest with the notation $n_{83}$.
In general, if $p$ is a prime then either $p|F_{p-1}$ or $p|F_{p+1}$ but not both. If, say, you consider $p = 83$, then $83 | F_{84}$ and so it must follow that $gcd(83, F_{84}) = 83$ for $83$ has no prime factors other than itself. The study of the Fibonacci sequence is perhaps best facilitated by an in-depth study of the Lucas sequences as the Fibonacci sequence is but one of a Lucas sequence.
Comment: This should be a comment.


Is there any integration of a defined function that could not be express as a convergent infinite series?

Question: Is there any integration of a defined function that could not be express as a convergent infinite series?Like if it could be getting a divergent series as an answer
I wonder if the answer is a yes or no.
Answer: If you're talking about power series, any function expressible by a  power series that converges in some open interval $(a,b)$ is analytic in a (complex) neighbourhood of that interval and so are its derivative and antiderivative.  So a counterexample would be a any function
that is integrable but not analytic.  For an example of a function that is smooth but nowhere analytic, see e.g. Wikipedia


Acronyms in HDD specification

Question: I wonder about acronyms in specification of Seagate Exos 7E8 8TB SAS (ST8000NM0075) and Seagate Exos X10 10TB SAS (ST10000NM0096) disks. In Performance part I can see:

Random Read/Write 4K QD16 WCD (IOPS) - Can you please tell me what's "4K QD16 WCD"?
Max. Sustained Transfer Rate OD (MB/s, MiB/s) - Can you please tell me what's "OD"?

Thanks.
Answer:
QD stands for "Queue Depth": it describe how many concurrent operation were issued to disk;
4K describes the size of the outstanding requests. In this case, it means 4 KB sized requests;
WCD stands for "Write Cache Disabled": it is a method to disable the disk DRAM writeback cache for enhanced data safety. Note that if WCD is set, HDDs without a NVC (non volatile cache) will have much lower random write performance. On the other hand, HDDs with NVC often have similar performance to a fully enabled writeback cache. Give a look here for more details. As a side note, this probably is the reason behind the significant random write performance difference between hyperscaler vs standard Exos model;
OD stands for "Outer Disk": as modern HDDs have a constant angular velocity, the outer disk tracks read/write faster than the inner one.
Answer: The results of IOPS performance tests depend for a large part on the settings used in the benchmarking tool. For any meaningful comparison with other drives (from the same manufacturer or not) you need to know what parameters were used in the test.
In addition to shodanshok's anwser :
4K = 4 kilobyte = the size of the read/write IO requests used in the test.
Aligning the IO request size with the native sector size used on a drive results in optimal (test) performance.
QD16 =  the Queue Depth used in the test.
By using the native command queuing a disk can optimize the order in which read/write commands are executed on the actual permanent storage. A high queue number is mainly of interest with SSD's as with their parallel channels maximizing the utilization of each channel requires sufficiently high queue depths, but even with spinning rust you see performance improvements by allowing the disk controller to optimize the order of requests.
Answer:
4K QD16 WCD means 4-kilobytes sector's size Queue Depth 16 commands Write Cache Disabled.
OD stands for Outer Disk tracks as described in the second answer.

Acronyms in HDD specification


Mobile menu closes automatically on scroll - how to hide or keep the address bar permanently?

Question: I'm having an issue with a responsive menu I've been working on for some of my designed sites. The jQuery part of it is made to show or hide the menu depending on window width (and hide/show a bar to toggle it).
In mobile browsers, the toggled-open menu will close again when you scroll -- but only if the address bar has been hidden or shown by scrolling down or up. This happens in Android and iOS.
I've definitely narrowed it down to the address bar's appearance and disappearance, because:

it only happens on mobile browsers.
the address bar doesn't disappear while the page is still loading (at least in Opera), and thus the menu doesn't close when I scroll under that condition.
the menu won't close if I scroll after the address bar has been hidden.

However, I don't know what to do to fix it; the address bar affects the height of the window/page, not the width, so I'm unsure of why the menu toggles when you scroll up/down.
This method is the simplest way for me to make a responsive menu with how things are set up currently.
Here's the relevant part of the code I'm using:
<code>    var winwidth = $(window).width();
    $(window).resize(function() {
        var newwinwidth = $(window).width();
        if(winwidth = newwinwidth && newwinwidth <= 768) {
            // if smaller or equal
            $('.menu ul').hide();
        } else {
            // if larger
            $('.menu ul').show();
        }
    }).resize();
</code>
Here's a live example of a site on which this happens: http://jessicacantlope.com
I've already tried a couple debounce methods to see if that would solve the problem (it doesn't; it just delays the action) and also scoured this website. I've included app-capable meta elements and a few other iOS-specific things.
I also looked into solutions that hide the address bar entirely, but they only work under certain conditions and rely on modifying system UI/UX, which is something I don't want to do. I just want to keep it simple.
Any help would be appreciated. I'm more of a designer than a developer, and I love elegant solutions.
EDIT, 2020: Five+ years later, after having implemented a solution that seemed to work for a while and then failed again, I started tinkering and realized that, for the way I had designed my mobile menu and website, and with some of the things I had tried since then, I had been mistakenly targeting the wrong selectors in my code! And I hadn't thought deeply enough about how to apply the first suggestion. It's not elegantly written so I won't post my final code, but I finally got things in working shape. Thanks, everyone!
Answer: I had the same issue when working on a responsive site of my own. I was unable to discover the root cause of the issue but I developed a work-around. The anchor which I use to display the menu had a "open" toggle class added to it. I essentially used the "window.onscroll" call to check whether or not the menu should be shown each time the user scrolls the page, "showing" the menu again after each scroll.
<code>window.onscroll = function (e) {
    var sidebar = $('#sidebar')
    var menu = $('#sidebar > ul');
    if(sidebar.hasClass('open'))
        {
            menu.show();
        }
    }
</code>
Hope this helps!
Comment: Thanks much, this is a decent workaround that I've now implemented! Of course, the menu still momentarily blips out when a scroll causes the address bar to hide and thus triggers the resize again, before it comes back via this solution. It wouldn't bug me so much if it blipped faster. I wonder if there's a way to control that? I'm thinking of coming up with a more CSS-oriented solution, too. But this is the kind of thing I was looking for, so thanks again.
Answer: I had faced the same problem. But I fixed the solution. The problem is, while scrolling the page some times it triggers the resize event of window. When it will check the width of the window it is less than 768px. So the menu will be hidden. There are two solutions for this. First one, you can remove window resize function. Second one, inside the window resize function you should check whether the navigation is opened or closed. According to that you can customize the hide and show process. Which means, if navigation is closed and window width is greater than 768px you can show navigation.
Comment: Thank's! That solved it for me! I just had to add an if statement around one of the resize functions to check if the menu was currently open and then it did not trigger the menu .slideUp() anymore =)
Answer: I was also facing the same issue and no matter what I do with resize() function matching height or width of dom the function was still triggering on mobile device so i tried using $(window).on("orientationchange",function() and the problem got fixed.
Answer: I found a solution for the problem here javascript resize event on scroll - mobile

<code>    var cachedWidth = $(window).width();
$(window).resize(function(){
    var newWidth = $(window).width();
    if(newWidth !== cachedWidth){
        //PUT YOUR RESIZE HERE
        cachedWidth = newWidth;
    }
});
</code>


How to select nested UL element without class in JavaScript

Question: In my Joomla template I've created a vertical menu including a dropdown which should "push" the elements below away when opening a submenu onclick. Somehow I don't get it to work..
I am trying to grab the UL inside an LI, but how can I do this in JavaScript without the UL's having a class or ID.
I've come to this yet:
function getElements(){
var listitems = {};
for(var i = 0; i< arguments.length; i++){
    var id = arguments[i];
    var item = navigation.getElementsByTagName("li");
    if (item == null)
        throw new Error ("No list items found.");
    listitems[id] = item;
}
return listitems;
}

Now I should get something like: (I now the following code is impossible, but it describes what I am trying)
var nav = document.getElementById("navigation");
var nestedList = nav ul li ul;
nestedList.onclick(nav ul li ul.style = "display: block";);

The HTML looks like:

The CSS looks like:
#navigation ul li ul{display: none;}

Now I want it to display: block when clicking on .parent
Thanks!
Comment: @VoogdWD If you already have MooTools, use that http://mootools.net/docs/core125/core/Utilities/Selectors
Comment: What is the variable `content`?
Comment: Can you please show your markup? Selection questions without markup are basically impossible to answer.
Comment: Is there any reason why you cant use jQuery? Just curious.
Comment: Oh excuse me, that has to be navigation.
Comment: Well, the Joomla version I am using has Mootools active to..
Comment: @Esteban jQuery is great and all, but basic DOM _traversal_ is not complicated enough to necessitate a whole library.
Comment: @Mathletics I've added some code above.
Answer: Since you already have MooTools included in your page, something like this should work (not a MooTools expert here):
$('#navigation li.parent').addEvent('click', function () {
  $('#navigation li.parent ul li ul').setStyle('display', 'block');
});

Old post:
Pure JS (this is not the full code, you have to loop over the elements several times for adding the click listener and applying the styles):
var listItems = document.querySelectorAll("nav ul li ul");
var count = listItems.length;

for (var i=0; i<count; i++) {
  var item = listItems.get(i);
  item.style.display = "block";
}

Answer: Of course the easiest is using jQuery or some other library.
To do it with pure JavaScript for modern browsers, use JS querySelector.
Otherwise you will spend a lot of time in this.


Generic UTC DateTime serialization in Apache Ignite

Question: I am working with Ignite .NET thin client.
In ignite documentation it is wriiten that to support platform interoperability we should store DateTime in UTC format. I can also store DateTime value in local format but data could not be viewed in DBeaver in this case.
When I put data in the cache or get data from the cache I have to manually convert DateTime values from UTC or local format. For the conversion I use DateTime.SpecifiyKind or DateTime.ToUniverslaTime, DateTime.ToLocalTime methods like in the example below.
Is there any generic solution to automatically convert all DateTime values beetween UTC and local formats instead of writing custom logic for each property of each model in application?
Perhaps it could be some kind of generic DateTime serializer.
public class Person
{
    public string FirstName { get; set; }
    public DateTime Birthday { get; set; }
}

[STAThread]
public static void Main()
{
    var configuration = new Core.Client.IgniteClientConfiguration
    {
        Endpoints = new List<string> { "127.0.0.1" },
        BinaryConfiguration = new BinaryConfiguration
        {
            Serializer = new BinaryReflectiveSerializer { ForceTimestamp = true }
        }
    };

    using (var ignite = Ignition.StartClient(configuration))
    {
        var person = new Person { FirstName = "John", Birthday = new DateTime(1990, 08, 17) };

        var cacheConfiguration = new CacheClientConfiguration("people", new QueryEntity(typeof(int), typeof(Person)));

        //person.Birthday = person.Birthday.ToUniversalTime();
        person.Birthday = DateTime.SpecifyKind(person.Birthday, DateTimeKind.Utc);

        var cache = ignite.GetOrCreateCache<int, Person>(cacheConfiguration);

        cache.Put(0, person);

        var personFromCache = cache.AsCacheQueryable().Select(x => x.Value).FirstOrDefault();

        //personFromCache.Birthday = personFromCache.Birthday.ToLocalTime();
        personFromCache.Birthday = DateTime.SpecifyKind(personFromCache.Birthday, DateTimeKind.Local);
    }
}

Answer: Ignite does not provide such an automatic conversion. Some options are:

Implement IBinarizable interface and perform conversions there:

    public class Person2 : IBinarizable
    {
        public DateTime Date { get; set; }

        public void WriteBinary(IBinaryWriter writer)
        {
            writer.WriteTimestamp("Date", Date.ToUniversalTime());
        }

        public void ReadBinary(IBinaryReader reader)
        {
            Date = reader.ReadTimestamp("Date").Value.ToLocalTime();
        }
    }

Use serialization attributes to hook into the process:

    [Serializable]
    public class Person
    {
        public DateTime Date { get; set; }

        [OnSerializing]
        internal void OnSerializingMethod(StreamingContext context)
        {
            Date = Date.ToUniversalTime();
            Console.WriteLine("OnSerializing");
        }

        [OnSerialized]
        internal void OnSerializedMethod(StreamingContext context)
        {
            Date = Date.ToLocalTime();
            Console.WriteLine("OnSerialized");
        }

        [OnDeserialized]
        internal void OnDeserializedMethod(StreamingContext context)
        {
            Date = Date.ToLocalTime();
            Console.WriteLine("OnDeserialized");
        }
    }

Use properties with backing fields and perform conversion in getter and setter

All of that requires individual handling for every property, though - I don't have better ideas without reflection and/or code generation.


Correlation of Markov process

Question: I have a problem where cars are entering an area according to a homogeneous Poisson process, with a rate of $\lambda = 9$ cars per hour. 20% of the cars entering the area are of type 1, and 80% of the cars entering the area are of type 2. I know that the type of arriving car is independent of the time of arrival, independent of the history of arrivals, and independent of the types of other vehicles to have arrived. I have a Markov process $X(t)$ that denotes the number of cars to arrive within a time interval of $t$ hours starting at 7am tomorrow.
I want to derive $\text{Corr}(X(s), X(t))$, the correlation coefficient of $X(s)$ and $X(t)$, for $0 \le s \le t$. However, when researching this, the only results I find are advanced research papers. How would one derive $\text{Corr}(X(s), X(t))$?
Comment: sry, that equation holds for covariance, not for correlation, my mistake. see my answer
Comment: (1) Your question seems to have nothing to do with the "two types of cars" you write about. (2) This is a Markov process, so increments are independent. Therefore Corr(X(s),X(t)) = Corr(X(s),X(s)) if s<t.
Comment: @Simon Hmm, this is how it was presented to me, so I wasn't really sure what to do. You say that $\text{Corr}(X(s), X(t)) = \text{Corr}(X(s), X(s))$, but how does this get us the correlation coefficient?
Answer: oh, my comment was actually incorrect. sorry. I mixed up covariance and correlation.
\begin{align}
\text{corr}(X(s),X(t))
&= \frac{\text{cov}(X(s),X(t))}{\sqrt{\text{var}(X(s))\text{var}(X(t))}}\\
&= \frac{\text{cov}(X(s),X(s))}{\sqrt{\text{var}(X(s))\text{var}(X(t))}}\\
&= \sqrt{\frac{\text{var}(X(s))}{\text{var}(X(t))}}\\
\end{align}
the variance of a poisson distribution you can either just look up on wikipedia, or compute it yourself.
Comment: sure, just did. no problem :)
Comment: Oh, ok, I see now. Thanks Simon! I'm not sure how much you know about Markov processes, but do you by any chance also know anything about this https://math.stackexchange.com/q/4157721/356308 ? If you have the time, I'd greatly appreciate it!

Correlation of Markov process


How to setup a Gerrit mirror in a remote location

Question: We use git with Gerrit for code reviewing in Europe and it works fine ;) The problem is that we have colleagues in Asia with an internet connection that makes cloning, pushing and pulling take ages. Is there a way to setup a Gerrit mirror so that every commit has to be transfered between Europe and Asia only once? I know Gerrit supports replication but I'm not sure that's the answer since I'd like to be able to push and pull on both sides.
Comment: I met similar issue on http://stackoverflow.com/questions/17258874/how-should-the-other-remote-site-using-gerrit-server-based-on-a-mirror-repo  could anyone come to help?

thanks
Answer: I don't use gerrit, but here problem doesn't seem to be that complex. You just need to create a "local" repository. Now for example set up a post-receive-hook on both sides, that push to each other. Now every time someone pushs something to your australian repository, it gets pushed to your mirror and you and your developers can push and pull from this one (which will then pushed to australia again).
Comment: If I remember correctly Gerrit doesn't fire the post-receive-hook :/
Comment: Gerrit is just a frontend, but the git repository itself should fire it.


If $w$, $x$, $y$, and $z$ are real numbers with $w < x$ and $y < z$, is the cardinality of the closed interval $[w,x]$ the same as that of $[y,z]$?

Question: My reasoning is yes. I tried to draw a few example functions and based on my workings, think that the answer should be yes but I couldn't figure out how exactly I should mathematically prove the fact. Any hints?
Comment: Is it possible to find a bijection (injective and surjective function) between them?
Answer: Hint: Consider the case where $[w,x] = [0,1]$ and $f\colon [0,1] \to [y,z]$ is defined by $$f(t) = tz + (1-t)y$$
Comment: Thank you, this is really helpful!
Answer: Yes. The most basic method to prove two sets having the same cardinality is by constructing a bijection.
For that, define a function f mapping [w,x] to [y,z]. A sufficient condition for f to be a bijection is simply that f be continuous and increasing.
Comment: Thank you, this is really helpful!
Answer: HINT
You can build a linear mapping $f:[w,x]\to[y,z]$ such that $f(w) = y$ and $f(x) = z$.
Precisely, if we let $f(t) = at + b$, it results into the following system:
\begin{align*}
\begin{cases}
aw + b = y\\\\
ax + b = z
\end{cases}
\end{align*}
Can you take it from here?
Comment: Thank you, this is really helpful!


Increment variable in Batch for rendering

Question: I have this code. It loads a sequence of .vrscene files
for /f %%a IN ('dir /b /s "C:\Users\Beqarion\Desktop\test_for_batch*.vrscene"') do call "C:\Program Files\Autodesk\Maya2015\vray\bin\vray.exe" -scenefile=%%a -imgFile="C:\Users\Beqarion\Desktop\test_for_batch\img.jpg" -frames=1 -autoclose=1

As you can see at the end it has an img output and frame number. I need to create a variable that will increment every time a .vrscene file is rendered and add it to img.jpg so that it saves a new img file after every render: img_0001, img_0002 etc. I tried set /a varname+=1 but it doesn't work. Also I want to add that I'm not a programmer and I don't code in batch. So things that some of people here consider very basic may not be for me.
Comment: Please update your question using the edit facility, _(adding new information to your question will not help you to get positive responders)_.
Comment: If it was easy you would be able to do it yourself.  Please provide more detail to your question.  Provide examples.
Comment: `set /a "varname=varname+1"`
Comment: better: `set /a varname+=1`
Comment: well i don't code in batch you see. so even if it is easy it's not so clear for me. here it is:  for /f %%a IN ('dir /b /s "C:\Users\Beqarion\Desktop\test_for_batch\*.vrscene"')  do call "C:\Program Files\Autodesk\Maya2015\vray\bin\vray.exe" -scenefile=%%a -imgFile="C:\Users\Beqarion\Desktop\test_for_batch\img.jpg"  -frames=1 -autoclose=1
Comment: so i need to add a variable to the "img.jpg" and "-frames" as well (instead of 1 i want -frames to be an incerement)
Comment: how can i make it increment every time a frame is rendered? set /a varname+=1 doesn't do that :(
Comment: @beqarion, update your question with your code.  DO  NOT PUT IT IN  A COMMENT.
Answer: @Echo off&SetLocal EnableDelayedExpansion
Set "Basefldr=C:\Users\Beqarion\Desktop"
Set "vray=C:\Program Files\Autodesk\Maya2015\vray\bin\vray.exe"
Pushd "%Basefldr%"||(Echo can't cd to %Basefldr% &Pause &Exit /B 1)
Set ImgNo=10000
for /f "delims=" %%a IN (
  'dir /b /s "test_for_batch*.vrscene"'
) do (Set /A ImgNo+=1
  "%vray%" ^
  -scenefile=%%a ^
  -imgFile=".\test_for_batch\img_!ImgNo:~-4!.jpg" ^
  -frames=1 ^
  -autoclose=1
)
PopD

The initial ImgNo=10000 is necessary to get the leading zeroes
when stripping the last four places with !ImgNo:~-4!
The use of EnableDelayedExpansion in combination with ! instead
of the usual % is required to get actual values in an area
surrounded by parentheses.
Comment: New to StackExchange/stackoverflow doesn't mean new to batch ;-)
Comment: Obvioulsy... I hope you will stay here. You seem to have a lot to contribute. Welcome to the "club" `:)`
Comment: @LotPings, never been a big fan of that kind of syntax for batch files. I love my indentation and never wrap the IN clause like that, but in this instance it does make the code to execute the program easier to read. Welcome to StackOverFlow.
Comment: @Stephan et all. (can only have one at) Thanks for the welcome.


Retrieve data from database as pdf file

Question: My application use Firebase, how can retrieve the data from database as pdf file?
Users should be able to download that pdf file on their device.
Note: this code not related to my question
<code> public void addinfo() {
    HashMap<String, String> datamap = new HashMap<>();
    datamap.put("", ed1.getText().toString().trim());
    datamap.put("", ed2.getText().toString().trim());
    datamap.put("", ed3.getText().toString().trim());
    datamap.put("", ed4.getText().toString().trim());
    datamap.put("", ed5.getText().toString().trim());
    datamap.put("", ed6.getText().toString().trim());
    datamap.put("", ed7.getText().toString().trim());
    datamap.put("", ed8.getText().toString().trim());

    databasestudent.push().setValue(datamap).addOnCompleteListener(new OnCompleteListener<Void>() {
        @Override
        public void onComplete(@NonNull Task<Void> task) {
            if (task.isSuccessful()) {
                Toast.makeText(Form4Activity.this, "done Successfully!!", Toast.LENGTH_LONG).show();
            } else {
                Toast.makeText(Form4Activity.this, "erorr!!", Toast.LENGTH_LONG).show();
            }
        }
    });
}
</code>
}
Answer: You could create a cloud function that reads your database and creates a pdf from the data. The pdf could then be saved to storage and the storage url is then sent back to the client.
Comment: thanks sir ... can you share me with tutorial that can help me to solve my question ?
Answer: The Best Way to Store The PDF file or any other file in Firebase Cloude Storage you can simply uplod a file using upload button
And Featching a file  by get Reference of the Firbase Storage using PDF view library
// get a child reference of file
 httpsReference = storage.getReference().child("xyz.pdf");
//and past the URL of file
new RetrivePdfStreamJ().execute("https://xyz");
it Working for me

Retrieve data from database as pdf file


Swift Vapor Leaf deliver html in a variable

Question: I need to create a complex html-table inside a Swift Vapor App.
Problem is: Leaf doesn't seem to support counting up variables like #(somevar += 1) nor concatenating string variables like #(somevar1 + somevar2)
So I decided to create my complex table inside the App and transfer it to the html template inside a variable. (in php I'm used to doing this all the time)
In the template I'd call the variable like
#(table)

but turns out, I'm getting the plain html code as leaf escapes all variables.
But there is the #raw() function to print out plain html as such.
So I do
<!DOCTYPE html>

<title>Server</title>

<..>

<form action="parameters" method="post">

// here is the thing: leaf gets a html table within the string 'table'.
// If I do it like that lead doesn't recognize #(table) as a leaf variable.
#raw( #(table) )

<button type="submit">Save</button>
</form>

only to find out that #raw() does not look for variables but just prints out unescaped what is between the {}. So I still get in the website "#(table)" instead of my complex html-table.
So now I'm stuck. How do I get App-generated html code into the template as html?
Probably I am doing this all wrong. How do I get html code inside a leaf template at all? Or do I have to send the whole page then myself, as a http stream with a header…?
Thanks in advance,
Tom
Comment: edited it trying to point out my question more clearly…
Answer: Update
Since Vapor 3 the #raw(<var>) tag was not embedded by default in --template=web when creating your Vapor Leaf project. I had to register it manually in my configure.swift file :
/// Leaf add tags
services.register { container -> LeafTagConfig in
    var config = LeafTagConfig.default()
    config.use(Raw(), as: "raw")   // #raw(<myVar>) to print it as raw html in leaf vars
    return config
}

https://docs.vapor.codes/3.0/leaf/custom-tags/
Also if someone is seeking for the complete list of available tags, you can silmply search for TagRenderer in vapor dependencies, which is the protocol to conform if you want to create a custom tag :

Hope this can help
Answer: Assuming you are not taking in user input to create this table, you should be able to use this:
#raw(table)

This does the same thing as #(table), but it doesn't escape the HTML, so it will properly render. Just make sure you are not making yourself vulnerable to XSS attacks if you do this.
Comment: I found I has to use #raw(table) without the {}.  If I included the {} the result was blank (Leaf 2.0.1).
Answer: In vapor 4 it is:
#unsafeHTML(variable)


Disable an input field when checking a checkbox in Backbone

Question: I'm completely new to Backbone.js and jQuery and I'm trying to set an input field of a form to "disabled" when I check a checkbox. I'm not sure if I have to do it the way I show in the code below, if so what should I do in the disableInput function?
JS
events: {
    'change #myCheckbox': 'disableInput',
},

disableInput : function(){
...
}

HTML

      <input type="text" id="myInput">
      <input type="checkbox" id="myCheckbox">

EDIT: This may seem like dupplicate of other posts, but those questions are about vanilla JS I'm using Backbone here so it's not the same.
Comment: Possible duplicate of [enable/disable input fields with checkboxes (javascript)](https://stackoverflow.com/questions/20907150/enable-disable-input-fields-with-checkboxes-javascript)
Comment: wont a vanilla javascript option work?
down vote
You check the state of the checkbox

`document.getElementById("myInput").disabled= document.getElementById('myCheckbox').checked`
Comment: Possible duplicate of [disable input on check checkbox](https://stackoverflow.com/questions/26409366/disable-input-on-check-checkbox)
Answer: If you want to go the pure CSS route, you can place the checkbox above the text and switch the order to your liking using flexbox. Then, you can write CSS that changes the opacity and pointer-events for the checkbox sibling.

.x {
  display: flex;
}

.x #myCheckbox {
  order: 2;
}

.x #myCheckbox:checked + #myInput {
  pointer-events: none;
  opacity: 0.6;
}

  <input type="checkbox" id="myCheckbox">
  <input type="text" tabindex="-1" id="myInput">

Tab Issue
In order to stop someone from tabbing into the input, you can add tabindex="-1" to the input.
Comment: Was just testing it, but if you add tabindex="-1"  to the input it will stop the tabbing. NVM :P
Comment: I just googled it and found the same solution, haha xD
Answer: Here is a simple one liner
Granted I am not familiar with backbone.js but you should be able to figure out how to incorporate this.

function disableInput(){
document.getElementById("myInput").disabled=document.getElementById('myCheckbox').checked
}

      <input type="text" id="myInput">
      <input type="checkbox" onchange="disableInput();" id="myCheckbox">

Comment: @happymacarts I accepted your answer because it essencially works, but as Emile Bergeron said I'm using Backbone so I will have to see how to get the element by id things the way Backbone does it, just to do it "more elegantly". For the inline onchange i just replaced it for the code i posted of my JS.
Comment: This is a Backbone question, using vanilla JS and inline `onchange` event is really going in the wrong direction.
Comment: @Emile Bergeron I only used the onchange for the purpose of the snippet. hopefully the poster can figure out how to use this best. Maybe someday i will add backbone to my toolbox :)
Answer: I think Backbone way would be the following
events: {
    "change #myCheckbox": function() {this.disableInput.apply(this, arguments);}
},

disableInput: function(args) {
    var checked = $(args.target).is(":checked");
    this.$el.find("#myInput").disabled = checked;
}


Java - Leitor de Disco (Linux)

Question: Boa noite,
Estava olhando como podemos abrir o leitor de disco no Windows utilizando Java existem vários meios como até mesmo utilizar o vbs.
Queria saber se preciso utilizar alguma biblioteca no Linux ou se posso fazer diretamente por algum comando.
Alguém poderia me orientar?
Obrigado!
Comment: Tente chamar o terminal e executar o comando para ejetar `Runtime run = Runtime.getRuntime(); run.exec("eject -T");`
Answer: Para o abrir o drive:
try {
  Runtime.getRuntime().exec("eject cdrom");
} catch (Exception e) {
  System.out.print(e);
}

Para fechar o drive:
try {
  Runtime.getRuntime().exec("eject -t cdrom");
} catch (Exception e) {
  System.out.print(e);
}

Comment: Mais fácil do que no Windows 1000x. Obrigado!

Java - Leitor de Disco (Linux)


How can I alter an external variable from inside my AJAX?

Question: I keep on having these same two problems. I have been trying to use Remy Sharp's wonderful tagSuggest plugin, and it works great. Until I try to use an AJAX call to get tags from my database.
My setGlobalTags() works great, with my defined myTagList at the top of the function. What I want to do is set myTagList equal to the result from my AJAX. My problem is that I can neither call setGlobalTags() from inside my success or error functions, nor actually alter the original myTagList.
Also, I keep on having this other issue as well. I keep this code in my Master page, and my AJAX returns 'success' on almost every page. I only (and always) get the error alert when I navigate to a page that actually contains something of id="ParentTags". I don't see why this is happening, because my $('#ParentTags').tagSuggest(); is definitely after my AJAX call.
I realize that this is probably just some dumb conventions error, but I am new to this and I'm here to learn from you guys. Thanks in advance!
$(function() {
        var myTagList = ['test', 'testMore', 'testALot'];

        $.ajax({
            type: "POST",
            url: 'Admin/GetTagList',
            dataType: 'json',
            success: function(resultTags) {
                myTagList = resultTags;
                alert(myTagList[0]);

                setGlobalTags(myTagList);
            },

            error: function() {
                alert('Error');
                setGlobalTags(myTagList);
            }
        });

        setGlobalTags(myTagList);

        $('#ParentTags').tagSuggest();
    });

Comment: What?  What do you mean that you can't call your "setGlobalTags" function?  What makes you think that you can't? What does that function look like?
Comment: i can call it outside of my AJAX. but inside my success/error functions, i don't think it works. (i tried to slip it an integer instead of an array, which is what it looks for as a parameter. my code didn't crash, so i assumed that setGlobalTags just wasn't getting called.
Comment: Please don't remove parts of your question that have been answered. As for the remaining part, the error is caused by something which can't be deduced from the question. For example, maybe the relative URL you are using is wrong on the pages with the error.
Comment: @interjay:
That's a good idea, I will check it out!
Answer: Actually, your call to $('#ParentTags').tagSuggest(); will happen before the AJAX call. The $.ajax function returns immediately, before the AJAX call has finished and before the error or success functions have been called. So you need to move whatever you want to do after the AJAX call into the success/error function.
$(function() {
        $.ajax({
            type: "POST",
            url: 'Admin/GetTagList',
            dataType: 'json',
            success: function(resultTags) {
                setGlobalTags(resultTags);
                $('#ParentTags').tagSuggest();
            },

            error: function() {
                //...
            }
        });
    });

For your second part of the question, try to see what response you are getting from the server to help track down the error:
error : function(xhr) {
    alert(xhr.status);
    alert(xhr.responseText);
    //you can use console.log instead of alert if using firebug
}

Comment: That fixed my first problem. Thanks!  :D
But I still get error on the page where i have my id="ParentTags".  :(
Answer: Check the kind of data you are passing from the server. If it is JSON array, you need to use eval or $.parseJSON to get the tags and set them to the global tags. So if you return an array, your code will be like this.
$(function() {
        var myTagList = ['test', 'testMore', 'testALot'];

        $.ajax({
            type: "POST",
            url: 'Admin/GetTagList',
            dataType: 'json',
            success: function(resultTags) {
                myTagList = eval(resultTags);
                alert(myTagList[0]);

                setGlobalTags(myTagList);

                $('#ParentTags').tagSuggest();
            },

            error: function() {
                alert('Error');
                setGlobalTags(myTagList);

                $('#ParentTags').tagSuggest();
            }
        });

    });

Answer: I used interjay's answer (the one I accepted) for the first half of my issue. To get my AJAX to run correctly on the page I needed, I simply changed the relative url from 'Admin/GetTagList' to 'GetTagList', because my page was already under the 'Admin' controller.


Panel.TabStop = true has no effect

Question: I Trying to switch Panel.TabStop property totrue but it does not affect anything.
How to enable TabStop in a Panel?
Comment: possible duplicate of [Panel not getting focus](http://stackoverflow.com/questions/3562235/panel-not-getting-focus)
Comment: @Hans Passant: Thanks, I found the answer there, I just needed to add this line to my ctor: `this.SetStyle(ControlStyles.Selectable, true);`
Comment: Well, don't cut it short.  The user not being able to see the focus isn't great.
Comment: I'll do the necessary things in `OnPaint`, this is not a problem for me. :)
Answer: A Panel does not accept keyboard focus because a Panel is not a control (per se), it's a container for other controls which probably accept keyboard focus.
If you're trying to create a custom control, derive from UserControl or Control.
Answer: The TabStop property has no effect on the Panel control as it is a container object.
Checkout this MSDN Link for details.
Comment: Not sure that is accurate. If you set Focusable=True then you can tab to a Panel no problems
Answer: As the others have said, the panel control will not accept focus. However, if you set TabStop to true and set its TabOrder, then the next control in the TabOrder should receive focus.
Answer: As I understand it, the TabStop property exists at the control level, but it really only affects what I would call interactive controls (there's probably an actual, correct term).   Since panels can't directly receive the focus, they won't behave differently based on that flag.
Answer: You have to put something that can accept focus onto it, like editbox.  There you go :)
Answer: Try setting Focusable=true for the Panel you are using.

Panel.TabStop = true has no effect


How to create a button on module configuration page that calls a custom php function?

Question: I am creating a custom module that has a button on the module's configuration page. When the button is clicked, a custom php function (located in the custom_module.module file) needs to run to perform some task.
How can I create a button on the custom module's configuration page that allows me to click the button to manually run the custom php function?
Answer: You should use the Drupal Form API for it.
Please, check it: https://api.drupal.org/api/drupal/developer!topics!forms_api_reference.html/7#submit (it is about adding button).
And it: https://api.drupal.org/api/drupal/developer!topics!forms_api_reference.html/7#submit_property (it is about run custom function).
Answer: Each different button on your form can perform a different function by assigning it the #submit property:
function mymodule_my_form($form, &$form_state) {
  $form['button1'] = array(
    '#type' => 'submit',
    '#value' => 'Perform 1st Action',
    '#submit' => array('mymodule_my_form_action_one')
  );

  $form['button2'] = array(
    '#type' => 'submit',
    '#value' => 'Perform 2nd Action',
    '#submit' => array('mymodule_my_form_action_two')
  );
}

function mymodule_my_form_action_one($form, &$form_state) {
  // Perform the 1st action
}

function mymodule_my_form_action_two($form, &$form_state) {
  // Perform the 2nd action
}

Only the specified submit function will run for each button click.


TypeError: Input 'b' of 'MatMul' Op has type float32 that does not match type int32 of argument 'a'

Question: I'm trying to follow word2vec example, but I'm getting this error:
TypeError: Input 'b' of 'MatMul' Op has type float32 that does not match type int32 of argument 'a'.

At this line
similarity = tf.matmul(
      tf.cast(valid_embeddings,tf.int32), tf.cast(normalized_embeddings,tf.int32), transpose_b=True)
This is the entire code:
graph = tf.Graph()

with graph.as_default():
  # Input data.
  train_inputs = tf.placeholder(tf.int32, shape=[batch_size])
  train_labels = tf.placeholder(tf.int32, shape=[batch_size, 1])
  valid_dataset = tf.constant(valid_examples, dtype=tf.int32)
  # Ops and variables pinned to the CPU because of missing GPU implementation
  with tf.device('/cpu:0'):
    # Look up embeddings for inputs.
    embeddings = tf.Variable(
        tf.random_uniform([vocabulary_size, embedding_size], -1.0, 1.0))
    embed = tf.nn.embedding_lookup(embeddings, train_inputs)
    # Construct the variables for the NCE loss
    nce_weights = tf.Variable(
        tf.truncated_normal([vocabulary_size, embedding_size],
                            stddev=1.0 / math.sqrt(embedding_size)))
    nce_biases = tf.Variable(tf.zeros([vocabulary_size]))
  # Compute the average NCE loss for the batch.
  # tf.nce_loss automatically draws a new sample of the negative labels each
  # time we evaluate the loss.
  loss = tf.reduce_mean(
      tf.nn.nce_loss(nce_weights, nce_biases, embed, train_labels,
                     num_sampled, vocabulary_size))
  # Construct the SGD optimizer using a learning rate of 1.0.
  optimizer = tf.train.GradientDescentOptimizer(1.0).minimize(loss)
  # Compute the cosine similarity between minibatch examples and all embeddings.
  norm = tf.sqrt(tf.reduce_sum(tf.square(embeddings), 1, keep_dims=True))
  normalized_embeddings = embeddings / norm
  valid_embeddings = tf.nn.embedding_lookup(
      normalized_embeddings, valid_dataset)
  similarity = tf.matmul(
      tf.cast(valid_embeddings,tf.int32), tf.cast(normalized_embeddings,tf.int32), transpose_b=True)
  # Add variable initializer.
  init = tf.initialize_all_variables()

How can I fix this?
Answer: I've met the same problem using Tensorflow r1.4 with Python 3.4.
Indeed, I think you need to change the code
tf.nn.nce_loss(nce_weights, nce_biases, embed, train_labels,
                 num_sampled, vocabulary_size))

into
tf.nn.nce_loss(nce_weights, nce_biases, train_labels, embed,
                 num_sampled, vocabulary_size))

or
loss = tf.reduce_mean(tf.nn.nce_loss(
        weights = softmax_weights,
        biases = softmax_biases,
        inputs = embed,
        labels = train_labels,
        num_sampled = num_sampled,
        num_classes = vocabulary_size))

Meanwhile, you need to change the code back to
similarity = tf.matmul(valid_embeddings, tf.transpose(normalized_embeddings))

It wrong to use tf.cast(..., tf.int32) and actually, there is no need to use tf.cast(..., tf.float32) because it's already been tf.float32.
p.s.
The solution is also useful when you meet the problem while using tf.nn.sampled_softmax_loss() because the usage of sampled_softmax_loss() is quite similar to nce_loss().
Answer: Why are you doing the matrix multiplication in integer space? You probably want both of those tf.cast to be to tf.float32.


Cronbach's alpha vs. Average Item-Sum correlation?

Question: I have heard that Cronbach's alpha is used to measure reliability of a test (to check if a set of items/question are measuring the same construct). How does the Cronbach's alpha compare with the average of Item-Sum correlation or the Item-(Sum minus Item) correlation of all the items?
I have a set of testing items and I am interested in understanding if they are measuring different concepts/constructs or are measuring the same construct.
Answer: The standardized alpha coefficient is more intuitive so let's start there:
$$\alpha_{standardized}=\frac{K\bar{r}}{1+(K-1)\bar{r}}$$
where $K$ is the number of items and $\bar{r}$ is the mean of the non-redundant correlations between items.
The non-standardized alpha coefficient just needs a few changes to the denominator.
$$\alpha=\frac{K\bar{c}}{\bar{v}+(K-1)\bar{c}}$$
where $K$ is the number of items, $\bar{v}$ is the average variance of each item, and $\bar{c}$ is the mean of the non-redundant covariances between  items.
Here is some sample data in subject-by-item format (with four items A, B, C, and D):

A   B   C   D
-------------
5   5   5   5
3   1   3   1
5   5   5   5
3   1   3   1
5   5   4   5
1   2   3   3
3   1   1   1
1   1   1   3
3   3   4   4
1   3   1   1
5   5   5   5
1   1   1   1
1   1   1   1
1   1   1   1
3   3   4   3
1   3   3   4
4   4   5   5
5   5   5   5
5   3   3   3
3   2   3   3
5   3   5   5
3   3   3   4
1   1   1   1
1   1   1   1
1   1   3   3
3   3   3   1
3   3   1   1
3   3   1   1
3   3   2   5

To calculate the standardized alpha, we need the inter-item correlations ($r$):
$r_{AB}=.776$
$r_{AC}=.756$
$r_{AD}=.630$
$r_{BC}=.730$
$r_{BD}=.750$
$r_{CD}=.810$
Which makes for a mean inter-item correlation of $\bar{r}=.742$.
$$\alpha_{standardized}=\frac{4(.742)}{1+(4-1).742}=.920$$
To calculate alpha, we need the variances ($v$) and covariances ($c$):
$v_A=2.433$
$v_B=2.101$
$v_C=2.384$
$v_D=2.933$
$c_{AB}=1.754$
$c_{AC}=1.820$
$c_{AD}=1.683$
$c_{BC}=1.633$
$c_{BD}=1.861$
$c_{CD}=2.142$
which makes for a mean variance of $\bar{v}=2.463$ and mean covariance of $\bar{c}=1.816$.
$$\alpha=\frac{4(1.816)}{2.463+(4-1)1.816}=.918$$
Now let's compare these results to your idea of the average item-sum correlation.
$$S=A+B+C+D$$
$r_{AS}=.877$
$r_{BS}=.901$
$r_{CS}=.919$
$r_{DS}=.895$
which makes for a mean item-sum correlation of $\bar{r}_{XS}=.898$.
So your result is similar to but lower than the alpha coefficient(s). Perhaps someone else who is better at algebra than I am can put together an equation for calculating one from the other.


Can PHP set it ini file at runtime?

Question: Is there any method to change php's config when it's running? My business requirement is on FunctionA start turn up it's max_execution_time and on FunctionA finish turn down it.
Comment: why not use http://php.net/manual/en/function.set-time-limit.php ?
Comment: That's not possible.. However you could try [`ini_set()`](https://secure.php.net/manual/en/function.ini-set.php)..
Comment: `max_execution_time` is changeable for [`PHP_INI_ALL`](http://php.net/manual/configuration.changes.modes.php) so yes, you can change it at runtime
Answer: Yes:
<?php
    function functionA ()
    {
      if (!ini_get('max_execution_time') || ini_get('max_execution_time') != 3000)
      {
        ini_set('max_execution_time', 3000); //300 seconds = 5 minutes
      }
      // Do some things....
    }

    echo ini_get('max_execution_time'); // We return system default

    functionA ();

    echo ini_get('max_execution_time'); will return 3000

Beware that some host disable this ability. If thats the case and it is still needed you will need to contact your host to enable it or move hosting companies.

Can PHP set it ini file at runtime?


Rewrite URL post formats (aside, link, gallery, ...) of Wordpress (translate slugs)

Question: I use WordPress in spanish language, and i like to have permalinks in spanish. It's more semantic for spanish users.
In settings > permalinks is possible to change "category base" ("category," by default) and "tag base" ("tage," by default). With some plugins, also "author base" and "pagination base" ("page", by default). But, I've changed post format base (type to tipo), but I don't know how to change slug name of post formats ("aside", "link", "quotes", ... by default).
I want to get a permalink like "http://domain.com/tipo/cita" instead "http://domain.com/type/quote" for listing quotes posts.
Thanks.
Comment: Great question.  Have you tried posting it on wordpress.stackexchange.com?
Answer: I see that @cscean received an answer a few days later, at http://justintadlock.com/archives/2012/09/11/custom-post-format-urls. To change the post format base from type to tipo, he would use
<code>add_filter( 'post_format_rewrite_base', 'my_post_format_rewrite_base' );

function my_post_format_rewrite_base( $slug ) {
return 'tipo';
}
</code>
The author includes a lot more code that finishes answering the permalinks question.


Blocks in Panopoly

Question: I'm working with Panopoly as my very first drupal distribution and am concerned about how I'll define persistent items. For example, with core drupal, I could use or create block regions to define special widgets/page elements that would appear on each page.
How would one best do this in a Panel's based environment like Panopoly? Is it possible to use both blocks and panels? concurrently?
Answer: You can still display blocks but now you have more control as to their placement.
How to Find them

Click Customize this page on the bottom of your screen.
Click + in the area you want, for example the header.
Once the Dialog appears click Blocks or Custom Blocks

This is the area where you will see all your Blocks appear.
Answer: Actually, Blocks is disabled by default in Panopoly. Panopoly uses fieldable panels panes instead. So, you probably need to do this first:

Enable Blocks in your modules list
Create your block (if necessary)
Enable your block as allowed at /admin/structure/panels/settings/panel-page

Now you can place blocks in your panel pages.
Source: https://www.drupal.org/node/1932120#comment-7235572

Blocks in Panopoly


MAX aggregate function principle in long to wide table transform

Question: https://dbfiddle.uk/Y2h4mq4X
It is an example where data table is tranforming from long to wide format. I have a question of principle of MAX aggregate function there. How does it work?
Comment: Creating a DBFiddle may be helpful when asking a question but should not be required in order for someone to understand your question. Please update your question with enough information (as editable text) so that someone can understand what you are asking. I assume you have read the documentation for this function so what is the specific issue that you don't understand or was not covered by the documentation?
Answer: Run your query without specifying GROUP BY and MAX(). With this you can visualize how those operations and functions transform your results. Try: (see Demo Here)
<code>  SELECT id2,
    CASE WHEN key = 3 THEN value END AS a3,
    CASE WHEN key = 7 THEN value END AS a7,
    CASE WHEN key = 101 THEN value END AS a101,
    CASE WHEN key = 102 THEN value END AS a102,
    CASE WHEN key = 133 THEN value END AS a133,
    CASE WHEN key = 140 THEN value END AS a140,
    CASE WHEN key = 239 THEN value END AS a239,
    CASE WHEN key = 250 THEN value END AS a250
FROM tmp
order by id2;
</code>


Criar um critério de importação

Question: Como eu crio regra, para que quando eu desse pd.read_excel e as colunas A e C estiverem vazias ele abortar a importação.
Preciso disso, pois o usuário ira buscar o arquivo pelo sd_principal = sg.popup_get_file('Qual o arquivo?') e essas colunas são importantes, mas elas não têm interação com as linhas de códigos, mas elas precisam estar no arquivo final que será exportado para o usuário.
Codigo:
import pandas as pd
import numpy as np
import PySimpleGUI as sg

try:
    sd_principal = sg.popup_get_file('Qual o arquivo?')
    output_workbook = sg.popup_get_folder('Onde quer salvar o arquivo final?')
    df1 = pd.read_excel(sd_principal)
except FileNotFoundError:
    sg.popup_ok('Arquivo não selecionado!')
except:
    sg.popup_ok('Erro inesperado')

Answer: Minha solução seria criar um df_test, baseado nas colunas necessárias. Coloque no seu bloco try:
df_test = df1['A','C'] # criando o df para teste
df_test.empty

df.empty > se vazio True
Lembre-se! Se as colunas estiverem repletas com NaN, não serão consideradas como vazias empty, se for o caso, melhor executar um .dropna também:
df_test.dropna().empty

Comment: ajudou muito em outro projeto,  muito obrigado.
Mas nesse precisava tratar cada coluna individualmente, escrevi um bem feio aqui:
`# Se alguma dessas colunas etiverem vazias, sairemos do programa
if df1['Employee Number'].sum() == 0:
    sg.popup_ok('Coluna Employee Number está vazia = SAINDO DO PROGRAMA!!')
elif df1['Last Name'].sum() == 0:
    sg.popup_ok('Coluna Last Name está vazia = SAINDO DO PROGRAMA!!')
elif df1['First Name'].sum() == 0:
    exit()`
Até achar uma solução melhor.

Criar um critério de importação


Can BigPipe exclude certain blocks?

Question: I've got BigPipe enabled in Drupal 8, and it helps to make pages initially load faster.
However, the header block is always one of the blocks that loads in on a delay, which visually looks bad since the content shifts down afterwards.
Is there any type of preprocess on a block to exclude it from BigPipe not be loaded on a delay, and force it to be in the initial page load?
Many thanks.
Answer: You can exclude a block from BigPipe by disabling placeholdering in the block build (preprocess is too late).
/**
 * Implements hook_block_build_BASE_BLOCK_ID_alter().
 */
function mymodule_block_build_example_block_alter(array &$build, \Drupal\Core\Block\BlockPluginInterface $block) {
  // Disable placeholdering of this block.
  $build['#create_placeholder'] = FALSE;
}

But if this is one of the blocks always having a delay it could make the entire module BigPipe useless.
You can solve the content shift in CSS. Delay or stop the block rendering (in this case you can use preprocess) and fill the gap in the partially loaded page with CSS.
Or make the header block more granular. When all dynamic parts are placeholdered the rest of the block is cacheable and loads with the initial page load.
Example block:
  public function build() {

    $build = [];

    $build[] = [
      '#markup' => '
Static part of the block, loads with the initial page.
',
    ];

    $build[] = [
      '#lazy_builder' => ['\Drupal\mymodule\LazyBuilders::getUser', []],
      '#cache' => ['contexts' => ['user']],
      // contexts user, session or max-age 0 are automatically placeholdered
    ];

    return $build;
  }

/src/LazyBuilders.php:
<?php

namespace Drupal\mymodule;

use Drupal\Core\Render\Element\RenderCallbackInterface;

class LazyBuilders implements RenderCallbackInterface {

  public static function getUser() {
    return [
      '#markup' => \Drupal::currentUser()->getDisplayName(),
    ];
  }

}

Comment: Thanks, I'll give this a try.
Answer: I could not get 4uk4 solution to work but based on it I was able to
use \Drupal\Core\Block\BlockPluginInterface;

function MYMODULE_block_build_alter(array &$build, BlockPluginInterface $block) {
  if ($block->getPluginId() === 'system_menu_block:main') {
    $build['#create_placeholder'] = FALSE;
  }
}

Can BigPipe exclude certain blocks?


Let $G$ and $H$ be groups, and let $X:G\to H$ be a group homomorphism.

Question: Let $G$ and $H$ be groups, and let $X : G\to H$ be a group homomorphism. Prove the
following statements.
A. If $K$ is a subgroup of  $H$, then $X^{-1}
(K)$ is a subgroup of $G$.
B. If $K$ is normal in $H$, then $X^{-1}(K)$ is normal in $G$.
C. If $X$ is surjective and $N$ is a normal subgroup of $G$, then $X (N)$ is a normal
subgroup of $H$.
Comment: I figured out A and B need direction on C
Answer: We must show $hX(N)h^{-1} \subseteq X(N)$ for all $h \in H$.  Let $hxh^{-1} \in hX(N)h^{-1}$.   We can find $a \in N, b \in G$ such that $X(a) = x$ and $X(b)= h$.  By normality, $bab^{-1} \in X(N)$.
I'll leave the rest to you.


Experimental design study on arousal/attention

Question: I hope this question is simple enough, suits this forum and does not consume much of your time. Essentially, want to make sure I have the appropriate design that answers my research question without interference from any confounding variables.
I want to specifically test the effect of an independent variable emotional arousal (high vs. low) on distraction measured by dependent variable (RTs).
For this I have an intersubject where in one condition two letters are superimposed against high arousal background images (condition 1) and in a different condition against low arousal background images (condition 2). The task is to judge whether the two letters are congruent (even) or incongruent (odd) and I want to control for this congruency/incongruency effect.
For this, across the two conditions I have used the same exact congruent and incongruent letters but the order in which they appear are randomized to avoid any sequential effect. To my view what really varies across varies is the emotional arousal while the congruency/incongruency factor is matched.
Is my design correct am I specifically testing the effect of variable emotional arousal (high vs. low) on distraction measured by dependent variable (RTs) and controlling for the confounding variable (congruency/incongruency)?
Thank you so much in advance
Jose
Answer: Welcome to CV! Your question may be a bit more about subject knowledge than statistics, but probably enough about statistics to fit here :)
In my reading, you will be able to find out the effect of high vs. low intensity on reaction time with your study design, assuming you are controlling for relevant confounding variables.
What is confusing to me is that you say the task your participants do is to judge congruency/incongruency but you also say you want to control for the "congruency/incongruency effect"? But in general, if your 2 conditions are identical in all aspects except the high vs. low arousal evoking background, and reaction time is a good measure of distraction (probably is), the design should work as intended.


Piano Notation "T"?

Question: I'm no high-end performer so probably won't matter but just curious what is this 'T'?
Second image has some notes of the first page, I supose the little schematic of the structure clarifies the T.
Comment: Does "T" appear elsewhere? Are any other letters like that used? Is there no editor comments/introduction explaining? What edition is this?
Comment: Yes, I also added the notes of the bottom of the page
Comment: I see. so "T" for "tema", and it seems it doesn't use "C" for "controsoggetto", etc.
Comment: Edition Breitkopf Nr. 2374. Only T appears but a couple of passages
Answer: Possibly it denotes this is the main melody ('Theme') of the piece.   What piece is it?  Is that bit the same as the opening statement?
Comment: I can recognise the notes because I have practiced this piece recently. It is Bach fugue number 2 in c minor from the well tempered piano vol 1. And yes this it is the theme, so since it is in fact the theme it is probably why the publisher printed a T.
Comment: Yes, this marks the theme. It is used in the instructive edition by Bruno Mugellini from 1908 as well as 1952 edition by Pietro Montani. There is also an edition by Alessadro Longo which uses boxed numbers for the theme with the number being the number of the voice.
Comment: @Tim it's a keyboard piece.  I wouldn't call it a "transcription."  The editor has changed the right hand clef from soprano to treble (standard practice in modern editions because nobody learns to read soprano clef these days) and added articulation marks, dynamics, and probably other expression and phrasing ideas, and these will be different for a piano than for a harpsichord, but the composer's explicit purpose is for the piece to be played on any keyboard instrument -- it's just that the modern piano didn't exist when he wrote it.
Comment: Since it's a fugue, it's a little non-standard to label a "theme". "Subject" is the word I would expect.
Comment: @ToddWilcox it might be nonstandard, but more likely it's [German](https://de.wikipedia.org/wiki/Fuge_(Musik)).
Comment: I don't think there's any doubt this marks the "thema," and it might be good for posterity to make the accepted answer more definite.
Comment: Does the "T" appear elsewhere? That should be a clue.
Comment: Is that sort of stating the obvious? Wouldn't a player maybe recognise what he's playing?
Comment: @Tim that's why most editions don't do this. :-)  If there are other fugues in the book (for example if it's the whole WTC or a larger subset of it), this suggestion should be very easy to test.
Comment: @phoog - or - is the engraver saying the 'theme' is in the l.h., judging by where the 'T' is?
Comment: @Tim yes.  If the engraver were saying anything else, the engraver would be wrong. Have a listen to it: you're right that most of the statements of the theme are completely obvious, but the first four notes of the theme often appear in sequential episodes without being a statement, and also the are a few statements that tend to sneak up on me so I'd mark them if I were learning it seriously: the soprano (major) in bar 11, the bass's final statement (m. 26) and perhaps the alto in the middle of the texture at bar 15. My conducting scores tend to have such marks no matter how obvious they are.
Comment: @phoog - since this is a piano transcription, the whole idea seems superfluous, don't you think?
Comment: @phoog - it was just your hint towards a 'conductor'. For piano, or even harpsichord?
Comment: @Tim I'm talking about conducting choral fugues, which I have far more experience with than playing keyboard fugues on any instrument.  So what I would or would not do in learning a keyboard fugue for performance is less certain than what I have done learning choral fugues.  Either way it can help to have redundant marks in the music for things you tend to forget. Surely you do this too from time to time?  Here the editor has done it for us.  It wouldn't be my first choice of edition, but it's not entirely unreasonable, especially if the edition is aimed at students or amateurs.
Comment: @phoog - I'm hardly into fugues of any sorts, as most of my answers portray, So, as far as that goes, my answers have not much bearing.
Answer: This is the (first) entry of the third voice, so I expect it is "T for Tenor". (My copy of these fugues is covered with my own pencil S, A, T, B, so it looks rather familiar.) In principle I don't think the voices are named (could arguably be SAB, or even ATB), so it could possibly be T for "Third voice", but that seems very unlikely. If this is a book with all of the P&Fs, look for other similar indications, S, A, T or B.
Answer: I'd hazard a guess at 'thumb'. Some older engravings used T, 1, 2, 3, 4 for fingering, rather than the modern 1, 2, 3, 4, 5, where 1 represents thumb. However, there appears '5' in the r.h., 1st and 2nd bars, and there's a suggested 2 under it, for index fingering. So that isn't it. It doesn't appear in any reference I possess, Dolmetsch being the go-to. However I'll leave this answer, as it may help later when fingering (notation) throws up a relevant question. Meanwhile, +1. Talking of which, I remember seeing thumb marked as +.
Maybe this ought to be a comment - powers that be..?
Comment: In addition to any other evidence against this guess is the fact that the note in question has a fingering of "2" below the staff.
Comment: @phoog - yes, I already mentioned that as a non-reason!
Comment: Ah, sorry, I didn't read very carefully.
Comment: I have never seen T for "thumb", but in what was called "English fingering" (as opposed to "Continental"), the signs were +1234, so that 1 meant your first finger.

Piano Notation "T"?


How to display different sets of images per page in sidebar?

Question: I'm trying to show different sets of four images in sidebar depending on which page a visitor is viewing. Aside some trouble I'm wondering whether a proper workflow should be as follows:

Create "Four Images" content type set up as a single multiupload image field.
Create "These Four Images", "Those Four Images", etc. content.
Create as many views as content units in step two set up as a grid block.
Add every block to sidebar in Block Design and restrict each block to be displayed using "Visibility->Pages".

So I'm getting a Sidebar in Block Design rapidly filled with four images views. Is there any other cleaner way of doing this?
Comment: It is not enough info about what you need, but i think you can create some content type "Four Images", create block in Views and set some context filter that will define what four images to show depending on page context.
Answer:
Create as many views as content units.
Is there any other cleaner way of doing this?

Yes, you do not need to create a View for each of your nodes/pages/content. You can create a dynamic view which automatically passes the Content ID to Views.

Create "Four Images" content type set up as a single multiupload image field.
Add these "Four Images" to you node.
Create a View Block

In View, for Fields, add your image
Click on Advanced (far right), for Contextual Filter add ID .Provide default value, Content ID from URL. (Note: The view preview will go blank, which is normal, since the View edit page does not have a Content ID.)

Go to blocks (/admin/structure/block), and add the View block to a region. For Visibility settings select the content type that you want this to appear in.
Comment: Nice. Works flawlessly!


proof by induction - explanation on it

Question: Proof by induction. It's pretty useful, and the purpose of it makes a lot of sense. However one thing has always bothered me concerning it. So when you apply induction, one has a base case where you choose a case and apply it to show it works. But then you assume it works for $k$ in the inductive case. Here is my question. Why is it that I can assume it works for $k$? Certainly the base case holds true but whose to say that some other case doesn't work. Maybe I am over thinking induction but that has always bothered me.
Comment: In induction, one proves (e.g.) that $P(1)$ is true and that $P(k)$ being true implies $P(k+1)$ is true. See if you can prove $P(5)$ is true using the two statements above.
Comment: "Why can I assume"... On a tangent note: in my first year we were taught about Post's classes in the following order: a) their exciting properties; b) a proof that they exist. In fact, the textbook literally said "Their properties are interesting, and techniques that we'll use to prove them are rather elegant, so even if they didn't actually exist they would still be worth to show you. Also, they do exits, but that's the boring part".
Comment: The core point here is that you choose your base case in such a way that the base case is case k for some k. (Often k=1 is chosen here)
Comment: Ordered set required.                               Note: Induction as a proof method only works on *ordered* sets.  It is possible to construct a pseudo proof with each individual explicit step valid.  However, if k comes from an unordered set like the complex numbers, there is no natural or predetermined progression from k to the next.
Comment: I think the source of misunderstanding is that we **do not** assume that is holds for _k_ - we rather show that **if** it does then it also holds for _k+1_ or whatever.
Answer: It works in the first case.
If it works in the first case, then it works in the second case.
If it works in the second case, then it works in the third case.
If it works in the third case, then it works in the fourth case.
$\ldots$ and so on.
That's what mathematical induction does.  But all of the statements above beginning with "if" are proved in one argument, rather than one by one.
Answer: Suppose you are making a mathematical argument.  You assume $A$, and then from this you show $B$.  Your question is, why are you allowed to assume $A$?
The answer is, you may not conclude from this argument that $B$ is true.  Because, as you observed, $A$ might not be true, since it was only an assumption.
What you can conclude is that if $A$ is true, then $B$ is true.
For example: Assume that all farmers are liars, and that Joe is a farmer.  Then Joe is a liar.  Can you conclude from this argument that Joe is a liar?  No, because maybe not all farmers are liars, or maybe Joe is not a farmer. But you can conclude that if all farmers were liars, and Joe was a farmer, then Joe would be a liar.
You're allowed to assume anything you want, as long as you remember at the end that the conclusion is only true if the assumption holds.  You can assume that the moon is made of green cheese, as long as your conclusions all have the form "If the moon were made of green cheese, then..."
In mathematical induction you assume that $P(n)$ is true, and using this you show that $P(n+1)$ is also true.  Can you actually conclude from this that $P(n+1)$ is true?  No, all you can conclude is that if $P(n)$ is true, then $P(n+1)$ is also true.
But mathematical induction does something wonderful here: You know (from the previous paragraph) that if $P(1)$ is true, then $P(2)$ is also true. And you do know that $P(1)$ is true, because you showed it separately as the base case.    So you can conclude that $P(2)$ is true, because you do know that $P(1)$ is true.
And because you now know that $P(2)$ is true, and you know that if $P(2)$ is true, then $P(3)$ is true, you can conclude that $P(3)$ is true.
And so on.
Answer: Assuming this and then showing the assumption means that must follow, proves that "if this then that".  The important part is the demonstration.
This is the second step in the induction proof:
$1. \quad P(1)
\\2. \quad P(k) \implies P(k+1)
\\\therefore \quad \forall k\in \mathbb Z^+ : P(k)$
You assume that the predicate holds for a general iteration in order to demonstrate that if it does so then it also holds for the next iteration.
Comment: +1, the first paragraph answers the question precisely: "Why is it that I can assume it works for $k$?"
Answer: A typical proof goes like this. Say you want to prove an assertion $A(n)$ is true. You prove that $A(0)$ is true, and then that if $A(k)$ is true, then $A(k + 1)$ must be true as well. That is, if it happens to be true for some number, then it must be true for the next.
If you manage to prove this, then since it's true for $0$, it must be true for the next number $1$. And since it's true for $1$, it must be true for the next number $2$. And so on.
Your question is why, when we do the induction step of proving $A(k) \Longrightarrow A(k+1)$, we are entitled to assume $A(k)$. The answer is that this is only a temporary, hypothetical assumption. Say that, while we are temporarily assuming $A(k)$ is true, we are able to prove $A(k+1)$. When we return to our main line of reasoning afterwards, we are not permitted to say that we have proved $A(k)$, or that we've proved $A(k+1)$. We can say only that we've proved $A(k) \Longrightarrow A(k+1)$.
Here is another example of the way this kind of temporary hypothesis is used. Say you want to prove that if a number $n$ is divisible by $6$, then it is divisible by $3$. The way to prove this is that we temporarily assume that you have some number $n$ that is divisible by $6$. From, there, we say that $n$ must be of the form $n = 6k$ for some integer $k$. Therefore $n = 3(2k)$, so we conclude (temporarily) that $n$ is divisible by $3$. Returning to our main line of reasoning, this proves the assertion $6 | n \Longrightarrow 3|n$. However, we abandon any idea that we know that $6|n$ or that $3|n$. These were temporary hypotheses. We know only that $6 | n \Longrightarrow 3|n$.
Now, the question you've asked is like asking, in this situation, why we were permitted to assume that $n$ was divisible by $6$. We certainly hadn't (and haven't) proved that $n$ is divisible by $6$. But we assumed it temporarily in order to prove a logical implication.
Answer: I've found that a much easier (yet equivalent for $\mathbb N$ under usual logic) way to view induction is the foundational approach.
Instead of the

Prove A(base)
Assume A(k)
Prove A(k+1)

You only get one step and a proof by contradiction. Assume $\neg\forall x A(x)$ then $\exists x \neg A(x)$. Take least such $x$ and prove contradiction.
The difference is small but it extends induction to all well-ordered sets and moreover allows you to use all $y<x$ in your proof of $A(x)$. At the same time it avoids having to assume $k$ to prove $k+1$.

proof by induction - explanation on it


Why SelectMany() not flattens string[] to char[]

Question: I was just trying to understand how linq works and trying different things to test Count(), GroupBy(),SelectMany(). i am stuck at a scenario and i can't understand why SelectMany() is not flatting the string[] to char type.
Here is the code:
string s = "A quick brown fox jumps over the lazy dog".ToLower();
char[] arratchar = s.ToCharArray();
var data= arratchar.GroupBy(x=>x).Select(y=> new {Alphabet = y.Key,Count = y.Count()});

This perfectly returns the alphabets count from a string.
When i do like this, it returns count of a:
string s = "A quick brown fox jumps over the lazy dog".ToLower();
var countofA = s.Count(x => x == 'a');

But now i am trying to test the SelectMany(), i know it flattens the Collection within a Collection, but it is not working in this case, here is the code i wrote:
string[] s = "A quick brown fox jumps over the lazy dog".ToLower().Split(' ') ;

var res = s.Select(x => x == "quick"); // this works
var re1s = s.SelectMany(x => x == 'q'); // but this not even compiles

Comment: Look at the actual types and values... it should all become clear once you do.
Comment: @Ehsan you are very confused, mate. That's not the correct usage of `SelectMany`
Comment: Using `var` does  neither help us to understand what you're trying to do nor you to understand what the compiler tries to do.
Comment: it was mistakenly added wrong corrected @TimSchmelter
Comment: @EhsanSajjad I think you understand SelectMany - you have written: `know it flattens the Collection within a Collection`. So - SelectMany expects collection to gave collection as output. Is `x == 'q'` collection? No - it's simple bool.
Comment: @EhsanSajjad the same applies...even worse..you are comparing a string with a `char`
Comment: @EhsanSajjad and I agree with pwas...I think you do understand it, that's why I stressed that you are getting confused (burning out?)...give your brain a break, leave the computer and go for a walk...trust me it'll help
Answer: SelectMany signature:
public static IEnumerable<TResult> SelectMany<TSource, TResult>(
    this IEnumerable<TSource> source,
    Func<TSource, IEnumerable<TResult>> selector
)

As you can see SelectMany (reffer) expects Func<TSource, IEnumerable<TResult>> as selector -  the return value of selector must be an IEnumerable implementation. In the first case, Select expect any value (Func<TSource, TResult>): x == "quick" evalutes true / false, so the result will be enumerable of bool (IEnumerable<bool>). Unfortunately, bool is not assignable to IEnumerable - that is why it doesn't compile.
Answer: x == "quick" is a Boolean expression, so when you call s.Select(x => x == "quick") it will return IEnumerable<bool>
For the same reason s.SelectMany(x => x == "quick") won't compile. Because it needs a function which returns IEnumerable<Something>. Obviously, bool doesn't implement IEnumerable<T> so it doesn't compile.
I beliebve you have some misconceptions about SelectMany. SelectMany is used to flat some data structure. It should return IEnumerable<T> and not a Boolean. Take a look at its signature.
public static IEnumerable<TResult> SelectMany<TSource, TResult>(this IEnumerable<TSource> source, Func<TSource, IEnumerable<TResult>> selector);

It takes Func<TSource, IEnumerable<TResult>> meaning it takes a function which takes TSource as parameter and must return IEnumerable<TResult>.
Let's say you have List<List<int>> which has there lists, all of them contains 3 integers. If you want to flatten the List<List<int>> to a single List<int> which contains all the 9 integers, you'll use SelectMany .
List<int> list1 = new List<int> {1, 2, 3};
List<int> list2 = new List<int> { 4, 5, 6 };
List<int> list3 = new List<int> { 7, 8, 9 };

List<List<int>> lists = new List<List<int>>
{
    list1,
    list2,
    list3
};

List<int> flatList = lists.SelectMany(x => x).ToList();
//flatList will contain numbers 1-9

Answer: Following shows what you can do with selectmany. Lets say you have a sentence word list as a character array and you want to know what characters are used :
List<char[]> sentence = "A quick brown fox jumps over the lazy dog"
    .ToLower().Split(' ').Select(o=>o.ToCharArray()).ToList();
List<char> characters = sentence.SelectMany(x => x).ToList();

Note how List<char[]> is flattened to List<char>.
Comment: "char[] is flattened to char." - I think it's not good sentence. `List` is rather flattened to `List` :)


Operations Equivalence

Question: Subtracting a number relates to summing a number, as dividing by a number relates to multiplying by a number, as ??? relates to powering by a number.
May I put it in a more mathematical manner:
$x-y \leftrightarrow x+y\space; \space\space\space\frac{x}{y} \leftrightarrow xy\space ; \space\space\space???\leftrightarrow x^y$
where$\space\space"\leftrightarrow "\space\space$represents a relationship between its sides.
Who is $\space$"???"$\space$ ?
I realise that there are actually two questions here: who is question marks and what is the relation to be considered.
(numbers are over the $\mathbb{R}$ field)
At first it seemed intuitive for me to set $\space\space ???\space\space =\space\space \log_{y}x \space\space\space$;
but then I could find no words to describe the relationship $\space"\leftrightarrow "\space$ which justifies that choice.
Answer: All the pairs of operations you mention are called "inverse operations" - you use one to undo the other. For example, if you wanted to solve an equation that involved subtraction, you would use addition:
$$x-3=0$$
$$x-3\color{red}{+3}=0\color{red}{+3}$$
$$x=3$$
The same is true for multiplication and division:
$$3x=6$$
$$\color{red}{\frac{\color{black}{3x}}3}=\color{red}{\frac{\color{black}6}{3}}$$
$$x=2$$
Now we can turn to exponentiation. Consider the equation $x^y=4$, and let's say we want to solve for $y$. Logarithms are the right way to handle that, so we end up with the following:
$$\color{red}{\log_x\color{black}{(x^y)}}=\color{red}{\log_x\color{black}4}$$
$$y=\log_x4$$
Comment: Thanks for clarifying, Robert. I also found a good answer here https://math.stackexchange.com/questions/956776/whats-the-inverse-operation-of-exponents . It turns out that there are two different ways of inverting an exponentiation.
Comment: Those are certainly some thorough explanations. Glad I could be of some help!

Operations Equivalence


Save FCM Notification Data in Ionic App

Question: I am able to send notifications to my app.
If my app is running then it is able to save the Incoming Notifications data
If my app is closed and i click on the notification on the notifications tray it opens my app but doesnt save the notification data
Any suggestions on how we can save the notifications data when the app is closed?
 below is the code
<code>    platform.ready().then(() => {

  fcm.onNotification().subscribe( data => {
    this.con.notification_title = data.notification_title;
    this.con.notification_message = data.notification_message;
      if(localStorage.getItem('oldmsg'))
      {
        this.temparr = JSON.parse(localStorage.getItem('oldmsg'));
        this.temparr.push({"notification_title":this.con.notification_title,"notification_message": this.con.notification_message});
        localStorage.setItem('oldmsg',JSON.stringify(this.temparr));
        this.presentToast("You Recieved A Message!");

      }
      else{

        this.temparr.push({"notification_title":this.con.notification_title,"notification_message": this.con.notification_message});
        localStorage.setItem('oldmsg',JSON.stringify(this.temparr));
        this.presentToast("You Recieved A Message!");

      }
    });

 statusBar.styleDefault();
  splashScreen.hide();

  this.storage.get('introShow').then((result) => {

    if(result){

      this.navCtrl.setRoot(LoginPage);
      this.storage.set('introShow', true);
    } else {

      this.navCtrl.setRoot(IntroPage);
      this.storage.set('introShow', true);
    }

    this.listenToLoginEvents();
  });

});
</code>
I have removed the data.wasTapped check to save the message no matter what.
Answer: Hopefully this helps someone
<code>        this.Onesignal.startInit(this.oneSignalAppId, this.sender_id);
    this.Onesignal.inFocusDisplaying(this.Onesignal.OSInFocusDisplayOption.Notification);
    this.Onesignal.handleNotificationReceived().subscribe(// when its received
        data => {
          if (localStorage.getItem('notifications')) {
            this.temparr = JSON.parse(localStorage.getItem('notifications'));
            this.temparr.push({body: data.payload.body,
            title: data.payload.title,
            type: data.payload.additionalData.type});
            localStorage.setItem('notifications', JSON.stringify(this.temparr.reverse()));

            this.events.publish('user:noti_done', {
              user: 'done',
              time: new Date()
            });

          } else {
            this.temparr.push({body: data.payload.body,
            title: data.payload.title,
            type: data.payload.additionalData.type});
            localStorage.setItem('notifications', JSON.stringify(this.temparr));

            this.events.publish('user:noti_done', {
              user: 'done',
              time: new Date()
            });
          }
        });

    this.Onesignal.handleNotificationOpened().subscribe(data => {
      console.log('handleNotificationOpened');
      console.log(data);

    });
    this.Onesignal.endInit();
}
</code>

Save FCM Notification Data in Ionic App


Calculated field in a Dextop C# model

Question: What is the best way to create a calculated field in a Dextop C# model that does the following:
Creates the value for the FullName field based both the FirstName and LastName fields, similar to the following in ExtJs:
<code>function fullName(v, record){
return record.name.last + ', ' + record.name.first;
}

Ext.define('Contact', {
extend: 'Ext.data.Model',
fields: [
{name: 'fullname', convert: fullName},
{name: 'firstname', mapping: 'name.first'},
{name: 'lastname', mapping: 'name.last'}
]
});
</code>
Updates the FullName field in realtime as the user is typing in either the FirstName or LastName fields on the form.
C# model code:
<code>[DextopModel]
[DextopGrid]
[DextopForm]
class MyModel
{

[DextopModelId]
[DextopGridColumn(width = 50, readOnly=true)]
public int Id { get; set; }

[DextopFormField(anchor = "0", allowBlank = false, labelAlign = "top")]
[DextopGridColumn()]
public String FirstName { get; set; }

[DextopFormField(anchor = "0", allowBlank = false, labelAlign = "top")]
[DextopGridColumn()]
public String LastName { get; set; }

[DextopFormField(anchor="0", readOnly=true, labelAlign = "top")]
[DextopGridColumn(flex=1)]
public String FullName { get; set; }
}
</code>
Answer: Answer is very simple. Dextop supports calculated columns on the server side. Change the FullName property like in the sample below.
<code>[DextopFormField(anchor="0", readOnly=true, labelAlign = "top")]
[DextopGridColumn(flex=1)]
public String FullName { get { return String.Format("{0} {1}", FirstName, LastName); } }
</code>
As an alternative you can use DextopModelField attribute to specify convert function which will be generated in the model.

Calculated field in a Dextop C# model


Power query - m language failing to show advanced editor steps

Question: I was creating applied steps in Power Query when I use advanced editor towards the end of my work to apply the same exact steps.
From Split Column by delimiter8 was the start of using advanced editor.
The problem is my final table when I refresh, only shows Column 10 with Order Items 10.1, Order Quantity 10.2 and Order Price 10.3. When it should apply the same principle to Order Items 6 to 10. See image below. Ideally I want to see 6.1 / 6.2 / 6.3 /7.1 / 7.2 / 7.3 repeat to 10.
Can you help me? I will respond as soon as I can to any replies.
Table Lay out
My code is below -
<code> #"Changed Type16" = Table.TransformColumnTypes(#"Split Column by Delimiter8",{{"Order Items.6.1", type text}, {"Order Items.6.2", Int64.Type}, {"Order Items.6.3", Int64.Type}}),
    #"Renamed Columns10" = Table.RenameColumns(#"Changed Type16",{{"Order Items.6.2", "Order Quantity.6.2"}, {"Order Items.6.3", "Order Price.6.3"}}),
    #"Changed Type17" = Table.TransformColumnTypes(#"Renamed Columns10",{{"Order Price.6.3", Currency.Type}}),
    #"Split Column by Delimiter9" = Table.SplitColumn(#"Changed Type15", "Order Items.7", Splitter.SplitTextByDelimiter(":", QuoteStyle.Csv), {"Order Items.7.1", "Order Items.7.2", "Order Items.7.3"}),
    #"Renamed Columns11" = Table.RenameColumns(#"Split Column by Delimiter9",{{"Order Items.7.2", "Order Quantity.7.2"}, {"Order Items.7.3", "Order Price.7.3"}}),
    #"Changed Type18" = Table.TransformColumnTypes(#"Renamed Columns11",{{"Order Quantity.7.2", Int64.Type}, {"Order Price.7.3", Currency.Type}}),
    #"Split Column by Delimiter10" = Table.SplitColumn(#"Changed Type15", "Order Items.8", Splitter.SplitTextByDelimiter(":", QuoteStyle.Csv), {"Order Items.8.1", "Order Items.8.2", "Order Items.8.3"}),
    #"Renamed Columns12" = Table.RenameColumns(#"Split Column by Delimiter10",{{"Order Items.8.2", "Order Quantity.8.2"}, {"Order Items.8.3", "Order Price.8.3"}}),
    #"Changed Type19" = Table.TransformColumnTypes(#"Renamed Columns12",{{"Order Quantity.8.2", Int64.Type}, {"Order Price.8.3", Currency.Type}}),
    #"Split Column by Delimiter11" = Table.SplitColumn(#"Changed Type15", "Order Items.9", Splitter.SplitTextByDelimiter(":", QuoteStyle.Csv), {"Order Items.9.1", "Order Items.9.2", "Order Items.9.3"}),
    #"Renamed Columns13" = Table.RenameColumns(#"Split Column by Delimiter11",{{"Order Items.9.2", "Order Quantity.9.2"}, {"Order Items.9.3", "Order Price.9.3"}}),
    #"Changed Type20" = Table.TransformColumnTypes(#"Renamed Columns13",{{"Order Quantity.9.2", Int64.Type}, {"Order Price.9.3", Currency.Type}}),
    #"Split Column by Delimiter12" = Table.SplitColumn(#"Changed Type15", "Order Items.10", Splitter.SplitTextByDelimiter(":", QuoteStyle.Csv), {"Order Items.10.1", "Order Items.10.2", "Order Items.10.3"}),
    #"Renamed Columns14" = Table.RenameColumns(#"Split Column by Delimiter12",{{"Order Items.10.2", "Order Quantity.10.2"}, {"Order Items.10.3", "Order Price.10.3"}}),
    #"Changed Type21" = Table.TransformColumnTypes(#"Renamed Columns14",{{"Order Quantity.10.2", Int64.Type}, {"Order Price.10.3", Currency.Type}})
</code>
Answer: This is because you reference the same step #"Changed Type15" everywhere and all intermediate results are simply overwritten. When you look at the first steps - which you are not showing here - every line depends on the preceding one.


Subtracting off Terms of a Polynomial

Question: I hope this is clear.  Suppose i have a polynomial
$$p(x)=c_nx^n+c_{n-1}x^{n-1}+...+c_1x+c_0$$
and I want to subtract off all terms of $p(x)$ whose powers are less than $k$.  So a new polynomial $q(x)$ is such that
$$q_k(x)=c_kx^k+c_{k-1}x^{k-1}+...+c_1x+c_0$$.
with $k<n$.  Then $(p-q_k)(x)$ is some new polynomial
$$p(x)-q_k(x)=c_nx^n+c_{n-1}x^{n-1}+...+c_{k+1}x^{k+1}$$
Here is my question.  Is there a way to write $p(x)-q_k(x)$ in terms of strictly the original polynomial $p(x)$?  Taking the $k$-th derivative would be one way and then multiplying the term by the appropriate power of $x$, but I was looking for someting simpler, strictly in terms of the original polynomial $p(x)$.  Perhaps its some shift in the argument, $p(x-\alpha)$, or maybe even a linear combination of $p(x)$.  Any hints?
Answer: Note $\ q = (p\ {\rm mod}\ x^{\large k+1})\ $ thus  $\ p - q\, =\, p - (p\ {\rm mod}\ x^{\large k+1}) $
Comment: Is there any way to not use the modular notation?  For example, just subtracting off  $c_0$, $c_0=p(0)$, and so we have $p(x)-p(0)$...
Comment: @AveryJessup $\ p(0) = (p\ {\rm mod}\ x)\ $ so the above is in fact  a generalization of that.

Subtracting off Terms of a Polynomial


How to block / restrict a list of URLs using Rules?

Question: I'm currently blocking access to some admin menu pages using the Rules module as follows:
Events: Drupal is initializing
Conditions:

Data comparison > Data to compare:[site:current-page:url] then URL1 to block
Data comparison > Data to compare:[site:current-page:url] then URL2 to block
Data comparison > Data to compare:[site:current-page:url] then URL3 to block
...

Actions:

Show a message on the site
Page redirect to home

I want to supply a list of URLs in one field rather than multiple data comparison conditions, is this possible in Rules?
Comment: You need to use PHP Snippet rather than other events. In PHP code use an array, which will have all the blocked URLs and compare `request_uri()` with this array (`array_search()` or `in_array()` will come in handy.
Comment: Are you saying to do this outside of Rules in a module? Sorry, slightly confused.
Comment: No you can execute PHP Snippets as part of Rules module, instead of Events you need to choose Execute as PHP Code in the drop down. Test your rules in local environment once as errors in codes can sometimes break your site.
Comment: @GoodSp33d Using PHP snippets as part of Rules (Conditions or Actions) is something you should try to avoid whenever you can. Have a look at my answer to this question here how you can do so, without PHP.
Answer: Assume the relative paths for your 3 URLs are like my/path1 (for ULR1),  my/path2 (for ULR2) and  my/path3 (for ULR3). And assume your homepage has a relative path MyHomePage. And assume this question is about D7.
With these assumptions, you could use a rule that answers your question which looks like so (in Rules export format):
{ "rules_limit_access_to_some_urls" : {
    "LABEL" : "Limit access to some URLs",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "ON" : { "init" : [] },
    "IF" : [
      { "data_is" : {
          "data" : [ "site:current-page:path" ],
          "op" : "IN",
          "value" : { "value" : [
              "my\/path1",
              "my\/path2",
              "my\/path3"
            ]
          }
        }
      }
    ],
    "DO" : [
      { "redirect" : { "url" : "MyHomePage" } },
      { "drupal_message" : {
          "message" : "Access to the content located at \u0022\u003Cstrong\u003E[site:current-page:path]\u003C\/strong\u003E\u0022 is not allowed.",
          "type" : "warning"
        }
      }
    ]
  }
}

Note site:current-page:path token in this rule, which is different from site:current-page:url.
To make the above rule work in similar situations, just adapt the paths by changing 'my/pathX' (with X=1, 2, 3) to whatever fits. And adapt the message to be shown.
Some more samples where you can see this technique at work:

How to use the Rules module to implement a custom redirect for an outdated URL?
How to hide the content of nodes/ completely, and still maintain use within Drupal 7?
What is the best way to restrict website's direct access through node urls?

Remark: Instead of using a data comparison in this Rules Condition, you may also want to try using a text comparison. That would allow you to use regular expressions. If your URLs have a common pattern for which you can write to single regular expression (such as URLx, with x=1, 2, 3, ..., 456, 457, ...), you would only need 1 such Rules Condition.
Answer: You can achieve what are you looking for by using "Execute custom PHP code"  as @2-Stroker mentioned.
If you consider Execute custom PHP code as an option to solve your issue, you need to do the following:

First enable PHP filter module
In your rule add a condition element
In condition dropdown list select Execute custom PHP code
In the PHP code section add the following code and change URLs accordingly

code:
$urls = array('/admin/whatever-url-1', '/admin/whatever-url-2', '/admin/whatever-url-3');

if(in_array(request_uri(), $urls)) {
  return true;
}