PLS: Find number of components for multiple dependent variables

Question: I created a PLS model with three dependent variables using mdatools. Variable A gets the best results when using two components. However for variables B and C it would be better to use four components.
Does it make sense to use different component counts for different variables or is this not allowed in PLS?
And how is this handled in PLS-DA? If a PLS-DA model has one variable with multiple groups. Is it allowed to use different component counts for different groups?
Answer: The first case where there are 3 dependent variables, it is in fact the usual way to have different number of components for each of them. This is also called PLS1. There is, however, another method where you can model multiple dependent variables and is called PLS2. PLS1 usually provides better prediction performance, but for some cases PLS2 can be advantageous i.e. when the dependent variables have collinearity. If unsure, you can test both.
PLS-DA can be defined as PLS regression where each class is treated as a dependent variables.
In single class(group) case, only for PLS-DA, PLS1 is equivalent to PLS2. For more than 2 classes, PLS-DA is basically applying PLS2 regression. For detailed explanation see here.


IoT Hub Event does not receive Azure device twin updated recorded property

Question: IoT Hub Event does not receive recorded property changes in the device twin. For example, property ledState is updated by the actual device (with patch) and the device twin updates the reported property, but the IoT Hub Event does not receive the event. This limits me in passing this property change to a digital twin with an azure function.
The IoT Hub Event does not show updated properties, unlike telemetry which IoT Hub Event receives. Considering IoT Hub Event only receives Device Created, Deleted, Connected, Disconnected, Telemetry Event Types.
How can I get IoT Hub Events to subscribe to property updates?
Further description:
The actual device sends packet (MQTT function _nxd_mqtt_client_publish_packet_send) and I can see this logged in Termite: $iothub/twin/PATCH/properties/reported/?$rid=1121{"ledState":true} . The hub successfully responds with 204.
This is my device as shown in IoT hub and the device's ledState (reported) property is updated to true when I press button A in mxchip:

<code>{
"deviceId": "mxchip",

"etag": "AAAAAAAAAF8=",
"deviceEtag": "NDY5NTIxODE1",
"status": "enabled",
"statusUpdateTime": "0001-01-01T00:00:00Z",
"connectionState": "Connected",
"lastActivityTime": "2022-09-16T14:51:32.9293466Z",
"cloudToDeviceMessageCount": 0,
"authenticationType": "sas",
"x509Thumbprint": {
    "primaryThumbprint": null,
    "secondaryThumbprint": null
},
"modelId": "dtmi:azurertos:devkit:gsgmxchip;2",
"version": 5310,
"properties": {
    "desired": {
        "telemetryInterval": 5,
        "$metadata": {
            "$lastUpdated": "2022-09-16T12:44:24.4494023Z",
            "$lastUpdatedVersion": 95,
            "telemetryInterval": {
                "$lastUpdated": "2022-09-16T12:44:24.4494023Z",
                "$lastUpdatedVersion": 95
            }
        },
        "$version": 95
    },
    "reported": {
        "deviceInformation": {
            "__t": "c",
            "manufacturer": "MXCHIP",
            "model": "AZ3166",
            "swVersion": "1.0.0",
            "osName": "Azure RTOS",
            "processorArchitecture": "Arm Cortex M4",
            "processorManufacturer": "STMicroelectronics",
            "totalStorage": 1024,
            "totalMemory": 128
        },
        "ledState": true,
        "telemetryInterval": {
            "ac": 200,
            "av": 1,
            "value": 5
        },
        "$metadata": {
            "$lastUpdated": "2022-09-16T14:55:52.6321409Z",
            "deviceInformation": {
                "$lastUpdated": "2022-09-16T13:54:57.5894378Z",
                "__t": {
                    "$lastUpdated": "2022-09-16T13:54:57.5894378Z"
                },
                "manufacturer": {
                    "$lastUpdated": "2022-09-16T13:54:57.5894378Z"
                },
                "model": {
                    "$lastUpdated": "2022-09-16T13:54:57.5894378Z"
                },
                "swVersion": {
                    "$lastUpdated": "2022-09-16T13:54:57.5894378Z"
                },
                "osName": {
                    "$lastUpdated": "2022-09-16T13:54:57.5894378Z"
                },
                "processorArchitecture": {
                    "$lastUpdated": "2022-09-16T13:54:57.5894378Z"
                },
                "processorManufacturer": {
                    "$lastUpdated": "2022-09-16T13:54:57.5894378Z"
                },
                "totalStorage": {
                    "$lastUpdated": "2022-09-16T13:54:57.5894378Z"
                },
                "totalMemory": {
                    "$lastUpdated": "2022-09-16T13:54:57.5894378Z"
                }
            },
            "ledState": {
                "$lastUpdated": "2022-09-16T14:55:52.6321409Z"
            },
            "telemetryInterval": {
                "$lastUpdated": "2022-09-16T13:54:58.1675571Z",
                "ac": {
                    "$lastUpdated": "2022-09-16T13:54:58.1675571Z"
                },
                "av": {
                    "$lastUpdated": "2022-09-16T13:54:58.1675571Z"
                },
                "value": {
                    "$lastUpdated": "2022-09-16T13:54:58.1675571Z"
                }
            }
        },
        "$version": 5215
    }
},
"capabilities": {
    "iotEdge": false
}
}</code>

I have commented out telemetry messages in the code so only recorded property changes are sent to IoT hub but property changes don't show for Events:
Answer: The following code snippet shows an example of simple IoTHubTrigger publisher function to Azure Event Grid Custom Topic.
<code>#r "Newtonsoft.Json"

using System;
using System.Collections;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Primitives;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

static HttpClient client = new HttpClient() { BaseAddress = new Uri(Environment.GetEnvironmentVariable("AEG_CustomTopic1")) };

public static async Task Run(string myIoTHubMessage, IDictionary<string, object> properties, IDictionary<string, object> systemProperties, ILogger log)
{
    log.LogInformation($"\nProperties: \n\t{string.Join(" | ", properties.Select(i => $"{i.Key}={i.Value}"))}");
    log.LogInformation($"\nSystemProperties: \n\t{string.Join(" | ", systemProperties.Select(i => $"{i.Key}={i.Value}"))}");
    log.LogInformation(myIoTHubMessage);

    // select only twinChangeEvents
    //if((string)systemProperties["iothub-message-source"] != "twinChangeEvents")
    //   return;

    // Fire event
    var ege = new {
         id=$"{systemProperties["Offset"]}",
         subject=$"devices/{systemProperties["iothub-connection-device-id"]}",
         eventType=$"{systemProperties["iothub-message-source"]}",
         eventTime=systemProperties["iothub-enqueuedtime"],
         data= new { properties = properties, systemProperties = systemProperties.ToDictionary(x=>x.Key, x=>$"{x.Value}"), body = JObject.Parse(myIoTHubMessage)},
         dataVersion="1.0"
         };
    var response = await client.PostAsJsonAsync("", new[] { ege } );
    log.LogInformation($"FireEvent: {response.StatusCode}");
    await Task.CompletedTask;
}
</code>
function.json:
<code>{
  "bindings": [
    {
      "type": "eventHubTrigger",
      "name": "myIoTHubMessage",
      "direction": "in",
      "eventHubName": "******",
      "connection": "******",
      "consumerGroup": "function",
      "cardinality": "one"
    }
  ]
}
</code>
Note, that the above function uses a REST POST request (no output AEG binding) to fire an event to the Azure Event Grid via a Custom Topic.
Answer: I'm having some trouble understanding the question, but it seems you're trying to get an Event Grid Subscription on a Twin Change event. The short answer is: you can't. Device Twin events are not supported for Event Grid.

How can I get IoT Hub Events to subscribe to property updates?

You mentioned that you want Device Twin changes sent to an Azure Function, you can do that by leveraging Endpoints and Message Routing. You can configure Message Routing to do that in this way:
[
The endpoint can be:

An Azure Event Hub
An Azure Service Bus Queue
An Azure Service Bus Topic
Blob Storage

All of these can be used as an input to your Azure Function.
Answer: Very helpful guidance by @Matthijs van der Veer ! I ended up doing this and can now capture digital twin change events. Expanded answer in case it helps anyone:

Created Event Hub -> create event hub instance. Then create Share Access Policy for this instance to receive mssgs.

Create Event Hub Trigger function app. Added nugget pckg Azure.Messaging.EventHubs.Processor and Microsoft.Azure.WebJobs.Extensions.EventHubs
<code> using System;
 using System.Collections.Generic;
 using System.Linq;
 using System.Text;
 using System.Threading.Tasks;
 using Azure.Messaging.EventHubs;
 using Microsoft.Azure.WebJobs;
 using Microsoft.Extensions.Logging;

 namespace BladeFunctionApps
 {
     public static class
 DeviceTwinSendAndReceivePropertyToEventHub
 {
     [FunctionName("DeviceTwinSendPropertyToEventHub")]
     public static async Task Run([EventHubTrigger("robo-eventhub", Connection = "EventHubConnectionString")] EventData[] events, ILogger log)
     {
         var exceptions = new List<Exception>();

         foreach (EventData eventData in events)
         {
             try
             {
                 // Replace these two lines with your processing logic.
                 log.LogInformation($"C# Event Hub trigger function processed a message: {eventData.EventBody}");
                 await Task.Yield();
             }
             catch (Exception e)
             {
                 // We need to keep processing the rest of the batch - capture this exception and continue.
                 // Also, consider capturing details of the message that failed processing so it can be processed again later.
                 exceptions.Add(e);
             }
         }

         // Once processing of the batch is complete, if any messages in the batch failed processing throw an exception so that there is a record of the failure.

         if (exceptions.Count > 1)
         {
             log.LogInformation("WE have exceptions:" + exceptions.Count);
             throw new AggregateException(exceptions);
         }

         if (exceptions.Count == 1)
         {
             log.LogInformation("WE have exceptions:" + exceptions.Count);
             throw exceptions.Single();
         }
     }
 }
</code>
}

Added to IotHub a message route: select Event Hub in message route and create and endpoint from the event hub instance shared access policy. Then create route for digital twin changes to route these to the end point.


Learning to map vectors to vectors

Question: Say we want to learn a function:
$f(\mathbf{x} \in \mathbf{R}^p) \rightarrow \mathbf{y} \in \mathbf{R}^q$
where $\mathbf{x}$ and $\mathbf{y}$ are vectors representing time series.
We have multiple examples of this mapping, i.e.:
$$\begin{pmatrix}\mathbf{x_0}\\...\\\mathbf{x_N}\end{pmatrix}\rightarrow \begin{pmatrix}\mathbf{y_0}\\...\\\mathbf{y_N} \end{pmatrix} $$
What type of problem is this? Is it a regression problem? If so, what metrics (loss functions) and methods would be appropiate for this problem? Anything specifically available in Python?
Comment: @whuber: I think $N$ is the number of paired sample time series, each of length $p$ (for the series that is mapped from) or $q$ (for the series that is mapped to).
Comment: I am a bit confused with your notation. Specifically $\mathbf{t}_x$ vs $\mathbf{t}_X$ and $t_X$. Perhaps standard (statistical) notation like $X_t$ or $X_{it}$ will help? Otherwise, example data will also help clarify things.
Comment: Thanks @qoheleth I just simplified the notation significantly. Hopefully it is a lot clearer now.
Comment: Did you really intend to imply that $N+1=p=q$?
Comment: Correct me if I'm wrong, but it looks like this the same problem as classifying elements of $\mathbf{x}$ with integers $\{1, \dots, N\}$. Not sure if that helps at all.
Comment: @ssdecontrol: If $f$ is linear and $q=1$ (weird time series, then ;) , it would be usual linear regression. If additionally $y$ would have a discrete domain, it would be classification.
Answer: This problem falls to the class called structured-output learning. First, you need to define a function $F(\mathbf{y}; \mathbf{x}, \mathbf{w})$ that scores predictions. It is supposed to return large values for the correct $\mathbf{y}$ and those similar to it. It is parametrized by the vector $\mathbf{w}$; usually $F$ depends linearly on $\mathbf{w}$. At test time, the decision is thus made by maximization:
$\hat{\mathbf{y}} = \arg\!\max_{\bar{\mathbf{y}}} F(\bar{\mathbf{y}}; \mathbf{x}, \mathbf{w})$.
So $F$ should be chosen the way to perform this maximization efficiently. See below for an example.
At training time, you need to find the parameters $\mathbf{w}^*$ such that for each training example $\mathbf{x}_i$ the corresponding prediction $\hat{\mathbf{y}}_i$ should be close $\mathbf{y}_i$ in some sense. Similarly to regression, it is unlikely to match perfectly, so one needs to define a loss function.
One such method is provided by structured SVM. The methods tries to find parameters $\mathbf{w}$ to maximize the margin
$F(\mathbf{y}_i; \mathbf{x}_i, \mathbf{w}) - \max_{\bar{\mathbf{y}}: \bar{\mathbf{y}} \ne \mathbf{y}_i} F(\bar{\mathbf{y}}; \mathbf{x}_i, \mathbf{w})$
for each training example $(\mathbf{x}_i, \mathbf{y}_i)$. To account for similarity in $\mathbf{y}$'s, it is usually augmented with the empirical loss function $\Delta(\bar{\mathbf{y}}; \mathbf{y})$ that measures some sort of distance; for discrete vectors it may measure Hamming distance. Thus, for each training example we want to maximize the following:
$F(\mathbf{y}_i; \mathbf{x}_i, \mathbf{w}) - \max_{\bar{\mathbf{y}}} \{ F(\bar{\mathbf{y}}; \mathbf{x}_i, \mathbf{w}) + \Delta(\bar{\mathbf{y}}; \mathbf{y}_i) \}$.
The idea is to strive for the larger margin if $\bar{\mathbf{y}}$ is more different from $\mathbf{y}_i$. We can put it together and add $L_2$ regularization to get the SVM-style optimization problem:
$\textrm{minimize}_{\mathbf{w}, \boldsymbol{\xi}} \quad \frac{\|\mathbf{w}\|^2}{2} + C \sum_{i=0}^N \xi_i,$
$\textrm{s.t.} \quad F(\mathbf{y}_i; \mathbf{x}_i, \mathbf{w}) - \max_{\bar{\mathbf{y}}} \{ F(\bar{\mathbf{y}}; \mathbf{x}_i, \mathbf{w}) + \Delta(\bar{\mathbf{y}}; \mathbf{y}_i) \} \ge -\xi_i, \quad \forall i.$
It is not trivial to solve, but there are well-studied methods that perform it, including the cutting-plane algorithm and subgradient descent. For implementations, you can try SVMstruct and pystruct.

What is left is the design of the scoring function $F$. It really depends on the problem you solve, but often some kind of graphical model is useful. Given that your data are sequential, something like Hidden Markov Model or some its generalization may be useful. For example, you may consider the following "factorization":
$F(\mathbf{y}; \mathbf{x}, \mathbf{w}) = \psi(y_{0}; \mathbf{x}, \mathbf{w}) + \sum_{j=1}^q \Big( \phi(y_{j-1}, y_{j}; \mathbf{w}) + \psi(y_{j}; \mathbf{x}, \mathbf{w}) \Big).$
It allows performing maximization over $\mathbf{y}$ in $\mathcal{O}(q)$ time using dynamic programming. The potential functions $\psi$ and $\phi$ should depend linearly on (different parts of) $\mathbf{w}$, but specific form depends on your problem (in particular, if the output variables are discrete or continuous). You also need to figure out the components of $\mathbf{x}$ the potential function depends on.
This form of scoring functions accounts for the "correlations" of neighbouring $y$'s, but it is possible to add higher-order connections at some computational cost (i.e. potentials like $\phi_4(y_{j-4}, y_{j}; \mathbf{w})$). SVMstruct library contains an example of training HMM.
Note that in case of such sequential models training can be done by maximizing likelihood, which leads to a different objective function, but in general case it is infeasible. See this paper for more details on probabilistic training of sequential models.
Answer: This problem is too general to be useful. A solution would be to map each $\mathbf{x}_i$ to $\mathbf{y}_i$ and to continue this mapping arbitrarily on $\mathbb{R}^p\setminus\{\mathbf{x}_i|i=1,\ldots,N\}$. So there is no unique solution for exactly this general problem. The function space $f$ belongs to is too large. If you could restrict $f$ to some parametrized function family (like polynomial regression) it might become feasible.
(Maybe you edit your question to make it more precise)

Learning to map vectors to vectors


Where does this O-ring belong on this Blue microphone?

Question: I recently took my Blue 888--000322 off of a normal mic stand and re-installed it on its desktop stand (which came packaged with it).  When I was done, I found this tiny o-ring on my desk.  Where does it belong?  Next to the microphone, there is a specially-shaped washer, then the stand itself; on the other side you can see 2-3 small round washers.  This o-ring must go somewhere in there, yes?
I suppose I could take apart the other side and look for the matching o-ring, but the design of the stand makes it hard to do this without the washers falling off.
enter image description here
Answer: I guess between 'contoured washer' and mic body. Shoud be a matching one the other side.
Comment: Boxes of mixed o-rings are cheap, and handy once in a while - this sounds like that while...
Comment: I didn't see one there (I probably lost that one already!  Thanks tho.
Answer: If the contour of the contoured washer (usually called a "saddle washer") mates snugly with the barrel of the microphone (as it seems to), I would assume they are meant to contact directly, without the O-ring.  The most likely place then for the O-ring is between the saddle washer and stand where it will keep the mic from tilting, even without having the nuts really tight.
Comment: This seems to be a likely case.  I tried it and having the O-ring between the stand and the contoured washer helps keep the contoured washer in its place on the microphone body.  Without it, it spins out of alignment.


How do you call when the same melody is played over and over with different bass notes

Question: There are a lot of songs that have a melody, usually a simple one or even a two-note pattern, that is played during many bars, but the bass note for each bar changes, implying chord changes?
One example is the intro to Sweet Child O'Mine.
UPDATE: Other is the two-note guitar melody in U2 "With or Without You".
UPDATE2: A perfect example is the guitar melody in Steve Vai's "Junkie", which keeps unaltered even after full strummed chord progression begins.
Is there a "formula" do achieve this?
Comment: Guns N' Roses song Sweet Child O' Mine?
Comment: @MichaelCurtis yes, from their "Appetite for Destruction" album. I have heard even better examples, but can't remember any of them...
Comment: Well I added a fine example: "With or Without You", by U2.
Comment: Is the verse vocal melody against the bass on 'In A Broken Dream' by Python Lee Jackson [Rod Stewart] similar to what you mean?
Comment: @Tetsujin not quite. I updated the question with a perfect example: Steve Vai's "Junkie".
Answer: A repeating phrase is usually called ostinato, regardless of whether or not the harmony underneath changes. It is common that an ostinato line changes a few notes to fit changing chords, but that's not necessary. Note that your example of Sweet Child O'Mine does exactly that, it doesn't repeat unaltered but there is always one note (the first one) that is changed to fit the current chord.
It is quite simple to find fixed phrases that fit well over diatonic changes. Especially if you use pentatonic ideas, the melodies will fit almost any chord of the key. As an example, use a simple two-tone motif with the notes A and G, and play it over the changes <code>||: Am | G | F | G :||</code>.
Comment: Good answer, one observation though: the way I see it, the first note of each bar in the Sweet Child example is the bass note I was referring to, and I wouldn't say it accomodates chord changes, but instead _defines_ them. What do you think?
Comment: To explain further, the pattern I am looking for is a strict repetition of a simple melodic theme, where harmonic progression is defined/implied exclusively by bass/pedal notes.
Comment: @heltonbiker: The second time around the first note is not the bass note but the third of the chord, whereas they play the root as the bass note, if I remember correctly.
Answer: A similar concept is found in "Cry me a River" by Davey Graham in 1959. In the intro, he arpeggiates an Am chord four times, and each time the arpeggio starts with a bass note that descends chromatically-- first A (matching the root of the chord), then Ab, G, and Gb.
Similar to this is the intro to "Stairway to Heaven," which features successive forms of an Am then D chord, with the same descending bass notes as Cry Me a River.
I believe this technique is called the "line cliche," and goes all the way back to Bach.  So it may help to search for that phrase.
Comment: That's indeed a [line cliché](http://music.stackexchange.com/q/24285/9724), but that's a constant harmony under a usually descending line, which is different from a constant phrase over changing harmonies.
Comment: I updated with another example, "With or Without You", by U2. Specifically, the effect I am referring to can be reproduced with only the ostinato two-note guitar part and the bass line. The harmony is then _implied_ by the notes present in each bar.
Comment: I have heard of the term C.E.S.H. (chromatic embellishment of static harmony or contrapuntal elaboration of static harmony) used synonymously for 'line cliche.' http://www.chordaddict.com/2011/08/line-cliche-chromatic-cliche-or-c-e-s-h-voicings/


Themng the grouping fields in Views

Question: I have a view which lists dishes by category. Category is a tag ("main", "soup", etc). I use grouping fields, and what i wanted is to make a kind of anchor menu for this view. Is it possible to style the grouping fields?
Right now, grouping fields are in h3 headers, just before the relevant views rows.
Is it possible to rewrite them,or alter their structure?
Answer: You have to override the view template.
In your views UI click on 'Theme:information'. This will open up a dialog with views templates and suggestions. As your view is using grouping, you need to override the 'Style output' theme template as it is the one that contains the h3 tag you want to alter. When you click on the blue 'Style output' link it will open up a dialog with the code you can copy and alter. That code needs to go into a file placed within the template's folder of your theme. The file name must be selected from the list of suggestions in the same line next to the blue 'Style output' link. First in the list is:
<code>views-view-list.tpl.php
</code>
If you override that template it will override it for all views of HTML List format, so you now have to select a more targeted suggestion. Going down the list you will see how different template suggestions target different contexts.
Have a look at this question for more information: Commerce Product Collection View Block: What Determines CSS For Each Header Link?
Comment: great! I was able to style it, and thanks to the transliteration module I was able to give the tag a content - relevant class. :-)

Themng the grouping fields in Views


Moving Average: question on Wiki derivation

Question: I'm reading Wiki's entry on a moving average and have questions on the derivation of $\textit{SMA}_{k, next}$.  Specifically, does anyone know step (2) was derived from step (1)?  The terms in the right cancel, but I still am confused how (2) is derived.  Thanks
$$
 \begin{align}
        \textit{SMA}_{k} &= \frac{p_{n-k+1} + p_{n-k+2} \cdots + p_{n}}{k} \\
        &= \frac{1}{k} \sum_{i=n-k+1}^{n} p_{i}
    \end{align}
$$
$$
\begin{align}
   \textit{SMA}_{k, next} &= \frac{1}{k} \sum_{i=n-k+2}^{n+1} p_{i}  \\
              &= \frac{1}{k} \Big( \underbrace{ p_{n-k+2} + p_{n-k+3} + \dots + p_{n} + p_{n+1} }_{ \sum_{i=n-k+2}^{n+1} p_{i} } + \underbrace{ p_{n-k+1} - p_{n-k+1} }_{= 0} \Big) && (1)\\
              &= \underbrace{ \frac{1}{k} \Big( p_{n-k+1} + p_{n-k+2} + \dots + p_{n} \Big) }_{= \textit{SMA}_{k, prev}} - \frac{p_{n-k+1}}{k} + \frac{p_{n+1}}{k}  && (2)\\
              &= \textit{SMA}_{k, prev} + \frac{1}{k} \Big( p_{n+1} - p_{n-k+1} \Big) && (3)
\end{align}
$$
Comment: In (2) there is p_{n-k+1} inside the bracket which is not in (1) therefore is has to be subracted. p_{n+1} is just taken out of the bracket..
Answer: The idea of this demonstration is to write $SMA_{k,n+1}$ in terms of $SMA_{k,n}$ (probably for computation reasons, its easier to add a few numbers than a lot).
They started writing $SMA_{k,n+1}$ and if you compare this with $SMA_{k,n}$, you will notice that the term $p_{n-k+1}$ (the first term in $SMA_{k,n}$) is missing, and the last term $p_{n+1}$ that is not in $SMA_{k,n}$, so they added and substracted the term $p_{n-k+1}$ and then separated the term $p_{n+1}$ from the summation.
Probably the confusion comes from the fact that the the term $p_{n-k+1}$ was located in the first position in the summation in (2).


Effect of distance on transfer speed (increases over time)

Question: I'm in Europe and I'm running a web site in the Unites States.
The service provider where the site is hosted offers large up/down bandwith (at good prices).
The server now have very low load (on network/cpu/storage)
As the server is far from me and the route the data have to take is long I have a quite high response time (ping gives 150 to 200 ms) but this is acceptable for me.
Data transfer speed is also good due to large upload bandwidth offered by the provider.
However it seem to me that data transfer starts slow and then reach its peak speed after a few seconds.
Questions:
Is this an effect of the long route/distance too?
What causes this "inertial" behaviour of the data transfer speed?
Answer:
However it seem to me that data transfer starts slow and then reach
  its peak speed after a few seconds.

This is expected behavior, especially on connections with higher latency. Look up TCP Slow Start and TCP Window Scaling for more info on this.

Is this an effect of the long route/distance too?

No, it's an effect of high latency. Latency and geographic distance are indeed correlated, but aside from from the speed of light in fiber, there is no strong correlation between the two. There are many factors that play into latency (congestion, number of EDFAs in line, number of route hops, etc.), and distance is only a small part of that.

What causes this "inertial" behaviour of the data transfer speed?

When a TCP socket opens, the network stack errs on the side of being conservative about how much data it will send before receiving acknowledgement from the other end of the socket that the packets have been received. As the socket ages, and more information is known about the quality of the connection, the network stack can increase the Window Size, which allows more packets to be "in flight" before receiving acknowledgment.
Comment: The High Energy Physics world has been dealing with this problem for many years and has developed some specialized tools to maximize data transfer speeds over long haul networks.

bbcp
is perhaps the easiest to deploy, but gridftp also uses the same technologies.

http://www.nics.tennessee.edu/computing-resources/data-transfer/bbcp  The small files problem is hard, you might look into tuning the tcp parameters in your kernel. The utilities above won't help with small files.
Comment: The simplest solution, if possible, is to reuse your TCP connections rather than closing them and opening new ones.
Comment: Thank you. Slow-start effect is an issue (for me) on small file requests (when they cannot be aggregated of course). Is there anything I can do to mitigate the effect?
Answer: Not really.
What you experience here is TCP adjusting it's window size to the conditions of your connection. See Slow-Start.


nested div classes with javascript

Question: I need some help with nested classes with javascript.
I made image, title, date and btn classes but I need a container that can cover these divs. I use createElement and setAttribute to make these divs but I have no idea how can I make a container with createElement with javascript. Thank you.

Titles

Desc

    <input id="search-bar" type="text" placeholder="Enter">
    <button id="search-btn" onclick="requested()">Search</button>

My Galaxy

function loaded() {
for (let i = 0; i < MAX_PAGE; i++) {
    const img = document.createElement('div');
    img.setAttribute("class", "image");
    document.body.appendChild(img);

    const title = document.createElement('div');
    title.setAttribute("class", "title");
    document.body.appendChild(title);

    const date = document.createElement('div');
    date.setAttribute("class", "date");
    document.body.appendChild(date);

    const btn = document.createElement('button');
    btn.setAttribute("id", "btn");
    document.body.appendChild(btn);
}

}
Comment: Can you not have a `` already on the page waiting for things to be appended into?
Comment: I need to add the container div as dynamic way : (
Comment: Does it have to wrap the elements you are adding? Where this `container` div should be placed?
Comment: You can do `const someElement = document.createElement('div');` then simply do `someOtherElement.append(someElement);`
Comment: Yes container wrap the image, title, date and btn divs. So it has to be inside the for loop. The container div should be at the beginning of the body tag.
Answer: I suppose you just need to create the container first, then append everything inside it. I will assume you want a separate container for each set of data, something like:
function loaded() {

  for (let i = 0; i < MAX_PAGE; i++) {
    const container = document.createElement('div');
    container.classList.add('container');
    document.body.appendChild(container);

    const img = document.createElement('div');
    img.setAttribute("class", "image");
    container.appendChild(img);

    const title = document.createElement('div');
    title.setAttribute("class", "title");
    container.appendChild(title);

    const date = document.createElement('div');
    date.setAttribute("class", "date");
    container.appendChild(date);

    const btn = document.createElement('button');
    btn.setAttribute("id", "btn");
    container.appendChild(btn);
  }
}

Answer: As stated by @Kinglish , the page can already come with a container that you append to using JavaScript, or you can create that container by appending it to document:
You do this by calling JavaScript div functions on an element selected y id (container) rather than 'document' directly.

function loaded() {
//set Constants
  var MAX_PAGE =5;
  var color=['red','yellow','green','blue','orange'];
  //Get refrence to the exsisting container object
  var baseContainer1 = document.getElementById('container1');

  //Create a new container object
  var baseContainer = document.createElement('div');
  document.body.appendChild(baseContainer);
  baseContainer.id="container";
  baseContainer.style.backgroundColor='green';
  baseContainer.innerHTML="Dynamic Container:\n";

  //Add elements to container object. For each child Element, create a new container element for that 'loop' in the for loop
  for (let i = 0; i < MAX_PAGE; i++) {
      var container = document.createElement('div');
      container.innerHTML='innerContainer(made dynamically):\n'
      container.id=("innerContainer"+i);
      container.style.fontWeight='bold';
      container.style.backgroundColor=color[i];
      container.style.border='1px black solid';
      container.style.margin='3px';
      const img = document.createElement('div');
      img.setAttribute("class", "image");
      img.innerHTML= 'img\n';
      container.appendChild(img);

      const title = document.createElement('div');
      title.setAttribute("class", "title");
      title.innerHTML= 'title\n';
      container.appendChild(title);

      const date = document.createElement('div');
      date.setAttribute("class", "date");
      date.innerHTML= 'date\n';
      container.appendChild(date);

      const btn = document.createElement('button');
      btn.setAttribute("id", "btn");
      btn.innerHTML= 'btn\n';
      container.appendChild(btn);

      baseContainer.appendChild(container.cloneNode(true)); //Use clone node as created element can't be used twice at once);
      baseContainer1.appendChild(container.cloneNode(true)); //Use clone node as created element can't be used twice at once);
  }
}
loaded();

Titles

Desc

      <input id="search-bar" type="text" placeholder="Enter">
      <button id="search-btn" onclick="requested()">Search</button>

My Galaxy

Container:

nested div classes with javascript


How to account for NFL divisions for predicting playoff chances?

Question: I'm trying to run logistic regression to find whether or not a team will make the playoffs based on their previous year stats, player awards, W-L record, etc. In the NFL, there are 2 conferences and 4 divisions within each conference. Every division winner makes the playoffs, plus 3 wildcard teams (the 3 wildcard teams are the 3 teams with the best record from the remaining non-division winners). This makes 7 teams making the playoffs from each Conference. The problem is, I do not know how to account for this in a logistic regression model. Theoretically, my model could predict 10 teams making the playoffs from one conference, and only 4 teams from the second conference, even though that is not possible. Does anyone know how I could go about accounting for these variables?
Comment: Please do not vandalize your own post.
Answer: "The problem is, I do not know how to account for this in a logistic regression model."
Interesting idea. Can you provide more information here? Specifically, how you are coding your outcome variables. The logistic regression model can only predict what you operationalize as your dependent variable. So if you have a multinomial model, which is what I'm assuming you have, the outcome, whether 10 or 4 teams, can only be whatever you code it as.


double implication proof

Question: How would I go about said proof: I know how to do it with just a single logical equivalence, but how would I prove a double implication?
Comment: "$\Rightarrow$" would be assume $x$ and $y$ rational. Then prove their product is rational.
"$\Leftarrow$" would be assume $xy$ rational. Then prove $x$ and $y$ are both rational.
Hint: The "$\Leftarrow$" implication is false.
Comment: There are two things to prove, each involving a single implication. But note that the double implication is not true. If $x$ and $y$ are rational, then $xy$ is rational. But if $xy$ is rational, it is not necessarily the case that $x$ and $y$ are rational.
Comment: You can just replace $\iff$ by $\implies$ in your proof to get the *only if* direction. Similarly for the other direction.
Answer: Hint:
$$\frac{m}{n}+\frac{p}{q}=\frac{m+p}{nq}.$$

double implication proof


Content is still attached to left edge in one column (responsive)

Question: I've a problem with this:
RWD
I'm trying to center these elements in one column (<960px) but I couldn't. I'm trying to use margin: 0 auto; but it still not working.
Comment: Add your code so we can understand what's going on.
Answer: this should work:

    <form>

            Text1
            <input type="text" id = "text1"/>

            Text 2
            <input type="email" id = "text2">

    </form>

And the CSS:
.form-group{
    display: flex;
    flex-direction: column;
    align-items: center;
 }
 img{
    display: block;
    margin: 0;
 }

Answer: .col-one-third, .col-half {
width: 100%;
float: none;

}
@media screen and (min-width: 960px) {
.col-one-third {
    width: 33.3333%;
    float: left;

}

.col-half {
    width: 50%;
    float: left;
}

}
For these elements on picture I set class="col-half"
Answer: Without more context I, this generally works for centering:
.centered-item {
 float: none;
 margin: auto;
 position: relative;
 display:block;
}


How to stop recording in android?

Question: i have this method,
    if(null != recorder){
      recorder.stop();
      recorder.reset();
      recorder.release();
      recorder = null;
    }

why it force closes my application?..
Thanks in advance!
this is my VoiceRecording2.java.. It has there buttons, start button and stop button and choose format..
 package com.example.voicexml;

 import java.io.File;
 import java.io.IOException;

 import android.app.Activity;
 import android.app.AlertDialog;
  import android.content.DialogInterface;
 import android.media.MediaRecorder;
  import android.os.Bundle;
 import android.os.Environment;
 import android.view.View;
import android.widget.Button;

 public class VoiceRecording2 extends Activity {
    private static final String AUDIO_RECORDER_FILE_EXT_3GP = ".3gp";
    private static final String AUDIO_RECORDER_FILE_EXT_MP4 = ".mp4";
    private static final String AUDIO_RECORDER_FOLDER = "AudioRecorder";

    private MediaRecorder recorder = null;
    private int currentFormat = 0;
    private int output_formats[] = { MediaRecorder.OutputFormat.MPEG_4, MediaRecorder.OutputFormat.THREE_GPP };
    private String file_exts[] = { AUDIO_RECORDER_FILE_EXT_MP4, AUDIO_RECORDER_FILE_EXT_3GP };

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.voice);

    setButtonHandlers();
    enableButtons(false);
    setFormatButtonCaption();
}

    private void setButtonHandlers() {
            ((Button)findViewById(R.id.btnStart)).setOnClickListener(btnClick);
    ((Button)findViewById(R.id.btnStop)).setOnClickListener(btnClick);
    ((Button)findViewById(R.id.btnFormat)).setOnClickListener(btnClick);
    }

    private void enableButton(int id,boolean isEnable){
            ((Button)findViewById(id)).setEnabled(isEnable);
    }

    private void enableButtons(boolean isRecording) {
            enableButton(R.id.btnStart,!isRecording);
            enableButton(R.id.btnFormat,!isRecording);
            enableButton(R.id.btnStop,isRecording);
    }

    private void setFormatButtonCaption(){
            ((Button)findViewById(R.id.btnFormat)).setText(getString(R.string.audio_format) + " (" + file_exts[currentFormat] + ")");
    }

    private String getFilename(){
            String filepath = Environment.getExternalStorageDirectory().getPath();
            File file = new File(filepath,AUDIO_RECORDER_FOLDER);

            if(!file.exists()){
                    file.mkdirs();
            }

            return (file.getAbsolutePath() + "/" + System.currentTimeMillis() + file_exts[currentFormat]);
    }

    private void startRecording(){
            recorder = new MediaRecorder();

            recorder.setAudioSource(MediaRecorder.AudioSource.MIC);
            recorder.setOutputFormat(output_formats[currentFormat]);
            recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
            recorder.setOutputFile(getFilename());

            recorder.setOnErrorListener(errorListener);
            recorder.setOnInfoListener(infoListener);

            try {
                    recorder.prepare();
                    recorder.start();
            } catch (IllegalStateException e) {
                    e.printStackTrace();
            } catch (IOException e) {
                    e.printStackTrace();
            }
    }

    private void stopRecording(){

    }

    private void displayFormatDialog(){
            AlertDialog.Builder builder = new AlertDialog.Builder(this);
            String formats[] = {"MPEG 4", "3GPP"};

            builder.setTitle(getString(R.string.choose_format_title))
                       .setSingleChoiceItems(formats, currentFormat, new DialogInterface.OnClickListener() {

                            public void onClick(DialogInterface dialog, int which) {
                                    currentFormat = which;
                                    setFormatButtonCaption();

                                    dialog.dismiss();
                            }
                       })
                       .show();
    }

    private MediaRecorder.OnErrorListener errorListener = new MediaRecorder.OnErrorListener() {
            public void onError(MediaRecorder mr, int what, int extra) {
                    AppLog.logString("Error: " + what + ", " + extra);
            }
    };

    private MediaRecorder.OnInfoListener infoListener = new MediaRecorder.OnInfoListener() {
            public void onInfo(MediaRecorder mr, int what, int extra) {
                    AppLog.logString("Warning: " + what + ", " + extra);
            }
    };

private View.OnClickListener btnClick = new View.OnClickListener() {
            public void onClick(View v) {
                    switch(v.getId()){
                            case R.id.btnStart:{
                                    AppLog.logString("Start Recording");

                                    enableButtons(true);
                                    startRecording();

                                    break;
                            }
                            case R.id.btnStop:{
                                if(null != recorder){
                                    //recorder.stop();
                                    //recorder.reset();
                                    //recorder.release();
                                    System.out.println("Churva");
                                    //recorder = null;
                            }
                                AppLog.logString("Start Recording");

                                    enableButtons(false);

                                    //stopRecording();

                                    break;
                            }
                            case R.id.btnFormat:{
                                    displayFormatDialog();

                                    break;
                            }
                    }
            }
    };

}
it a simple porgram that records a voice in your android device..
Comment: Please post the logcat output
Comment: Please share some more code and which class instance is this recorder of?
Comment: i posted the whole VoiceRecording2.java, it has also AppLog.java, and the layout..
Comment: post the logcat showing the error...
Comment: crash is occurring because of selecting output source to 3GPP or MPEG 4?
Comment: no, errorlog says stop called in an invalid state:4
Answer: Check the Java text of stop() method of recorder which says:

{public void stop ()  Since: API Level 1  Stops recording. Call this
   after start(). Once recording is stopped, you will have to configure
   it again as if it has just been constructed.
Note that a
   RuntimeException is intentionally thrown to the application, if no
   valid audio/video data has been received when stop() is called. This
   happens if stop() is called immediately after start(). The failure
   lets the application take action accordingly to clean up the output
   file (delete the output file, for instance), since the output file is
   not properly constructed when this happens.
Throws IllegalStateException  if it is called before start()}

So may be exception is arising due to no valid audio/video data has been received when stop() method is called.
Comment: I believe its force closing because the audio is not being processed properly in the audio file. Please do some googling to process audio file in particular extension in android may be that may help you. mean while you can add try catch to stopping recorder so that app should not crash
Answer: First of all, create a new instance of the MediaRecorder class (android.media.MediaRecorder)
MediaRecorder mr = new MediaRecorder();

Next, set the audio source or the recording device. Usually, you will want to set it to MIC
mr.setAudioSource(MediaRecorder.AudioSource.MIC);

Now specify the output format. This is the audio format the recorded file will be stored in.
mr.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);

Also specify the AudioEncoder type
mr.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);

Finally, specify the file name where the recorded data will be stored. The Path name is the full path to the audio file.
mr.setOutputFile(PATH_NAME);

Now, the whole setup is complete. You just need to prepare the instance by calling prepare() and call the start() and stop() functions to start / stop recording.
mr.prepare();mr.start();.......mr.stop();

Once the recording is finished, you can release the resources associated with that particular instance by calling
mr.release();

You can also reset the MediaRecorder instance to the initial state by calling
mr.reset();

Optionally, you can also use mr.setMaxDuration() to set the maximum duration of the recording and mr.setMaxFileSize() to set the maximum file size used for recording.
Add <uses-permission android:name="android.permission.RECORD_AUDIO"> in your Manifest

How to stop recording in android?


Apache : How to print value of MaxRequestsPerChild in log files

Question: I am trying to troubleshoot some issue and need to print out the value of MaxRequestsPerChild in the log file. I set LogLevel to debug but it does not print out the value. Does anyone know how I can print this value out ?
Comment: That's a static value, why do you want to print it ?
Answer: I figured it out the hard way but creating a test environment and sending high number of requests to it and checking the number of processes.
I am not marking this as an answer. I would still like to know if displaying this information in the log files is possible.


Exibindo mensagem de boas vindas na navbar!

Question: Estou fazendo uma aplicação em MVC asp.net. Quando o usuário fizer login eu gostaria que exibisse a mensagem de boas vindas trazendo o nome do usuário, contudo está trazendo o email, como altero isso?
O meu action está dessa forma:
@Html.ActionLink("Olá " + User.Identity.GetUserName() + "!", "Index", "Manage", routeValues: null, htmlAttributes: new { title = "Manage" })

Comment: Algumas respostas em perguntas do SO indicam usar o `User.Identity.Name`; já testou?
Comment: Dessa forma da erro indicando que não há nenhum argumento fornecido que corresponde ao parâmetro necessário.
Comment: Está usando Windows Authentication? Ou qual a forma de autenticação do usuário?
Answer: Se você está usando o template do ASP.NET MVC com Identity, por padrão ele já salva o Username com o email informado no método Register, veja só:
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Register(RegisterViewModel model)
{
    if (ModelState.IsValid)
    {
        var user = new ApplicationUser { UserName = model.Email, Email = model.Email };
        var result = await UserManager.CreateAsync(user, model.Password);
        if (result.Succeeded)
        {
            await SignInManager.SignInAsync(user, isPersistent:false, rememberBrowser:false);
            return RedirectToAction("Index", "Home");
        }
            AddErrors(result);
    }
        return View(model);
}

Você pode modificar este comportamento... Como?
Altere sua classe RegisterViewModel:
public class RegisterViewModel
{
    [Required]
    [EmailAddress]
    [Display(Name = "Email")]
    public string Email { get; set; }

    [Required,Display(Name = "Username")]
    public string Username { get; set; }

    [Required]
    [StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 6)]
    [DataType(DataType.Password)]
    [Display(Name = "Password")]
    public string Password { get; set; }

    [DataType(DataType.Password)]
    [Display(Name = "Confirm password")]
    [Compare("Password", ErrorMessage = "The password and confirmation password do not match.")]
    public string ConfirmPassword { get; set; }
}

E na View Register.cshtml adicione o campo que ira receber o Username

        @Html.LabelFor(m => m.Username, new { @class = "col-md-2 control-label" })

            @Html.TextBoxFor(m => m.Username, new { @class = "form-control" })

Feito isso, altere o que o Username está recebendo no método Register em AccountController
var user = new ApplicationUser { UserName = model.Username, Email = model.Email };

E pronto, seu Username terá o valor informado, no momento do Registro. =)
Comment: @WPfan aí você tem que ver como está sendo feito o login, acredito que pelo email, dê uma olhada no `AccountController` e tente entender o que ela está fazendo no login.
Comment: perfeito cara, isso mesmo.. muito obrigado!!
Comment: Só tem um problema, eu faço o registro e da tudo ok, portanto quando saio que tento entrar novamente da tentativa de login invalida!
Comment: Consegui, alterei aqui para que requisitasse o nome de usuário e senha ao invés de email e senha, dai deu tudo certo... valeu mesmo!!!


Pictures inserted on some computers are not clear

Question: I insert the picture into the eyeshot. The inserted picture is as clear as the source picture, but on a few computers, the picture will become particularly blurred. I send the customer's system information to see if it is helpful to solve this problem?
Thanks a lot!

system info source picture piture in eyeshot
Comment: Please clarify your specific problem or provide additional details to highlight exactly what you need. As it's currently written, it's hard to tell exactly what you're asking.
Answer: You need to check the graphics adapter drivers and update them to the latest version available.
The system info you provided does not include data from the graphics adapter.
Comment: The driver is the latest, but the picture is not clear yet.

https://i.stack.imgur.com/jKIWq.jpg
Comment: Is the picture resolution good enough? Can you attach the raster image in your OP?
Comment: sure, the picture resolution is very good,  I have attached the source picture file in the question。
Answer: The driver is the latest, but the picture is not clear yet.


Calculating standard error for a Normal population

Question: I'm a programmer, with a decent but not-expert knowledge of stats, and I'm working through these instructions for how to create funnel plots.
I understand from a previous question that the standard error in these instructions is being calculated using p(1-p) (in step 4), because these are events and therefore follow a Bernoulli distribution.
However, if the data was about individuals in the population, rather than events, how would I calculate the standard error?
I know it would be a Normal distribution and therefore standard error would be the square root of the standard deviation, but what formula would I calculate that, given the data I have in the example? (i.e. a set of samples with denominator and numerator population).
Thanks for your help.
Answer: This is true for any continuous distribution and not just a normal.  You simply calculate the sample standard deviation and divide it by the square root of n.
Let m be the the mean for the sample sum the squared deviations of the observations Xi for the sample mean m divide by n-1 (of the unbiased variance estimate) and take the square root for the sample standard deviation estimate.  Then divide by the square root of n to get the standard error.


Prove that this rearrangement is convergent and find a simple formula for the summation of it

Question: Assume that $p$ and $q$ are natural numbers and consider another way of writing the sequence :
$1-1+\frac{1}{2}-\frac{1}{2}+\frac{1}{3}-\frac{1}{3}+\frac{1}{4}-\frac{1}{4}+\frac{1}{5}-\frac{1}{5}+ \dots$
Such that this rewriting (rearrangement) consists of $p$ positive terms and after that, $q$ negative terms.
Notice that in this rearrangement, terms with equal signs should should come like the original order they had before.
For example, if $p=3$ and $q=2$, this rearrangement is like this :
$1+\frac{1}{2}+\frac{1}{3}-1-\frac{1}{2}+\frac{1}{4}+\frac{1}{5}+\frac{1}{6}-\frac{1}{3}-\frac{1}{4}+\dots$
Prove that this rearrangement is convergent and find a simple formula for the summation of it.
Note : In the class, we learned some kind of theorem. It states that we can arrange each series in a way that it is convergent. I don't know how to apply that for this question. Also it would be good if someone wrote an explanation on how these rearrangements are good.
Thanks in advance.
Answer: EDIT: General case below
Consider the series for p=2,q=1: $$ 1 + \frac{1}{2}-1 + \frac{1}{3} + \frac{1}{4} - \frac{1}{2} + \frac{1}{5} + \frac{1}{6}-\frac{1}{3} \ldots$$
We can write this in groups of three as
$$\sum_{n=1}^\infty \frac{1}{2n-1}+\frac{1}{2n} - \frac{1}{n}$$
and simplify to
$$\sum_{n=1}^\infty \frac{1}{2n-1}- \frac{1}{2n}  = \sum_{n=1}^\infty (-1)^{n-1} \frac{1}{n} = \ln(2)$$
General case:
Look at the partial sum just after the n-th time through the cycle of p positive and q negative entries. Call this $A_n.$ Then we have $$A_n = H_{pn} - H_{qn}$$ where $H_n$ is the harmonic number defined by
$$
H_n = \sum_{k=1}^n\frac{1}{k}.
$$
The harmonic number has the property
$$
\lim_{n\rightarrow\infty} H_n - \ln(n) = \gamma
$$
where $\gamma$ is the Euler-Mascheroni Constant
So,
\begin{eqnarray}
\lim_{n\rightarrow\infty}A_n &=& \lim_{n\rightarrow\infty} H_{pn} - H_{qn} \\&=& \lim_{n\rightarrow\infty} \left(H_{pn} -\ln(n)\right) - \left(H_{qn} -\ln(n)\right) \\&=& \lim_{n\rightarrow\infty} \left( H_{pn} - \ln(pn) + \ln(p)\right) - \lim_{n\rightarrow\infty} \left( H_{qn} - \ln(qn) + \ln(q)\right)\\&=& (\gamma + \ln(p)) - (\gamma + \ln(q)) \\&=&  \ln(p/q).
\end{eqnarray}
If we call the partial sums of the whole series $B_n$ then we have $A_n = B_{n(p+q)}, $ so we've proven the convergence of a subsequence of the partial sums.  To establish convergence of the sequence $B_n$ to the same value as $A_n$ you can bound the deviation $|A_n - B_{(p+q)n + j}|$ for $0\leq j < p+q .$ For instance, if $p\geq q,$ the largest magnitude term in the sum in between index $(p+q)n$ and $(p+q+1)n$ has absolute value $\frac{1}{qn+1}$ so for $0\leq j < p+q,$ we have
$$
| A_n - B_{(p+q)n + j}|\leq \frac{p+q}{qn+1} \rightarrow 0
$$
for $n\rightarrow \infty$.
The theorem you're thinking about is probably some version of Riemann's theorem on conditionally convergent series that says conditionally convergent series can be rearranged to converge to any number (including plus or minus infinity). I don't know if this is "good" so much a warning not to do any rearrangements when manipulating a sum unless it is absolutely convergent.


Angular dynamic attribute binding via function

Question: I want to bind a range of functions to a range of buttons' [disabled] attribute. I have a range of buttons and a range of functions:
<mat-button-toggle
  *ngFor="let button of buttons"
  [disabled]="this['auth' + button.authLevel + '()']">
  {{button.displayName}}
</mat-button-toggle>

auth100(){
    let var = complicatedStuff();
    return var;
}
auth200(){
    return false;
}

(and yes, buttons is a JSON like [{authLevel: '100', displayName: 'Button Name'}, ...] etc.)
And this does not seem to work. If I try it with variables instead of functions, e.g. auth100 = false; and "this['auth' + button.authLevel]", it does work, but I want to be able to bind it to a function. Currently I'm thinking I should just do auth100var = auth100(); and just bind the auth100var variable instead a function, but I feel like you should be able to bind a function and that would be the proper way to do it, but how?
Comment: why do not you think in something like `[disabled]="function(button.authLevel)"` ? I can imagine what kind of validation you need to disable buttons.
Answer: Just change the place where you put the parentheses for calling the function. They are not part of the key by which you access the property.
  [disabled]="this['auth' + button.authLevel]()">

See live demo (stackblitz)
Comment: This does not seem to recognize it as a function, it binds as `ng-reflect-disabled="auth100() {return tru"` (yes, cut off like that).
Comment: Don't forget about the parentheses at the end. See [live example](https://stackblitz.com/edit/angular-qxtdud)


How to change File field icons (without changing core)?

Question: The generated markup for displaying a file field is (PDF in this example):

I'd like to use a different icon image. How could I do this without changing the content of /modules/file/icons?
I guess I could hide the default image and display a different one with CSS, but seems a bit messy.
Answer: You can override theme_file_icon in your theme, and specify different icon images. See file_icon_path for reference regarding how core determines which icons to use.
You can also set the "file_icon_directory" variable to the path to your icons, as the file_icon_path function looks for the path in that variable.
Comment: Following on from what jhedstrom says I've written a novice blog on how to use the two functions above to achieve this solution [here](http://www.alisonhover.com/blog/201208/how-customise-default-file-icons-drupal-7). Hope that's helpful to someone!
Answer: Two additional notes on this:

It is not necessary to copy all of the default icon files to your theme directory.
If you are using a custom icon, it must be appropriately named in order for it to be found.

As an example, I had a need to use a custom icon for a .bib (bibtex) file.  This type is mapped in file_default_mimetype_mapping(), but it defaults to the default text icon since there isn't an icon specifically defined for that mime type (text/x-bibtex).
I overrode theme_file_icon() in my theme's template.php, but I did it so that the icon path is only modified as needed, and I didn't have to copy the default icons directory to my theme directory:
function mytheme_file_icon($variables) {
  $file = $variables['file'];
  $icon_directory = $variables['icon_directory'];

  $mime = check_plain($file->filemime);

  if ($mime == 'text/x-bibtex') {
    $icon_directory = drupal_get_path('theme', 'mytheme') . '/images';
  }

  $icon_url = file_icon_url($file, $icon_directory);
  return '';
}

The second thing is that you have to name the icon appropriately.  If you just keep the use of file_icon_url(), this code from that function will determine the file name for the icon:
// For a few mimetypes, we can "manually" map to a generic icon.
$generic_mime = (string) file_icon_map($file);
$icon_path = $icon_directory . '/' . $generic_mime . '.png';
if ($generic_mime && file_exists($icon_path)) {
  return $icon_path;
}

So in my case, I needed to name my file text-x-bibtex.png.  Of course, if you want to just name it whatever you want (bibtex.png in this case), you could just set the file name manually:
$icon_url = $icon_directory . '/bibtex.png';

Either one will work, but this method allows you to keep the default icons where they are and only tweak things as needed.
Answer: Me and tregis got this File Field Icons module done a while ago. Hope this helps

This modules adds the ability to change default file field icons. You can use core icon packages (included in this module), or you can define a custom icon package.
Answer: You can (usually) preprocess theme functions. So if you:

Are okay with copying all the icons into your theme to override one or more icons.
Don't care to override theme_file_icon() in your theme.

Copy the entire modules/file/icons directory to your theme (I used file_icons) and add this preprocess function to your theme's template.php:
/**
 * Implements hook_preprocess_HOOK() for theme_file_icon().
 *
 * Change the icon directory to use icons from this theme.
 */
function MYTHEME_preprocess_file_icon(&$variables) {
  $variables['icon_directory'] = drupal_get_path('theme', 'MYTHEME') . '/file_icons';
}

You could also do conditional overrides this way ala @wonder95 but I wanted to keep things simple.
Answer: While not being as clean as some of the solutions given, a really simple way of dealing with this is to make use of the CSS3 'type' attribute selector. You can use this to quickly add your custom icon as background image to your link. The result that both are linked to the target file. You can then hide the original image. I did this to get the following appearance:

This is the CSS I used to achieve the results above:
.views-field-field-image-files img.file-icon {display:none;}
.views-field-field-image-files a {padding-left: 100px; height: 80px; display: block; margin-bottom: 20px;}
.views-field-field-image-files a[type*="application/pdf"] {background: url(../img/icons/file-icon-pdf.gif) no-repeat; }
.views-field-field-image-files a[type*="application/zip"] {background: url(../img/icons/file-icon-zip.gif) no-repeat; }
.views-field-field-image-files a[type*="application/ppt"] {background: url(../img/icons/file-icon-ppt.gif) no-repeat; }
.views-field-field-image-files a[type*="application/pptx"] {background: url(../img/icons/file-icon-ppt.gif) no-repeat; }

In my example I was showing the file fields using views.


defrecord Class Not Found Exception

Question: I have two files knapsack.clj and core.clj.
There is defrecord Item in knapsack.clj. I want to use it in core.clj but it is giving me error in cider-repl of java.lang.ClassNotFoundException: discrete-optimization.knapsack.Item even though i have require for the knapsack namespace.
Code is here :
;; ---- knapsack.clj ---------
(ns discrete-optimization.knapsack)
;; Item record has weight and value of the Item
(defrecord Item
    [weight value])

;; ---- core.clj --------
(ns discrete-optimization.core
  (:require [discrete-optimization.knapsack :as KS])
  (:import [discrete-optimization.knapsack Item]))

;; doing some knapsack in here.. :)
(and
 (= 5 (KS/knapsack-value 5 [(Item. 3 5)]))
 (= 5 (KS/knapsack-value 5 [(Item. 3 3) (Item. 2 2)])))

My clojure version is 1.5.1
Solution :
For portable solution :
use ->KS/item when referring to item outside of namespace.
Answer: While the answer from xsc is not wrong, my preference is to use the constructor functions that are generated from defrecord and avoiding the Java constructor and Java import -isms. This is likely to be more portable over time/platforms.
;; ---- knapsack.clj ---------
(ns discrete-optimization.knapsack)
;; Item record has weight and value of the Item
(defrecord Item
    [weight value])
;; The ->Item constructor is generated automatically

;; ---- core.clj --------
(ns discrete-optimization.core
  (:require [discrete-optimization.knapsack :as KS]))

;; doing some knapsack in here.. :)
(and
 (= 5 (KS/knapsack-value 5 [(KS/->Item 3 5)]))
 (= 5 (KS/knapsack-value 5 [(KS/->Item 3 3) (KS/->Item 2 2)])))

Comment: `KS/->Item.` should be `KS/->Item`
Answer: :import references a Java class - and when creating package/class names for those the Clojure compiler converts dashes to underscores. This might thus work:
(:import [discrete_optimization.knapsack Item])

defrecord Class Not Found Exception


What exactly is controlling single HTTP requests speed?

Question: As you may know using multiple HTTP threads when downloading a file from a server can significantly increase your download speeds if not max it out.
What is control of determine the throughput of every request?
I have three possibilities: the client, the server and the ISP.
Example: I'm currently at college using its 100Mbit connection (I really have this kind of BW confirmed by the speedtest.net. If I download from my VPS (nginx) with a single HTTP request the speed is stuck at 800-900KB/s, however if I use 4 or more threads I can almost max it out to about 9MB/s (probably limit of the VPS connection).
So why isn't the BW given all together if it's there available to use from both ends?
Comment: Probably bandwidth delay product.
Answer:
I have three possibilities: the client, the server and the ISP.

That are N possibilities. THe last one "the ISP" is really:

The server ISP
THe client ISP
ANYONE IN BETWEEN

There also is some loss in large latency scenarios mostly.
But assuming you have a 100mbit link because both ends have more bandiwdth is possibly ignoring items like the bandwidth of in between links. Unless you are VERY local, the traffic will cross multiple networks.
Comment: Not to mention he said he's on a college campus. Almost all colleges implement rate-limiting to some degree.
Comment: And likely do not have a HUUUUGH bandiwdth. Or, it may LOOK big, but it is not during prime time when everyone is utilizing it ;)
Comment: http://careers.stackoverflow.com/jobs/46482/tech-lead-dba-postgres-oracle-tomtom?a=UGKxPxWU :)  Found that for you...I'll delete it but you aren't in chat to tell you about the funny.
Answer: There are plently ways of capping/limiting bandwidth on a per-flow basis. Without more information I cannot say which one is being used.


Custom block won't display in admin - Drupal 7

Question: I am running into an issue where my block won't show up in the admin section of my site. I've added it to example_block_info() where the other existing blocks are declared. I've also added content in example_block_view():
/*block_info*/

$blocks['example'] = array(
    'info' => 'Example',
    'status' => TRUE,
    'visibility' => BLOCK_VISIBILITY_LISTED,
    'pages' => 'example/1*',
            'cache' => DRUPAL_NO_CACHE
);

/*block_view*/

switch($delta){

...

    case 'example':
        $block['content'] = '
            //content
        ';
        break;

}

Am I missing something? All the other blocks show up and work fine. I can modify them as well. This one doesn't work/show up.
Comment: you don't show the rest of the blocks in the code... is there a duplicate name?
Answer: Try the next code below, it work for me:
/**
 * implements hook_block_info().
 */
function mymodule_block_info() {
  $blocks['hello-message'] = array(
    'info' => t('Message'),
    'status' => TRUE,
    'visibility' => BLOCK_VISIBILITY_LISTED,
    'pages' => 'example/1*',
    'cache' => DRUPAL_NO_CACHE,
  );

  return $blocks;
}

/**
 * implements hook_block_view().
 */
function mymodule_block_view($delta = '') {
  $block = array();

  if ($delta == 'hello-message') {
    $block['subject'] = t('Message');
    $block['content'] = t('Hello World!');
  }

  return $block;
}

See https://api.drupal.org/api/examples/block_example%21block_example.module/7


How to use different layout in recyclerview?

Question: How to use two different layout in recyclerview
I have news_layout_one , news_layout_two  but i don't know to use two layout please help me in this code... thanks
public class CardAdapter extends RecyclerView.Adapter {
//Imageloader to load image
private ImageLoader imageLoader;
private Context context;
private Activity activity;
private LayoutInflater inflater;

private static String Title="title";
private static String Genre="genre";
private static String Rating="rating";

//List to store all superheroes
List<SuperHero> superHeroes;

//Constructor of this class
public CardAdapter(List<SuperHero> superHeroes, Context context){
    super();
    //Getting all superheroes
    this.superHeroes = superHeroes;
    this.context = context;
}

@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {

        View  v = LayoutInflater.from(parent.getContext()).inflate(R.layout.news_layout_one, parent, false);
         ViewHolder viewHolder = new ViewHolder(v);
         return viewHolder;
}

@Override
public void onBindViewHolder(final ViewHolder holder, int position) {

    //Getting the particular item from the list
    final SuperHero superHero =  superHeroes.get(position);
    //Loading image from url
    imageLoader = CustomVolleyRequest.getInstance(context).getImageLoader();
    imageLoader.get(superHero.getThumbnailUrl(), ImageLoader.getImageListener(holder.imageView, R.drawable.au_small_logo, android.R.drawable.ic_dialog_alert));

    //Showing data on the views
    holder.imageView.setImageUrl(superHero.getThumbnailUrl(), imageLoader);
    holder.textViewName.setText(superHero.getTitle());
    holder.textViewPublisher.setText(superHero.getRating());
    holder.secid.setText(superHero.getSec_id());
    holder.category.setText(superHero.getCategory());

    holder.relativeLayout.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent intent = new Intent(v.getContext(), News_Detail.class);

            intent.putExtra("images", superHero.getThumbnailUrl());
            intent.putExtra(Title, superHero.getTitle());
            intent.putExtra(Genre, superHero.getGenre());
            intent.putExtra(Rating, superHero.getRating());
            v.getContext().startActivity(intent);
        }
    });

    holder.share.setOnClickListener(new View.OnClickListener(){
        @Override
        public void onClick( View view)
        {
            Intent intent = new Intent(android.content.Intent.ACTION_SEND);
            intent.setType("text/plain");
            intent.putExtra(Intent.EXTRA_TEXT,  "\n" + "\n" + "http://abc.news/News/"+holder.secid.getText().toString()+"/"+holder.category.getText().toString());
            view.getContext().startActivity(intent);
        }

    });
}

@Override
public int getItemCount() {
    return superHeroes.size();
}

class ViewHolder extends RecyclerView.ViewHolder{
    //Views
    public NetworkImageView imageView;
    public TextView textViewName;
    public TextView textViewPublisher;
    public TextView secid;
    public TextView category;
    public RelativeLayout relativeLayout;
    public ImageView share;

    //Initializing Views
    public ViewHolder(View itemView) {
        super(itemView);
        imageView = (NetworkImageView) itemView.findViewById(R.id.thumbnail);
        textViewName = (TextView) itemView.findViewById(R.id.title);
        textViewPublisher = (TextView) itemView.findViewById(R.id.rating);
        secid = (TextView) itemView.findViewById(R.id.sec_id);
        category = (TextView) itemView.findViewById(R.id.category);
        relativeLayout = (RelativeLayout) itemView.findViewById(R.id.relat);
        share = (ImageView) itemView.findViewById(R.id.share);

    }
}

}
Comment: complete code? and what are you gonna do?
Comment: see `RecyclerView.Adapter#getItemViewType`
Comment: could you paste complete code pls.
Answer: You need to override getItemViewType(int position) as follow :
class CardAdapter extends RecyclerView.Adapter<CardAdapter.ViewHolder> {
    private static final int VIEW_TYPE_ONE = 1;
    private static final int VIEW_TYPE_TWO = 2;

    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        if (viewType == VIEW_TYPE_ONE) {
            // inflate first view type
        } else {
            // inflate second view type
        }
    }

    @Override
    public int getItemViewType(int position) {
        // return your ViewType depending on position here
    }
}

Then you have to do the same logic in onBindViewHolder than in onCreateViewHolder via holder.getItemViewType()
Answer: You have to create different viewHolder class for different layout and attach different view in onCreateVIewHolder. Here is an example:
@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    View view;
    RecyclerView.ViewHolder viewHolder;

    switch (viewType) {
        case TYPE_ONE: {
            view = getLayoutView(parent, R.layout.list_one);
            viewHolder = new OneViewHolders(view, currActivity);
            break;
        }
        case TYPE_TWO: {
            view = getLayoutView(parent, R.layout.list_two);
            viewHolder = new TwoViewHolders(view, currActivity, getItem(viewType));
            break;
        }
        case TYPE_THREE: {
            view = getLayoutView(parent, R.layout.list_three);
            viewHolder = new ThreeViewHolders(view, currActivity, getItem(viewType));
            break;
        }
        default: {
            viewHolder = null;
        }

    }
    return viewHolder;
}

Then create three different viewHolder class(in this case OneViewHolders, TwoViewHolders, ThreeViewHolders) and define your views there.


dimension of operations of subspaces

Question:
$\text{If}\\
W1= {(X,Y,Z | x+y-z=0 )},\\
W2= {(X,Y,Z | 3x+y-2z=0 )},\\
W3= {(X,Y,Z | x-7y+3z=0 )},\\
\text{then find dim ($W_1\cap W_2 \cap W_3$ ) and dim ($W_1 + W_2 $).}
$

is this correct answer ?
dim ($W_1\cap W_2 \cap W_3$ ) = 2 and base ($W_1\cap W_2 \cap W_3$ )= {(1,1,-1) (0,-2,1)}
dim  (W1 ) = 2 and
dim  (W2 ) = 2 and
dim ( W1 ∩ W2 )= 2 and
base ( W1 ∩ W2 )= {(1,1,-1) (0,-2,1)}
Comment: If $v\in W_1\cap W_2\cap W_3$ then $v$ satisfies each of those equations, so $$\begin{bmatrix} 1&1&-1\\3&1&-2\\1&-7&3\end{bmatrix}v=0$$
Comment: You need to know what $W_1\cap W_2\cap W_3$ and $W_1+W_2$ are before considering dimension.
Comment: Now after converting to echelon form, we can find basis  & dimension for the same .
Comment: but don't we construct matrix like that for W1+W2 +W3 instead of  W1∩W2∩W3 ?
Comment: dim (W1 ∩ W2 ∩ W3) = 2 and base (W1 ∩ W2 ∩ W3 )= {(1,1,-1) (0,-2,1)}

dim (W1 ) = 2 and dim (W2 ) = 2 and dim ( W1 ∩ W2 )= 2 and base ( W1 ∩ W2 )= {(1,1,-1) (0,-2,1)}
Answer: A column vector $\begin{bmatrix}x\\y\\z\end{bmatrix}$ belongs to $W_1\cap W_2\cap W_3$ if and only if
$$
\begin{bmatrix}
1 & 1 & -1 \\
3 & 1 & -2 \\
1 & -7 & 3
\end{bmatrix}
\begin{bmatrix}x\\y\\z\end{bmatrix}
=
\begin{bmatrix}0\\0\\0\end{bmatrix}
$$
Let's compute the RREF of the matrix
$$
\begin{bmatrix}
1 & 1 & -1 \\
3 & 1 & -2 \\
1 & -7 & 3
\end{bmatrix}
\to
\begin{bmatrix}
1 & 1 & -1 \\
0 & -2 & 1 \\
0 & -8 & 4
\end{bmatrix}
\to
\begin{bmatrix}
1 & 1 & -1 \\
0 & 1 & -1/2 \\
0 & 0 & 0
\end{bmatrix}
\to
\begin{bmatrix}
1 & 0 & -1/2 \\
0 & 1 & -1/2 \\
0 & 0 & 0
\end{bmatrix}
$$
This shows (justify it) that
$$
\begin{bmatrix}1/2 \\ 1/2 \\ 1\end{bmatrix}
$$
makes a basis for $W_1\cap W_2\cap W_3$.
This also shows (justify it) that $W_1\cap W_2=W_1\cap W_2\cap W_3$; thus
$$
\dim(W_1+W_2)=\dim W_1+\dim W_2-\dim(W_1\cap W_2)=\dots
$$
Comment: thnx..my approach was completely wrong..I just equated base= number of non zero rows after reducing to echelon form..
Comment: @chandan You have to find the null space, rather than the column space.
Comment: absolutely..thanks

dimension of operations of subspaces


Idiom to describe possibility of effect

Question: Sometimes I need to write a function that may or may not have an effect.
Is there a functional (or otherwise) idiom to describe this state of affairs? The prefix maybe describes it, but is there something idiomatic?
For example:
function maybe(guardCb) {
  return function(cb) {
    return function() {
      if(guardCb.apply(this, arguments)) {
        return cb.apply(this, arguments);
      }
    }
  };
}

function isFoo(args) {
  return args.isFoo();
}

function doSomething(args) {
  return foo.bar(args.bam);
}

maybe(isFoo)(doSomething)(args);

I am aware of the maybe monad, but it seems different to this.
Comment: Are you looking for naming conventions or a programming technique?
Comment: As of me, I will write the condition of `doSomething()` getting invoked into the function name.
Comment: Programming technique I suppose. I am interested in implementing a conditional in a "functional" style.
Answer: This is just a pure function. The equivalent Haskell code is:
maybe :: (a -> Bool) -> (a -> b) -> a -> Maybe b
maybe p f x = if p x then Just (f x) else Nothing

example = maybe p f x

There's no special name for this function. However, it can be simplified:
maybe :: Bool -> b -> Maybe b
maybe b y = if b then Just y else Nothing

example = (maybe <$> p <*> f) x

Notice that p :: a -> Bool, f :: a -> b and maybe p f :: a -> Maybe b all have one thing in common (i.e. ((->) a)). This is the Reader interface and it can be abstracted out using the Applicative type class, which is what I did.
However, this is not good code. A better abstraction would be:
maybe :: (a -> Maybe b) -> (b -> c) -> a -> Maybe c
maybe p f = fmap f . p

Notice that p :: a -> Maybe b is now a Kleisli arrow instead of a simple predicate function. We have moved the conditional logic out of the maybe function. In JavaScript your code would now be:
isFoo(args).map(doSomething);

All you need to do is define a Maybe data type and implement its Functor interface:
function Maybe(constructor) {
    this.constructor = constructor || this;
}

var Nothing = new Maybe;

function Just(value) {
    var maybe = new Maybe(Just);
    maybe.value = value;
    return maybe;
}

Maybe.prototype.map = function (functor) {
    switch (this.constructor) {
    case Nothing: return Nothing;
    case Just:    return Just(functor(this.value));
    }
};

Of course, you would also need to redefine isFoo as follows:
function isFoo(args) {
    return args.isFoo() ? Just(args) : Nothing;
}

The doSomthing function can remain as is. Hope that helps.
The idiom that you are looking for is a Functor interface.
Comment: What is the name for this field of expertise? Language theory? Did you learn this from Haskell or academically?
Comment: It's [category theory](https://en.wikipedia.org/wiki/Category_theory), a branch of mathematics. Category theory generalizes mathematics. However, it's useful in programming as well (for generalizing various common interfaces like `Functor` and `Monad`). Therefore, it's used extensively in Haskell and you learn a lot of category theory when you learn Haskell.
Answer: I think the word "possible" is appropriate to hint about the effect of the function.
correctPossibleError()

handlePossibleNameChange()

erasePossibleOuterCircle()

includePossibleMatches()

Idiom to describe possibility of effect


Ordering a monthly and quarterly query

Question: I want to start off by giving a tremendous thanks to everyone who participates in this forum.  The plethora of knowledge and examples has been an amazing resource at 3 am the day before [INSERT PROJECT NAME HERE] was due and I arrived at a wall...lol.
I've created a simple query to run as a regular report of data broken out by month and quarter, and it pulls the correct values.  However i'm having trouble with ordering.  This is what I would like the query results to return:
Month   DM          TM          FI          GR          NM          Total
JAN     0           0           50000       0           0           50000
FEB     0           0           535000      0           620043.77   1255043.77
MAR     0           0           614146      5611        3016237.91  3637788.91
Q1      0           0           1199146     5611        3636281.68  4942832.68
APR     0           0           1230059     6395        1278525.79  2578589.79
MAY     0           45796       101160      15473.18    1357877.7   1932405.88
JUN     213716.34   141050      746302.28   25007.68    2552277.35  3963233.35
Q2      213716.34   186846      2077521.28  46875.86    5188680.84  8474229.02
JUL     258362.92   49541       359178.5    19674.33    803987.99   1928917.74
AUG     62750.35    9159        151561.28   15020.88    1248746.28  1533091.93
SEP     262246.37   136064      198365.99   37397.73    3271355.71  4017822.94
Q3      583359.64   194764      709105.77   72092.94    5324089.98  7479832.61
OCT     198565.1    189847      626951.11   29517       978947.85   2048681.2
NOV     22391       53652       155140.84   11444.75    470482.95   714747.68
Q4      220956.1    243499      782091.95   40961.75    1449430.8   2763428.88

However, this is where I get stuck:
Month   DM          TM          FI          GR          NM          Total
APR     0.00        0.00        1230059.00  6395.00     1275636.61  2575700.61
AUG     62750.35    9159.00     151561.28   15020.88    1248286.28  1532631.93
FEB     0.00        0.00        535000.00   0.00        587337.00   1222337.00
JAN     0.00        0.00        50000.00    0.00        0.00        50000.00
JUL     258362.92   49541.00    359178.50   19674.33    803417.96   1933347.71
JUN     213716.34   141050.00   746302.28   25007.68    2551383.23  3962339.23
MAR     0.00        0.00        614146.00   5611.00     2920193.41  3541744.41
MAY     0.00        45796.00    101160.00   15473.18    1356653.55  1931181.73
NOV     26213.00    61683.00    130270.90   13099.75    496460.05   729362.84
OCT     198565.10   189847.00   626951.11   29517.00    978797.85   2043531.20
Q1      0.00        0.00        1199146.00  5611.00     3507530.41  4814081.41
Q2      213716.34   186846.00   2077521.28  46875.86    5183673.39  8469221.57
Q3      583359.64   194764.00   709105.77   72092.94    5322894.95  7483637.58
Q4      224778.10   251530.00   757222.01   42616.75    1475257.90  2772894.04
SEP     262246.37   136064.00   198365.99   37397.73    3271190.71  4017657.94

Here is the Query that gets me the alphabetized results:
SELECT
CASE DATEPART(mm, dtDate)
WHEN 01 THEN 'JAN' WHEN 02 THEN 'FEB' WHEN 03 THEN 'MAR'
WHEN 04 THEN 'APR' WHEN 05 THEN 'MAY' WHEN 06 THEN 'JUN'
WHEN 07 THEN 'JUL' WHEN 08 THEN 'AUG' WHEN 09 THEN 'SEP'
WHEN 10 THEN 'OCT' WHEN 11 THEN 'NOV' WHEN 12 THEN 'DEC'
END
AS 'Month',

SUM(CASE WHEN sAccount = 'DM' AND sChannel = 'DM' THEN mAmount
    ELSE 0 END) AS 'DM',
SUM(CASE WHEN sAccount = 'DM' AND sChannel = 'TM' THEN mAmount
    ELSE 0 END) AS 'TM',
SUM(CASE WHEN sAccount = 'FI' AND sChannel = 'FI' THEN mAmount
    ELSE 0 END) AS 'FI',
SUM(CASE WHEN sAccount = 'FI' AND sChannel = 'GR' THEN mAmount
    ELSE 0 END) AS 'GR',
SUM(CASE WHEN sAccount = 'NM' THEN mAmount
    ELSE 0 END) AS 'NM',
SUM(mAmount) AS 'Total'

FROM Contrib
WHERE iDeleted = '0'

GROUP BY DATEPART(mm, dtDate)

UNION

SELECT
CASE DATEPART(qq, dtDate)
WHEN 01 THEN 'Q1'
WHEN 02 THEN 'Q2'
WHEN 03 THEN 'Q3'
WHEN 04 THEN 'Q4'
END
AS 'Month',

SUM(CASE WHEN sAccount = 'DM' AND sChannel = 'DM' THEN mAmount
    ELSE 0 END) AS 'DM',
SUM(CASE WHEN sAccount = 'DM' AND sChannel = 'TM' THEN mAmount
    ELSE 0 END) AS 'M',
SUM(CASE WHEN sAccount = 'FI' AND sChannel = 'FI' THEN mAmount
    ELSE 0 END) AS 'FI',
SUM(CASE WHEN sAccount = 'FI' AND sChannel = 'GR' THEN mAmount
    ELSE 0 END) AS 'GR',
SUM(CASE WHEN sAccount = 'NM' THEN mAmount
    ELSE 0 END) AS 'NM',
SUM(mAmount) AS 'Total'

FROM Contrib
WHERE iDeleted = '0'

GROUP BY DATEPART(qq, dtDate)

I've tried a number of ways to add an order by clause into the query, but have had no success (usually getting Msg 104, Level 16... "ORDER BY items must appear in the select list if the statement contains a UNION, INTERSECT or EXCEPT operator").  I suspect that my issue is due to the union and 2 different datepart functions (month vs quarter).
I'm still pretty green, so please let me know if there is a more efficient way of organizing this query or if you think you know where I might be running into my snag.  .
Many thanks!
Pat
Comment: Have you tried a simple just "ORDER BY 1" in your query?
Comment: @abhi well, for one, [never use ORDER BY ](https://sqlblog.org/blogs/aaron_bertrand/archive/2009/10/06/bad-habits-to-kick-order-by-ordinal.aspx). Second, how will this help? The first column is the month name. I don't think the goal is to order by APR, AUG, FEB...
Answer: I think you'll need to add another column to the select, and use it for ordering ... something like this, maybe ?
SELECT
CASE DATEPART(mm, dtDate)
WHEN 01 THEN '01' WHEN 02 THEN '02' WHEN 03 THEN '04'
WHEN 04 THEN '05' WHEN 05 THEN '06' WHEN 06 THEN '07'
WHEN 07 THEN '09' WHEN 08 THEN '10' WHEN 09 THEN '11'
WHEN 10 THEN '13' WHEN 11 THEN '14' WHEN 12 THEN '15'
END
AS 'Order',
CASE DATEPART(mm, dtDate)
WHEN 01 THEN 'JAN' WHEN 02 THEN 'FEB' WHEN 03 THEN 'MAR'
WHEN 04 THEN 'APR' WHEN 05 THEN 'MAY' WHEN 06 THEN 'JUN'
WHEN 07 THEN 'JUL' WHEN 08 THEN 'AUG' WHEN 09 THEN 'SEP'
WHEN 10 THEN 'OCT' WHEN 11 THEN 'NOV' WHEN 12 THEN 'DEC'
END
AS 'Month',

SUM(CASE WHEN sAccount = 'DM' AND sChannel = 'DM' THEN mAmount
    ELSE 0 END) AS 'DM',
SUM(CASE WHEN sAccount = 'DM' AND sChannel = 'TM' THEN mAmount
    ELSE 0 END) AS 'TM',
SUM(CASE WHEN sAccount = 'FI' AND sChannel = 'FI' THEN mAmount
    ELSE 0 END) AS 'FI',
SUM(CASE WHEN sAccount = 'FI' AND sChannel = 'GR' THEN mAmount
    ELSE 0 END) AS 'GR',
SUM(CASE WHEN sAccount = 'NM' THEN mAmount
    ELSE 0 END) AS 'NM',
SUM(mAmount) AS 'Total'

FROM Contrib
WHERE iDeleted = '0'

GROUP BY DATEPART(mm, dtDate)

UNION

SELECT
CASE DATEPART(qq, dtDate)
WHEN 01 THEN '05'
WHEN 02 THEN '08'
WHEN 03 THEN '12'
WHEN 04 THEN '16'
END
AS 'Order',

CASE DATEPART(qq, dtDate)
WHEN 01 THEN 'Q1'
WHEN 02 THEN 'Q2'
WHEN 03 THEN 'Q3'
WHEN 04 THEN 'Q4'
END
AS 'Month',

SUM(CASE WHEN sAccount = 'DM' AND sChannel = 'DM' THEN mAmount
    ELSE 0 END) AS 'DM',
SUM(CASE WHEN sAccount = 'DM' AND sChannel = 'TM' THEN mAmount
    ELSE 0 END) AS 'M',
SUM(CASE WHEN sAccount = 'FI' AND sChannel = 'FI' THEN mAmount
    ELSE 0 END) AS 'FI',
SUM(CASE WHEN sAccount = 'FI' AND sChannel = 'GR' THEN mAmount
    ELSE 0 END) AS 'GR',
SUM(CASE WHEN sAccount = 'NM' THEN mAmount
    ELSE 0 END) AS 'NM',
SUM(mAmount) AS 'Total'

FROM Contrib
WHERE iDeleted = '0'

GROUP BY DATEPART(qq, dtDate)

ORDER BY 'Order'

Answer: Using AdventureWorks 2012 I came up with this solution using ROLLUP
SELECT
    [Month] = CASE WHEN GROUPING(DATEPART(MM, OrderDate)) = 1 THEN 'Q' + CAST(DATEPART(QQ, OrderDate) AS VARCHAR(2))
                   ELSE CAST(DATEPART(MM, OrderDate) AS VARCHAR(4)) END,
    SUM(TotalDue) [TotalDue]
FROM AdventureWorks.Sales.SalesOrderHeader
GROUP BY DATEPART(YY, OrderDate), DATEPART(QQ, OrderDate), DATEPART(MM, OrderDate) WITH ROLLUP
HAVING GROUPING(DATEPART(QQ, OrderDate))=0
ORDER BY MAX(OrderDate)

Adapting it for your query
SELECT
  CASE WHEN GROUPING(DATEPART(MM, dtDate)) = 1 THEN 'Q' + CAST(DATEPART(QQ, dtDate) AS VARCHAR(2))
       ELSE STUFF(CAST(DATEPART(MM, dtDate) AS VARCHAR(4)), 1, 0, REPLICATE('0', 2 - LEN(CAST(DATEPART(MM, dtDate) AS VARCHAR(4))))) END,
  SUM(CASE WHEN sAccount = 'DM' AND sChannel = 'DM' THEN mAmount
           ELSE 0 END) AS 'DM',
  SUM(CASE WHEN sAccount = 'DM' AND sChannel = 'TM' THEN mAmount
    ELSE 0 END) AS 'TM',
  SUM(CASE WHEN sAccount = 'FI' AND sChannel = 'FI' THEN mAmount
           ELSE 0 END) AS 'FI',
  SUM(CASE WHEN sAccount = 'FI' AND sChannel = 'GR' THEN mAmount
           ELSE 0 END) AS 'GR',
  SUM(CASE WHEN sAccount = 'NM' THEN mAmount
           ELSE 0 END) AS 'NM',
  SUM(mAmount) AS 'Total'
FROM Contrib
WHERE iDeleted = '0'
GROUP BY DATEPART(YY, dtDate), DATEPART(QQ, dtDate), DATEPART(MM, dtDate) WITH ROLLUP
HAVING GROUPING(DATEPART(QQ, dtDate))=0
ORDER BY MAX(dtDate)

Ordering a monthly and quarterly query


Make first item in array appear at the last item

Question:
Just to note I dont mean to reverse the whole array, just one item which is at the beginning of the array to also appear at the end of the array

I have an example of an array but i dont know how i can make mine to look the same.
I wanted to create a polygon using co-ordinate, and i found an example on the net that draws the polygon using an array. Below is the array that i found from the site
$polygon = array("-50 30","50 70","100 50","80 10","110 -10","110 -30","-20 -50","-30 -40","10 -10","-10 10","-30 -20","-50 30");

Condition is that the first and last array must be the same. And their example is from static numbers.
In my case i have dynamic list of coordinates from the database and i would wish it to generate something like the example given above.
Here is what i have tried but it does not seem to work. My code now
$query_points = mysqli_query($link,"SELECT * FROM ec");
$row_points = mysqli_fetch_assoc($query_points);

$query_lastpoint = mysqli_query($link,"SELECT * FROM ec"
$row_lastpoint = mysqli_fetch_assoc($query_lastpoint);

$longitude_last = $row_lastpoint['longitude'];
$latitude_last = $row_lastpoint['latitude'];
$polygon= array();
while ($row_points = mysqli_fetch_assoc($query_points))
{
    $longitude_xx = $row_points['longitude'];
    $latitude_yy = $row_points['latitude'];
    $xx_yy = ''.$longitude_xx.' '.$latitude_yy.'';
    $polygon[] = $xx_yy;

}
$polygon[] = "$longitude_last $latitude_last";

Its like from the source they use the variable directly as $polygon while mine is $polygon[]; and i cant say $polygon = $polygon[];
Any Assistance?
Comment: Your code generates an array `$polygon`, so there is no difference in that aspect. The `$polygon[]` is just a notation to *append* to that array. So is your only remaining question how to add the first element also as last? Or what is the problem?
Comment: The problem is when i use my code it does not work. Since the variable $polygon is used somewhere as it is from the example provided here http://assemblysys.com/php-point-in-polygon-algorithm/. But mine is $polygon[], how do i retain the variable $polygon with the condition
Comment: No, yours is not `$polygon[]`. It is also `$polygon`. What does it mean *does not work*? Which errors?
Comment: No errors but, when experimenting with values the result says 'coordinate not in polygon' while it is supposed to be in polygon. The first example i stated the that it is not my code. it is what i am trying to achieve
Answer: You can just append it again, if its already there it wont make a differnce
$array[]=  $array[0];

otherwise you can do
if (end($array) != reset($array)) {  //add the first element here

http://php.net/manual/en/function.end.php
http://php.net/manual/en/function.reset.php
Comment: finally i would also like to have the variable $array instead of $array[] so that i can use it somewhere.
Comment: @krushiovida, You misunderstand the `[]` notation: it is not a variable, it is an operator on `$array`, which is the variable.
Comment: @trincot so therefore i can still use the variable $array after appending items using $array[] ?
Comment: Yes, `$array[] = 13` is just a notation for `array_push($array, 13)`. See [documentation](http://php.net/manual/en/function.array-push.php).


SQL Join - displaying table, even if second joined table has no relevence

Question: I have two tables, one with persons and the other with various dogs that each person owns. I would like to only query the database once.
I would like to always display the active people, even if they don't have any dogs attached to their id. How would I query this?
SELECT person.*, dog.*
FROM person
LEFT OUTER JOIN dog ON person.id = dog.person_id AND
WHERE person.active=true and dog.active=true

Comment: This query does not work due to the extra `AND` in the join. Which is also the answer to your problem.... :)
Comment: Is it an extra `AND` before the `WHERE`, or a `WHERE` in the `ON` clause? There are important distinctions to be understood...
Answer: Move the condition to the join (on clause); that way you will left join any records that match both the person_id and the active flag. If no active dog is found, the person is still present in the result.
If you add the condition in the where clause, first the left join is evaluated, and then all records that are not active dogs (including those that don't have a dog at all) are filtered out. It effectively turns your left join into an inner join if you do that.
SELECT
  person.*,
  dog.*
FROM
  person
  LEFT JOIN dog ON person.id = dog.person_id AND dog.active=true
WHERE
  person.active=true

Comment: Because you will left join any records that match both the person_id and the active flag. If no dog is found, the person is still present in the result. If you add the condition in the `where` clause, first the left join is evaluated, and then all records that are not active dogs (including those that don't have a dog at all) are filtered out. It effectively turns your left join into an inner join if you do that.
Comment: @IMSoP You're actually right about that, but I felt I've personally answered this question at least 5 times on SO before. Maybe I should have spent time on either finding a duplicate or providing more context, but I hoped the code would be self-explanatory. But you're right. I'll do better next time. ;)
Comment: How does moving it change the output of the query
Comment: @SabashanRagavan Because in an `OUTER JOIN` (a.k.a. `LEFT JOIN` / `RIGHT JOIN`) the `ON` clause filters *which rows of the joined table will be used* whereas the `WHERE` clause filters *the final result set*. So a condition in the `WHERE` clauses removes people with no dogs because it doesn't match; in the `ON` clause, it just removes the dogs and leaves the people.
Comment: @GolezTrol A good example of why answers should include a full explanation of the solution rather than just fixed code. :) (That was in response to your great explanation, not about the downvote, BTW. Simulpost. (Although seeing Sabashan's next comment, I guess it was about the downvote after all, in a way!))


xamarin android support library v7 and v13 in the same app

Question: Until today I've been using support library v13 in my app. Now I also need to use support library v7.
I added them to my app, but I have some problems.

At the first compile I got a lot of error about not found resources.
I solved this one by setting the api level to 15 and min to 8. This was suggested on  stackoverflow.
Can someone explain why this is needed?
2.Now I receive some errors saying Duplicate managed type found! Mappings between managed types and Java types must be unique. First Type: 'Android.Support.V4.Content.Loader/IOnLoadCompleteListenerImplementor, Xamarin.Android.Support.v13, Version=188.8.131.52, Culture=neutral, PublicKeyToken=null'; Second Type: 'Android.Support.V4.Content.Loader/IOnLoadCompleteListenerImplementor, Xamarin.Android.Support.v4, Version=188.8.131.52, Culture=neutral, PublicKeyToken=null'.
I guess this is because v13 allready has some types from v4 and v7 is referencing v4.
Any idea?
Answer: From http://developer.android.com/tools/support-library/features.html:
v4 Support Library:
This library is designed to be used with Android 1.6 (API level 4) and higher. It includes the largest set of APIs compared to the other libraries, including support for application components, user interface features, accessibility, data handling, network connectivity, and programming utilities. Here are a few of the key classes included in the v4 library:
v7 Support Library:
There are several libraries designed to be used with Android 2.1 (API level 7) and higher. These libraries provide specific feature sets and can be included in your application independently from each other.
v8 Support Library:
This library is designed to be used with Android (API level 8) and higher. It adds support for the RenderScript computation framework. These APIs are included in the android.support.v8.renderscript package. You should be aware that the steps for including these APIs in your application is very different from other support library APIs. For more information about using these APIs in your application, see the RenderScript developer guide.
v13 Support Library:
This library is designed to be used for Android 3.2 (API level 13) and higher. It adds support for the Fragment user interface pattern with the (FragmentCompat) class and additional fragment support classes For more information about fragments, see the Fragments developer guide. For detailed information about the v13 Support Library APIs, see the android.support.v13 package in the API reference.
If you look at your error, you have two dependencies conflicting because you have both v4 and v13 imported. You can see how they have similar classes here:
http://developer.android.com/reference/android/support/v4/app/package-summary.html
http://developer.android.com/reference/android/support/v13/app/package-summary.html
You should use v4 for min-sdk = 4-12 and v13 for min-sdk = 13+
Though you can use v13 in lower API versions of android, your apps will crash on anything <12 API. You should be able to use v7 and v13 just fine as long as you don't conflict with v4.
EDIT:
Here's a video explaining android support libraries that came out recently
http://xamarin.wistia.com/medias/guqtgpdqms
Source Code:
https://github.com/jamesmontemagno/Xamarin.Android-AppCompat
Source:
Xamarin
Comment: Thank you! But this I already know. My problem is that the xamarin DLL for v7 references the v4 DLL. So when I reference v7 DLL I automatically reference v4, when I also reference v13 I get the error described above.
Comment: @user3149483 Im experiencing the same problem, after we dropped support for API < 14, v13 was added to the app and alongside Facebook SDK there'sa conflict of dependencies.. How have you worked this out?


Why do some players have trouble finishing off a point in tennis?

Question: I played a match with a 19 year old girl (division ? college player). During warm up we were hitting back and forth, she hit hard, had some spin, was pretty consistent, I thought this was going to be a good match.
But then, when we started playing, she couldn't finish the points. When we had rallies she did ok, but when it came to a short ball, or trying to put it away, she would overhit it, or hit it into the net. So it ended up being an easy short match. Maybe if she just stuck with the rallies more, and not tried being so aggressive she would have done better.
I have heard from some friends having problem with that too. They can rally, but then can't put away a short ball. Why is that?
Answer: What you are describing sounds like a player that has trouble with their "transition" game -  the shots and strategies you use when an opponent hits a short or attack-able shot to you and it draws you up to the net or puts you in a position to attempt hitting a winner. In my experience, players that have trouble with their transition game are your stereotypical "baseline basher" type players that have a pretty consistent and topspin-heavy stroke from around the baseline, but don't spend too much time developing other shots (slice, drop shots, volleys, etc.). Some players just don't develop an all-court game and try to get by on overpowering their opponent from the baseline. That type of game works up until a certain level of opponent, just not against better opponents that know how to handle power and can effectively defend against it.
Answer: This is a very common problem for many players at the "club" level, and a typical reason I've seen is that the desire to put the short ball away or forcing a play creates tension in the swing/stroke and modifies it (unconsciously). The tension is greater during match play due to pressure so the strokes seem to work well during practice. It's not easy to fix: she can try to develop more variety as suggested by jamauss to play different strokes altogether on shorter balls, or she can try to address the fundamentals of her regular strokes so that unwanted tension is removed as much as possible - the aim here is to produce consistent swing regardless of ball position or mental pressure.